public static function hookExec($hook_name, $hookArgs = array(), $id_module = NULL) { $t0 = microtime(true); $result = parent::hookExec($hook_name, $hookArgs, $id_module); self::$hookTime[$hook_name] = microtime(true) - $t0; return $result; }
public function display($file, $template, $cacheId = null, $compileId = null) { require_once dirname(__FILE__) . '../../../../modules/designerpreview/defines.inc.php'; // turn off cache for PS base theme & preview - troubles with include files, capture, assign smarty variables in php //if (isPreviewTheme()) $cacheId = null; return parent::display($file, $template, $cacheId, $compileId); }
public static function getInstanceByName($module_name) { $modules2skip = array('agilebankwire', 'agilepaybycheque'); if (in_array($module_name, $modules2skip)) { include_once _PS_MODULE_DIR_ . $module_name . '/' . $module_name . '.php'; $module = new $module_name(); return $module; } return parent::getInstanceByName($module_name); }
public function display($file, $template, $cache_id = null, $compile_id = null) { $result = parent::display($file, $template, $cache_id, $compile_id); $ip = Configuration::get('witm_config'); $ip_array = explode(',', $ip); if (!in_array(Tools::getRemoteAddr(), $ip_array) && !in_array('*', $ip_array)) { return $result; } return '<div class="div_infos_tpl"><span class="infos_tpl">TPL<span class="file_template">FILE : ' . $file . '<br/>TEMPLATE : ' . $template . '</span></span>' . $result . '</div>'; }
public static function getModulesOnDisk($useConfig = false, $loggedOnAddons = false, $id_employee = false) { $modules_list = parent::getModulesOnDisk($useConfig, $loggedOnAddons, $id_employee); foreach ($modules_list as &$module) { if (self::isModuleOverridden($module->name)) { $module->version_addons = null; } } return $modules_list; }
public static function getCheckout(Cart $cart, $moduleId, $orderId) { /** @var Aplazame $aplazame */ $aplazame = ModuleCore::getInstanceByName('aplazame'); $link = Context::getContext()->link; $confirmationQuery = array('id_cart' => $cart->id, 'key' => $cart->secure_key); $cancelQuery = array('id_cart' => $cart->id, 'key' => $cart->secure_key); $successQuery = array('id_cart' => $cart->id, 'id_module' => $moduleId, 'id_order' => $orderId, 'key' => $cart->secure_key); return array('toc' => true, 'merchant' => array('confirmation_url' => $link->getModuleLink('aplazame', 'confirmation', $confirmationQuery), 'cancel_url' => $link->getModuleLink('aplazame', 'cancel', $cancelQuery), 'checkout_url' => $link->getPageLink('order'), 'success_url' => $link->getPageLink('order-confirmation', null, null, $successQuery)), 'customer' => self::getCustomer(new Customer($cart->id_customer)), 'order' => self::checkoutOrder($cart), 'billing' => self::getAddress(new Address($cart->id_address_invoice)), 'shipping' => self::checkoutShipping(null, $cart), 'meta' => array('module' => array('name' => 'aplazame:prestashop', 'version' => $aplazame->version), 'version' => _PS_VERSION_)); }
protected function getCacheId($name = null) { $cache_id = parent::getCacheId($name); if ($this->context->cookie->exists() && $this->context->cookie->WebPSupport) { $cache_id .= '|w'; } else { $cache_id .= '|j'; } // j for conventional jpegs return $cache_id; }
public function postProcess() { if (Module::isInstalled('aplazame') && Module::isEnabled('aplazame')) { if (Tools::isSubmit('id_order') && Tools::getValue('id_order') > 0) { $order = new Order(Tools::getValue('id_order')); if (Validate::isLoadedObject($order)) { if (Tools::isSubmit('partialRefund') && isset($order)) { if ($this->tabAccess['edit'] == '1') { if (is_array($_POST['partialRefundProduct'])) { $amount = 0; $order_detail_list = array(); foreach ($_POST['partialRefundProduct'] as $id_order_detail => $amount_detail) { $order_detail_list[$id_order_detail] = array('quantity' => (int) $_POST['partialRefundProductQuantity'][$id_order_detail], 'id_order_detail' => (int) $id_order_detail); $order_detail = new OrderDetail((int) $id_order_detail); if (empty($amount_detail)) { $order_detail_list[$id_order_detail]['unit_price'] = $order_detail->unit_price_tax_excl; $order_detail_list[$id_order_detail]['amount'] = $order_detail->unit_price_tax_incl * $order_detail_list[$id_order_detail]['quantity']; } else { $order_detail_list[$id_order_detail]['unit_price'] = (double) str_replace(',', '.', $amount_detail / $order_detail_list[$id_order_detail]['quantity']); $order_detail_list[$id_order_detail]['amount'] = (double) str_replace(',', '.', $amount_detail); } $amount += $order_detail_list[$id_order_detail]['amount']; } $choosen = false; $voucher = 0; if ((int) Tools::getValue('refund_voucher_off') == 1) { $amount -= $voucher = (double) Tools::getValue('order_discount_price'); } elseif ((int) Tools::getValue('refund_voucher_off') == 2) { $choosen = true; $amount = $voucher = (double) Tools::getValue('refund_voucher_choose'); } $shipping_cost_amount = (double) str_replace(',', '.', Tools::getValue('partialRefundShippingCost')) ? (double) str_replace(',', '.', Tools::getValue('partialRefundShippingCost')) : false; if ($shipping_cost_amount > 0) { $amount += $shipping_cost_amount; } if ($amount > 0) { if (!Tools::isSubmit('generateDiscountRefund') && $order->module == 'aplazame') { $aplazame = ModuleCore::getInstanceByName('aplazame'); $aplazame->refundAmount($order, $amount); } } } } } } } } parent::postProcess(); }
public function upgrade($name) { // Calling this function will init legacy module data $module_list = \ModuleCore::getModulesOnDisk(); foreach ($module_list as $module) { if ($module->name != $name) { continue; } if (\ModuleCore::initUpgradeModule($module)) { $legacy_instance = \ModuleCore::getInstanceByName($name); $legacy_instance->runUpgradeModule(); \ModuleCore::upgradeModuleVersion($name, $module->version); return !count($legacy_instance->getErrors()); } elseif (\ModuleCore::getUpgradeStatus($name)) { return true; } return true; } return false; }
public function renderList() { $this->toolbar_title = $this->l('Order Management'); $statuses_array = array(); $statuses = ErpOrderState::getOrderStates((int) $this->context->language->id); foreach ($statuses as $status) { $statuses_array[$status['id_order_state']] = $status['name']; } require_once _PS_MODULE_DIR_ . 'erpillicopresta/models/ErpFeature.php'; $this->context->smarty->assign(array('token_mr' => ModuleCore::isEnabled('mondialrelay') ? MondialRelay::getToken('back') : 'false', 'token_expeditor' => ModuleCore::isEnabled('expeditor') ? Tools::getAdminToken('AdminExpeditor' . (int) Tab::getIdFromClassName('AdminExpeditor') . (int) $this->context->employee->id) : 'false', 'id_employee' => (int) $this->context->employee->id, 'order_statuses' => $statuses_array, 'controller_status' => $this->controller_status, 'erp_feature' => ErpFeature::getFeaturesWithToken($this->context->language->iso_code), 'template_path' => $this->template_path, 'expeditor_status' => Configuration::get('EXPEDITOR_STATE_EXP'), '_module_dir_' => _MODULE_DIR_)); $this->tpl_list_vars['has_bulk_actions'] = 'true'; // handle may contain error messages $handle = Tools::getValue('handle'); switch (trim($handle)) { case '': break; case 'false': $this->confirmations[] = $this->l('All orders have been updated') . '<br/>'; break; default: if (!empty($handle)) { // $handle = str_replace('u00e9', 'é', $handle); // $handle = str_replace('u00ea', 'ê', $handle); $handle = Tools::replaceAccentedChars($handle); // We take note about orders with error: no valid carrier (split on order number #) $orderWithoutShipping = strstr($handle, '#') != false ? true : false; $errors = explode('<br/>', str_replace('#', '<br/>', $handle)); foreach ($errors as $key => $error) { if (!empty($error)) { if (!$orderWithoutShipping) { $message = $error; } else { $message = $error; } $this->errors[] = Tools::displayError($message); } } } break; } if (Tools::getValue('linkPDF') != '' && Tools::getValue('newState') != '') { // if state need invoice generation if (ErpOrderState::invoiceAvailable(Tools::getValue('newState'))) { $pdf_link = new Link(); $pdf_link = $pdf_link->getAdminLink("AdminAdvancedOrder", true) . '&submitAction=generateInvoicesPDF3&id_orders=' . Tools::getValue('linkPDF'); $this->confirmations[] = ' <a target="_blank" href="' . $pdf_link . '" alt="invoices">' . $this->l('Download all invoices') . '<br/></a>'; } // if state need delivery slip generation if (ErpOrderState::deliverySlipAvailable(Tools::getValue('newState'))) { $pdf_link = new Link(); $pdf_link = $pdf_link->getAdminLink("AdminAdvancedOrder", true) . '&submitAction=generateDeliverySlipsPDF2&id_orders=' . Tools::getValue('linkPDF'); $this->confirmations[] = ' <a target="_blank" href="' . $pdf_link . '" alt="delivery">' . $this->l('Download all delivery slip') . '<br/></a>'; } } if (Tools::getValue('linkPDFPrint') != '') { if ($this->controller_status == STATUS1 && count(explode(',', Tools::getValue('linkPDFPrint'))) > ERP_ORDERFR) { $this->informations[] = sprintf($this->l('You are using the free version of 1-Click ERP which limits the possible number of documents to print to %d orders'), ERP_ORDERFR); } else { $invoices = ''; $delivery = ''; foreach (explode(',', Tools::getValue('linkPDFPrint')) as $id_order) { if (ErpOrderState::invoiceAvailable(ErpOrder::getIdStateByIdOrder($id_order))) { $invoices .= $id_order . ','; } if (ErpOrderState::deliverySlipAvailable(ErpOrder::getIdStateByIdOrder($id_order))) { $delivery .= $id_order . ','; } } if ($invoices != '') { $pdf_link = new Link(); $pdf_link = $pdf_link->getAdminLink("AdminAdvancedOrder", true) . '&submitAction=generateInvoicesPDF3&id_orders=' . Tools::substr($invoices, 0, -1); $this->confirmations[] = ' <a target="_blank" href="' . $pdf_link . '" alt="invoices">' . $this->l('Download all invoices') . '</br></a>'; } if ($delivery != '') { $pdf_link = new Link(); $pdf_link = $pdf_link->getAdminLink("AdminAdvancedOrder", true) . '&submitAction=generateDeliverySlipsPDF2&id_orders=' . Tools::substr($delivery, 0, -1); $this->confirmations[] = ' <a target="_blank" href="' . $pdf_link . '" alt="delivery">' . $this->l('Download all delivery slip') . '</br></a>'; } if ($invoices == '' && $delivery == '') { $this->errors[] = $this->l('The selected orders have no invoice or delivery !') . '<br/>'; } } } if (Tools::getValue('etiquettesMR') != '') { // Downlad all pdf and zip then delete and display link to zip file $etiquettesMR = explode(' ', Tools::getValue('etiquettesMR')); unset($etiquettesMR[count($etiquettesMR) - 1]); $zipPath = '../modules/erpillicopresta/export/mondialrelay.zip'; $zip = new ZipArchive(); if ($zip->open($zipPath, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE) !== true) { throw new Exception($this->l('Impossible to create the zip archive containing the shipping labels to Mondial Relay carrier !') . '<br/>'); } foreach ($etiquettesMR as $key => $i) { $zip->addFromString('mondialrelay_' . $key . '.pdf', Tools::file_get_contents($i)); } $zip->close(); //Display link to dl zip file $this->confirmations[] = ' <a target="_blank" href="' . $zipPath . '" alt="zip_file">' . $this->l('Download zip archive which contents all labels for Mondial Relay shipment') . '<br/></a>'; if (Tools::getValue('deliveryNumbersMR') != '') { // Get all tracking numbers $numbers = explode(" ", Tools::getValue('deliveryNumbersMR')); unset($numbers[count($numbers) - 1]); foreach ($numbers as $number) { $tabNumber = explode("-", $number); $order_carrier = new OrderCarrier(ErpOrder::getIdCarrierbyIdOrder((int) $tabNumber[1])); $order = new ErpOrder((int) $tabNumber[1]); // Update carrier $order->shipping_number = $tabNumber[0]; $order->update(); // Update order_carrier $order_carrier->tracking_number = pSQL($tabNumber[0]); $order_carrier->update(); } } } if (Tools::getValue('expeditorCSV') != '') { // CSV file creation $csvPath = '../modules/erpillicopresta/export/expeditor_inet.csv'; $fileCSV = fopen($csvPath, 'w'); // Fill in file fwrite($fileCSV, str_replace(',', '', Tools::getValue('expeditorCSV'))); //Close fclose($fileCSV); // link creation $this->confirmations[] = ' <a target="_blank" href="' . $csvPath . '" alt="csv_file">' . $this->l('Download export file (CSV) for ExpeditorInet') . '</br></a>'; } if (Tools::getValue('idOthers') != '') { //BEGIN Initialisations for TNT if (Module::isEnabled('tntcarrier')) { $TNTCheck = false; require_once _PS_MODULE_DIR_ . '/tntcarrier/classes/PackageTnt.php'; if (class_exists('ZipArchive', false) && ($tnt_zip = new ZipArchive())) { // Protection du ZIP $dateday = new DateTime(); $uniqid_file = uniqid('file_'); $token = md5($dateday->getTimestamp() . $uniqid_file); // Put all tnt pdf into a zip $tnt_zip_path = 'erpillicopresta/export/tnt_' . date('Y-m-d_His') . '_' . $uniqid_file . $token . '.zip'; if ($tnt_zip->open(_PS_MODULE_DIR_ . $tnt_zip_path, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE) !== true) { $this->errors[] = Tools::displayError($this->l('Failed to create a ZIP archive containing the shipping labels to TNT carrier !') . '<br/>'); } else { // one or several id orders $id_others_order_array = strpos(Tools::getValue('idOthers'), ',') !== false ? explode(',', Tools::getValue('idOthers')) : (int) Tools::getValue('idOthers'); // Browse all orders not in ExpeditorInet nor MondialRelay foreach ((array) $id_others_order_array as $i => $id_order) { // BEGIN Commande TNT $id_order = (int) $id_order; if (ErpOrder::isTntOrder($id_order)) { // status change $currOrder = new ErpOrder($id_order); $currOrder->setCurrentState(4, $this->context->employee->id); // Start to check that weight order is valid if not tnt crash ! //echo($data['poid'] * 1000);die; // Get tracking number : dedicated class created for this action // Execution of the hook generating the tracking number at an order opening ... So ctrl c / ctrl v to execute here /*$erp_tntCarrier = new ErpTntCarrier(); $generate = $erp_tntCarrier->generateShipping($id_order);*/ $generateShipping = Hook::exec('adminOrder', array('id_order' => $id_order)); $tnt = new PackageTnt($id_order); $tntNumber = $tnt->getShippingNumber(); if (count($tntNumber) == 0) { $this->errors[] = Tools::displayError($this->l('Failed to get shipping number from TNT services : you have to fit the weight of the order.')); continue; } $tntNumber = $tntNumber[0]['shipping_number']; // Update order $order_carrier = new OrderCarrier(ErpOrder::getIdCarrierbyIdOrder((int) $id_order)); $order = new ErpOrder((int) $id_order); $order->shipping_number = $tntNumber; $order->update(); $order_carrier->tracking_number = pSQL($tntNumber); $order_carrier->update(); // Add pdf to zip $tnt_zip->addFile(_PS_MODULE_DIR_ . '/tntcarrier/pdf/' . $tntNumber . '.pdf', $tntNumber . '.pdf'); $TNTCheck = true; } // END Order TNT // SPLICE idOther if (is_array($id_others_order_array)) { unset($id_others_order_array[$i]); } else { unset($id_others_order_array); } } //Display dl zip link $tnt_zip->close(); if ($TNTCheck) { $this->confirmations[] = ' <a target="_blank" href="' . _MODULE_DIR_ . $tnt_zip_path . '" alt="zip_file">' . $this->l('Download zip archive which contents all labels for TNT shipment') . '<br/></a>'; } } } else { $this->errors[] = Tools::displayError($this->l('Class ZipArchive does not exist !') . '<br/>'); } //END Initialisations for TNT } // Display for order not processed : idothers if (isset($id_others_order_array)) { if (count($id_others_order_array) == 1) { //var_dump($id_others_order_array);die(); if (is_array($id_others_order_array)) { $id_others_order_array = $id_others_order_array[1]; } $this->errors[] = Tools::displayError($this->l('The following order has not been processed : order #') . $id_others_order_array . '. ' . $this->l('Please make sure that the carrier is either TNT, ExpeditorInet, or MondialRelay and that the order fits the carrier requirements.')); } elseif (count($id_others_order_array) > 1) { $this->errors[] = Tools::displayError($this->l('The following orders have not been processed : orders #') . implode(", ", $id_others_order_array) . '. ' . $this->l('Please make sure that the carrier is either TNT, ExpeditorInet, or MondialRelay and that the orders fit the carrier requirements.')); } } } return parent::renderList(); }
/** * Return available modules * * @param boolean $useConfig in order to use config.xml file in module dir * @return array Modules */ public static function getModulesOnDisk($useConfig = false, $loggedOnAddons = false, $id_employee = false) { global $_MODULES; // Init var $module_list = array(); $module_name_list = array(); $modulesNameToCursor = array(); $errors = array(); // Get modules directory list and memory limit $modules_dir = Module::getModulesDirOnDisk(); $memory_limit = Tools::getMemoryLimit(); $modules_installed = array(); $result = Db::getInstance()->executeS(' SELECT m.name, m.version, mp.interest FROM `' . _DB_PREFIX_ . 'module` m ' . Shop::addSqlAssociation('module', 'm') . ' LEFT JOIN `' . _DB_PREFIX_ . 'module_preference` mp ON (mp.`module` = m.`name` AND mp.`id_employee` = ' . (int) $id_employee . ')'); foreach ($result as $row) { $modules_installed[$row['name']] = $row; } foreach ($modules_dir as $module) { // Memory usage checking if (function_exists('memory_get_usage') && $memory_limit != '-1') { $current_memory = memory_get_usage(true); // memory_threshold in MB $memory_threshold = Tools::isX86_64arch() ? 3 : 1.5; if ($memory_limit - $current_memory <= $memory_threshold * 1024 * 1024) { $errors[] = Tools::displayError('All modules cannot be loaded due to memory limit restrictions, please increase your memory_limit value on your server configuration'); break; } } // Check if config.xml module file exists and if it's not outdated $configFile = _PS_MODULE_DIR_ . $module . '/config.xml'; $xml_exist = file_exists($configFile); if ($xml_exist) { $needNewConfigFile = filemtime($configFile) < filemtime(_PS_MODULE_DIR_ . $module . '/' . $module . '.php'); } else { $needNewConfigFile = true; } // If config.xml exists and that the use config flag is at true if ($useConfig && $xml_exist) { // Load config.xml libxml_use_internal_errors(true); $xml_module = simplexml_load_file($configFile); foreach (libxml_get_errors() as $error) { $errors[] = '[' . $module . '] ' . Tools::displayError('Error found in config file:') . ' ' . htmlentities($error->message); } libxml_clear_errors(); // If no errors in Xml, no need instand and no need new config.xml file, we load only translations if (!count($errors) && (int) $xml_module->need_instance == 0 && !$needNewConfigFile) { $file = _PS_MODULE_DIR_ . $module . '/' . Context::getContext()->language->iso_code . '.php'; if (Tools::file_exists_cache($file) && (include_once $file)) { if (isset($_MODULE) && is_array($_MODULE)) { $_MODULES = !empty($_MODULES) ? array_merge($_MODULES, $_MODULE) : $_MODULE; } } $item = new stdClass(); $item->id = 0; $item->warning = ''; foreach ($xml_module as $k => $v) { $item->{$k} = (string) $v; } $item->displayName = stripslashes(Translate::getModuleTranslation((string) $xml_module->name, Module::configXmlStringFormat($xml_module->displayName), (string) $xml_module->name)); $item->description = stripslashes(Translate::getModuleTranslation((string) $xml_module->name, Module::configXmlStringFormat($xml_module->description), (string) $xml_module->name)); $item->author = stripslashes(Translate::getModuleTranslation((string) $xml_module->name, Module::configXmlStringFormat($xml_module->author), (string) $xml_module->name)); if (isset($xml_module->confirmUninstall)) { $item->confirmUninstall = Translate::getModuleTranslation((string) $xml_module->name, Module::configXmlStringFormat($xml_module->confirmUninstall), (string) $xml_module->name); } $item->active = 0; $item->onclick_option = false; $module_list[] = $item; $module_name_list[] = '\'' . pSQL($item->name) . '\''; $modulesNameToCursor[strval($item->name)] = $item; } } // If use config flag is at false or config.xml does not exist OR need instance OR need a new config.xml file if (!$useConfig || !$xml_exist || isset($xml_module->need_instance) && (int) $xml_module->need_instance == 1 || $needNewConfigFile) { // If class does not exists, we include the file if (!class_exists($module, false)) { // Get content from php file $filepath = _PS_MODULE_DIR_ . $module . '/' . $module . '.php'; $file = trim(file_get_contents(_PS_MODULE_DIR_ . $module . '/' . $module . '.php')); if (substr($file, 0, 5) == '<?php') { $file = substr($file, 5); } if (substr($file, -2) == '?>') { $file = substr($file, 0, -2); } // If (false) is a trick to not load the class with "eval". // This way require_once will works correctly if (eval('if (false){ ' . $file . ' }') !== false) { require_once _PS_MODULE_DIR_ . $module . '/' . $module . '.php'; } else { $errors[] = sprintf(Tools::displayError('%1$s (parse error in %2$s)'), $module, substr($filepath, strlen(_PS_ROOT_DIR_))); } } // If class exists, we just instanciate it if (class_exists($module, false)) { $tmp_module = new $module(); $item = new stdClass(); $item->id = $tmp_module->id; $item->warning = $tmp_module->warning; $item->name = $tmp_module->name; $item->version = $tmp_module->version; $item->tab = $tmp_module->tab; $item->displayName = $tmp_module->displayName; $item->description = stripslashes($tmp_module->description); $item->author = $tmp_module->author; $item->limited_countries = $tmp_module->limited_countries; $item->parent_class = get_parent_class($module); $item->is_configurable = $tmp_module->is_configurable = method_exists($tmp_module, 'getContent') ? 1 : 0; $item->need_instance = isset($tmp_module->need_instance) ? $tmp_module->need_instance : 0; $item->active = $tmp_module->active; $item->currencies = isset($tmp_module->currencies) ? $tmp_module->currencies : null; $item->currencies_mode = isset($tmp_module->currencies_mode) ? $tmp_module->currencies_mode : null; $item->confirmUninstall = isset($tmp_module->confirmUninstall) ? $tmp_module->confirmUninstall : null; $item->onclick_option = method_exists($module, 'onclickOption') ? true : false; if ($item->onclick_option) { $href = Context::getContext()->link->getAdminLink('Module', true) . '&module_name=' . $tmp_module->name . '&tab_module=' . $tmp_module->tab; $item->onclick_option_content = array(); $option_tab = array('desactive', 'reset', 'configure', 'delete'); foreach ($option_tab as $opt) { $item->onclick_option_content[$opt] = $tmp_module->onclickOption($opt, $href); } } $module_list[] = $item; if (!$xml_exist || $needNewConfigFile) { self::$_generate_config_xml_mode = true; $tmp_module->_generateConfigXml(); self::$_generate_config_xml_mode = false; } unset($tmp_module); } else { $errors[] = sprintf(Tools::displayError('%1$s (class missing in %2$s)'), $module, substr($filepath, strlen(_PS_ROOT_DIR_))); } } } // Get modules information from database if (!empty($module_name_list)) { $list = Shop::getContextListShopID(); $sql = 'SELECT m.id_module, m.name, ( SELECT COUNT(*) FROM ' . _DB_PREFIX_ . 'module_shop ms WHERE m.id_module = ms.id_module AND ms.id_shop IN (' . implode(',', $list) . ') ) as total FROM ' . _DB_PREFIX_ . 'module m WHERE m.name IN (' . implode(',', $module_name_list) . ')'; $results = Db::getInstance()->executeS($sql); foreach ($results as $result) { $moduleCursor = $modulesNameToCursor[$result['name']]; $moduleCursor->id = $result['id_module']; $moduleCursor->active = $result['total'] == count($list) ? 1 : 0; } } // Get Default Country Modules and customer module $files_list = array(array('type' => 'addonsNative', 'file' => _PS_ROOT_DIR_ . self::CACHE_FILE_DEFAULT_COUNTRY_MODULES_LIST, 'loggedOnAddons' => 0), array('type' => 'addonsBought', 'file' => _PS_ROOT_DIR_ . self::CACHE_FILE_CUSTOMER_MODULES_LIST, 'loggedOnAddons' => 1), array('type' => 'addonsMustHave', 'file' => _PS_ROOT_DIR_ . self::CACHE_FILE_MUST_HAVE_MODULES_LIST, 'loggedOnAddons' => 0)); foreach ($files_list as $f) { if (file_exists($f['file']) && ($f['loggedOnAddons'] == 0 || $loggedOnAddons)) { $file = $f['file']; $content = Tools::file_get_contents($file); $xml = @simplexml_load_string($content, null, LIBXML_NOCDATA); if ($xml && isset($xml->module)) { foreach ($xml->module as $modaddons) { $flag_found = 0; foreach ($module_list as $k => $m) { if ($m->name == $modaddons->name && !isset($m->available_on_addons)) { $flag_found = 1; if ($m->version != $modaddons->version && version_compare($m->version, $modaddons->version) === -1) { $module_list[$k]->version_addons = $modaddons->version; } } } if ($flag_found == 0) { $item = new stdClass(); $item->id = 0; $item->warning = ''; $item->type = strip_tags((string) $f['type']); $item->name = strip_tags((string) $modaddons->name); $item->version = strip_tags((string) $modaddons->version); $item->tab = strip_tags((string) $modaddons->tab); $item->displayName = strip_tags((string) $modaddons->displayName) . ' (Addons)'; $item->description = stripslashes(strip_tags((string) $modaddons->description)); $item->author = strip_tags((string) $modaddons->author); $item->limited_countries = array(); $item->parent_class = ''; $item->onclick_option = false; $item->is_configurable = 0; $item->need_instance = 0; $item->not_on_disk = 1; $item->available_on_addons = 1; $item->active = 0; if (isset($modaddons->img)) { if (!file_exists(_PS_TMP_IMG_DIR_ . md5($modaddons->name) . '.jpg')) { if (!file_put_contents(_PS_TMP_IMG_DIR_ . md5($modaddons->name) . '.jpg', Tools::file_get_contents($modaddons->img))) { copy(_PS_IMG_DIR_ . '404.gif', _PS_TMP_IMG_DIR_ . md5($modaddons->name) . '.jpg'); } } if (file_exists(_PS_TMP_IMG_DIR_ . md5($modaddons->name) . '.jpg')) { $item->image = '../img/tmp/' . md5($modaddons->name) . '.jpg'; } } if ($item->type == 'addonsMustHave') { $item->addons_buy_url = strip_tags((string) $modaddons->url); $prices = (array) $modaddons->price; $id_default_currency = Configuration::get('PS_CURRENCY_DEFAULT'); foreach ($prices as $currency => $price) { if ($id_currency = Currency::getIdByIsoCode($currency)) { $item->price = (double) $price; $item->id_currency = (int) $id_currency; if ($id_default_currency == $id_currency) { break; } } } } $module_list[] = $item; } } } } } foreach ($module_list as &$module) { if (isset($modules_installed[$module->name])) { $module->installed = true; $module->database_version = $modules_installed[$module->name]['version']; $module->interest = $modules_installed[$module->name]['interest']; } else { $module->installed = false; $module->database_version = 0; $module->interest = 0; } } usort($module_list, create_function('$a,$b', 'return strnatcasecmp($a->displayName, $b->displayName);')); if ($errors) { echo '<div class="alert error"><h3>' . Tools::displayError('The following module(s) could not be loaded') . ':</h3><ol>'; foreach ($errors as $error) { echo '<li>' . $error . '</li>'; } echo '</ol></div>'; } return $module_list; }
public function getExceptions($hookID, $dispatch = false) { if (self::$exceptionsCache === null) { self::$exceptionsCache = array(); $sql = 'SELECT * FROM `' . _DB_PREFIX_ . 'hook_module_exceptions` WHERE `id_shop` IN (' . implode(', ', Shop::getContextListShopID()) . ')'; $result = Db::getInstance()->executeS($sql); foreach ($result as $row) { if (!$row['file_name']) { continue; } $key = $row['id_hook'] . '-' . $row['id_module']; if (!isset(self::$exceptionsCache[$key])) { self::$exceptionsCache[$key] = array(); } if (!isset(self::$exceptionsCache[$key][$row['id_shop']])) { self::$exceptionsCache[$key][$row['id_shop']] = array(); } self::$exceptionsCache[$key][$row['id_shop']][] = $row['file_name']; } } $key = $hookID . '-' . $this->id; if (!$dispatch) { $files = array(); foreach (Shop::getContextListShopID() as $shop_id) { if (isset(self::$exceptionsCache[$key], self::$exceptionsCache[$key][$shop_id])) { foreach (self::$exceptionsCache[$key][$shop_id] as $file) { if (!in_array($file, $files)) { $files[] = $file; } } } } return $files; } else { $list = array(); foreach (Shop::getContextListShopID() as $shop_id) { if (isset(self::$exceptionsCache[$key], self::$exceptionsCache[$key][$shop_id])) { $list[$shop_id] = self::$exceptionsCache[$key][$shop_id]; } } return $list; } }
public function __construct() { parent::__construct(); $this->aplazame = ModuleCore::getInstanceByName('aplazame'); }
/** * Return available modules * * @param bool $use_config in order to use config.xml file in module dir * @return array Modules */ public static function getModulesOnDisk($use_config = false, $logged_on_addons = false, $id_employee = false) { global $_MODULES; // Init var $module_list = array(); $module_name_list = array(); $modules_name_to_cursor = array(); $errors = array(); // Get modules directory list and memory limit $modules_dir = Module::getModulesDirOnDisk(); $modules_installed = array(); $result = Db::getInstance()->executeS(' SELECT m.name, m.version, mp.interest, module_shop.enable_device FROM `' . _DB_PREFIX_ . 'module` m ' . Shop::addSqlAssociation('module', 'm') . ' LEFT JOIN `' . _DB_PREFIX_ . 'module_preference` mp ON (mp.`module` = m.`name` AND mp.`id_employee` = ' . (int) $id_employee . ')'); foreach ($result as $row) { $modules_installed[$row['name']] = $row; } foreach ($modules_dir as $module) { $module_errors = array(); if (Module::useTooMuchMemory()) { $module_errors[] = Tools::displayError('All modules cannot be loaded due to memory limit restrictions, please increase your memory_limit value on your server configuration'); break; } $iso = substr(Context::getContext()->language->iso_code, 0, 2); // Check if config.xml module file exists and if it's not outdated if ($iso == 'en') { $config_file = _PS_MODULE_DIR_ . $module . '/config.xml'; } else { $config_file = _PS_MODULE_DIR_ . $module . '/config_' . $iso . '.xml'; } $xml_exist = file_exists($config_file); $need_new_config_file = $xml_exist ? @filemtime($config_file) < @filemtime(_PS_MODULE_DIR_ . $module . '/' . $module . '.php') : true; // If config.xml exists and that the use config flag is at true if ($use_config && $xml_exist && !$need_new_config_file) { // Load config.xml libxml_use_internal_errors(true); $xml_module = @simplexml_load_file($config_file); if (!$xml_module) { $module_errors[] = Tools::displayError(sprintf('%1s could not be loaded.', $config_file)); break; } foreach (libxml_get_errors() as $error) { $module_errors[] = '[' . $module . '] ' . Tools::displayError('Error found in config file:') . ' ' . htmlentities($error->message); } libxml_clear_errors(); // If no errors in Xml, no need instand and no need new config.xml file, we load only translations if (!count($module_errors) && (int) $xml_module->need_instance == 0) { $file = _PS_MODULE_DIR_ . $module . '/' . Context::getContext()->language->iso_code . '.php'; if (Tools::file_exists_cache($file) && (include_once $file)) { if (isset($_MODULE) && is_array($_MODULE)) { $_MODULES = !empty($_MODULES) ? array_merge($_MODULES, $_MODULE) : $_MODULE; } } $item = new stdClass(); $item->id = 0; $item->warning = ''; foreach ($xml_module as $k => $v) { $item->{$k} = (string) $v; } $item->displayName = stripslashes(Translate::getModuleTranslation((string) $xml_module->name, Module::configXmlStringFormat($xml_module->displayName), (string) $xml_module->name)); $item->description = stripslashes(Translate::getModuleTranslation((string) $xml_module->name, Module::configXmlStringFormat($xml_module->description), (string) $xml_module->name)); $item->author = stripslashes(Translate::getModuleTranslation((string) $xml_module->name, Module::configXmlStringFormat($xml_module->author), (string) $xml_module->name)); $item->author_uri = isset($xml_module->author_uri) && $xml_module->author_uri ? stripslashes($xml_module->author_uri) : false; if (isset($xml_module->confirmUninstall)) { $item->confirmUninstall = Translate::getModuleTranslation((string) $xml_module->name, html_entity_decode(Module::configXmlStringFormat($xml_module->confirmUninstall)), (string) $xml_module->name); } $item->active = 0; $item->onclick_option = false; $item->trusted = Module::isModuleTrusted($item->name); $module_list[$item->name . '_disk'] = $item; $module_name_list[] = '\'' . pSQL($item->name) . '\''; $modules_name_to_cursor[Tools::strtolower(strval($item->name))] = $item; } } // If use config flag is at false or config.xml does not exist OR need instance OR need a new config.xml file if (!$use_config || !$xml_exist || isset($xml_module->need_instance) && (int) $xml_module->need_instance == 1 || $need_new_config_file) { // If class does not exists, we include the file if (!class_exists($module, false)) { // Get content from php file $file_path = _PS_MODULE_DIR_ . $module . '/' . $module . '.php'; $file = trim(file_get_contents(_PS_MODULE_DIR_ . $module . '/' . $module . '.php')); if (substr($file, 0, 5) == '<?php') { $file = substr($file, 5); } if (substr($file, -2) == '?>') { $file = substr($file, 0, -2); } // We check any parse error before including the file. // If (false) is a trick to not load the class with "eval". // This way require_once will works correctly // But namespace and use statements need to be removed $content = preg_replace('/\\n[\\s\\t]*?use\\s.*?;/', '', $file); $content = preg_replace('/\\n[\\s\\t]*?namespace\\s.*?;/', '', $content); try { if (substr(`php -l {$file_path}`, 0, 16) == 'No syntax errors' || eval('if (false){ ' . $content . ' }') !== false) { require_once _PS_MODULE_DIR_ . $module . '/' . $module . '.php'; } else { throw new ParseError("Parse error"); } } catch (ParseError $e) { $errors[] = sprintf(Tools::displayError('%1$s (parse error in %2$s)'), $module, substr($file_path, strlen(_PS_ROOT_DIR_))); } preg_match('/\\n[\\s\\t]*?namespace\\s.*?;/', $file, $ns); if (!empty($ns)) { $ns = preg_replace('/\\n[\\s\\t]*?namespace\\s/', '', $ns[0]); $ns = rtrim($ns, ';'); $module = $ns . '\\' . $module; } } // If class exists, we just instanciate it if (class_exists($module, false)) { try { $tmp_module = \PrestaShop\PrestaShop\Adapter\ServiceLocator::get($module); $item = new stdClass(); $item->id = (int) $tmp_module->id; $item->warning = $tmp_module->warning; $item->name = $tmp_module->name; $item->version = $tmp_module->version; $item->tab = $tmp_module->tab; $item->displayName = $tmp_module->displayName; $item->description = stripslashes($tmp_module->description); $item->author = $tmp_module->author; $item->author_uri = isset($tmp_module->author_uri) && $tmp_module->author_uri ? $tmp_module->author_uri : false; $item->limited_countries = $tmp_module->limited_countries; $item->parent_class = get_parent_class($module); $item->is_configurable = $tmp_module->is_configurable = method_exists($tmp_module, 'getContent') ? 1 : 0; $item->need_instance = isset($tmp_module->need_instance) ? $tmp_module->need_instance : 0; $item->active = $tmp_module->active; $item->trusted = Module::isModuleTrusted($tmp_module->name); $item->currencies = isset($tmp_module->currencies) ? $tmp_module->currencies : null; $item->currencies_mode = isset($tmp_module->currencies_mode) ? $tmp_module->currencies_mode : null; $item->confirmUninstall = isset($tmp_module->confirmUninstall) ? html_entity_decode($tmp_module->confirmUninstall) : null; $item->description_full = stripslashes($tmp_module->description_full); $item->additional_description = isset($tmp_module->additional_description) ? stripslashes($tmp_module->additional_description) : null; $item->compatibility = isset($tmp_module->compatibility) ? (array) $tmp_module->compatibility : null; $item->nb_rates = isset($tmp_module->nb_rates) ? (array) $tmp_module->nb_rates : null; $item->avg_rate = isset($tmp_module->avg_rate) ? (array) $tmp_module->avg_rate : null; $item->badges = isset($tmp_module->badges) ? (array) $tmp_module->badges : null; $item->url = isset($tmp_module->url) ? $tmp_module->url : null; $item->onclick_option = method_exists($module, 'onclickOption') ? true : false; if ($item->onclick_option) { $href = Context::getContext()->link->getAdminLink('Module', true) . '&module_name=' . $tmp_module->name . '&tab_module=' . $tmp_module->tab; $item->onclick_option_content = array(); $option_tab = array('desactive', 'reset', 'configure', 'delete'); foreach ($option_tab as $opt) { $item->onclick_option_content[$opt] = $tmp_module->onclickOption($opt, $href); } } $module_list[$item->name . '_disk'] = $item; if (!$xml_exist || $need_new_config_file) { self::$_generate_config_xml_mode = true; $tmp_module->_generateConfigXml(); self::$_generate_config_xml_mode = false; } unset($tmp_module); } catch (Exception $e) { } } else { $module_errors[] = sprintf(Tools::displayError('%1$s (class missing in %2$s)'), $module, substr($file_path, strlen(_PS_ROOT_DIR_))); } } $errors = array_merge($errors, $module_errors); } // Get modules information from database if (!empty($module_name_list)) { $list = Shop::getContextListShopID(); $sql = 'SELECT m.id_module, m.name, ( SELECT COUNT(*) FROM ' . _DB_PREFIX_ . 'module_shop ms WHERE m.id_module = ms.id_module AND ms.id_shop IN (' . implode(',', $list) . ') ) as total FROM ' . _DB_PREFIX_ . 'module m WHERE LOWER(m.name) IN (' . Tools::strtolower(implode(',', $module_name_list)) . ')'; $results = Db::getInstance()->executeS($sql); foreach ($results as $result) { if (isset($modules_name_to_cursor[Tools::strtolower($result['name'])])) { $module_cursor = $modules_name_to_cursor[Tools::strtolower($result['name'])]; $module_cursor->id = (int) $result['id_module']; $module_cursor->active = $result['total'] == count($list) ? 1 : 0; } } } // Get Default Country Modules and customer module $files_list = array(array('type' => 'addonsNative', 'file' => _PS_ROOT_DIR_ . self::CACHE_FILE_DEFAULT_COUNTRY_MODULES_LIST, 'loggedOnAddons' => 0), array('type' => 'addonsMustHave', 'file' => _PS_ROOT_DIR_ . self::CACHE_FILE_MUST_HAVE_MODULES_LIST, 'loggedOnAddons' => 0), array('type' => 'addonsBought', 'file' => _PS_ROOT_DIR_ . self::CACHE_FILE_CUSTOMER_MODULES_LIST, 'loggedOnAddons' => 1)); foreach ($files_list as $f) { if (file_exists($f['file']) && ($f['loggedOnAddons'] == 0 || $logged_on_addons)) { if (Module::useTooMuchMemory()) { $errors[] = Tools::displayError('All modules cannot be loaded due to memory limit restrictions, please increase your memory_limit value on your server configuration'); break; } $file = $f['file']; $content = Tools::file_get_contents($file); $xml = @simplexml_load_string($content, null, LIBXML_NOCDATA); if ($xml && isset($xml->module)) { foreach ($xml->module as $modaddons) { $flag_found = 0; foreach ($module_list as $k => &$m) { if (Tools::strtolower($m->name) == Tools::strtolower($modaddons->name) && !isset($m->available_on_addons)) { $flag_found = 1; if ($m->version != $modaddons->version && version_compare($m->version, $modaddons->version) === -1) { $module_list[$k]->version_addons = $modaddons->version; } } } if ($flag_found == 0) { $item = new stdClass(); $item->id = 0; $item->warning = ''; $item->type = strip_tags((string) $f['type']); $item->name = strip_tags((string) $modaddons->name); $item->version = strip_tags((string) $modaddons->version); $item->tab = strip_tags((string) $modaddons->tab); $item->displayName = strip_tags((string) $modaddons->displayName); $item->description = stripslashes(strip_tags((string) $modaddons->description)); $item->description_full = stripslashes(strip_tags((string) $modaddons->description_full)); $item->author = strip_tags((string) $modaddons->author); $item->limited_countries = array(); $item->parent_class = ''; $item->onclick_option = false; $item->is_configurable = 0; $item->need_instance = 0; $item->not_on_disk = 1; $item->available_on_addons = 1; $item->trusted = Module::isModuleTrusted($item->name); $item->active = 0; $item->description_full = stripslashes($modaddons->description_full); $item->additional_description = isset($modaddons->additional_description) ? stripslashes($modaddons->additional_description) : null; $item->compatibility = isset($modaddons->compatibility) ? (array) $modaddons->compatibility : null; $item->nb_rates = isset($modaddons->nb_rates) ? (array) $modaddons->nb_rates : null; $item->avg_rate = isset($modaddons->avg_rate) ? (array) $modaddons->avg_rate : null; $item->badges = isset($modaddons->badges) ? (array) $modaddons->badges : null; $item->url = isset($modaddons->url) ? $modaddons->url : null; if (isset($item->description_full) && trim($item->description_full) != '') { $item->show_quick_view = true; } if (isset($modaddons->img)) { $item->image = Module::copyModAddonsImg($modaddons); } if ($item->type == 'addonsMustHave') { $item->addons_buy_url = strip_tags((string) $modaddons->url); $prices = (array) $modaddons->price; $id_default_currency = Configuration::get('PS_CURRENCY_DEFAULT'); foreach ($prices as $currency => $price) { if ($id_currency = Currency::getIdByIsoCode($currency)) { $item->price = (double) $price; $item->id_currency = (int) $id_currency; if ($id_default_currency == $id_currency) { break; } } } } $module_list[$item->name . '_feed'] = $item; } if (isset($module_list[$modaddons->name . '_disk'])) { $module_list[$modaddons->name . '_disk']->description_full = stripslashes(strip_tags((string) $modaddons->description_full)); $module_list[$modaddons->name . '_disk']->additional_description = stripslashes(strip_tags((string) $modaddons->additional_description)); $module_list[$modaddons->name . '_disk']->image = Module::copyModAddonsImg($modaddons); $module_list[$modaddons->name . '_disk']->show_quick_view = true; } } } } } foreach ($module_list as $key => &$module) { if (defined('_PS_HOST_MODE_') && in_array($module->name, self::$hosted_modules_blacklist)) { unset($module_list[$key]); } elseif (isset($modules_installed[$module->name])) { $module->installed = true; $module->database_version = $modules_installed[$module->name]['version']; $module->interest = $modules_installed[$module->name]['interest']; $module->enable_device = $modules_installed[$module->name]['enable_device']; } else { $module->installed = false; $module->database_version = 0; $module->interest = 0; } } usort($module_list, create_function('$a,$b', 'return strnatcasecmp($a->displayName, $b->displayName);')); if ($errors) { if (!isset(Context::getContext()->controller) && !Context::getContext()->controller->controller_name) { echo '<div class="alert error"><h3>' . Tools::displayError('The following module(s) could not be loaded') . ':</h3><ol>'; foreach ($errors as $error) { echo '<li>' . $error . '</li>'; } echo '</ol></div>'; } else { foreach ($errors as $error) { Context::getContext()->controller->errors[] = $error; } } } return $module_list; }
function ajaxProcessRegenerateMethod() { $process = array('categories' => _PS_CAT_IMG_DIR_, 'manufacturers' => _PS_MANU_IMG_DIR_, 'suppliers' => _PS_SUPP_IMG_DIR_, 'scenes' => _PS_SCENE_IMG_DIR_, 'products' => _PS_PROD_IMG_DIR_, 'stores' => _PS_STORE_IMG_DIR_); $baseType = Tools::getValue('type'); $type = ImageType::getImagesTypes($baseType); $image = Tools::getValue('image'); $watermark = (int) Tools::getValue('watermark'); $dir = $process[$baseType]; $success = null; $errors = null; $watermarked = 0; if ($baseType != "products") { if (preg_match('/^[0-9]*\\.jpg$/', $image)) { foreach ($type as $k => $imageType) { // Customizable writing dir $newDir = $dir; if ($imageType['name'] == 'thumb_scene') { $newDir .= 'thumbs/'; } if (!file_exists($newDir)) { $errors = 1; } $newFile = $newDir . substr($image, 0, -4) . '-' . stripslashes($imageType['name']) . '.jpg'; if (file_exists($newFile) && !unlink($newFile)) { $errors = 1; } if (!file_exists($newFile)) { if (!file_exists($dir . $image) || !filesize($dir . $image)) { $errors = sprintf(Tools::displayError('Source file does not exist or is empty (%s)', $dir . $image)); } elseif (!ImageManager::resize($dir . $image, $newFile, (int) $imageType['width'], (int) $imageType['height'])) { $errors = 1; } else { $success = 1; } } else { $errors = 1; } } } else { $success = 1; } } else { $imageObj = new Image($image); $existing_img = $dir . $imageObj->getExistingImgPath() . '.jpg'; if (file_exists($existing_img) && filesize($existing_img)) { if ($watermark == 1) { $watermarked = 1; $watermark = ModuleCore::getInstanceByName("watermark"); $valid_types = array(); $watermark_types = explode(',', Configuration::get('WATERMARK_TYPES')); foreach ($type as $k => $t) { if (in_array($t['id_image_type'], $watermark_types)) { $valid_types[] = $t; unset($type[$k]); } } if ($watermark->hookActionWatermark(array('image_type' => $valid_types, 'id_image' => $imageObj->id_image, 'id_product' => $imageObj->id_product))) { $success = 1; } else { $errors = 1; } } if (count($type) > 0) { foreach ($type as $imageType) { $newFile = $dir . $imageObj->getExistingImgPath() . '-' . stripslashes($imageType['name']) . '.jpg'; if (file_exists($newFile) && !unlink($newFile)) { $errors = 1; } if (!file_exists($newFile)) { if (!ImageManager::resize($existing_img, $newFile, (int) $imageType['width'], (int) $imageType['height'])) { $errors = sprintf('Original image is corrupt (%s) or bad permission on folder', $existing_img); } else { $success = 1; } } else { $errors = 1; } } } } else { $errors = sprintf('Original image is missing or empty (%s)', $existing_img); } } echo json_encode(array('success' => $success, 'error' => $errors, 'watermark' => $watermarked)); exit; }
* http://opensource.org/licenses/AFL-3.0 * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to interfaces@shopgate.com so we can send you a copy immediately. * * @author Shopgate GmbH, Schloßstraße 10, 35510 Butzbach <*****@*****.**> * @copyright Shopgate GmbH * @license http://opensource.org/licenses/AFL-3.0 Academic Free License ("AFL"), in the version 3.0 */ require_once dirname(__FILE__) . '/../../config/config.inc.php'; require_once dirname(__FILE__) . '/shopgate.php'; require_once dirname(__FILE__) . '/override/classes/Cart.php'; if (version_compare(_PS_VERSION_, '1.4.0.2', '>=')) { $controller = new FrontController(); $controller->init(); $modules = ModuleCore::getModulesInstalled(); } else { // in versions before 1.4.0.2 FrontController doesn't exist require_once dirname(__FILE__) . '/../../init.php'; $modules = Module::getModulesInstalled(); } $moduleIsActive = 0; foreach ($modules as $key => $module) { if ($module['name'] == 'shopgate' && !empty($module['active'])) { $moduleIsActive = 1; } } if ($moduleIsActive == 0) { throw new ShopgateLibraryException(ShopgateLibraryException::UNKNOWN_ERROR_CODE, 'shopgate module is not installed!'); exit; }
public function getExceptions($id_hook) { if (self::$exceptionsCache == NULL and !is_array(self::$exceptionsCache)) { self::$exceptionsCache = array(); $result = Db::getInstance()->ExecuteS(' SELECT CONCAT(id_hook, \'-\', id_module) as `key`, `file_name` as value FROM `' . _DB_PREFIX_ . 'hook_module_exceptions`'); foreach ($result as $row) { if (empty($row['value'])) { continue; } if (!array_key_exists($row['key'], self::$exceptionsCache)) { self::$exceptionsCache[$row['key']] = array(); } self::$exceptionsCache[$row['key']][] = array('file_name' => $row['value']); } } return array_key_exists((int) $id_hook . '-' . (int) $this->id, self::$exceptionsCache) ? self::$exceptionsCache[(int) $id_hook . '-' . (int) $this->id] : array(); }
/** * Validate an order in database * Function called from a payment module * * @param integer $id_cart * @param integer $id_order_state * @param float $amount_paid Amount really paid by customer (in the default currency) * @param string $payment_method Payment method (eg. 'Credit card') * @param null $message Message to attach to order * @param array $extra_vars * @param null $currency_special * @param bool $dont_touch_amount * @param bool $secure_key * @param Shop $shop * * @return bool * @throws PrestaShopException */ public function validateOrder($id_cart, $id_order_state, $amount_paid, $payment_method = 'Unknown', $message = null, $extra_vars = array(), $currency_special = null, $dont_touch_amount = false, $secure_key = false, Shop $shop = null) { if (self::DEBUG_MODE) { PrestaShopLogger::addLog('PaymentModule::validateOrder - Function called', 1, null, 'Cart', (int) $id_cart, true); } $this->context->cart = new Cart($id_cart); $this->context->customer = new Customer($this->context->cart->id_customer); $this->context->language = new Language($this->context->cart->id_lang); $this->context->shop = $shop ? $shop : new Shop($this->context->cart->id_shop); ShopUrl::resetMainDomainCache(); $id_currency = $currency_special ? (int) $currency_special : (int) $this->context->cart->id_currency; $this->context->currency = new Currency($id_currency, null, $this->context->shop->id); if (Configuration::get('PS_TAX_ADDRESS_TYPE') == 'id_address_delivery') { $context_country = $this->context->country; } $order_status = new OrderState((int) $id_order_state, (int) $this->context->language->id); if (!Validate::isLoadedObject($order_status)) { PrestaShopLogger::addLog('PaymentModule::validateOrder - Order Status cannot be loaded', 3, null, 'Cart', (int) $id_cart, true); throw new PrestaShopException('Can\'t load Order status'); } if (!$this->active) { PrestaShopLogger::addLog('PaymentModule::validateOrder - Module is not active', 3, null, 'Cart', (int) $id_cart, true); die(Tools::displayError()); } // Does order already exists ? if (Validate::isLoadedObject($this->context->cart) && $this->context->cart->OrderExists() == false) { if ($secure_key !== false && $secure_key != $this->context->cart->secure_key) { PrestaShopLogger::addLog('PaymentModule::validateOrder - Secure key does not match', 3, null, 'Cart', (int) $id_cart, true); die(Tools::displayError()); } // For each package, generate an order $delivery_option_list = $this->context->cart->getDeliveryOptionList(); $package_list = $this->context->cart->getPackageList(); $cart_delivery_option = $this->context->cart->getDeliveryOption(); // If some delivery options are not defined, or not valid, use the first valid option foreach ($delivery_option_list as $id_address => $package) { if (!isset($cart_delivery_option[$id_address]) || !array_key_exists($cart_delivery_option[$id_address], $package)) { foreach ($package as $key => $val) { $cart_delivery_option[$id_address] = $key; break; } } } $order_list = array(); $order_detail_list = array(); do { $reference = Order::generateReference(); } while (Order::getByReference($reference)->count()); $this->currentOrderReference = $reference; $order_creation_failed = false; $cart_total_paid = (double) Tools::ps_round((double) $this->context->cart->getOrderTotal(true, Cart::BOTH), 2); foreach ($cart_delivery_option as $id_address => $key_carriers) { foreach ($delivery_option_list[$id_address][$key_carriers]['carrier_list'] as $id_carrier => $data) { foreach ($data['package_list'] as $id_package) { // Rewrite the id_warehouse $package_list[$id_address][$id_package]['id_warehouse'] = (int) $this->context->cart->getPackageIdWarehouse($package_list[$id_address][$id_package], (int) $id_carrier); $package_list[$id_address][$id_package]['id_carrier'] = $id_carrier; } } } // Make sure CarRule caches are empty CartRule::cleanCache(); $cart_rules = $this->context->cart->getCartRules(); foreach ($cart_rules as $cart_rule) { if (($rule = new CartRule((int) $cart_rule['obj']->id)) && Validate::isLoadedObject($rule)) { if ($error = $rule->checkValidity($this->context, true, true)) { $this->context->cart->removeCartRule((int) $rule->id); if (isset($this->context->cookie) && isset($this->context->cookie->id_customer) && $this->context->cookie->id_customer && !empty($rule->code)) { if (Configuration::get('PS_ORDER_PROCESS_TYPE') == 1) { Tools::redirect('index.php?controller=order-opc&submitAddDiscount=1&discount_name=' . urlencode($rule->code)); } Tools::redirect('index.php?controller=order&submitAddDiscount=1&discount_name=' . urlencode($rule->code)); } else { $rule_name = isset($rule->name[(int) $this->context->cart->id_lang]) ? $rule->name[(int) $this->context->cart->id_lang] : $rule->code; $error = Tools::displayError(sprintf('CartRule ID %1s (%2s) used in this cart is not valid and has been withdrawn from cart', (int) $rule->id, $rule_name)); PrestaShopLogger::addLog($error, 3, '0000002', 'Cart', (int) $this->context->cart->id); } } } } foreach ($package_list as $id_address => $packageByAddress) { foreach ($packageByAddress as $id_package => $package) { $order = new Order(); $order->product_list = $package['product_list']; if (Configuration::get('PS_TAX_ADDRESS_TYPE') == 'id_address_delivery') { $address = new Address($id_address); $this->context->country = new Country($address->id_country, $this->context->cart->id_lang); if (!$this->context->country->active) { throw new PrestaShopException('The delivery address country is not active.'); } } $carrier = null; if (!$this->context->cart->isVirtualCart() && isset($package['id_carrier'])) { $carrier = new Carrier($package['id_carrier'], $this->context->cart->id_lang); $order->id_carrier = (int) $carrier->id; $id_carrier = (int) $carrier->id; } else { $order->id_carrier = 0; $id_carrier = 0; } $order->id_customer = (int) $this->context->cart->id_customer; $order->id_address_invoice = (int) $this->context->cart->id_address_invoice; $order->id_address_delivery = (int) $id_address; $order->id_currency = $this->context->currency->id; $order->id_lang = (int) $this->context->cart->id_lang; $order->id_cart = (int) $this->context->cart->id; $order->reference = $reference; $order->id_shop = (int) $this->context->shop->id; $order->id_shop_group = (int) $this->context->shop->id_shop_group; $order->date_in_hand = $this->context->cart->date_in_hand; $order->secure_key = $secure_key ? pSQL($secure_key) : pSQL($this->context->customer->secure_key); $order->payment = $payment_method; if (isset($this->name)) { $order->module = $this->name; } $order->recyclable = $this->context->cart->recyclable; $order->gift = (int) $this->context->cart->gift; $order->gift_message = $this->context->cart->gift_message; $order->mobile_theme = $this->context->cart->mobile_theme; $order->conversion_rate = $this->context->currency->conversion_rate; $amount_paid = !$dont_touch_amount ? Tools::ps_round((double) $amount_paid, 2) : $amount_paid; $order->total_paid_real = 0; $order->total_products = (double) $this->context->cart->getOrderTotal(false, Cart::ONLY_PRODUCTS, $order->product_list, $id_carrier); $order->total_products_wt = (double) $this->context->cart->getOrderTotal(true, Cart::ONLY_PRODUCTS, $order->product_list, $id_carrier); $order->total_discounts_tax_excl = (double) abs($this->context->cart->getOrderTotal(false, Cart::ONLY_DISCOUNTS, $order->product_list, $id_carrier)); $order->total_discounts_tax_incl = (double) abs($this->context->cart->getOrderTotal(true, Cart::ONLY_DISCOUNTS, $order->product_list, $id_carrier)); $order->total_discounts = $order->total_discounts_tax_incl; $order->total_shipping_tax_excl = (double) $this->context->cart->getPackageShippingCost((int) $id_carrier, false, null, $order->product_list); $order->total_shipping_tax_incl = (double) $this->context->cart->getPackageShippingCost((int) $id_carrier, true, null, $order->product_list); $order->total_shipping = $order->total_shipping_tax_incl; if (!is_null($carrier) && Validate::isLoadedObject($carrier)) { $order->carrier_tax_rate = $carrier->getTaxesRate(new Address($this->context->cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')})); } $order->total_wrapping_tax_excl = (double) abs($this->context->cart->getOrderTotal(false, Cart::ONLY_WRAPPING, $order->product_list, $id_carrier)); $order->total_wrapping_tax_incl = (double) abs($this->context->cart->getOrderTotal(true, Cart::ONLY_WRAPPING, $order->product_list, $id_carrier)); $order->total_wrapping = $order->total_wrapping_tax_incl; $order->total_paid_tax_excl = (double) Tools::ps_round((double) $this->context->cart->getOrderTotal(false, Cart::BOTH, $order->product_list, $id_carrier), 2); $order->total_paid_tax_incl = (double) Tools::ps_round((double) $this->context->cart->getOrderTotal(true, Cart::BOTH, $order->product_list, $id_carrier), 2); $order->total_paid = $order->total_paid_tax_incl; $order->invoice_date = '0000-00-00 00:00:00'; $order->delivery_date = '0000-00-00 00:00:00'; if (self::DEBUG_MODE) { PrestaShopLogger::addLog('PaymentModule::validateOrder - Order is about to be added', 1, null, 'Cart', (int) $id_cart, true); } // Creating order $result = $order->add(); if (!$result) { PrestaShopLogger::addLog('PaymentModule::validateOrder - Order cannot be created', 3, null, 'Cart', (int) $id_cart, true); throw new PrestaShopException('Can\'t save Order'); } // Amount paid by customer is not the right one -> Status = payment error // We don't use the following condition to avoid the float precision issues : http://www.php.net/manual/en/language.types.float.php // if ($order->total_paid != $order->total_paid_real) // We use number_format in order to compare two string if ($order_status->logable && number_format($cart_total_paid, 2) != number_format($amount_paid, 2)) { $id_order_state = Configuration::get('PS_OS_ERROR'); } $order_list[] = $order; if (self::DEBUG_MODE) { PrestaShopLogger::addLog('PaymentModule::validateOrder - OrderDetail is about to be added', 1, null, 'Cart', (int) $id_cart, true); } // Insert new Order detail list using cart for the current order $order_detail = new OrderDetail(null, null, $this->context); $order_detail->createList($order, $this->context->cart, $id_order_state, $order->product_list, 0, true, $package_list[$id_address][$id_package]['id_warehouse']); $order_detail_list[] = $order_detail; if (self::DEBUG_MODE) { PrestaShopLogger::addLog('PaymentModule::validateOrder - OrderCarrier is about to be added', 1, null, 'Cart', (int) $id_cart, true); } // Adding an entry in order_carrier table if (!is_null($carrier)) { $order_carrier = new OrderCarrier(); $order_carrier->id_order = (int) $order->id; $order_carrier->id_carrier = (int) $id_carrier; $order_carrier->weight = (double) $order->getTotalWeight(); $order_carrier->shipping_cost_tax_excl = (double) $order->total_shipping_tax_excl; $order_carrier->shipping_cost_tax_incl = (double) $order->total_shipping_tax_incl; $order_carrier->add(); } } } // The country can only change if the address used for the calculation is the delivery address, and if multi-shipping is activated if (Configuration::get('PS_TAX_ADDRESS_TYPE') == 'id_address_delivery') { $this->context->country = $context_country; } if (!$this->context->country->active) { PrestaShopLogger::addLog('PaymentModule::validateOrder - Country is not active', 3, null, 'Cart', (int) $id_cart, true); throw new PrestaShopException('The order address country is not active.'); } if (self::DEBUG_MODE) { PrestaShopLogger::addLog('PaymentModule::validateOrder - Payment is about to be added', 1, null, 'Cart', (int) $id_cart, true); } // Register Payment only if the order status validate the order if ($order_status->logable) { // $order is the last order loop in the foreach // The method addOrderPayment of the class Order make a create a paymentOrder // linked to the order reference and not to the order id if (isset($extra_vars['transaction_id'])) { $transaction_id = $extra_vars['transaction_id']; } else { $transaction_id = null; } if (!$order->addOrderPayment($amount_paid, null, $transaction_id)) { PrestaShopLogger::addLog('PaymentModule::validateOrder - Cannot save Order Payment', 3, null, 'Cart', (int) $id_cart, true); throw new PrestaShopException('Can\'t save Order Payment'); } } // Next ! $only_one_gift = false; $cart_rule_used = array(); $products = $this->context->cart->getProducts(); // Make sure CarRule caches are empty CartRule::cleanCache(); foreach ($order_detail_list as $key => $order_detail) { $order = $order_list[$key]; if (!$order_creation_failed && isset($order->id)) { if (!$secure_key) { $message .= '<br />' . Tools::displayError('Warning: the secure key is empty, check your payment account before validation'); } // Optional message to attach to this order if (isset($message) & !empty($message)) { $msg = new Message(); $message = strip_tags($message, '<br>'); if (Validate::isCleanHtml($message)) { if (self::DEBUG_MODE) { PrestaShopLogger::addLog('PaymentModule::validateOrder - Message is about to be added', 1, null, 'Cart', (int) $id_cart, true); } $msg->message = $message; $msg->id_order = intval($order->id); $msg->private = 1; $msg->add(); } } // Insert new Order detail list using cart for the current order //$orderDetail = new OrderDetail(null, null, $this->context); //$orderDetail->createList($order, $this->context->cart, $id_order_state); // Construct order detail table for the email $products_list = ''; $virtual_product = true; $product_var_tpl_list = array(); foreach ($order->product_list as $product) { $price = Product::getPriceStatic((int) $product['id_product'], false, $product['id_product_attribute'] ? (int) $product['id_product_attribute'] : null, 6, null, false, true, $product['cart_quantity'], false, (int) $order->id_customer, (int) $order->id_cart, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')}); $price_wt = Product::getPriceStatic((int) $product['id_product'], true, $product['id_product_attribute'] ? (int) $product['id_product_attribute'] : null, 2, null, false, true, $product['cart_quantity'], false, (int) $order->id_customer, (int) $order->id_cart, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')}); $product_price = Product::getTaxCalculationMethod() == PS_TAX_EXC ? Tools::ps_round($price, 2) : $price_wt; $product_var_tpl = array('reference' => $product['reference'], 'name' => $product['name'] . (isset($product['attributes']) ? ' - ' . $product['attributes'] : ''), 'unit_price' => Tools::displayPrice($product_price, $this->context->currency, false), 'price' => Tools::displayPrice($product_price * $product['quantity'], $this->context->currency, false), 'quantity' => $product['quantity'], 'customization' => array()); $product_var_tpl['customization'] = array(); $customized_datas = Product::getAllCustomizedDatas((int) $order->id_cart); if (isset($customized_datas[$product['id_product']][$product['id_product_attribute']])) { foreach ($customized_datas[$product['id_product']][$product['id_product_attribute']][$order->id_address_delivery] as $customization) { $customization_text = ''; $i = 0; $row = 0; $deco_data = $customization['datas'][1]; foreach ($deco_data as $data1) { $row = $row + 1; if ($row > 2) { if ($i == 0) { $col1 = $data1['value']; $i = $i + 1; $row = $row + 1; continue; } if ($i == 1) { $col1_info = explode(";", $col1); $col2 = $data1['value']; $col2_info = explode(";", $col2); $inc = 0; foreach ($col1_info as $col1) { $customization_text .= '<tr id="product_' . $product['id_product'] . '_' . $product['id_product_attribute'] . '_' . $id_customization . '_' . $product['id_address_delivery'] . '"' . 'class="product_customization_for_' . $product['id_product'] . '_' . $product['id_product_attribute'] . '_' . $product['id_address_delivery']; if ($odd) { $customization_text .= ' odd'; } else { $customization_text .= ' even'; } $customization_text .= ' customization alternate_item '; $customization_text .= '"><td style="border:1px solid #D6D4D4; padding-left:2px;" colspan="4">' . $col1 . '</td>'; $customization_text .= '<td style="border:1px solid #D6D4D4; padding-left:20px;">'; $customization_text .= '<span>$' . $col2_info[$inc] . '</span>'; $inc = $inc + 1; $customization_text .= '</td>'; } $i = 0; } $customization_text .= '</tr>'; } } } $customization_quantity = (int) $product['customization_quantity']; $product_var_tpl['customization'][] = array('customization_text' => $customization_text, 'customization_quantity' => $customization_quantity, 'quantity' => Tools::displayPrice($customization_quantity * $product_price, $this->context->currency, false)); } $product_var_tpl_list[] = $product_var_tpl; // Check if is not a virutal product for the displaying of shipping if (!$product['is_virtual']) { $virtual_product &= false; } } // end foreach ($products) $product_list_txt = ''; $product_list_html = ''; if (count($product_var_tpl_list) > 0) { $product_list_txt = $this->getEmailTemplateContent('order_conf_product_list.txt', Mail::TYPE_TEXT, $product_var_tpl_list); $product_list_html = $this->getEmailTemplateContent('order_conf_product_list.tpl', Mail::TYPE_HTML, $product_var_tpl_list); } $cart_rules_list = array(); $total_reduction_value_ti = 0; $total_reduction_value_tex = 0; foreach ($cart_rules as $cart_rule) { $package = array('id_carrier' => $order->id_carrier, 'id_address' => $order->id_address_delivery, 'products' => $order->product_list); $values = array('tax_incl' => $cart_rule['obj']->getContextualValue(true, $this->context, CartRule::FILTER_ACTION_ALL_NOCAP, $package), 'tax_excl' => $cart_rule['obj']->getContextualValue(false, $this->context, CartRule::FILTER_ACTION_ALL_NOCAP, $package)); // If the reduction is not applicable to this order, then continue with the next one if (!$values['tax_excl']) { continue; } /* IF ** - This is not multi-shipping ** - The value of the voucher is greater than the total of the order ** - Partial use is allowed ** - This is an "amount" reduction, not a reduction in % or a gift ** THEN ** The voucher is cloned with a new value corresponding to the remainder */ if (count($order_list) == 1 && $values['tax_incl'] > $order->total_products_wt - $total_reduction_value_ti && $cart_rule['obj']->partial_use == 1 && $cart_rule['obj']->reduction_amount > 0) { // Create a new voucher from the original $voucher = new CartRule($cart_rule['obj']->id); // We need to instantiate the CartRule without lang parameter to allow saving it unset($voucher->id); // Set a new voucher code $voucher->code = empty($voucher->code) ? substr(md5($order->id . '-' . $order->id_customer . '-' . $cart_rule['obj']->id), 0, 16) : $voucher->code . '-2'; if (preg_match('/\\-([0-9]{1,2})\\-([0-9]{1,2})$/', $voucher->code, $matches) && $matches[1] == $matches[2]) { $voucher->code = preg_replace('/' . $matches[0] . '$/', '-' . (intval($matches[1]) + 1), $voucher->code); } // Set the new voucher value if ($voucher->reduction_tax) { $voucher->reduction_amount = $values['tax_incl'] - ($order->total_products_wt - $total_reduction_value_ti); // Add total shipping amout only if reduction amount > total shipping if ($voucher->free_shipping == 1 && $voucher->reduction_amount >= $order->total_shipping_tax_incl) { $voucher->reduction_amount -= $order->total_shipping_tax_incl; } } else { $voucher->reduction_amount = $values['tax_excl'] - ($order->total_products - $total_reduction_value_tex); // Add total shipping amout only if reduction amount > total shipping if ($voucher->free_shipping == 1 && $voucher->reduction_amount >= $order->total_shipping_tax_excl) { $voucher->reduction_amount -= $order->total_shipping_tax_excl; } } $voucher->id_customer = $order->id_customer; $voucher->quantity = 1; $voucher->quantity_per_user = 1; $voucher->free_shipping = 0; if ($voucher->add()) { // If the voucher has conditions, they are now copied to the new voucher CartRule::copyConditions($cart_rule['obj']->id, $voucher->id); $params = array('{voucher_amount}' => Tools::displayPrice($voucher->reduction_amount, $this->context->currency, false), '{voucher_num}' => $voucher->code, '{firstname}' => $this->context->customer->firstname, '{lastname}' => $this->context->customer->lastname, '{id_order}' => $order->reference, '{order_name}' => $order->getUniqReference()); Mail::Send((int) $order->id_lang, 'voucher', sprintf(Mail::l('New voucher for your order %s', (int) $order->id_lang), $order->reference), $params, $this->context->customer->email, $this->context->customer->firstname . ' ' . $this->context->customer->lastname, null, null, null, null, _PS_MAIL_DIR_, false, (int) $order->id_shop); } $values['tax_incl'] -= $values['tax_incl'] - $order->total_products_wt; $values['tax_excl'] -= $values['tax_excl'] - $order->total_products; } $total_reduction_value_ti += $values['tax_incl']; $total_reduction_value_tex += $values['tax_excl']; $order->addCartRule($cart_rule['obj']->id, $cart_rule['obj']->name, $values, 0, $cart_rule['obj']->free_shipping); if ($id_order_state != Configuration::get('PS_OS_ERROR') && $id_order_state != Configuration::get('PS_OS_CANCELED') && !in_array($cart_rule['obj']->id, $cart_rule_used)) { $cart_rule_used[] = $cart_rule['obj']->id; // Create a new instance of Cart Rule without id_lang, in order to update its quantity $cart_rule_to_update = new CartRule($cart_rule['obj']->id); $cart_rule_to_update->quantity = max(0, $cart_rule_to_update->quantity - 1); $cart_rule_to_update->update(); } $cart_rules_list[] = array('voucher_name' => $cart_rule['obj']->name, 'voucher_reduction' => ($values['tax_incl'] != 0.0 ? '-' : '') . Tools::displayPrice($values['tax_incl'], $this->context->currency, false)); } $cart_rules_list_txt = ''; $cart_rules_list_html = ''; if (count($cart_rules_list) > 0) { $cart_rules_list_txt = $this->getEmailTemplateContent('order_conf_cart_rules.txt', Mail::TYPE_TEXT, $cart_rules_list); $cart_rules_list_html = $this->getEmailTemplateContent('order_conf_cart_rules.tpl', Mail::TYPE_HTML, $cart_rules_list); } // Specify order id for message $old_message = Message::getMessageByCartId((int) $this->context->cart->id); if ($old_message) { $update_message = new Message((int) $old_message['id_message']); $update_message->id_order = (int) $order->id; $update_message->update(); // Add this message in the customer thread $customer_thread = new CustomerThread(); $customer_thread->id_contact = 0; $customer_thread->id_customer = (int) $order->id_customer; $customer_thread->id_shop = (int) $this->context->shop->id; $customer_thread->id_order = (int) $order->id; $customer_thread->id_lang = (int) $this->context->language->id; $customer_thread->email = $this->context->customer->email; $customer_thread->status = 'open'; $customer_thread->token = Tools::passwdGen(12); $customer_thread->add(); $customer_message = new CustomerMessage(); $customer_message->id_customer_thread = $customer_thread->id; $customer_message->id_employee = 0; $customer_message->message = $update_message->message; $customer_message->private = 0; if (!$customer_message->add()) { $this->errors[] = Tools::displayError('An error occurred while saving message'); } } if (self::DEBUG_MODE) { PrestaShopLogger::addLog('PaymentModule::validateOrder - Hook validateOrder is about to be called', 1, null, 'Cart', (int) $id_cart, true); } // Hook validate order Hook::exec('actionValidateOrder', array('cart' => $this->context->cart, 'order' => $order, 'customer' => $this->context->customer, 'currency' => $this->context->currency, 'orderStatus' => $order_status)); foreach ($this->context->cart->getProducts() as $product) { if ($order_status->logable) { ProductSale::addProductSale((int) $product['id_product'], (int) $product['cart_quantity']); } } if (self::DEBUG_MODE) { PrestaShopLogger::addLog('PaymentModule::validateOrder - Order Status is about to be added', 1, null, 'Cart', (int) $id_cart, true); } // Set the order status $new_history = new OrderHistory(); $new_history->id_order = (int) $order->id; $new_history->changeIdOrderState((int) $id_order_state, $order, true); $new_history->addWithemail(true, $extra_vars); // Switch to back order if needed if (Configuration::get('PS_STOCK_MANAGEMENT') && $order_detail->getStockState()) { $history = new OrderHistory(); $history->id_order = (int) $order->id; $history->changeIdOrderState(Configuration::get('PS_OS_OUTOFSTOCK'), $order, true); $history->addWithemail(); } unset($order_detail); // Order is reloaded because the status just changed $order = new Order($order->id); // Send an e-mail to customer (one order = one email) if ($id_order_state != Configuration::get('PS_OS_ERROR') && $id_order_state != Configuration::get('PS_OS_CANCELED') && $this->context->customer->id) { $invoice = new Address($order->id_address_invoice); $delivery = new Address($order->id_address_delivery); $delivery_state = $delivery->id_state ? new State($delivery->id_state) : false; $invoice_state = $invoice->id_state ? new State($invoice->id_state) : false; $data = array('{firstname}' => $this->context->customer->firstname, '{lastname}' => $this->context->customer->lastname, '{email}' => $this->context->customer->email, '{delivery_block_txt}' => $this->_getFormatedAddress($delivery, "\n"), '{invoice_block_txt}' => $this->_getFormatedAddress($invoice, "\n"), '{delivery_block_html}' => $this->_getFormatedAddress($delivery, '<br />', array('firstname' => '<span style="font-weight:bold;">%s</span>', 'lastname' => '<span style="font-weight:bold;">%s</span>')), '{invoice_block_html}' => $this->_getFormatedAddress($invoice, '<br />', array('firstname' => '<span style="font-weight:bold;">%s</span>', 'lastname' => '<span style="font-weight:bold;">%s</span>')), '{delivery_company}' => $delivery->company, '{delivery_firstname}' => $delivery->firstname, '{delivery_lastname}' => $delivery->lastname, '{delivery_address1}' => $delivery->address1, '{delivery_address2}' => $delivery->address2, '{delivery_city}' => $delivery->city, '{delivery_postal_code}' => $delivery->postcode, '{delivery_country}' => $delivery->country, '{delivery_state}' => $delivery->id_state ? $delivery_state->name : '', '{delivery_phone}' => $delivery->phone ? $delivery->phone : $delivery->phone_mobile, '{delivery_other}' => $delivery->other, '{invoice_company}' => $invoice->company, '{invoice_vat_number}' => $invoice->vat_number, '{invoice_firstname}' => $invoice->firstname, '{invoice_lastname}' => $invoice->lastname, '{invoice_address2}' => $invoice->address2, '{invoice_address1}' => $invoice->address1, '{invoice_city}' => $invoice->city, '{invoice_postal_code}' => $invoice->postcode, '{invoice_country}' => $invoice->country, '{invoice_state}' => $invoice->id_state ? $invoice_state->name : '', '{invoice_phone}' => $invoice->phone ? $invoice->phone : $invoice->phone_mobile, '{invoice_other}' => $invoice->other, '{order_name}' => $order->getUniqReference(), '{date}' => Tools::displayDate(date('Y-m-d H:i:s'), null, 1), '{carrier}' => $virtual_product || !isset($carrier->name) ? Tools::displayError('No carrier') : $carrier->name, '{payment}' => Tools::substr($order->payment, 0, 32), '{products}' => $product_list_html, '{products_txt}' => $product_list_txt, '{discounts}' => $cart_rules_list_html, '{discounts_txt}' => $cart_rules_list_txt, '{total_paid}' => Tools::displayPrice($order->total_paid, $this->context->currency, false), '{total_products}' => Tools::displayPrice($order->total_paid - $order->total_shipping - $order->total_wrapping + $order->total_discounts, $this->context->currency, false), '{total_discounts}' => Tools::displayPrice($order->total_discounts, $this->context->currency, false), '{total_shipping}' => Tools::displayPrice($order->total_shipping, $this->context->currency, false), '{total_wrapping}' => Tools::displayPrice($order->total_wrapping, $this->context->currency, false), '{total_tax_paid}' => Tools::displayPrice($order->total_products_wt - $order->total_products + ($order->total_shipping_tax_incl - $order->total_shipping_tax_excl), $this->context->currency, false)); if (is_array($extra_vars)) { $data = array_merge($data, $extra_vars); } // Join PDF invoice if ((int) Configuration::get('PS_INVOICE') && $order_status->invoice && $order->invoice_number) { $pdf = new PDF($order->getInvoicesCollection(), PDF::TEMPLATE_INVOICE, $this->context->smarty); $file_attachement['content'] = $pdf->render(false); $file_attachement['name'] = Configuration::get('PS_INVOICE_PREFIX', (int) $order->id_lang, null, $order->id_shop) . sprintf('%06d', $order->invoice_number) . '.pdf'; $file_attachement['mime'] = 'application/pdf'; } else { $file_attachement = null; } if (self::DEBUG_MODE) { PrestaShopLogger::addLog('PaymentModule::validateOrder - Mail is about to be sent', 1, null, 'Cart', (int) $id_cart, true); } if (Validate::isEmail($this->context->customer->email)) { Mail::Send((int) $order->id_lang, 'order_conf', Mail::l('Order confirmation', (int) $order->id_lang), $data, $this->context->customer->email, $this->context->customer->firstname . ' ' . $this->context->customer->lastname, null, null, $file_attachement, null, _PS_MAIL_DIR_, false, (int) $order->id_shop); } $manager_approval = Configuration::get('ADMIN_CONFIRM_ORDER'); if ($manager_approval == "1") { $adminorderapproval = ModuleCore::getInstanceByName("adminorderapproval"); //include PS_PRODUCT_IMG_PATH.'/modules/adminorderapproval/adminorderapproval.php'; //$adminorderapproval = new adminorderapproval(); //var_dump($adminorderapproval); $result = $adminorderapproval->sendAdminApprovalMail((int) $order->id, $data); } } // updates stock in shops if (Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT')) { $product_list = $order->getProducts(); foreach ($product_list as $product) { // if the available quantities depends on the physical stock if (StockAvailable::dependsOnStock($product['product_id'])) { // synchronizes StockAvailable::synchronize($product['product_id'], $order->id_shop); } } } } else { $error = Tools::displayError('Order creation failed'); PrestaShopLogger::addLog($error, 4, '0000002', 'Cart', intval($order->id_cart)); die($error); } } // End foreach $order_detail_list // Use the last order as currentOrder $this->currentOrder = (int) $order->id; if (self::DEBUG_MODE) { PrestaShopLogger::addLog('PaymentModule::validateOrder - End of validateOrder', 1, null, 'Cart', (int) $id_cart, true); } return true; } else { $error = Tools::displayError('Cart cannot be loaded or an order has already been placed using this cart'); PrestaShopLogger::addLog($error, 4, '0000001', 'Cart', intval($this->context->cart->id)); die($error); } }