* VirtueMart is free software. This version may have been modified pursuant * to the GNU General Public License, and as distributed it includes or * is derivative of works licensed under the GNU General Public License or * other free or open source software licenses. * See /administrator/components/com_virtuemart/COPYRIGHT.php for copyright notices and details. * * http://tsmart.net */ /* Require the config */ defined('DS') or define('DS', DIRECTORY_SEPARATOR); if (!class_exists('tsmConfig')) { require JPATH_ROOT . DS . 'administrator' . DS . 'components' . DS . 'com_virtuemart' . DS . 'helpers' . DS . 'config.php'; } tsmConfig::loadConfig(); vmRam('Start'); vmSetStartTime('Start'); tsmConfig::loadJLang('com_virtuemart', true); $doc = JFactory::getDocument(); JHtml::_('jquery.framework'); $doc->addScript(JUri::root() . '/media/system/js/jquery.utility.js'); $doc->addScript(JUri::root() . '/media/system/js/bootstrap-notify-master/bootstrap-notify.js'); $doc->addScript(JUri::root() . '/media/system/js/tipso-master/src/tipso.js'); $doc->addStyleSheet(JUri::root() . '/media/system/js/tipso-master/src/tipso.css'); $doc->addLessStyleSheet(JUri::root() . '/components/com_virtuemart/assets/less/etravelservice.less'); if (tsmConfig::get('shop_is_offline', 0)) { //$cache->setCaching (1); $_controller = 'tsmart'; require VMPATH_SITE . DS . 'controllers' . DS . 'tsmart.php'; vRequest::setVar('view', 'tsmart'); $task = ''; $basePath = VMPATH_SITE;
/** * Get the list of child categories for a given category, is cached * * @param int $virtuemart_category_id Category id to check for child categories * @return object List of objects containing the child categories * */ public function getChildCategoryList($vendorId, $virtuemart_category_id, $selectedOrdering = null, $orderDir = null, $useCache = true) { if (empty($this) or get_class($this) != 'VirtueMartModelCategory') { $useCache = false; } if ($selectedOrdering === null) { if ($useCache) { $selectedOrdering = $this->_selectedOrdering; } else { $selectedOrdering = VmConfig::get('browse_cat_orderby_field', 'category_name'); } } if (trim($selectedOrdering) == 'c.ordering') { $selectedOrdering = 'c.ordering,category_name'; } if (!in_array($selectedOrdering, self::$_validOrderingFields)) { $selectedOrdering = 'c.ordering,category_name'; } if ($orderDir === null) { if ($useCache) { $orderDir = $this->_selectedOrderingDir; } else { $orderDir = VmConfig::get('cat_brws_orderby_dir', 'ASC'); } } $validOrderingDir = array('ASC', 'DESC'); if (!in_array(strtoupper($orderDir), $validOrderingDir)) { $orderDir = 'ASC'; } static $_childCategoryList = array(); $key = (int) $vendorId . '_' . (int) $virtuemart_category_id . $selectedOrdering . $orderDir . VmConfig::$vmlang; //We have here our internal key to preven calling of the cache if (!array_key_exists($key, $_childCategoryList)) { vmSetStartTime('com_virtuemart_cats'); if ($useCache) { $cache = JFactory::getCache('com_virtuemart_cats', 'callback'); $cache->setCaching(true); vmdebug('Calling cache getChildCategoryListObject'); $_childCategoryList[$key] = $cache->call(array('VirtueMartModelCategory', 'getChildCategoryListObject'), $vendorId, $virtuemart_category_id, $selectedOrdering, $orderDir, VmConfig::$vmlang); } else { $_childCategoryList[$key] = VirtueMartModelCategory::getChildCategoryListObject($vendorId, $virtuemart_category_id, $selectedOrdering, $orderDir, VmConfig::$vmlang); } vmTime('Time to load cats ' . (int) $useCache, 'com_virtuemart_cats'); } return $_childCategoryList[$key]; }
/** * Loads the configuration and works as singleton therefore called static. The call using the program cache * is 10 times faster then taking from the session. The session is still approx. 30 times faster then using the file. * The db is 10 times slower then the session. * * Performance: * * Fastest is * Program Cache: 1.5974044799805E-5 * Session Cache: 0.00016094612121582 * * First config db load: 0.00052118301391602 * Parsed and in session: 0.001554012298584 * * After install from file: 0.0040450096130371 * Parsed and in session: 0.0051419734954834 * * * Functions tests if already loaded in program cache, session cache, database and at last the file. * * Load the configuration values from the database into a session variable. * This step is done to prevent accessing the database for every configuration variable lookup. * * @author Max Milbers * @param $force boolean Forces the function to load the config from the db * Note Patrick Kohl STUDIO42 * added prefix from joomla in like to prevent getting false config for multiple use of joomla in same database */ public static function loadConfig($force = FALSE, $fresh = FALSE) { if ($fresh) { return self::$_jpConfig = new VmConfig(); } vmSetStartTime('loadConfig'); if (!$force) { if (!empty(self::$_jpConfig) && !empty(self::$_jpConfig->_params)) { return self::$_jpConfig; } } self::$_jpConfig = new VmConfig(); $db = JFactory::getDBO(); $prefix = $db->getPrefix(); $query = 'SHOW TABLES LIKE "' . $prefix . 'virtuemart_configs"'; $db->setQuery($query); $configTable = $db->loadResult(); // self::$_debug = true; if (empty($configTable)) { self::$_jpConfig->installVMconfig(); } $app = JFactory::getApplication(); $install = 'no'; if (empty(self::$_jpConfig->_raw)) { $query = ' SELECT `config` FROM `#__virtuemart_configs` WHERE `virtuemart_config_id` = "1";'; $db->setQuery($query); self::$_jpConfig->_raw = json_decode($db->loadResult(), TRUE); if (empty(self::$_jpConfig->_raw)) { if (self::installVMconfig()) { $install = 'yes'; $db->setQuery($query); self::$_jpConfig->_raw = json_decode($db->loadResult(), TRUE); self::$_jpConfig->_params =& self::$_jpConfig->_raw; } else { $app->enqueueMessage('Error loading configuration file', 'Error loading configuration file, please contact the storeowner'); } } } $i = 0; $pair = array(); if (!empty(self::$_jpConfig->_raw)) { // $pair['sctime'] = microtime(true); self::$_jpConfig->_params =& self::$_jpConfig->_raw; self::$_jpConfig->set('sctime', microtime(TRUE)); self::$_jpConfig->set('vmlang', self::setdbLanguageTag()); self::$_jpConfig->setSession(); vmTime('loadConfig db ' . $install, 'loadConfig'); return self::$_jpConfig; } $app->enqueueMessage('Attention config is empty'); return self::$_jpConfig; }
/** * Get the Order By Select List * * notice by Max Milbers html tags should never be in a model. This function should be moved to a helper or simular,... * * @author Kohl Patrick * @access public * @param $fieds from config Back-end * @return $orderByList * Order,order By, manufacturer and category link List to echo Out **/ function getOrderByList($virtuemart_category_id = FALSE) { $getArray = vRequest::getGet(); $fieldLink = ''; foreach ($getArray as $key => $value) { if (is_array($value)) { foreach ($value as $k => $v) { if ($v == '') { continue; } $fieldLink .= '&' . urlencode($key) . '[' . urlencode($k) . ']' . '=' . urlencode($v); } } else { if ($key == 'dir' or $key == 'orderby') { continue; } if ($value == '') { continue; } $fieldLink .= '&' . urlencode($key) . '=' . urlencode($value); } } $fieldLink = 'index.php?' . ltrim($fieldLink, '&'); $orderDirLink = ''; $orderDirConf = VmConfig::get('prd_brws_orderby_dir'); $orderDir = vRequest::getCmd('dir', $orderDirConf); if ($orderDir != $orderDirConf) { $orderDirLink .= '&dir=' . $orderDir; //was '&order=' } $orderbyTxt = ''; $orderby = vRequest::getString('orderby', VmConfig::get('browse_orderby_field')); $orderby = $this->checkFilterOrder($orderby); $orderbyCfg = VmConfig::get('browse_orderby_field'); if ($orderby != $orderbyCfg) { $orderbyTxt = '&orderby=' . $orderby; } $manufacturerTxt = ''; $manufacturerLink = ''; if (VmConfig::get('show_manufacturers')) { $manuM = VmModel::getModel('manufacturer'); vmSetStartTime('mcaching'); $mlang = (!VmConfig::get('prodOnlyWLang', false) and VmConfig::$defaultLang != VmConfig::$vmlang and Vmconfig::$langCount > 1); if (true) { $cache = JFactory::getCache('com_virtuemart_cat_manus', 'callback'); $cache->setCaching(true); $manufacturers = $cache->call(array('VirtueMartModelManufacturer', 'getManufacturersOfProductsInCategory'), $virtuemart_category_id, VmConfig::$vmlang, $mlang); vmTime('Manufacturers by Cache', 'mcaching'); } else { $manufacturers = $manuM->getManufacturersOfProductsInCategory($virtuemart_category_id, VmConfig::$vmlang, $mlang); vmTime('Manufacturers by function', 'mcaching'); } // manufacturer link list $manufacturerLink = ''; $virtuemart_manufacturer_id = vRequest::getInt('virtuemart_manufacturer_id', ''); if ($virtuemart_manufacturer_id != '') { $manufacturerTxt = '&virtuemart_manufacturer_id=' . $virtuemart_manufacturer_id; } if (count($manufacturers) > 0) { $manufacturerLink = '<div class="orderlist">'; if ($virtuemart_manufacturer_id > 0) { $allLink = str_replace($manufacturerTxt, $fieldLink, ''); $allLink .= '&virtuemart_manufacturer_id=0'; $manufacturerLink .= '<div><a title="" href="' . JRoute::_($allLink . $orderbyTxt . $orderDirLink, FALSE) . '">' . vmText::_('COM_VIRTUEMART_SEARCH_SELECT_ALL_MANUFACTURER') . '</a></div>'; } if (count($manufacturers) > 1) { foreach ($manufacturers as $mf) { $link = JRoute::_($fieldLink . '&virtuemart_manufacturer_id=' . $mf->virtuemart_manufacturer_id . $orderbyTxt . $orderDirLink, FALSE); if ($mf->virtuemart_manufacturer_id != $virtuemart_manufacturer_id) { $manufacturerLink .= '<div><a title="' . $mf->mf_name . '" href="' . $link . '">' . $mf->mf_name . '</a></div>'; } else { $currentManufacturerLink = '<div class="title">' . vmText::_('COM_VIRTUEMART_PRODUCT_DETAILS_MANUFACTURER_LBL') . '</div><div class="activeOrder">' . $mf->mf_name . '</div>'; } } } elseif ($virtuemart_manufacturer_id > 0) { $currentManufacturerLink = '<div class="title">' . vmText::_('COM_VIRTUEMART_PRODUCT_DETAILS_MANUFACTURER_LBL') . '</div><div class="activeOrder">' . $manufacturers[0]->mf_name . '</div>'; } else { $currentManufacturerLink = '<div class="title">' . vmText::_('COM_VIRTUEMART_PRODUCT_DETAILS_MANUFACTURER_LBL') . '</div><div class="Order"> ' . $manufacturers[0]->mf_name . '</div>'; } $manufacturerLink .= '</div>'; } } /* order by link list*/ $orderByLink = ''; $fields = VmConfig::get('browse_orderby_fields'); if (count($fields) > 1) { $orderByLink = '<div class="orderlist">'; foreach ($fields as $field) { if ($field != $orderby) { $dotps = strrpos($field, '.'); if ($dotps !== FALSE) { $prefix = substr($field, 0, $dotps + 1); $fieldWithoutPrefix = substr($field, $dotps + 1); } else { $prefix = ''; $fieldWithoutPrefix = $field; } $text = vmText::_('COM_VIRTUEMART_' . strtoupper($fieldWithoutPrefix)); $field = explode('.', $field); if (isset($field[1])) { $field = $field[1]; } else { $field = $field[0]; } $link = JRoute::_($fieldLink . $manufacturerTxt . '&orderby=' . $field, FALSE); $orderByLink .= '<div><a title="' . $text . '" href="' . $link . '">' . $text . '</a></div>'; } } $orderByLink .= '</div>'; } if ($orderDir == 'ASC') { $orderDir = 'DESC'; } else { $orderDir = 'ASC'; } if ($orderDir != $orderDirConf) { $orderDirLink = '&dir=' . $orderDir; //was '&order=' } else { $orderDirLink = ''; } $orderDirTxt = vmText::_('COM_VIRTUEMART_' . $orderDir); $link = JRoute::_($fieldLink . $orderbyTxt . $orderDirLink . $manufacturerTxt, FALSE); // full string list if ($orderby == '') { $orderby = $orderbyCfg; } $orderby = strtoupper($orderby); $dotps = strrpos($orderby, '.'); if ($dotps !== FALSE) { $prefix = substr($orderby, 0, $dotps + 1); $orderby = substr($orderby, $dotps + 1); } else { $prefix = ''; } $orderByList = '<div class="orderlistcontainer"><div class="title">' . vmText::_('COM_VIRTUEMART_ORDERBY') . '</div><div class="activeOrder"><a title="' . $orderDirTxt . '" href="' . $link . '">' . vmText::_('COM_VIRTUEMART_SEARCH_ORDER_' . $orderby) . ' ' . $orderDirTxt . '</a></div>'; $orderByList .= $orderByLink . '</div>'; $manuList = ''; if (VmConfig::get('show_manufacturers')) { if (empty($currentManufacturerLink)) { $currentManufacturerLink = '<div class="title">' . vmText::_('COM_VIRTUEMART_PRODUCT_DETAILS_MANUFACTURER_LBL') . '</div><div class="activeOrder">' . vmText::_('COM_VIRTUEMART_SEARCH_SELECT_MANUFACTURER') . '</div>'; } $manuList = ' <div class="orderlistcontainer">' . $currentManufacturerLink; $manuList .= $manufacturerLink . '</div><div class="clear"></div>'; } return array('orderby' => $orderByList, 'manufacturer' => $manuList); }
/** * prepare display of cart * * @author RolandD * @author Max Milbers * @access public */ public function prepareCartData($checkAutomaticSelected = true) { vmSetStartTime('prepareCartData'); if (!empty($this->couponCode)) { $this->setCouponCode($this->couponCode); vmdebug('ValidateCouponCode', $this->couponCode); //CouponHelper::ValidateCouponCode($this->couponCode, $this->pricesUnformatted['salesPrice']); } else { // Get the products for the cart, the setCouponCode does it for us $this->getCartPrices($checkAutomaticSelected); } if (empty($this->pricesUnformatted)) { return null; } if (!class_exists('CurrencyDisplay')) { require JPATH_VM_ADMINISTRATOR . DS . 'helpers' . DS . 'currencydisplay.php'; } $currency = CurrencyDisplay::getInstance(); $calculator = calculationHelper::getInstance(); $this->pricesCurrency = $currency->getCurrencyForDisplay(); if (!class_exists('vmPSPlugin')) { require JPATH_VM_PLUGINS . DS . 'vmpsplugin.php'; } JPluginHelper::importPlugin('vmpayment'); $dispatcher = JDispatcher::getInstance(); $returnValues = $dispatcher->trigger('plgVmgetPaymentCurrency', array($this->virtuemart_paymentmethod_id, &$this->paymentCurrency)); $cartData = $calculator->getCartData(); return $cartData; }
function checkFilterOrder($toCheck) { if (empty($toCheck)) { return $this->_selectedOrdering; } if (!in_array($toCheck, $this->_validOrderingFieldName)) { $break = false; vmSetStartTime(); foreach ($this->_validOrderingFieldName as $name) { if (!empty($name) and strpos($name, $toCheck) !== FALSE) { $this->_selectedOrdering = $name; $break = true; break; } } if (!$break) { $app = JFactory::getApplication(); $view = vRequest::getCmd('view'); if (empty($view)) { $view = 'virtuemart'; } $app->setUserState('com_virtuemart.' . $view . '.filter_order', $this->_selectedOrdering); } } else { $this->_selectedOrdering = $toCheck; } return $this->_selectedOrdering; }
/** * Technic to inject params as table attributes * @author Max Milbers * $TableJoins array of table names to add and left join to find ID */ function load($oid = null, $overWriteLoadName = 0, $andWhere = 0, $tableJoins = array(), $joinKey = 0) { if ($this->_translatable) { vmSetStartTime('vmtableload'); } if ($overWriteLoadName !== 0) { $k = $overWriteLoadName; } else { $k = $this->_pkey; } if ($oid !== null) { $this->{$k} = $oid; } else { $oid = $this->{$k}; } if (empty($oid)) { if (!empty($this->_xParams)) { if (!empty($this->_varsToPushParam)) { foreach ($this->_varsToPushParam as $key => $v) { if (!isset($this->{$key})) { $this->{$key} = $v[0]; } } } else { //vmdebug('_varsToPushParam empty ',$this); } } //vmdebug('vmtable load empty $oid return proto',$this); return $this; } //Version load the tables using JOIN if ($this->_translatable) { $mainTable = $this->_tbl; $langTable = $this->_tbl . '_' . $this->_langTag; $select = 'SELECT `' . $mainTable . '`.* ,`' . $langTable . '`.* '; $from = ' FROM `' . $mainTable . '` INNER JOIN `' . $langTable . '` using (`' . $this->_tbl_key . '`)'; } else { $mainTable = $this->_tbl; $select = 'SELECT `' . $mainTable . '`.* '; $from = ' FROM `' . $mainTable . '` '; } if (count($tableJoins)) { if (!$joinKey) { $joinKey = $this->_tbl_key; } foreach ($tableJoins as $tableId => $table) { if (strpos($tableId, ',') !== false) { $tableIds = explode(',', $tableId); foreach ($tableIds as $sel) { if (strpos($sel, ' as ') !== false) { $temp = explode(' as ', $sel); $select .= ',`' . $table . '`.`' . trim($temp[0]) . '` as ' . $temp[1] . ' '; } else { $select .= ',`' . $table . '`.`' . $sel . '` '; } } } else { $select .= ',`' . $table . '`.`' . $tableId . '` '; } $from .= ' LEFT JOIN `' . $table . '` on `' . $table . '`.`' . $joinKey . '`=`' . $mainTable . '`.`' . $joinKey . '`'; } } //the cast to int here destroyed the query for keys like tsmart_userinfo_id, so no cast on $oid // $query = $select.$from.' WHERE '. $mainTable .'.`'.$this->_tbl_key.'` = "'.$oid.'"'; if ($andWhere === 0) { $andWhere = ''; } $query = $select . $from . ' WHERE `' . $mainTable . '`.`' . $k . '` = "' . $oid . '" ' . $andWhere; $hashVarsToPush = ''; if (!empty($this->_varsToPushParam)) { $hashVarsToPush = json_encode($this->_varsToPushParam); } $this->_lhash = md5($oid . $select . $k . $mainTable . $andWhere . $hashVarsToPush); //$this->showFullColumns(); if (isset(self::$_cache['l'][$this->_lhash])) { $this->bind(self::$_cache['l'][$this->_lhash]); if (!empty($this->_xParams) and !empty($this->_varsToPushParam)) { self::bindParameterable($this, $this->_xParams, $this->_varsToPushParam); } if ($this->_cryptedFields) { $this->decryptFields($this); } //vmTime('loaded by cache '.$this->_pkey.' '.$this->_slugAutoName.' '.$oid,'vmtableload'); return $this; } else { //vmdebug('loading '.$this->_pkey.' '.$this->_slugAutoName.' '.$oid); } $db = $this->getDBO(); $db->setQuery($query); $result = $db->loadAssoc(); if ($result) { $this->_loaded = true; $this->bind($result); if (!empty($this->_xParams)) { //Maybe better to use for $this an & self::bindParameterable($this, $this->_xParams, $this->_varsToPushParam); } if (count($tableJoins)) { foreach ($tableJoins as $tableId => $table) { if (strpos($tableId, ',') !== false) { $tableIds = explode(',', $tableId); foreach ($tableIds as $sel) { if (strpos($sel, ' as ') !== false) { $temp = explode(' as ', $sel); $key = trim($temp[1]); //vmdebug('my $result ',$result[$key]); if (isset($result[$key])) { $this->{$key} = $result[$key]; } else { $this->{$key} = false; } } else { if (isset($result[$sel])) { $this->{$sel} = $result[$sel]; } } } } else { if (isset($result[$tableId])) { $this->{$tableId} = $result[$tableId]; } } } } } else { if ($this->_translatable and tsmConfig::$langCount > 1 and $this->_ltmp != tsmConfig::$jDefLang) { if (tsmConfig::$defaultLang != tsmConfig::$jDefLang) { if ($this->_langTag != tsmConfig::$defaultLang) { $this->_ltmp = $this->_langTag; $this->_langTag = tsmConfig::$defaultLang; $this->_tempHash = $this->_lhash; } else { $this->_langTag = tsmConfig::$jDefLang; } } else { $this->_ltmp = $this->_langTag; $this->_langTag = tsmConfig::$defaultLang; $this->_tempHash = $this->_lhash; } //vmdebug('No result for '.$this->_ltmp.', lets check for Fallback lang '.$this->_langTag); //vmSetStartTime('lfallback'); $this->load($oid, $overWriteLoadName, $andWhere, $tableJoins, $joinKey); //vmTime('Time to load language fallback '.$this->_langTag, 'lfallback'); } else { $this->_loaded = false; } } if ($this->_ltmp) { //vmdebug('Set Ltmp '.$this->_ltmp.' back to false'); $this->_langTag = $this->_ltmp; self::$_cache['l'][$this->_lhash] = self::$_cache['l'][$this->_tempHash] = $this->loadFieldValues(false); } else { self::$_cache['l'][$this->_lhash] = $this->loadFieldValues(false); } if ($this->_cryptedFields) { $this->decryptFields(); } //if($this->_translatable) vmTime('loaded '.$this->_langTag.' '.$mainTable.' '.$oid ,'vmtableload'); $this->_ltmp = false; return $this; }
/** * Loads the configuration and works as singleton therefore called static. The call using the program cache * is 10 times faster then taking from the session. The session is still approx. 30 times faster then using the file. * The db is 10 times slower then the session. * * Performance: * * Fastest is * Program Cache: 1.5974044799805E-5 * Session Cache: 0.00016094612121582 * * First config db load: 0.00052118301391602 * Parsed and in session: 0.001554012298584 * * After install from file: 0.0040450096130371 * Parsed and in session: 0.0051419734954834 * * * Functions tests if already loaded in program cache, session cache, database and at last the file. * * Load the configuration values from the database into a session variable. * This step is done to prevent accessing the database for every configuration variable lookup. * * @author Max Milbers * @param $force boolean Forces the function to load the config from the db */ public static function loadConfig($force = FALSE, $fresh = FALSE) { if ($fresh) { return self::$_jpConfig = new VmConfig(); } vmSetStartTime('loadConfig'); if (!$force) { if (!empty(self::$_jpConfig) && !empty(self::$_jpConfig->_params)) { return self::$_jpConfig; } } self::$_jpConfig = new VmConfig(); if (!class_exists('VirtueMartModelConfig')) { require JPATH_VM_ADMINISTRATOR . DS . 'models' . DS . 'config.php'; } $configTable = VirtueMartModelConfig::checkConfigTableExists(); $db = JFactory::getDBO(); $app = JFactory::getApplication(); $freshInstall = vRequest::getInt('install', false); if (empty($configTable) or $freshInstall) { if (!$freshInstall) { $installed = VirtueMartModelConfig::checkVirtuemartInstalled(); if (!$installed) { $jlang = JFactory::getLanguage(); $selectedLang = $jlang->getTag(); if (empty($selectedLang)) { $selectedLang = $jlang->setLanguage($selectedLang); } $msg = ''; $q = 'SELECT `element` FROM `#__extensions` WHERE type = "language" and enabled = "1"'; $db->setQuery($q); $knownLangs = $db->loadColumn(); //vmdebug('Selected language '.$selectedLang.' $knownLangs ',$knownLangs); if ($app->isAdmin() and !in_array($selectedLang, $knownLangs)) { $link = 'index.php?option=com_installer&view=languages'; $msg = 'Install your selected language <b>' . $selectedLang . '</b> first in <a href="' . $link . '">joomla language manager</a>, just select then the component VirtueMart under menu "component", to proceed with the installation '; $app->enqueueMessage($msg); } //else { if ($app->isSite()) { $link = 'index.php?option=com_virtuemart'; } else { $link = 'index.php?option=com_virtuemart&view=updatesmigration&install=1'; $msg = 'Install Virtuemart first, click on the menu component and select VirtueMart'; } if ($app->isSite()) { $link = JURI::root(true) . '/administrator/' . $link; } $app->redirect($link, $msg); //} } if ($installed) { self::$_jpConfig->installVMconfig(); } } else { self::$_jpConfig->installVMconfig($freshInstall); } } $install = 'no'; if (empty(self::$_jpConfig->_raw)) { $query = ' SELECT `config` FROM `#__virtuemart_configs` WHERE `virtuemart_config_id` = "1";'; $db->setQuery($query); self::$_jpConfig->_raw = $db->loadResult(); if (empty(self::$_jpConfig->_raw)) { if (self::installVMconfig($freshInstall)) { $install = 'yes'; $db->setQuery($query); self::$_jpConfig->_raw = $db->loadResult(); self::$_jpConfig->_params = NULL; } else { $app->enqueueMessage('Error loading configuration file', 'Error loading configuration file, please contact the storeowner'); } } } $i = 0; $pair = array(); if (!empty(self::$_jpConfig->_raw)) { $config = explode('|', self::$_jpConfig->_raw); foreach ($config as $item) { $item = explode('=', $item); if (!empty($item[1])) { // if($item[0]!=='offline_message' && $item[0]!=='dateformat' ){ if ($item[0] !== 'offline_message') { try { $value = @unserialize($item[1]); if ($value === FALSE) { $app->enqueueMessage('Exception in loadConfig for unserialize ' . $item[0] . ' ' . $item[1]); $uri = JFactory::getURI(); $configlink = $uri->root() . 'administrator/index.php?option=com_virtuemart&view=config'; $app->enqueueMessage('To avoid this message, enter your virtuemart <a href="' . $configlink . '">config</a> and just save it one time'); } else { $pair[$item[0]] = $value; } } catch (Exception $e) { vmdebug('Exception in loadConfig for unserialize ' . $e->getMessage(), $item); } } else { $pair[$item[0]] = unserialize(base64_decode($item[1])); } } else { $pair[$item[0]] = ''; } } // $pair['sctime'] = microtime(true); self::$_jpConfig->_params = $pair; self::$_jpConfig->_params['sctime'] = microtime(TRUE); //self::$_jpConfig->set('sctime',microtime(TRUE)); //self::setdbLanguageTag(); self::$_jpConfig->_params['vmlang'] = self::setdbLanguageTag(); vmTime('loadConfig db ' . $install, 'loadConfig'); // try plugins if ($app->isSite()) { if (!class_exists('VmImage')) { require JPATH_VM_ADMINISTRATOR . DS . 'helpers' . DS . 'image.php'; } JPluginHelper::importPlugin('vmuserfield'); $dispatcher = JDispatcher::getInstance(); $dispatcher->trigger('plgVmInitialise', array()); } return self::$_jpConfig; } $app->enqueueMessage('Attention config is empty'); return self::$_jpConfig; }
function getTax($calculationHelper, $calc, $price, $sale = false, $committ = false) { if ($calc->activated == 0) { return false; } $shopperData = $this->getShopperData(); if (!$shopperData) { return false; } //if(self::$stop) return self::$stop; if (!class_exists('TaxServiceSoap')) { require VMAVALARA_CLASS_PATH . DS . 'TaxServiceSoap.class.php'; } if (!class_exists('DocumentType')) { require VMAVALARA_CLASS_PATH . DS . 'DocumentType.class.php'; } if (!class_exists('DetailLevel')) { require VMAVALARA_CLASS_PATH . DS . 'DetailLevel.class.php'; } if (!class_exists('Line')) { require VMAVALARA_CLASS_PATH . DS . 'Line.class.php'; } if (!class_exists('ServiceMode')) { require VMAVALARA_CLASS_PATH . DS . 'ServiceMode.class.php'; } if (!class_exists('Line')) { require VMAVALARA_CLASS_PATH . DS . 'Line.class.php'; } if (!class_exists('GetTaxRequest')) { require VMAVALARA_CLASS_PATH . DS . 'GetTaxRequest.class.php'; } if (!class_exists('GetTaxResult')) { require VMAVALARA_CLASS_PATH . DS . 'GetTaxResult.class.php'; } $client = new TaxServiceSoap('Development'); $request = new GetTaxRequest(); $origin = new Address(); //$destination = $this->fillValidateAvalaraAddress($calc); //In Virtuemart we have not differenct warehouses, but we have a shipment address //So when the vendor has a shipment address, we assume that it is his warehouse //Later we can combine products with shipment addresses for different warehouse (yehye, future music) //But for now we just use the BT address if (!class_exists('VirtueMartModelVendor')) { require JPATH_VM_ADMINISTRATOR . DS . 'models' . DS . 'vendor.php'; } $userId = VirtueMartModelVendor::getUserIdByVendorId($calc->virtuemart_vendor_id); $userModel = VmModel::getModel('user'); $virtuemart_userinfo_id = $userModel->getBTuserinfo_id($userId); // this is needed to set the correct user id for the vendor when the user is logged $userModel->getVendor($calc->virtuemart_vendor_id); $vendorFieldsArray = $userModel->getUserInfoInUserFields('mail', 'BT', $virtuemart_userinfo_id, FALSE, TRUE); $vendorFields = $vendorFieldsArray[$virtuemart_userinfo_id]; //vmdebug('my vendor fields',$vendorFields); $origin->setLine1($vendorFields['fields']['address_1']['value']); $origin->setLine2($vendorFields['fields']['address_2']['value']); $origin->setCity($vendorFields['fields']['city']['value']); $origin->setCountry($vendorFields['fields']['virtuemart_country_id']['country_2_code']); $origin->setRegion($vendorFields['fields']['virtuemart_state_id']['state_2_code']); $origin->setPostalCode($vendorFields['fields']['zip']['value']); $request->setOriginAddress($origin); //Address if (isset($this->addresses[0])) { $destination = $this->addresses[0]; } else { return FALSE; } $request->setDestinationAddress($destination); //Address //vmdebug('The date',$origin,$destination); $request->setCompanyCode($calc->company_code); // Your Company Code From the Dashboard if ($calc->committ and $sale) { $request->setDocType(DocumentType::$SalesInvoice); // Only supported types are SalesInvoice or SalesOrder $request->setCommit(true); //invoice number, problem is that the invoice number is at this time not known, but the order_number may reachable $request->setDocCode($committ); vmdebug('Request as SalesInvoice with invoiceNumber ' . $committ); } else { $request->setDocType(DocumentType::$SalesOrder); $request->setCommit(false); //invoice number, problem is that the invoice number is at this time not known, neither the order_number $request->setDocCode('VM2.0.16_order_request'); vmdebug('Request as SalesOrder'); } $request->setDocDate(date('Y-m-d')); //date //$request->setSalespersonCode(""); // string Optional $request->setCustomerCode($shopperData['customer_id']); //string Required if (isset($shopperData['tax_usage_type'])) { $request->setCustomerUsageType($shopperData['tax_usage_type']); //string Entity Usage } $cartPrices = $calculationHelper->getCartPrices(); //vmdebug('$cartPrices',$cartPrices); $request->setDiscount($cartPrices['discountAmount']); //decimal //$request->setDiscount(0.0); // $request->setPurchaseOrderNo(""); //string Optional //If I understand correctly, we need to add for this an userfield, for example with the name //exemption_no, then user could enter their number. if (isset($shopperData['tax_exemption_number'])) { $request->setExemptionNo($shopperData['tax_exemption_number']); //string if not using ECMS which keys on customer code } $request->setDetailLevel('Tax'); //Summary or Document or Line or Tax or Diagnostic // $request->setReferenceCode1(""); //string Optional // $request->setReferenceCode2(""); //string Optional // $request->setLocationCode(""); //string Optional - aka outlet id for tax forms ///////////////////////////////////////// if (!class_exists('VirtueMartCart')) { require JPATH_VM_SITE . DS . 'helpers' . DS . 'cart.php'; } $cart = VirtueMartCart::getCart(); $products = array(); if ($calculationHelper->inCart) { $products = $cart->products; $prices = $calculationHelper->getCartPrices(); foreach ($products as $k => $product) { if (!empty($prices[$k]['discountedPriceWithoutTax'])) { $price = $prices[$k]['discountedPriceWithoutTax']; } else { if (!empty($prices[$k]['basePriceVariant'])) { $price = $prices[$k]['basePriceVariant']; } else { vmdebug('There is no price in getTax for product ' . $k . ' ', $prices); $price = 0.0; } } $product->price = $price; if (!empty($price[$k]['discountAmount'])) { $product->discount = $price[$k]['discountAmount']; } else { $product->discount = FALSE; } } } else { $calculationHelper->_product->price = $price; $products[0] = $calculationHelper->_product; if (!isset($products[0]->amount)) { $products[0]->amount = 1; } if (isset($calculationHelper->productPrices['discountAmount'])) { $products[0]->discount = $calculationHelper->productPrices['discountAmount']; } else { $products[0]->discount = FALSE; } } $lines = array(); $n = 0; $lineNumbersToCartProductId = array(); foreach ($products as $k => $product) { $n++; $lineNumbersToCartProductId[$n] = $k; $line = new Line(); $line->setNo($n); //string // line Number of invoice $line->setItemCode($product->product_sku); //string $line->setDescription($product->product_name); //product description, like in cart, atm only the name, todo add customfields //$line->setTaxCode(""); //string $line->setQty($product->amount); //decimal $line->setAmount($product->price * $product->amount); //decimal // TotalAmmount $line->setDiscounted($product->discount * $product->amount); //boolean $line->setRevAcct(""); //string $line->setRef1(""); //string $line->setRef2(""); //string if (isset($shopperData['tax_exemption_number'])) { $line->setExemptionNo($shopperData['tax_exemption_number']); //string } if (isset($shopperData['tax_usage_type'])) { $line->setCustomerUsageType($shopperData['tax_usage_type']); //string } $lines[] = $line; } $line = new Line(); $line->setNo(++$n); //$lineNumbersToCartProductId[$n] = count($products)+1; $line->setItemCode($cart->virtuemart_shipmentmethod_id); $line->setDescription('Shipment'); $line->setQty(1); //$line->setTaxCode(); $cartPrices = $calculationHelper->getCartPrices(); //vmdebug('$calculationHelper $cartPrices',$cartPrices); $line->setAmount($cartPrices['shipmentValue']); if (isset($shopperData['tax_exemption_number'])) { $line->setExemptionNo($shopperData['tax_exemption_number']); //string } if (isset($shopperData['tax_usage_type'])) { $line->setCustomerUsageType($shopperData['tax_usage_type']); //string } $lines[] = $line; //vmdebug('avalaragetTax setLines',$lines); $request->setLines($lines); //vmdebug('My request',$request); $totalTax = 0.0; try { if (!class_exists('TaxLine')) { require VMAVALARA_CLASS_PATH . DS . 'TaxLine.class.php'; } if (!class_exists('TaxDetail')) { require VMAVALARA_CLASS_PATH . DS . 'TaxDetail.class.php'; } vmSetStartTime('avagetTax'); $getTaxResult = $client->getTax($request); vmTime('Avalara getTax', 'avagetTax'); /* * [0] => getDocCode [1] => getAdjustmentDescription [2] => getAdjustmentReason [3] => getDocDate [4] => getTaxDate [5] => getDocType [6] => getDocStatus [7] => getIsReconciled [8] => getLocked [9] => getTimestamp [10] => getTotalAmount [11] => getTotalDiscount [12] => getTotalExemption [13] => getTotalTaxable [14] => getTotalTax [15] => getHashCode [16] => getVersion [17] => getTaxLines [18] => getTotalTaxCalculated [19] => getTaxSummary [20] => getTaxLine [21] => getTransactionId [22] => getResultCode [23] => getMessages */ //vmdebug( 'GetTax is: '. $getTaxResult->getResultCode(),$getTaxResult); if ($getTaxResult->getResultCode() == SeverityLevel::$Success) { //vmdebug("DocCode: ".$request->getDocCode() ); //vmdebug("DocId: ".$getTaxResult->getDocId()."\n"); vmdebug("TotalAmount: " . $getTaxResult->getTotalAmount()); $totalTax = $getTaxResult->getTotalTax(); vmdebug("TotalTax: " . $totalTax); foreach ($getTaxResult->getTaxLines() as $ctl) { if ($calculationHelper->inCart) { $nr = $ctl->getNo(); if (isset($lineNumbersToCartProductId[$nr])) { $quantity = $products[$lineNumbersToCartProductId[$nr]]->amount; //on the long hand, the taxAmount must be replaced by taxAmountQuantity to avoid rounding errors $prices[$lineNumbersToCartProductId[$ctl->getNo()]]['taxAmount'] = $ctl->getTax() / $quantity; $prices[$lineNumbersToCartProductId[$ctl->getNo()]]['taxAmountQuantity'] = $ctl->getTax(); } else { //$this->_cartPrices['shipmentValue'] = 0; //could be automatically set to a default set in the globalconfig //$this->_cartPrices['shipmentTax'] = 0; //$this->_cartPrices['shipmentTotal'] = 0; //$prices = array('shipmentValue'=>$cartPrices['shipmentValue'],'shipmentTax'=> $ctl->getTax(), 'shipmentTotal' =>($cartPrices['shipmentValue'] +$ctl->getTax() )); //vmdebug('my $cartPrices',$cartPrices); $prices['shipmentTax'] = $ctl->getTax(); $prices['salesPriceShipment'] = $prices['shipmentValue'] + $ctl->getTax(); //$cartPrices = array_merge($prices,$cartPrices); //$calculationHelper->setCartPrices( $cartPrices ); $totalTax = $totalTax - $ctl->getTax(); //vmdebug('my $cartPrices danach',$cartPrices); } } //vmdebug('my lines ',$ctl); //vmdebug( " Line: ".$ctl->getNo()." Tax: ".$ctl->getTax()." TaxCode: ".$ctl->getTaxCode()); foreach ($ctl->getTaxDetails() as $ctd) { //vmdebug( " Juris Type: ".$ctd->getJurisType()."; Juris Name: ".$ctd->getJurisName()."; Rate: ".$ctd->getRate()."; Amt: ".$ctd->getTax() ); } } if ($calculationHelper->inCart) { $calculationHelper->setCartPrices($prices); } } else { foreach ($getTaxResult->getMessages() as $msg) { vmError($msg->getName() . ": " . $msg->getSummary()); } } } catch (SoapFault $exception) { $msg = "Exception: "; if ($exception) { $msg .= $exception->faultstring; } vmdebug($msg . '<br />' . $client->__getLastRequest() . '<br />' . $client->__getLastResponse()); } //self::$stop = $totalTax; return $totalTax; }
public function getCheckoutPrices(&$cart) { //vmdebug('in function getCheckoutPrices in function getCheckoutPrices'); $this->_cart =& $cart; $this->inCart = TRUE; //$pricesPerId = array(); $resultWithTax = 0.0; $resultWithOutTax = 0.0; $this->_cart->cartData['VatTax'] = array(); $this->_cart->cartPrices = array(); $this->_cart->cartPrices['basePrice'] = 0; $this->_cart->cartPrices['basePriceWithTax'] = 0; $this->_cart->cartPrices['discountedPriceWithoutTax'] = 0; $this->_cart->cartPrices['salesPrice'] = 0; $this->_cart->cartPrices['taxAmount'] = 0; $this->_cart->cartPrices['salesPriceWithDiscount'] = 0; $this->_cart->cartPrices['discountAmount'] = 0; $this->_cart->cartPrices['priceWithoutTax'] = 0; $this->_cart->cartPrices['subTotalProducts'] = 0; $this->_cart->cartPrices['billTotal'] = 0; $this->_cart->cartData['duty'] = 1; $this->_cart->cartData['payment'] = 0; //could be automatically set to a default set in the globalconfig $this->_cart->cartData['paymentName'] = ''; $cartpaymentTax = 0; $this->_amountCart = 0; $customfieldModel = VmModel::getModel('customfields'); foreach ($this->_cart->products as $cprdkey => $productCart) { if (empty($this->_cart->products[$cprdkey]->quantity) || empty($this->_cart->products[$cprdkey]->virtuemart_product_id)) { if (!is_object($this->_cart->products[$cprdkey])) { //vmdebug( 'Error the product for calculation is not an object',$product); } else { vmError('Error the quantity of the product for calculation is 0, please notify the shopowner, the product id ' . $this->_cart->products[$cprdkey]->virtuemart_product_id); } continue; } $this->productCurrency = isset($this->_cart->products[$cprdkey]->product_currency) ? $this->_cart->products[$cprdkey]->product_currency : 0; $variantmod = $customfieldModel->calculateModificators($this->_cart->products[$cprdkey]); $productPrice = $this->getProductPrices($this->_cart->products[$cprdkey], $variantmod, $this->_cart->products[$cprdkey]->quantity); //vmTrace('getProductPrices $productPrice '.$variantmod.' '.$productPrice['basePriceVariant'].' '.$productPrice['salesPrice']); //vmdebug('getCheckoutPrices ',$productPrice['salesPrice']); $selectedPrice = $this->_cart->products[$cprdkey]->selectedPrice; $this->_cart->products[$cprdkey]->allPrices[$selectedPrice] = array_merge($this->_cart->products[$cprdkey]->allPrices[$selectedPrice], $productPrice); $this->_cart->cartPrices[$cprdkey] = $productPrice; //$this->_cart->products[$cprdkey]->allPrices[$selectedPrice]; $this->_amountCart += $this->_cart->products[$cprdkey]->quantity; if ($this->_currencyDisplay->_priceConfig['basePrice']) { $this->_cart->cartPrices['basePrice'] += self::roundInternal($this->_cart->products[$cprdkey]->allPrices[$selectedPrice]['basePrice'], 'basePrice') * $this->_cart->products[$cprdkey]->quantity; } if ($this->_currencyDisplay->_priceConfig['basePriceWithTax']) { $this->_cart->cartPrices['basePriceWithTax'] += self::roundInternal($this->_cart->products[$cprdkey]->allPrices[$selectedPrice]['basePriceWithTax']) * $this->_cart->products[$cprdkey]->quantity; } if ($this->_currencyDisplay->_priceConfig['discountedPriceWithoutTax']) { $this->_cart->cartPrices['discountedPriceWithoutTax'] += self::roundInternal($this->_cart->products[$cprdkey]->allPrices[$selectedPrice]['discountedPriceWithoutTax'], 'discountedPriceWithoutTax') * $this->_cart->products[$cprdkey]->quantity; } if ($this->_currencyDisplay->_priceConfig['salesPrice']) { $this->_cart->products[$cprdkey]->allPrices[$selectedPrice]['subtotal_with_tax'] = self::roundInternal($this->_cart->products[$cprdkey]->allPrices[$selectedPrice]['salesPrice'], 'salesPrice') * $this->_cart->products[$cprdkey]->quantity; $this->_cart->cartPrices['salesPrice'] += $this->_cart->products[$cprdkey]->allPrices[$selectedPrice]['subtotal_with_tax']; $this->_cart->cartPrices[$cprdkey]['subtotal_with_tax'] = $this->_cart->products[$cprdkey]->allPrices[$selectedPrice]['subtotal_with_tax']; } if ($this->_currencyDisplay->_priceConfig['taxAmount']) { $this->_cart->products[$cprdkey]->allPrices[$selectedPrice]['subtotal_tax_amount'] = self::roundInternal($this->_cart->products[$cprdkey]->allPrices[$selectedPrice]['taxAmount'], 'taxAmount') * $this->_cart->products[$cprdkey]->quantity; $this->_cart->cartPrices['taxAmount'] += $this->_cart->products[$cprdkey]->allPrices[$selectedPrice]['subtotal_tax_amount']; } if ($this->_currencyDisplay->_priceConfig['salesPriceWithDiscount']) { $this->_cart->cartPrices['salesPriceWithDiscount'] += self::roundInternal($this->_cart->products[$cprdkey]->allPrices[$selectedPrice]['salesPriceWithDiscount'], 'salesPriceWithDiscount') * $this->_cart->products[$cprdkey]->quantity; } if ($this->_currencyDisplay->_priceConfig['discountAmount']) { $this->_cart->products[$cprdkey]->allPrices[$selectedPrice]['subtotal_discount'] = self::roundInternal($this->_cart->products[$cprdkey]->allPrices[$selectedPrice]['discountAmount'], 'discountAmount') * $this->_cart->products[$cprdkey]->quantity; $this->_cart->cartPrices['discountAmount'] += $this->_cart->products[$cprdkey]->allPrices[$selectedPrice]['subtotal_discount']; } if ($this->_currencyDisplay->_priceConfig['priceWithoutTax']) { $this->_cart->products[$cprdkey]->allPrices[$selectedPrice]['subtotal'] = self::roundInternal($this->_cart->products[$cprdkey]->allPrices[$selectedPrice]['priceWithoutTax'], 'priceWithoutTax') * $this->_cart->products[$cprdkey]->quantity; $this->_cart->cartPrices['priceWithoutTax'] += $this->_cart->products[$cprdkey]->allPrices[$selectedPrice]['subtotal']; } $this->_cart->products[$cprdkey]->prices = $this->_cart->products[$cprdkey]->allPrices[$selectedPrice]; } $this->_product = null; $this->_cart->cartData['DBTaxRulesBill'] = $this->gatherEffectingRulesForBill('DBTaxBill'); $this->_cart->cartData['taxRulesBill'] = $this->gatherEffectingRulesForBill('TaxBill'); $this->_cart->cartData['DATaxRulesBill'] = $this->gatherEffectingRulesForBill('DATaxBill'); $this->_cart->cartPrices['salesPriceDBT'] = array(); $this->_cart->cartPrices['taxRulesBill'] = array(); $this->_cart->cartPrices['DATaxRulesBill'] = array(); foreach ($this->_cart->products as $cprdkey => $product) { //for Rules with Categories / Manufacturers foreach ($this->_cart->cartData['DBTaxRulesBill'] as &$dbrule) { $applyRule = FALSE; if (!empty($dbrule['calc_categories']) || !empty($dbrule['virtuemart_manufacturers'])) { $setCat = !empty($dbrule['calc_categories']) ? array_intersect($dbrule['calc_categories'], $product->categories) : array(); $setMan = !empty($dbrule['virtuemart_manufacturers']) ? array_intersect($dbrule['virtuemart_manufacturers'], $product->virtuemart_manufacturer_id) : array(); if (!empty($dbrule['calc_categories']) && !empty($dbrule['virtuemart_manufacturers'])) { if (count($setCat) > 0 && count($setMan) > 0) { $applyRule = TRUE; } } else { if (count($setCat) > 0 || count($setMan) > 0) { $applyRule = TRUE; } } } else { $applyRule = TRUE; } if ($applyRule) { if (!isset($dbrule['subTotal'])) { $dbrule['subTotal'] = 0.0; } $dbrule['subTotal'] += $this->_cart->cartPrices[$cprdkey]['subtotal_with_tax']; // subarray with subTotal for each taxID necessary to calculate tax correct if there are more than one VatTaxes if (!isset($dbrule['subTotalPerTaxID'])) { $dbrule['subTotalPerTaxID'] = array(); } if ($product->product_tax_id != 0) { if (!isset($dbrule['subTotalPerTaxID'][$product->product_tax_id])) { $dbrule['subTotalPerTaxID'][$product->product_tax_id] = 0.0; } $dbrule['subTotalPerTaxID'][$product->product_tax_id] += $this->_cart->cartPrices[$cprdkey]['subtotal_with_tax']; } else { $taxRules = array_merge($this->allrules[$product->virtuemart_vendor_id]['VatTax'], $this->_cart->cartData['taxRulesBill']); foreach ($taxRules as $virtuemart_calc_id => $rule) { if (!empty($rule['calc_categories']) || !empty($rule['virtuemart_manufacturers'])) { $setCat = !empty($rule['calc_categories']) ? array_intersect($rule['calc_categories'], $product->categories) : array(); $setMan = !empty($rule['virtuemart_manufacturers']) ? array_intersect($rule['virtuemart_manufacturers'], $product->virtuemart_manufacturer_id) : array(); if (!empty($rule['calc_categories']) && !empty($rule['virtuemart_manufacturers'])) { if (count($setCat) > 0 && count($setMan) > 0) { if (!isset($dbrule['subTotalPerTaxID'][$rule['virtuemart_calc_id']])) { $dbrule['subTotalPerTaxID'][$rule['virtuemart_calc_id']] = 0.0; } $dbrule['subTotalPerTaxID'][$rule['virtuemart_calc_id']] += $this->_cart->cartPrices[$cprdkey]['subtotal_with_tax']; } } else { if (count($setCat) > 0 || count($setMan) > 0) { if (!isset($dbrule['subTotalPerTaxID'][$rule['virtuemart_calc_id']])) { $dbrule['subTotalPerTaxID'][$rule['virtuemart_calc_id']] = 0.0; } $dbrule['subTotalPerTaxID'][$rule['virtuemart_calc_id']] += $this->_cart->cartPrices[$cprdkey]['subtotal_with_tax']; } } } else { if (!isset($dbrule['subTotalPerTaxID'][$rule['virtuemart_calc_id']])) { $dbrule['subTotalPerTaxID'][$rule['virtuemart_calc_id']] = 0.0; } $dbrule['subTotalPerTaxID'][$rule['virtuemart_calc_id']] += $this->_cart->cartPrices[$cprdkey]['subtotal_with_tax']; } } } } } // subTotal for each taxID necessary, equal if calc_categories exists ore not if (!empty($this->_cart->cartData['taxRulesBill'])) { foreach ($this->_cart->cartData['taxRulesBill'] as $k => &$trule) { if (empty($trule['subTotal'])) { $trule['subTotal'] = 0.0; } if ($product->product_tax_id != 0) { if ($product->product_tax_id == $k) { $trule['subTotal'] += $this->_cart->cartPrices[$cprdkey]['subtotal_with_tax']; } } else { if (!empty($trule['calc_categories']) || !empty($trule['virtuemart_manufacturers'])) { $setCat = !empty($trule['calc_categories']) ? array_intersect($trule['calc_categories'], $product->categories) : array(); $setMan = !empty($trule['virtuemart_manufacturers']) ? array_intersect($trule['virtuemart_manufacturers'], $product->virtuemart_manufacturer_id) : array(); if (!empty($trule['calc_categories']) && !empty($trule['virtuemart_manufacturers'])) { if (count($setCat) > 0 && count($setMan) > 0) { $trule['subTotal'] += $this->_cart->cartPrices[$cprdkey]['subtotal_with_tax']; } } else { if (count($setCat) > 0 || count($setMan) > 0) { $trule['subTotal'] += $this->_cart->cartPrices[$cprdkey]['subtotal_with_tax']; } } } else { $trule['subTotal'] += $this->_cart->cartPrices[$cprdkey]['subtotal_with_tax']; } } //vmdebug('$this->_cart->cartData["taxRulesBill"]',$this->_cart->cartPrices[$cprdkey]); } } foreach ($this->_cart->cartData['DATaxRulesBill'] as &$darule) { if (!empty($darule['calc_categories']) || !empty($darule['virtuemart_manufacturers'])) { if (!isset($darule['subTotal'])) { $darule['subTotal'] = 0.0; } $setCat = !empty($darule['calc_categories']) ? array_intersect($darule['calc_categories'], $product->categories) : array(); $setMan = !empty($darule['virtuemart_manufacturers']) ? array_intersect($darule['virtuemart_manufacturers'], $product->virtuemart_manufacturer_id) : array(); if (!empty($darule['calc_categories']) && !empty($darule['virtuemart_manufacturers'])) { if (count($setCat) > 0 && count($setMan) > 0) { $darule['subTotal'] += $this->_cart->cartPrices[$cprdkey]['subtotal_with_tax']; } } else { if (count($setCat) > 0 || count($setMan) > 0) { $darule['subTotal'] += $this->_cart->cartPrices[$cprdkey]['subtotal_with_tax']; } } } } } // Calculate the discount from all rules before tax to calculate billTotal $cartdiscountBeforeTax = $this->roundInternal($this->cartRuleCalculation($this->_cart->cartData['DBTaxRulesBill'], $this->_cart->cartPrices['salesPrice'])); // We need the discount for each taxID to reduce the total discount before calculate percentage from hole cart discounts foreach ($this->_cart->cartData['DBTaxRulesBill'] as &$rule) { if (!empty($rule['subTotalPerTaxID'])) { foreach ($rule['subTotalPerTaxID'] as $k => $DBTax) { $this->roundInternal($this->cartRuleCalculation($this->_cart->cartData['DBTaxRulesBill'], $this->_cart->cartPrices['salesPrice'], $k, true)); } } } // combine the discounts before tax for each taxID foreach ($this->_cart->cartData['VatTax'] as &$rule) { if (!empty($rule['DBTax'])) { $sum = 0; foreach ($rule['DBTax'] as $key => $val) { $sum += $val; } $rule['DBTax'] = $sum; } } // calculate the new subTotal with discounts before tax, necessary for billTotal $toTax = $this->_cart->cartPrices['salesPrice'] + $cartdiscountBeforeTax; //Avalara wants to calculate the tax of the shipment. Only disadvantage to set shipping here is that the discounts per bill respectivly the tax per bill // is not considered. Todo create a generic system, for example a param for billing rules, excluding/including shipment/payment $shipmentCalculated = false; if (!empty($this->_cart->cartData['taxRulesBill'])) { foreach ($this->_cart->cartData['taxRulesBill'] as $taxRulesBill) { if (!empty($taxRulesBill['calc_value_mathop']) and $taxRulesBill['calc_value_mathop'] == 'avalara') { $this->calculateShipmentPrice(); $shipmentCalculated = true; } } } // next step is handling a coupon, if given $this->_cart->cartData['vmVat'] = TRUE; $this->_cart->cartPrices['salesPriceCoupon'] = 0.0; if (!empty($this->_cart->couponCode)) { $this->couponHandler($this->_cart->couponCode); } // now calculate the discount for hole cart and reduce subTotal for each taxRulesBill, to calculate correct tax, also if there are more than one tax rules $totalDiscountBeforeTax = $this->_cart->cartPrices['salesPriceCoupon']; foreach ($this->_cart->cartData['taxRulesBill'] as $k => &$rule) { if (!empty($rule['subTotal'])) { if (isset($this->_cart->cartData['VatTax'][$k]['DBTax'])) { $rule['subTotal'] += $this->_cart->cartData['VatTax'][$k]['DBTax']; } if (!isset($rule['percentage']) && $rule['subTotal'] < $this->_cart->cartPrices['salesPrice']) { $rule['percentage'] = $rule['subTotal'] / ($this->_cart->cartPrices['salesPrice'] + $cartdiscountBeforeTax); } else { if (!isset($rule['percentage'])) { $rule['percentage'] = 1; } } $rule['subTotal'] += $totalDiscountBeforeTax * $rule['percentage']; } else { $rule['subTotal'] = $toTax; } } // now each taxRule subTotal is reduced with DBTax and we can calculate the cartTax $cartTax = $this->roundInternal($this->cartRuleCalculation($this->_cart->cartData['taxRulesBill'], $toTax)); // toDisc is new subTotal after tax, now it comes discount afterTax and we can calculate the final cart price with tax. $toDisc = $toTax + $cartTax; $cartdiscountAfterTax = $this->roundInternal($this->cartRuleCalculation($this->_cart->cartData['DATaxRulesBill'], $toDisc)); $this->_cart->cartPrices['withTax'] = $toDisc + $cartdiscountAfterTax; vmSetStartTime('methods'); if (!$shipmentCalculated) { $this->calculateShipmentPrice(); } $this->calculatePaymentPrice(); vmTime('Time consumed for shipment/payment plugins', 'methods'); if ($this->_currencyDisplay->_priceConfig['salesPrice']) { $this->_cart->cartPrices['billSub'] = $this->_cart->cartPrices['basePrice'] + $this->_cart->cartPrices['shipmentValue'] + $this->_cart->cartPrices['paymentValue']; } if ($this->_currencyDisplay->_priceConfig['discountAmount']) { $this->_cart->cartPrices['billDiscountAmount'] = $this->_cart->cartPrices['discountAmount'] + $cartdiscountBeforeTax + $cartdiscountAfterTax; } // + $this->_cart->cartPrices['shipmentValue'] + $this->_cart->cartPrices['paymentValue'] ; if ($this->_cart->cartPrices['salesPriceShipment'] < 0) { $this->_cart->cartPrices['billDiscountAmount'] += $this->_cart->cartPrices['salesPriceShipment']; } if ($this->_cart->cartPrices['salesPricePayment'] < 0) { $this->_cart->cartPrices['billDiscountAmount'] += $this->_cart->cartPrices['salesPricePayment']; } if ($this->_currencyDisplay->_priceConfig['taxAmount']) { $this->_cart->cartPrices['billTaxAmount'] = $this->_cart->cartPrices['taxAmount'] + $this->_cart->cartPrices['shipmentTax'] + $this->_cart->cartPrices['paymentTax'] + $cartTax; } //+ $this->_cart->cartPrices['withTax'] - $toTax //The coupon handling is only necessary if a salesPrice is displayed, otherwise we have a kind of catalogue mode if ($this->_currencyDisplay->_priceConfig['salesPrice']) { $this->_cart->cartPrices['billTotal'] = $this->_cart->cartPrices['salesPriceShipment'] + $this->_cart->cartPrices['salesPricePayment'] + $this->_cart->cartPrices['withTax'] + $this->_cart->cartPrices['salesPriceCoupon']; if (empty($this->_cart->cartPrices['billTotal']) or $this->_cart->cartPrices['billTotal'] < 0) { $this->_cart->cartPrices['billTotal'] = 0.0; } if ($this->_cart->cartData['vmVat'] and (!empty($cartdiscountBeforeTax) and isset($this->_cart->cartData['VatTax']) and count($this->_cart->cartData['VatTax']) > 0) or !empty($this->_cart->couponCode)) { $totalDiscountToTax = $this->_cart->cartPrices['salesPriceCoupon']; foreach ($this->_cart->cartData['VatTax'] as &$vattax) { if (isset($vattax['subTotal']) && !isset($vattax['percentage'])) { if (isset($vattax['DBTax'])) { $vattax['subTotal'] += $vattax['DBTax']; } if ($vattax['subTotal'] < $this->_cart->cartPrices['salesPrice']) { $vattax['percentage'] = $vattax['subTotal'] / ($this->_cart->cartPrices['salesPrice'] + $cartdiscountBeforeTax); } else { $vattax['percentage'] = 1; } } if (isset($vattax['calc_value']) && isset($vattax['percentage'])) { if (!isset($vattax['DBTax'])) { $vattax['DBTax'] = 0.0; } $vattax['discountTaxAmount'] = round(($totalDiscountToTax * $vattax['percentage'] + $vattax['DBTax']) / (100 + $vattax['calc_value']) * $vattax['calc_value'], $this->_currencyDisplay->_priceConfig['taxAmount'][1]); } if (isset($vattax['discountTaxAmount'])) { $this->_cart->cartPrices['billTaxAmount'] += $vattax['discountTaxAmount']; } } } if ($this->_cart->cartPrices['billTaxAmount'] < 0) { $this->_cart->cartPrices['billTaxAmount'] = 0.0; } } //Calculate VatTax result if ($this->_cart->cartPrices['shipment_calc_id']) { if (!is_array($this->_cart->cartPrices['shipment_calc_id'])) { $this->_cart->cartPrices['shipment_calc_id'] = array($this->_cart->cartPrices['shipment_calc_id']); } foreach ($this->_cart->cartPrices['shipment_calc_id'] as $calcID) { if (isset($this->_cart->cartPrices['shipmentTaxPerID'][$calcID])) { $this->_cart->cartData['VatTax'][$calcID]['shipmentTax'] = $this->_cart->cartPrices['shipmentTaxPerID'][$calcID]; if (!isset($this->_cart->cartData['VatTax'][$calcID]['virtuemart_calc_id'])) { $this->_cart->cartData['VatTax'][$calcID]['virtuemart_calc_id'] = $calcID; } } } } if ($this->_cart->cartPrices['payment_calc_id']) { if (!is_array($this->_cart->cartPrices['payment_calc_id'])) { $this->_cart->cartPrices['payment_calc_id'] = array($this->_cart->cartPrices['payment_calc_id']); } foreach ($this->_cart->cartPrices['payment_calc_id'] as $calcID) { if (isset($this->_cart->cartPrices['paymentTaxPerID'][$calcID])) { $this->_cart->cartData['VatTax'][$calcID]['paymentTax'] = $this->_cart->cartPrices['paymentTaxPerID'][$calcID]; if (!isset($this->_cart->cartData['VatTax'][$calcID]['virtuemart_calc_id'])) { $this->_cart->cartData['VatTax'][$calcID]['virtuemart_calc_id'] = $calcID; } } } } foreach ($this->_cart->cartData['VatTax'] as &$vattax) { $vattax['result'] = isset($vattax['taxAmount']) ? $vattax['taxAmount'] : 0; if (isset($vattax['discountTaxAmount'])) { $vattax['result'] += $vattax['discountTaxAmount']; } if (isset($vattax['shipmentTax'])) { $vattax['result'] += $vattax['shipmentTax']; } if (isset($vattax['paymentTax'])) { $vattax['result'] += $vattax['paymentTax']; } if (!isset($vattax['virtuemart_calc_id'])) { $vattax['virtuemart_calc_id'] = $this->getCalcRuleData($vattax['virtuemart_calc_id'])->virtuemart_calc_id; } if (!isset($vattax['calc_name'])) { $vattax['calc_name'] = $this->getCalcRuleData($vattax['virtuemart_calc_id'])->calc_name; } if (!isset($vattax['calc_value'])) { $vattax['calc_value'] = $this->getCalcRuleData($vattax['virtuemart_calc_id'])->calc_value; } } foreach ($this->_cart->cartData['taxRulesBill'] as &$rule) { $this->_cart->cartData['VatTax'][$rule['virtuemart_calc_id']]['result'] = isset($this->_cart->cartData['VatTax'][$rule['virtuemart_calc_id']]['result']) ? $this->_cart->cartData['VatTax'][$rule['virtuemart_calc_id']]['result'] : 0; $this->_cart->cartData['VatTax'][$rule['virtuemart_calc_id']]['result'] += round($this->_cart->cartPrices[$rule['virtuemart_calc_id'] . 'Diff'], $this->_currencyDisplay->_priceConfig['salesPrice'][1]); if (!isset($this->_cart->cartData['VatTax'][$rule['virtuemart_calc_id']]['virtuemart_calc_id'])) { $this->_cart->cartData['VatTax'][$rule['virtuemart_calc_id']]['virtuemart_calc_id'] = $rule['virtuemart_calc_id']; } if (!isset($this->_cart->cartData['VatTax'][$rule['virtuemart_calc_id']]['calc_name'])) { $this->_cart->cartData['VatTax'][$rule['virtuemart_calc_id']]['calc_name'] = $rule['calc_name']; } if (!isset($this->_cart->cartData['VatTax'][$rule['virtuemart_calc_id']]['calc_value'])) { $this->_cart->cartData['VatTax'][$rule['virtuemart_calc_id']]['calc_value'] = $rule['calc_value']; } } }
* to the GNU General Public License, and as distributed it includes or * is derivative of works licensed under the GNU General Public License or * other free or open source software licenses. * See /administrator/components/com_virtuemart/COPYRIGHT.php for copyright notices and details. * * http://virtuemart.net */ /* Require the config */ defined('DS') or define('DS', DIRECTORY_SEPARATOR); if (!class_exists('VmConfig')) { require JPATH_ROOT . DS . 'administrator' . DS . 'components' . DS . 'com_virtuemart' . DS . 'helpers' . DS . 'config.php'; } VmConfig::loadConfig(); vmRam('Start'); //vmTime('joomla start until Vm is called','joomlaStart'); vmSetStartTime('vmStart'); VmConfig::loadJLang('com_virtuemart', true); if (VmConfig::get('shop_is_offline', 0)) { //$cache->setCaching (1); $_controller = 'virtuemart'; require VMPATH_SITE . DS . 'controllers' . DS . 'virtuemart.php'; vRequest::setVar('view', 'virtuemart'); $task = ''; $basePath = VMPATH_SITE; } else { // Front-end helpers if (!class_exists('VmImage')) { require VMPATH_ADMIN . DS . 'helpers' . DS . 'image.php'; } //dont remove that file it is actually in every view except the state view if (!class_exists('shopFunctionsF')) {
public function calculateCostprice($productId, $data) { $this->_revert = true; vmSetStartTime('calculateCostprice'); $this->_db->setQuery('SELECT * FROM #__virtuemart_product_prices WHERE `virtuemart_product_id`="' . $productId . '" '); $row = $this->_db->loadAssoc(); if ($row) { if (!empty($row['product_price'])) { // $costPrice = $row['product_price']; $this->productCurrency = $row['product_currency']; // $this->override = $row['override']; // $this->product_override_price = $row['product_override_price']; $this->product_tax_id = $row['product_tax_id']; $this->product_discount_id = $row['product_discount_id']; } else { $app = Jfactory::getApplication(); $app->enqueueMessage('cost Price empty, if child, everything okey, this is just a dev note'); return false; } } $this->_db->setQuery('SELECT `virtuemart_vendor_id` FROM #__virtuemart_products WHERE `virtuemart_product_id`="' . $productId . '" '); $single = $this->_db->loadResult(); $this->productVendorId = $single; if (empty($this->productVendorId)) { $this->productVendorId = 1; } $this->_db->setQuery('SELECT `virtuemart_category_id` FROM #__virtuemart_product_categories WHERE `virtuemart_product_id`="' . $productId . '" '); $this->_cats = $this->_db->loadResultArray(); // vmTime('getProductPrices no object given query time','getProductCalcs'); if (VmConfig::get('multix', 'none') != 'none' and empty($this->vendorCurrency)) { $this->_db->setQuery('SELECT `vendor_currency` FROM #__virtuemart_vendors WHERE `virtuemart_vendor_id`="' . $this->productVendorId . '" '); $single = $this->_db->loadResult(); $this->vendorCurrency = $single; } if (!empty($amount)) { $this->_amount = $amount; } //$this->setCountryState($this->_cart); $this->rules['Marge'] = $this->gatherEffectingRulesForProductPrice('Marge', $this->product_marge_id); $this->rules['Tax'] = $this->gatherEffectingRulesForProductPrice('Tax', $this->product_tax_id); $this->rules['VatTax'] = $this->gatherEffectingRulesForProductPrice('VatTax', $this->product_tax_id); $this->rules['DBTax'] = $this->gatherEffectingRulesForProductPrice('DBTax', $this->product_discount_id); $this->rules['DATax'] = $this->gatherEffectingRulesForProductPrice('DATax', $this->product_discount_id); $salesPrice = $data['salesPrice']; $withoutVatTax = $this->roundInternal($this->executeCalculation($this->rules['VatTax'], $salesPrice)); $withoutVatTax = !empty($withoutVatTax) ? $withoutVatTax : $salesPrice; $withDiscount = $this->roundInternal($this->executeCalculation($this->rules['DATax'], $withoutVatTax)); $withDiscount = !empty($withDiscount) ? $withDiscount : $withoutVatTax; // vmdebug('Entered final price '.$salesPrice.' discount '.$withDiscount); $withTax = $this->roundInternal($this->executeCalculation($this->rules['Tax'], $withDiscount)); $withTax = !empty($withTax) ? $withTax : $withDiscount; $basePriceP = $this->roundInternal($this->executeCalculation($this->rules['DBTax'], $withTax)); $basePriceP = !empty($basePriceP) ? $basePriceP : $withTax; $basePrice = $this->roundInternal($this->executeCalculation($this->rules['Marge'], $basePriceP)); $basePrice = !empty($basePrice) ? $basePrice : $basePriceP; $productCurrency = CurrencyDisplay::getInstance(); $costprice = $productCurrency->convertCurrencyTo($this->productCurrency, $basePrice, false); // $productCurrency = CurrencyDisplay::getInstance(); $this->_revert = false; return $costprice; }
function checkFilterOrder($toCheck) { //vmdebug('checkFilterOrder',$this->_validOrderingFieldName); if (!in_array($toCheck, $this->_validOrderingFieldName)) { $break = false; vmSetStartTime(); foreach ($this->_validOrderingFieldName as $name) { if (strpos($name, $toCheck) !== FALSE) { $this->_selectedOrdering = $name; $break = true; break; } } if (!$break) { $app = JFactory::getApplication(); $view = JRequest::getWord('view', 'virtuemart'); $app->setUserState('com_virtuemart.' . $view . '.filter_order', $this->_selectedOrdering); } //vmdebug('checkValidOrderingField:'.get_class($this).' programmer choosed invalid ordering '.$toCheck.', use '.$this->_selectedOrdering); } else { $this->_selectedOrdering = $toCheck; } return $this->_selectedOrdering; }
private function creditMemo($data) { $orderModel = VmModel::getModel('orders'); $orderDetails = $orderModel->getOrder($data->virtuemart_order_id); $calc = $this->getOrderCalc($orderDetails); if (!$calc) { return false; } if (!is_array($calc['avatax_virtuemart_country_id'])) { $calc['avatax_virtuemart_country_id'] = json_decode($calc['avatax_virtuemart_country_id'], true); } if ($calc['activated'] == 0) { avadebug('Avatax creditMemo rule not activated', $calc); return false; } if ($calc['accrual'] and $data->order_status != 'R') { avadebug('Avatax creditMemo, type is accrual and not a Refund', $calc); return false; } if (!class_exists('TaxServiceSoap')) { require VMAVALARA_CLASS_PATH . DS . 'TaxServiceSoap.class.php'; } if (!class_exists('DocumentType')) { require VMAVALARA_CLASS_PATH . DS . 'DocumentType.class.php'; } if (!class_exists('DetailLevel')) { require VMAVALARA_CLASS_PATH . DS . 'DetailLevel.class.php'; } if (!class_exists('Line')) { require VMAVALARA_CLASS_PATH . DS . 'Line.class.php'; } if (!class_exists('ServiceMode')) { require VMAVALARA_CLASS_PATH . DS . 'ServiceMode.class.php'; } if (!class_exists('Line')) { require VMAVALARA_CLASS_PATH . DS . 'Line.class.php'; } if (!class_exists('GetTaxResult')) { require VMAVALARA_CLASS_PATH . DS . 'GetTaxResult.class.php'; } $this->addresses = $this->fillValidateAvalaraAddress($calc, $orderDetails['details']['BT']); if (!$this->addresses) { vmdebug('Avatax: on order status update: no valid addresses'); return false; } if (is_object($orderDetails['details']['BT'])) { self::$vmadd = get_object_vars($orderDetails['details']['BT']); } else { self::$vmadd = $orderDetails['details']['BT']; } $toInvoice = VmConfig::get('inv_os', array('C')); if (!is_array($toInvoice)) { $toInvoice = (array) $toInvoice; } //Lets find first if the committ was already done, the committ was already done, if one of history orderstatuses //have one status for create invoice. //vmdebug('my orderDetails ',$orderDetails); self::$vmadd['taxOverride'] = null; foreach ($orderDetails['history'] as $item) { if (in_array($item->order_status_code, $toInvoice)) { //the date of the order status used to create the invoice self::$vmadd['taxOverride'] = $this->createTaxOverride(substr($item->created_on, 0, 10), $data->order_status, $item->comments); //self::$vmadd['paymentDate'] = substr($item->created_on,0,10); //Date when order is created //self::$vmadd['taxOverride'] = $orderDetails['details']['BT']->created_on; break; } } //Accrual Accounting means the committ is done directly after pressing the confirm button in the cart //Therefore the date of the committ/invoice is the first order date and we dont need to check the order history if (empty(self::$vmadd['taxOverride']) and $calc['accrual']) { self::$vmadd['taxOverride'] = $this->createTaxOverride($orderDetails['details']['BT']->created_on, $data->order_status); } //create the products $products = array(); foreach ($orderDetails['items'] as $k => $item) { $product = array(); $item = (array) $item; //vmdebug('my item',$item); $product['product_sku'] = $item['order_item_sku']; $product['product_name'] = $item['order_item_name']; $product['amount'] = $item['product_quantity']; //$product['price'] = $item['product_final_price']; $product['price'] = $item['product_item_price']; $product['discount'] = $item['product_subtotal_discount']; $model = VmModel::getModel('product'); $rProduct = $model->getProduct($item['virtuemart_product_id']); $product['categories'] = $rProduct->categories; $products[] = $product; } if (!empty($orderDetails['details']['BT']->virtuemart_shipmentmethod_id)) { $shipment = array(); $shipment['product_sku'] = 'VMShipmentId_' . $orderDetails['details']['BT']->virtuemart_shipmentmethod_id; $shipmentModel = VmModel::getModel('Shipmentmethod'); $shipmentModel->setId($orderDetails['details']['BT']->virtuemart_shipmentmethod_id); $shipmentMethod = $shipmentModel->getShipment(); $shipment['product_name'] = $shipmentMethod->shipment_name; $shipment['amount'] = 1; $shipment['price'] = $orderDetails['details']['BT']->order_shipment; //decimal // TotalAmmount $shipment['discount'] = 0.0; $products[] = $shipment; } $products['discountAmount'] = $orderDetails['details']['BT']->order_discountAmount - $orderDetails['details']['BT']->coupon_discount; if ($data->order_status == 'R') { $sign = -1; } else { $sign = 1; } $request = $this->createStandardRequest($calc, $products, $sign); $request->setCompanyCode($calc['company_code']); // Your Company Code From the Dashboard $request->setDocDate(date('Y-m-d')); //date $request->setCustomerCode($orderDetails['details']['BT']->customer_number); //string Required if ($orderDetails['details']['BT']->order_number) { $request->setPurchaseOrderNo($orderDetails['details']['BT']->order_number); //string Optional } $totalTax = 0.0; $invoiceNumber = 'onr_' . $orderDetails['details']['BT']->order_number; vRequest::setVar('create_invoice', 1); $orderModel->createInvoiceNumber($orderDetails['details']['BT'], $invoiceNumber); if (is_array($invoiceNumber)) { $invoiceNumber = $invoiceNumber[0]; } if ($calc['committ'] and $invoiceNumber) { if ($data->order_status == 'R') { $request->setDocType(DocumentType::$ReturnInvoice); } else { $request->setDocType(DocumentType::$SalesInvoice); } // Only supported types are SalesInvoice or SalesOrder $request->setCommit(true); $request->setDocCode($invoiceNumber); self::$_taxResult = FALSE; } vmSetStartTime('avagetTax'); self::$_taxResult = $this->executeRequest($request); vmTime('Avalara executeRequest ', 'avagetTax'); if (self::$_taxResult) { if (isset(self::$_taxResult['totalTax'])) { $totalTax = self::$_taxResult['totalTax']; } } return $totalTax; }
function display($tpl = null) { if (!class_exists('VmImage')) require(VMPATH_ADMIN . DS . 'helpers' . DS . 'image.php'); VmConfig::loadJLang('com_virtuemart_orders',TRUE); $model = VmModel::getModel('virtuemart'); $nbrCustomers = $model->getTotalCustomers(); $this->nbrCustomers=$nbrCustomers; $nbrActiveProducts = $model->getTotalActiveProducts(); $this->nbrActiveProducts= $nbrActiveProducts; $nbrInActiveProducts = $model->getTotalInActiveProducts(); $this->nbrInActiveProducts= $nbrInActiveProducts; $nbrFeaturedProducts = $model->getTotalFeaturedProducts(); $this->nbrFeaturedProducts= $nbrFeaturedProducts; $ordersByStatus = $model->getTotalOrdersByStatus(); $this->ordersByStatus= $ordersByStatus; $recentOrders = $model->getRecentOrders(); if(!class_exists('CurrencyDisplay'))require(VMPATH_ADMIN.DS.'helpers'.DS.'currencydisplay.php'); /* Apply currency This must be done per order since it's vendor specific */ $_currencies = array(); // Save the currency data during this loop for performance reasons foreach ($recentOrders as $virtuemart_order_id => $order) { //This is really interesting for multi-X, but I avoid to support it now already, lets stay it in the code if (!array_key_exists('v'.$order->virtuemart_vendor_id, $_currencies)) { $_currencies['v'.$order->virtuemart_vendor_id] = CurrencyDisplay::getInstance('',$order->virtuemart_vendor_id); } $order->order_total = $_currencies['v'.$order->virtuemart_vendor_id]->priceDisplay($order->order_total); } $this->recentOrders= $recentOrders; $recentCustomers = $model->getRecentCustomers(); $this->recentCustomers=$recentCustomers; if (!class_exists('vmRSS')) require(VMPATH_ADMIN.'/helpers/vmrss.php'); $this->extensionsFeed = vmRSS::getExtensionsRssFeed(); $virtuemartFeed = vmRSS::getVirtueMartRssFeed(); $this->virtuemartFeed=$virtuemartFeed; if(JFactory::getApplication()->isSite()){ $bar = JToolBar::getInstance('toolbar'); $bar->appendButton('Link', 'back', 'COM_VIRTUEMART_LEAVE', 'index.php?option=com_virtuemart&manage=0'); } if($this->manager('report')){ vmSetStartTime('report'); $reportModel = VmModel::getModel('report'); vRequest::setvar('task',''); $myCurrencyDisplay = CurrencyDisplay::getInstance(); $revenueBasic = $reportModel->getRevenue(60,true); $this->report = $revenueBasic['report']; vmJsApi::addJScript( "jsapi","//google.com/jsapi",false,false,'' ); vmJsApi::addJScript('vm.stats_chart',$revenueBasic['js'],false); vmTime('Created report','report'); } parent::display($tpl); }
/** * Roughly taken from the forum, a bit rewritten by Max Milbers to use the joomla database * Thank you oneforallsoft * * http://forum.virtuemart.net/index.php?topic=116403.0 * http://www.oneforallsoft.com/related-products-missing-after-virtuemart-upgrade/ * @author oneforallsoft */ function portVm1RelatedProducts() { if ($this->_stop || microtime(true) - $this->starttime >= $this->maxScriptTime) { return; } vmSetStartTime('relatedproducts'); $maxItems = $this->_getMaxItems('relatedproducts'); $startLimit = $this->_getStartLimit('relatedproducts_start'); $i = 0; $continue = true; $alreadyKnownIds = $this->getMigrationProgress('relatedproducts'); $out = array(); $out2 = array(); while ($continue) { $q = 'select * from #__vm_product_relations LIMIT ' . $startLimit . ',' . $maxItems; $doneStart = $startLimit; $res = self::loadCountListContinue($q, $startLimit, $maxItems, 'port Related products'); $oldVm1relateds = $res[0]; $startLimit = $res[1]; $continue = $res[2]; foreach ($oldVm1relateds as $v) { $pid = $v['product_id']; $ids = explode('|', $v['related_products']); $out = array_merge($ids, $out); $out[] = $pid; $out2[$pid] = $ids; $i++; } // GET SkuS for Products $skus = array(); $q = "select product_id,product_sku from #__vm_product where product_id in (" . implode(',', $out) . ") "; $this->_db->setQuery($q); $product_skus = $this->_db->loadAssocList(); if (empty($product_skus)) { vmError("Port Related products: The following SKUs were not found " . implode(',', $out)); break; } foreach ($product_skus as $v) { $skus[$v['product_id']] = $v['product_sku']; } foreach ($out2 as $k => $v) { $tmp = array(); foreach ($v as $vv) { if (isset($skus[$vv])) { $tmp[] = $skus[$vv]; } } $out[$skus[$k]] = $tmp; } // GET virtuemart_product_id for those SKUs $q = "select virtuemart_product_id,product_sku from #__virtuemart_products where product_sku in ('" . implode("','", $skus) . "') "; $this->_db->setQuery($q); $out3 = array(); $products = $this->_db->loadAssocList(); if (empty($products)) { vmError("Port Related products: Some of those SKUs were not found " . implode(',', $skus)); break; } foreach ($products as $v) { $out3[$v['product_sku']] = $v["virtuemart_product_id"]; } $now = date('Y-m-d H:i:s', time()); $sql = ''; foreach ($out as $k => $v) { foreach ($v as $vv) { if (isset($out3[$k]) and isset($out3[$vv])) { $sql .= ",({$out3[$k]},1,{$out3[$vv]},'" . $now . "')"; } } } if (empty($sql)) { vmError("Port Related products: Error while inserting new related products "); break; } $q = "INSERT INTO #__virtuemart_product_customfields (virtuemart_product_id,virtuemart_custom_id,customfield_value,modified_on) values " . substr($sql, 1); $this->_db->setQuery($q); $this->_db->execute(); if (microtime(true) - $this->starttime >= $this->maxScriptTime) { vmdebug('Related products import breaked, you may rise the execution time, this is not an error, just a hint'); $continue = false; break; } } if ($out and count($out) == 0) { vmdebug('no related products found'); return; } else { vmdebug('FOUND Related products ', count($out)); } $limitStartToStore = ', relatedproducts = "' . ($doneStart + $i) . '" '; $this->storeMigrationProgress('relatedproducts', $alreadyKnownIds, $limitStartToStore); vmInfo('Migration: ' . $i . ' Related products processed '); }
private static function _checkCreateKeyFile($date) { jimport('joomla.filesystem.file'); vmSetStartTime('check'); static $existingKeys = false; $keyPath = self::_getEncryptSafepath(); if (!$existingKeys) { $dir = opendir($keyPath); if (is_resource($dir)) { $existingKeys = array(); while (false !== ($file = readdir($dir))) { if ($file != '.' && $file != '..') { if (!is_dir($keyPath . DS . $file)) { $ext = Jfile::getExt($file); if ($ext == 'ini' and file_exists($keyPath . DS . $file)) { $content = parse_ini_file($keyPath . DS . $file); if ($content and is_array($content) and isset($content['unixtime'])) { $key = $content['unixtime']; unset($content['unixtime']); $existingKeys[$key] = $content; //vmdebug('Reading '.$keyPath .DS. $file,$content); } } else { //vmdebug('Resource says there is file, but does not exists? '.$keyPath .DS. $file); } } else { //vmdebug('Directory in they keyfolder? '.$keyPath .DS. $file); } } else { //vmdebug('Directory in the keyfolder '.$keyPath .DS. $file); } } } else { static $warn = false; if (!$warn) { vmWarn('Key folder in safepath unaccessible ' . $keyPath); } $warn = true; } } if ($existingKeys and is_array($existingKeys) and count($existingKeys) > 0) { ksort($existingKeys); if (!empty($date)) { $key = ''; foreach ($existingKeys as $unixDate => $values) { if ($unixDate - 30 >= $date) { vmdebug('$unixDate ' . $unixDate . ' >= $date ' . $date); continue; } vmdebug('$unixDate < $date ' . $date); $key = $values['key']; $usedKey = $values; } if (!isset($usedKey['b64']) or $usedKey['b64']) { vmdebug('Doing base64_decode ', $usedKey); $key = base64_decode($key); } } else { $usedKey = end($existingKeys); $key = $usedKey['key']; //No key means, we wanna encrypt something, when it has not the new attribute, //it is an old key and must be replaced $ksize = tsmConfig::get('keysize', 24); if (empty($key) or !isset($usedKey['b64']) or !isset($usedKey['size']) or $usedKey['size'] != $ksize) { $key = self::_createKeyFile($keyPath, $ksize); $existingKeys[$key['unixtime']] = $key; return $key['key']; } } //vmdebug('Length of key',strlen($key)); //vmTime('my time','check'); return $key; } else { $key = self::_createKeyFile($keyPath, tsmConfig::get('keysize', 24)); $existingKeys[$key['unixtime']] = $key; return $key['key']; } }
/** * Loads the configuration and works as singleton therefore called static. The call using the program cache * is 10 times faster then taking from the session. The session is still approx. 30 times faster then using the file. * The db is 10 times slower then the session. * * Performance: * * Fastest is * Program Cache: 1.5974044799805E-5 * Session Cache: 0.00016094612121582 * * First config db load: 0.00052118301391602 * Parsed and in session: 0.001554012298584 * * After install from file: 0.0040450096130371 * Parsed and in session: 0.0051419734954834 * * * Functions tests if already loaded in program cache, session cache, database and at last the file. * * Load the configuration values from the database into a session variable. * This step is done to prevent accessing the database for every configuration variable lookup. * * @author Max Milbers * @param $force boolean Forces the function to load the config from the db */ public static function loadConfig($force = FALSE) { vmSetStartTime('loadConfig'); if (!$force) { if (!empty(self::$_jpConfig) && !empty(self::$_jpConfig->_params)) { return self::$_jpConfig; } } self::$_jpConfig = new VmConfig(); $db = JFactory::getDBO(); $query = 'SHOW TABLES LIKE "%virtuemart_configs%"'; $db->setQuery($query); $configTable = $db->loadResult(); // self::$_debug = true; if (empty($configTable)) { self::$_jpConfig->installVMconfig(); } $app = JFactory::getApplication(); $install = 'no'; if (empty(self::$_jpConfig->_raw)) { $query = ' SELECT `config` FROM `#__virtuemart_configs` WHERE `virtuemart_config_id` = "1";'; $db->setQuery($query); self::$_jpConfig->_raw = $db->loadResult(); if (empty(self::$_jpConfig->_raw)) { if (self::installVMconfig()) { $install = 'yes'; $db->setQuery($query); self::$_jpConfig->_raw = $db->loadResult(); self::$_jpConfig->_params = NULL; } else { $app->enqueueMessage('Error loading configuration file', 'Error loading configuration file, please contact the storeowner'); } } } $i = 0; $pair = array(); if (!empty(self::$_jpConfig->_raw)) { $config = explode('|', self::$_jpConfig->_raw); foreach ($config as $item) { $item = explode('=', $item); if (!empty($item[1])) { // if($item[0]!=='offline_message' && $item[0]!=='dateformat' ){ if ($item[0] !== 'offline_message') { try { $value = @unserialize($item[1]); if ($value === FALSE) { $app->enqueueMessage('Exception in loadConfig for unserialize ' . $item[0] . ' ' . $item[1]); $uri = JFactory::getURI(); $configlink = $uri->root() . 'administrator/index.php?option=com_virtuemart&view=config'; $app->enqueueMessage('To avoid this message, enter your virtuemart <a href="' . $configlink . '">config</a> and just save it one time'); } else { $pair[$item[0]] = $value; } } catch (Exception $e) { vmdebug('Exception in loadConfig for unserialize ' . $e->getMessage(), $item); } } else { $pair[$item[0]] = unserialize(base64_decode($item[1])); } } else { $pair[$item[0]] = ''; } } // $pair['sctime'] = microtime(true); self::$_jpConfig->_params = $pair; self::$_jpConfig->set('sctime', microtime(TRUE)); self::$_jpConfig->set('vmlang', self::setdbLanguageTag()); self::$_jpConfig->setSession(); vmTime('loadConfig db ' . $install, 'loadConfig'); return self::$_jpConfig; } $app->enqueueMessage('Attention config is empty'); return self::$_jpConfig; }
/** * Loads the configuration and works as singleton therefore called static. The call using the program cache * is 10 times faster then taking from the session. The session is still approx. 30 times faster then using the file. * The db is 10 times slower then the session. * * Performance: * * Fastest is * Program Cache: 1.5974044799805E-5 * Session Cache: 0.00016094612121582 * * First config db load: 0.00052118301391602 * Parsed and in session: 0.001554012298584 * * After install from file: 0.0040450096130371 * Parsed and in session: 0.0051419734954834 * * * Functions tests if alread loaded in program cache, session cache, database and at last the file. * * Load the configuration values from the database into a session variable. * This step is done to prevent accessing the database for every configuration variable lookup. * * @author Max Milbers * @param $force boolean Forces the function to load the config from the db */ public function loadConfig($force = false) { vmSetStartTime('loadConfig'); if (!$force) { if (!empty(self::$_jpConfig) && !empty(self::$_jpConfig->_params)) { // vmTime('loadConfig Program Cache','loadConfig'); return self::$_jpConfig; } /* else { $session = JFactory::getSession(); $vmConfig = $session->get('vmconfig','','vm'); if(!empty($vmConfig)){ $params = unserialize($vmConfig); if(!empty($params)) { //This is our cache valid time, atm I use 5 minutes, that means that for exampel changes at the config //have at least 5 minutes later an effect of a currently logged in user (shopper) // 5 minutes until the config settings takes effect for OTHER users. $app = JFactory::getApplication(); $cacheenabled = $app->getCfg('caching'); $cachetime = $app->getCfg('cachetime'); if(!empty($cacheenabled) and !empty($params['sctime']) and (microtime(true) - $params['sctime'])<$cachetime) { $params['offline_message'] = base64_decode($params['offline_message']); // $params['dateformat'] = base64_decode($params['dateformat']); self::$_jpConfig = new VmConfig(); self::$_jpConfig->_params = $params; self::$_jpConfig->set('vmlang',self::setdbLanguageTag()); vmTime('loadConfig Session','loadConfig'); return self::$_jpConfig; } else { // VmInfo('empty $params->sctime'); } } } } */ } self::$_jpConfig = new VmConfig(); $db = JFactory::getDBO(); $query = 'SHOW TABLES LIKE "%virtuemart_configs%"'; $db->setQuery($query); $configTable = $db->loadResult(); // self::$_debug = true; if (empty($configTable)) { self::$_jpConfig->installVMconfig(); } $install = 'no'; if (empty(self::$_jpConfig->_raw)) { $query = ' SELECT `config` FROM `#__virtuemart_configs` WHERE `virtuemart_config_id` = "1";'; $db->setQuery($query); self::$_jpConfig->_raw = $db->loadResult(); if (empty(self::$_jpConfig->_raw)) { if (self::installVMconfig()) { $install = 'yes'; $db->setQuery($query); self::$_jpConfig->_raw = $db->loadResult(); self::$_jpConfig->_params = null; } else { VmError('Error loading configuration file', 'Error loading configuration file, please contact the storeowner'); } } } $i = 0; $pair = array(); if (!empty(self::$_jpConfig->_raw)) { $config = explode('|', self::$_jpConfig->_raw); foreach ($config as $item) { $item = explode('=', $item); if (!empty($item[1])) { // if($item[0]!=='offline_message' && $item[0]!=='dateformat' ){ if ($item[0] !== 'offline_message') { $pair[$item[0]] = unserialize($item[1]); } else { $pair[$item[0]] = unserialize(base64_decode($item[1])); } } else { $pair[$item[0]] = ''; } } // $pair['sctime'] = microtime(true); self::$_jpConfig->_params = $pair; self::$_jpConfig->set('sctime', microtime(true)); self::$_jpConfig->set('vmlang', self::setdbLanguageTag()); self::$_jpConfig->setSession(); vmTime('loadConfig db ' . $install, 'loadConfig'); return self::$_jpConfig; } $app = JFactory::getApplication(); $app->enqueueMessage('Attention config is empty'); return 'Was not able to create config'; }
function display($tpl = null) { if (!class_exists('VmImage')) { require VMPATH_ADMIN . DS . 'helpers' . DS . 'image.php'; } tsmConfig::loadJLang('com_tsmart_orders', TRUE); if (JFactory::getApplication()->isSite()) { $bar = JToolBar::getInstance('toolbar'); $bar->appendButton('Link', 'back', 'com_tsmart_LEAVE', 'index.php?option=com_tsmart&manage=0'); } $layout = $this->getLayout(); if ($this->manager('report')) { vmSetStartTime('report'); $model = tmsModel::getModel('tsmart'); $nbrCustomers = $model->getTotalCustomers(); $this->nbrCustomers = $nbrCustomers; $nbrActiveProducts = $model->getTotalActiveProducts(); $this->nbrActiveProducts = $nbrActiveProducts; $nbrInActiveProducts = $model->getTotalInActiveProducts(); $this->nbrInActiveProducts = $nbrInActiveProducts; $nbrFeaturedProducts = $model->getTotalFeaturedProducts(); $this->nbrFeaturedProducts = $nbrFeaturedProducts; $ordersByStatus = $model->getTotalOrdersByStatus(); $this->ordersByStatus = $ordersByStatus; $recentOrders = $model->getRecentOrders(); if (!class_exists('CurrencyDisplay')) { require VMPATH_ADMIN . DS . 'helpers' . DS . 'currencydisplay.php'; } /* Apply currency This must be done per order since it's vendor specific */ $_currencies = array(); // Save the currency data during this loop for performance reasons foreach ($recentOrders as $tsmart_order_id => $order) { //This is really interesting for multi-X, but I avoid to support it now already, lets stay it in the code if (!array_key_exists('v' . $order->tsmart_vendor_id, $_currencies)) { $_currencies['v' . $order->tsmart_vendor_id] = CurrencyDisplay::getInstance('', $order->tsmart_vendor_id); } $order->order_total = $_currencies['v' . $order->tsmart_vendor_id]->priceDisplay($order->order_total); } $this->recentOrders = $recentOrders; $recentCustomers = $model->getRecentCustomers(); $this->recentCustomers = $recentCustomers; $reportModel = tmsModel::getModel('report'); vRequest::setvar('task', ''); $myCurrencyDisplay = CurrencyDisplay::getInstance(); $revenueBasic = $reportModel->getRevenue(60, true); $this->report = $revenueBasic['report']; vmJsApi::addJScript("jsapi", "//google.com/jsapi", false, false, ''); vmJsApi::addJScript('vm.stats_chart', $revenueBasic['js'], false, true); vmTime('Created report', 'report'); } //if($layout=='default'){ $j = 'jQuery("#feed").ready(function(){ var datas = ""; vmSiteurl = "' . JURI::root() . '" jQuery.ajax({ type: "GET", async: true, cache: false, dataType: "json", url: vmSiteurl + "index.php?option=com_tsmart&view=tsmart&task=feed", data: datas, dataType: "html" }) .done(function( data ) { jQuery("#feed").append(data); }); })'; vmJsApi::addJScript('getFeed', $j, false, true); //} self::showACLPref($this); parent::display($tpl); }
private static function _checkCreateKeyFile($date) { vmSetStartTime('check'); static $existingKeys = false; $keyPath = self::_getEncryptSafepath(); if (!$existingKeys) { $dir = opendir($keyPath); if (is_resource($dir)) { $existingKeys = array(); while (false !== ($file = readdir($dir))) { if ($file != '.' && $file != '..') { if (!is_dir($keyPath . DS . $file)) { $ext = Jfile::getExt($file); if ($ext == 'ini' and file_exists($keyPath . DS . $file)) { $content = parse_ini_file($keyPath . DS . $file); if ($content and is_array($content) and isset($content['unixtime'])) { $key = $content['unixtime']; unset($content['unixtime']); $existingKeys[$key] = $content; //vmdebug('Reading '.$keyPath .DS. $file,$content); } } else { vmdebug('Resource says there is file, but does not exists? ' . $keyPath . DS . $file); } } else { //vmdebug('Directory in they keyfolder? '.$keyPath .DS. $file); } } else { //vmdebug('Directory in the keyfolder '.$keyPath .DS. $file); } } } else { static $warn = false; if (!$warn) { vmWarn('Key folder in safepath unaccessible ' . $keyPath); } $warn = true; } } if ($existingKeys and is_array($existingKeys) and count($existingKeys) > 0) { ksort($existingKeys); if (!empty($date)) { $key = ''; foreach ($existingKeys as $unixDate => $values) { if ($unixDate - 30 >= $date) { vmdebug('$unixDate ' . $unixDate . ' >= $date ' . $date); continue; } vmdebug('$unixDate < $date'); //$usedKey = $values; $key = $values['key']; } vmdebug('Use key file ', $key); //include($keyPath .DS. $usedKey.'.php'); } else { $usedKey = end($existingKeys); $key = $usedKey['key']; } vmTime('my time', 'check'); return $key; } else { $usedKey = date("ymd"); $filename = $keyPath . DS . $usedKey . '.ini'; if (!JFile::exists($filename)) { if (JVM_VERSION < 3) { $token = JUtility::getHash(JUserHelper::genRandomPassword()); } else { $token = JApplication::getHash(JUserHelper::genRandomPassword()); } $salt = JUserHelper::getSalt('crypt-md5'); $hashedToken = md5($token . $salt); $key = base64_encode($hashedToken); //$options = array('costs'=>VmConfig::get('cryptCost',8)); /*if(!function_exists('password_hash')){ require(JPATH_VM_ADMINISTRATOR . DS . 'helpers' . DS . 'password_compat.php'); } if(function_exists('password_hash')){ $key = password_hash($key, PASSWORD_BCRYPT, $options); }*/ $date = JFactory::getDate(); $today = $date->toUnix(); //$key = pack('H*',$key); $content = ';<?php die(); */ [keys] key = "' . $key . '" unixtime = "' . $today . '" date = "' . date("Y-m-d H:i:s") . '" ; */ ?>'; $result = JFile::write($filename, $content); vmTime('my time', 'check'); return $key; } } vmTime('my time', 'check'); //return pack('H*',$key); }
/** * Loads the configuration and works as singleton therefore called static. The call using the program cache * is 10 times faster then taking from the session. The session is still approx. 30 times faster then using the file. * The db is 10 times slower then the session. * * Performance: * * Fastest is * Program Cache: 1.5974044799805E-5 * Session Cache: 0.00016094612121582 * * First config db load: 0.00052118301391602 * Parsed and in session: 0.001554012298584 * * After install from file: 0.0040450096130371 * Parsed and in session: 0.0051419734954834 * * * Functions tests if already loaded in program cache, session cache, database and at last the file. * * Load the configuration values from the database into a session variable. * This step is done to prevent accessing the database for every configuration variable lookup. * * @author Max Milbers * @param $force boolean Forces the function to load the config from the db */ public static function loadConfig($force = FALSE, $fresh = FALSE) { if ($fresh) { self::$_jpConfig = new VmConfig(); return self::$_jpConfig; } vmSetStartTime('loadConfig'); if (!$force) { if (!empty(self::$_jpConfig) && !empty(self::$_jpConfig->_params)) { return self::$_jpConfig; } } self::$_jpConfig = new VmConfig(); if (!class_exists('VirtueMartModelConfig')) { require VMPATH_ADMIN . '/models/config.php'; } $configTable = VirtueMartModelConfig::checkConfigTableExists(); $app = JFactory::getApplication(); $db = JFactory::getDBO(); self::$installed = true; $install = vRequest::getInt('install', false); $redirected = vRequest::getInt('redirected', false); $link = ''; if (empty($configTable)) { self::$installed = false; $jlang = JFactory::getLanguage(); $selectedLang = $jlang->getTag(); if (empty($selectedLang)) { $selectedLang = $jlang->setLanguage($selectedLang); } $q = 'SELECT `element` FROM `#__extensions` WHERE type = "language" and enabled = "1"'; $db->setQuery($q); $knownLangs = $db->loadColumn(); //vmdebug('Selected language '.$selectedLang.' $knownLangs ',$knownLangs); if ($app->isAdmin() and !in_array($selectedLang, $knownLangs)) { $link = 'index.php?option=com_installer&view=languages'; $msg = 'Install your selected language <b>' . $selectedLang . '</b> first in <a href="' . $link . '">joomla language manager</a>, just select then the component VirtueMart under menu "component", to proceed with the installation '; $app->enqueueMessage($msg); } self::$installed = VirtueMartModelConfig::checkVirtuemartInstalled(); if (!self::$installed) { if (!$redirected and !$install) { $link = 'index.php?option=com_virtuemart&view=updatesmigration&redirected=1'; $msg = ''; if ($app->isSite()) { $link = JURI::root(true) . '/administrator/' . $link; } else { $msg = 'Install Virtuemart first, click on the menu component and select VirtueMart'; } } } } else { $query = ' SELECT `config` FROM `#__virtuemart_configs` WHERE `virtuemart_config_id` = "1";'; $db->setQuery($query); self::$_jpConfig->_raw = $db->loadResult(); //vmTime('time to load config','loadConfig'); } if (empty(self::$_jpConfig->_raw)) { $_value = VirtueMartModelConfig::readConfigFile(); if (!$_value) { vmError('Serious error, config file could not be filled with data'); return FALSE; } $_value = join('|', $_value); self::$_jpConfig->_raw = $_value; self::$_jpConfig->setParams(self::$_jpConfig->_raw); self::$_jpConfig->storeConfig(); } else { self::$_jpConfig->setParams(self::$_jpConfig->_raw); } self::$_secret = JFactory::getConfig()->get('secret'); self::$_jpConfig->_params['sctime'] = microtime(TRUE); self::$_jpConfig->_params['vmlang'] = self::setdbLanguageTag(); vmTime('time to load config', 'loadConfig'); if ($app->isSite()) { // try plugins JPluginHelper::importPlugin('vmuserfield'); $dispatcher = JDispatcher::getInstance(); $dispatcher->trigger('plgVmInitialise', array()); } if (!self::$installed) { $user = JFactory::getUser(); if ($user->authorise('core.admin', 'com_virtuemart') and ($install or $redirected)) { VmConfig::$_jpConfig->set('dangeroustools', 1); } if (!empty($link)) { $app->redirect($link, $msg); } } return self::$_jpConfig; }
/** * prepare display of cart * * @author RolandD * @author Max Milbers * @access public */ public function prepareCartData($checkAutomaticSelected = true) { vmSetStartTime('prepareCartData'); // Get the products for the cart $product_prices = $this->getCartPrices($checkAutomaticSelected); if (empty($product_prices)) { return null; } if (!class_exists('CurrencyDisplay')) { require JPATH_VM_ADMINISTRATOR . DS . 'helpers' . DS . 'currencydisplay.php'; } $currency = CurrencyDisplay::getInstance(); $calculator = calculationHelper::getInstance(); $this->pricesCurrency = $currency->getCurrencyForDisplay(); if (!class_exists('vmPSPlugin')) { require JPATH_VM_PLUGINS . DS . 'vmpsplugin.php'; } JPluginHelper::importPlugin('vmpayment'); $dispatcher = JDispatcher::getInstance(); $returnValues = $dispatcher->trigger('plgVmgetPaymentCurrency', array($this->virtuemart_paymentmethod_id, &$this->paymentCurrency)); $cartData = $calculator->getCartData(); return $cartData; }