public static function str2url($str)
 {
     static $allow_accented_chars = null;
     if ($allow_accented_chars === null) {
         $allow_accented_chars = Configuration::get('PS_ALLOW_ACCENTED_CHARS_URL');
     }
     $str = trim($str);
     if (function_exists('mb_strtolower')) {
         $str = mb_strtolower($str, 'utf-8');
     }
     if (!$allow_accented_chars) {
         $str = Tools::replaceAccentedChars($str);
     }
     // Remove all non-whitelist chars.
     if ($allow_accented_chars) {
         $str = preg_replace('/[^a-zA-Z0-9\\s\'\\:\\/\\[\\]-\\pL\\pM]/u', '', $str);
     } else {
         $str = preg_replace('/[^a-zA-Z0-9\\s\'\\:\\/\\[\\]-]/', '', $str);
     }
     $str = preg_replace('/[\\s\'\\:\\/\\[\\]-]+/', ' ', $str);
     $str = str_replace(array(' ', '/'), '-', $str);
     // If it was not possible to lowercase the string with mb_strtolower, we do it after the transformations.
     // This way we lose fewer special chars.
     if (!function_exists('mb_strtolower')) {
         $str = strtolower($str);
     }
     return $str;
 }
 /**
  * Assign template vars related to page content
  * @see FrontController::initContent()
  */
 public function initContent()
 {
     $original_query = Tools::getValue('q');
     $query = Tools::replaceAccentedChars(urldecode($original_query));
     if ($this->ajax_search) {
         $searchResults = Search::find((int) Tools::getValue('id_lang'), $query, 1, 10, 'position', 'desc', true);
         if (is_array($searchResults)) {
             foreach ($searchResults as &$product) {
                 $product['product_link'] = $this->context->link->getProductLink($product['id_product'], $product['prewrite'], $product['crewrite']);
             }
             Hook::exec('actionSearch', array('expr' => $query, 'total' => count($searchResults)));
         }
         $this->ajaxDie(Tools::jsonEncode($searchResults));
     }
     //Only controller content initialization when the user use the normal search
     parent::initContent();
     $product_per_page = isset($this->context->cookie->nb_item_per_page) ? (int) $this->context->cookie->nb_item_per_page : Configuration::get('PS_PRODUCTS_PER_PAGE');
     if ($this->instant_search && !is_array($query)) {
         $this->productSort();
         $this->n = abs((int) Tools::getValue('n', $product_per_page));
         $this->p = abs((int) Tools::getValue('p', 1));
         $search = Search::find($this->context->language->id, $query, 1, 10, 'position', 'desc');
         Hook::exec('actionSearch', array('expr' => $query, 'total' => $search['total']));
         $nbProducts = $search['total'];
         $this->pagination($nbProducts);
         $this->addColorsToProductList($search['result']);
         $this->context->smarty->assign(array('products' => $search['result'], 'search_products' => $search['result'], 'nbProducts' => $search['total'], 'search_query' => $original_query, 'instant_search' => $this->instant_search, 'homeSize' => Image::getSize(ImageType::getFormatedName('home'))));
     } elseif (($query = Tools::getValue('search_query', Tools::getValue('ref'))) && !is_array($query)) {
         $this->productSort();
         $this->n = abs((int) Tools::getValue('n', $product_per_page));
         $this->p = abs((int) Tools::getValue('p', 1));
         $original_query = $query;
         $query = Tools::replaceAccentedChars(urldecode($query));
         $search = Search::find($this->context->language->id, $query, $this->p, $this->n, $this->orderBy, $this->orderWay);
         if (is_array($search['result'])) {
             foreach ($search['result'] as &$product) {
                 $product['link'] .= (strpos($product['link'], '?') === false ? '?' : '&') . 'search_query=' . urlencode($query) . '&results=' . (int) $search['total'];
             }
         }
         Hook::exec('actionSearch', array('expr' => $query, 'total' => $search['total']));
         $nbProducts = $search['total'];
         $this->pagination($nbProducts);
         $this->addColorsToProductList($search['result']);
         $this->context->smarty->assign(array('products' => $search['result'], 'search_products' => $search['result'], 'nbProducts' => $search['total'], 'search_query' => $original_query, 'homeSize' => Image::getSize(ImageType::getFormatedName('home'))));
     } elseif (($tag = urldecode(Tools::getValue('tag'))) && !is_array($tag)) {
         $nbProducts = (int) Search::searchTag($this->context->language->id, $tag, true);
         $this->pagination($nbProducts);
         $result = Search::searchTag($this->context->language->id, $tag, false, $this->p, $this->n, $this->orderBy, $this->orderWay);
         Hook::exec('actionSearch', array('expr' => $tag, 'total' => count($result)));
         $this->addColorsToProductList($result);
         $this->context->smarty->assign(array('search_tag' => $tag, 'products' => $result, 'search_products' => $result, 'nbProducts' => $nbProducts, 'homeSize' => Image::getSize(ImageType::getFormatedName('home'))));
     } else {
         $this->context->smarty->assign(array('products' => array(), 'search_products' => array(), 'pages_nb' => 1, 'nbProducts' => 0));
     }
     $this->context->smarty->assign(array('add_prod_display' => Configuration::get('PS_ATTRIBUTE_CATEGORY_DISPLAY'), 'comparator_max_item' => Configuration::get('PS_COMPARATOR_MAX_ITEM')));
     $this->setTemplate(_PS_THEME_DIR_ . 'search.tpl');
 }
Example #3
0
 public function add($autodate = true, $nullValues = false)
 {
     $this->alias = Tools::replaceAccentedChars($this->alias);
     $this->search = Tools::replaceAccentedChars($this->search);
     if (parent::add($autodate, $nullValues)) {
         // Set cache of feature detachable to true
         Configuration::updateGlobalValue('PS_ALIAS_FEATURE_ACTIVE', '1');
         return true;
     }
     return false;
 }
Example #4
0
 public static function str2url($str)
 {
     $str = trim($str);
     if (function_exists('mb_strtolower')) {
         $str = mb_strtolower($str, 'utf-8');
     }
     $str = Tools::replaceAccentedChars($str);
     $str = preg_replace('/[^a-zA-Z0-9\\s\'\\:\\/\\[\\]-]/', '', $str);
     $str = preg_replace('/[\\s\'\\:\\/\\[\\]\\-]+/', ' ', $str);
     $str = str_replace(array(' ', '/'), '-', $str);
     return $str;
 }
 /**
  * Assign template vars related to page content
  * @see FrontController::initContent()
  */
 public function initContent()
 {
     parent::initContent();
     $query = Tools::replaceAccentedChars(urldecode(Tools::getValue('q')));
     if ($this->ajax_search) {
         $searchResults = Search::find((int) Tools::getValue('id_lang'), $query, 1, 10, 'position', 'desc', true);
         foreach ($searchResults as &$product) {
             $product['product_link'] = $this->context->link->getProductLink($product['id_product'], $product['prewrite'], $product['crewrite']);
         }
         die(Tools::jsonEncode($searchResults));
     }
     if ($this->instant_search && !is_array($query)) {
         $this->productSort();
         $this->n = abs((int) Tools::getValue('n', Configuration::get('PS_PRODUCTS_PER_PAGE')));
         $this->p = abs((int) Tools::getValue('p', 1));
         $search = Search::find($this->context->language->id, $query, 1, 10, 'position', 'desc');
         Hook::exec('actionSearch', array('expr' => $query, 'total' => $search['total']));
         $nbProducts = $search['total'];
         $this->pagination($nbProducts);
         $this->context->smarty->assign(array('products' => $search['result'], 'search_products' => $search['result'], 'nbProducts' => $search['total'], 'search_query' => $query, 'instant_search' => $this->instant_search, 'homeSize' => Image::getSize('home_default')));
     } else {
         if (($query = Tools::getValue('search_query', Tools::getValue('ref'))) && !is_array($query)) {
             $this->productSort();
             $this->n = abs((int) Tools::getValue('n', Configuration::get('PS_PRODUCTS_PER_PAGE')));
             $this->p = abs((int) Tools::getValue('p', 1));
             $search = Search::find($this->context->language->id, $query, $this->p, $this->n, $this->orderBy, $this->orderWay);
             Hook::exec('actionSearch', array('expr' => $query, 'total' => $search['total']));
             $nbProducts = $search['total'];
             $this->pagination($nbProducts);
             $this->context->smarty->assign(array('products' => $search['result'], 'search_products' => $search['result'], 'nbProducts' => $search['total'], 'search_query' => $query, 'homeSize' => Image::getSize('home_default')));
         } else {
             if (($tag = urldecode(Tools::getValue('tag'))) && !is_array($tag)) {
                 $nbProducts = (int) Search::searchTag($this->context->language->id, $tag, true);
                 $this->pagination($nbProducts);
                 $result = Search::searchTag($this->context->language->id, $tag, false, $this->p, $this->n, $this->orderBy, $this->orderWay);
                 Hook::exec('actionSearch', array('expr' => $tag, 'total' => count($result)));
                 $this->context->smarty->assign(array('search_tag' => $tag, 'products' => $result, 'search_products' => $result, 'nbProducts' => $nbProducts, 'homeSize' => Image::getSize('home_default')));
             } else {
                 $this->context->smarty->assign(array('products' => array(), 'search_products' => array(), 'pages_nb' => 1, 'nbProducts' => 0));
             }
         }
     }
     $this->context->smarty->assign(array('add_prod_display' => Configuration::get('PS_ATTRIBUTE_CATEGORY_DISPLAY'), 'comparator_max_item' => Configuration::get('PS_COMPARATOR_MAX_ITEM')));
     $this->setTemplate(_PS_THEME_DIR_ . 'search.tpl');
 }
 public static function str2url($str)
 {
     if (function_exists('mb_strtolower')) {
         $str = mb_strtolower($str, 'utf-8');
     }
     $str = trim($str);
     if (!function_exists('mb_strtolower')) {
         $str = Tools::replaceAccentedChars($str);
     }
     // Remove all non-whitelist chars.
     $str = preg_replace('/[^a-zA-Z0-9\\s\'\\:\\/\\[\\]-\\pL\\pM]/u', '', $str);
     $str = preg_replace('/[\\s\'\\:\\/\\[\\]-]+/', ' ', $str);
     $str = str_replace(array(' ', '/'), '-', $str);
     // If it was not possible to lowercase the string with mb_strtolower, we do it after the transformations.
     // This way we lose fewer special chars.
     if (!function_exists('mb_strtolower')) {
         $str = strtolower($str);
     }
     return $str;
 }
function ps16012_update_alias()
{
    $step = 3000;
    $count_alias = Db::getInstance()->getValue('SELECT count(id_alias) FROM ' . _DB_PREFIX_ . 'alias');
    $nb_loop = $start = 0;
    if ($count_alias > 0) {
        $nb_loop = ceil($count_alias / $step);
    }
    for ($i = 0; $i < $nb_loop; $i++) {
        $sql = 'SELECT id_alias, alias, search FROM `' . _DB_PREFIX_ . 'alias`';
        $start = intval(($i + 1) * $step);
        if ($aliass = Db::getInstance()->query($sql)) {
            while ($alias = Db::getInstance()->nextRow($aliass)) {
                if (is_array($alias)) {
                    Db::getInstance()->execute('
					UPDATE `' . _DB_PREFIX_ . 'alias`
					SET alias = \'' . pSQL(Tools::replaceAccentedChars($alias['alias'])) . '\',
					search = \'' . pSQL(Tools::replaceAccentedChars($alias['search'])) . '\'
					WHERE id_alias = ' . (int) $alias['id_alias']);
                }
            }
        }
    }
}
Example #8
0
 /**
  * Return a friendly url made from the provided string
  * If the mbstring library is available, the output is the same as the js function of the same name
  *
  * @param string $str
  * @return string
  */
 public static function str2url($str)
 {
     static $array_str = array();
     static $allow_accented_chars = null;
     static $has_mb_strtolower = null;
     if ($has_mb_strtolower === null) {
         $has_mb_strtolower = function_exists('mb_strtolower');
     }
     if (isset($array_str[$str])) {
         return $array_str[$str];
     }
     if (!is_string($str)) {
         return false;
     }
     if ($str == '') {
         return '';
     }
     if ($allow_accented_chars === null) {
         $allow_accented_chars = Configuration::get('PS_ALLOW_ACCENTED_CHARS_URL');
     }
     $return_str = trim($str);
     if ($has_mb_strtolower) {
         $return_str = mb_strtolower($return_str, 'utf-8');
     }
     if (!$allow_accented_chars) {
         $return_str = Tools::replaceAccentedChars($return_str);
     }
     // Remove all non-whitelist chars.
     if ($allow_accented_chars) {
         $return_str = preg_replace('/[^a-zA-Z0-9\\s\'\\:\\/\\[\\]\\-\\p{L}]/u', '', $return_str);
     } else {
         $return_str = preg_replace('/[^a-zA-Z0-9\\s\'\\:\\/\\[\\]\\-]/', '', $return_str);
     }
     $return_str = preg_replace('/[\\s\'\\:\\/\\[\\]\\-]+/', ' ', $return_str);
     $return_str = str_replace(array(' ', '/'), '-', $return_str);
     // If it was not possible to lowercase the string with mb_strtolower, we do it after the transformations.
     // This way we lose fewer special chars.
     if (!$has_mb_strtolower) {
         $return_str = Tools::strtolower($return_str);
     }
     $array_str[$str] = $return_str;
     return $return_str;
 }
Example #9
0
 private function replaceAccentedChars($text)
 {
     if (version_compare(_PS_VERSION_, '1.4.5.1', '>=')) {
         return Tools::replaceAccentedChars($text);
     }
     $patterns = array('/[\\x{00E0}\\x{00E1}\\x{00E2}\\x{00E3}\\x{00E4}\\x{00E5}\\x{0101}\\x{0103}\\x{0105}\\x{0430}]/u', '/[\\x{0431}]/u', '/[\\x{00E7}\\x{0107}\\x{0109}\\x{010D}\\x{0446}]/u', '/[\\x{010F}\\x{0111}\\x{0434}]/u', '/[\\x{00E8}\\x{00E9}\\x{00EA}\\x{00EB}\\x{0113}\\x{0115}\\x{0117}\\x{0119}\\x{011B}\\x{0435}\\x{044D}]/u', '/[\\x{0444}]/u', '/[\\x{011F}\\x{0121}\\x{0123}\\x{0433}\\x{0491}]/u', '/[\\x{0125}\\x{0127}]/u', '/[\\x{00EC}\\x{00ED}\\x{00EE}\\x{00EF}\\x{0129}\\x{012B}\\x{012D}\\x{012F}\\x{0131}\\x{0438}\\x{0456}]/u', '/[\\x{0135}\\x{0439}]/u', '/[\\x{0137}\\x{0138}\\x{043A}]/u', '/[\\x{013A}\\x{013C}\\x{013E}\\x{0140}\\x{0142}\\x{043B}]/u', '/[\\x{043C}]/u', '/[\\x{00F1}\\x{0144}\\x{0146}\\x{0148}\\x{0149}\\x{014B}\\x{043D}]/u', '/[\\x{00F2}\\x{00F3}\\x{00F4}\\x{00F5}\\x{00F6}\\x{00F8}\\x{014D}\\x{014F}\\x{0151}\\x{043E}]/u', '/[\\x{043F}]/u', '/[\\x{0155}\\x{0157}\\x{0159}\\x{0440}]/u', '/[\\x{015B}\\x{015D}\\x{015F}\\x{0161}\\x{0441}]/u', '/[\\x{00DF}]/u', '/[\\x{0163}\\x{0165}\\x{0167}\\x{0442}]/u', '/[\\x{00F9}\\x{00FA}\\x{00FB}\\x{00FC}\\x{0169}\\x{016B}\\x{016D}\\x{016F}\\x{0171}\\x{0173}\\x{0443}]/u', '/[\\x{0432}]/u', '/[\\x{0175}]/u', '/[\\x{00FF}\\x{0177}\\x{00FD}\\x{044B}]/u', '/[\\x{017A}\\x{017C}\\x{017E}\\x{0437}]/u', '/[\\x{00E6}]/u', '/[\\x{0447}]/u', '/[\\x{0445}]/u', '/[\\x{0153}]/u', '/[\\x{0448}]/u', '/[\\x{0449}]/u', '/[\\x{044F}]/u', '/[\\x{0454}]/u', '/[\\x{0457}]/u', '/[\\x{0451}]/u', '/[\\x{044E}]/u', '/[\\x{0436}]/u', '/[\\x{0100}\\x{0102}\\x{0104}\\x{00C0}\\x{00C1}\\x{00C2}\\x{00C3}\\x{00C4}\\x{00C5}\\x{0410}]/u', '/[\\x{0411}]]/u', '/[\\x{00C7}\\x{0106}\\x{0108}\\x{010A}\\x{010C}\\x{0426}]/u', '/[\\x{010E}\\x{0110}\\x{0414}]/u', '/[\\x{00C8}\\x{00C9}\\x{00CA}\\x{00CB}\\x{0112}\\x{0114}\\x{0116}\\x{0118}\\x{011A}\\x{0415}\\x{042D}]/u', '/[\\x{0424}]/u', '/[\\x{011C}\\x{011E}\\x{0120}\\x{0122}\\x{0413}\\x{0490}]/u', '/[\\x{0124}\\x{0126}]/u', '/[\\x{0128}\\x{012A}\\x{012C}\\x{012E}\\x{0130}\\x{0418}\\x{0406}]/u', '/[\\x{0134}\\x{0419}]/u', '/[\\x{0136}\\x{041A}]/u', '/[\\x{0139}\\x{013B}\\x{013D}\\x{0139}\\x{0141}\\x{041B}]/u', '/[\\x{041C}]/u', '/[\\x{00D1}\\x{0143}\\x{0145}\\x{0147}\\x{014A}\\x{041D}]/u', '/[\\x{00D3}\\x{014C}\\x{014E}\\x{0150}\\x{041E}]/u', '/[\\x{041F}]/u', '/[\\x{0154}\\x{0156}\\x{0158}\\x{0420}]/u', '/[\\x{015A}\\x{015C}\\x{015E}\\x{0160}\\x{0421}]/u', '/[\\x{0162}\\x{0164}\\x{0166}\\x{0422}]/u', '/[\\x{00D9}\\x{00DA}\\x{00DB}\\x{00DC}\\x{0168}\\x{016A}\\x{016C}\\x{016E}\\x{0170}\\x{0172}\\x{0423}]/u', '/[\\x{0412}]/u', '/[\\x{0174}]/u', '/[\\x{0176}\\x{042B}]/u', '/[\\x{0179}\\x{017B}\\x{017D}\\x{0417}]/u', '/[\\x{00C6}]/u', '/[\\x{0427}]/u', '/[\\x{0425}]/u', '/[\\x{0152}]/u', '/[\\x{0428}]/u', '/[\\x{0429}]/u', '/[\\x{042F}]/u', '/[\\x{0404}]/u', '/[\\x{0407}]/u', '/[\\x{0401}]/u', '/[\\x{042E}]/u', '/[\\x{0416}]/u');
     // ö to oe
     // å to aa
     // ä to ae
     $replacements = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'r', 's', 'ss', 't', 'u', 'v', 'w', 'y', 'z', 'ae', 'ch', 'kh', 'oe', 'sh', 'shh', 'ya', 'ye', 'yi', 'yo', 'yu', 'zh', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'R', 'S', 'T', 'U', 'V', 'W', 'Y', 'Z', 'AE', 'CH', 'KH', 'OE', 'SH', 'SHH', 'YA', 'YE', 'YI', 'YO', 'YU', 'ZH');
     return preg_replace($patterns, $replacements, $text);
 }
Example #10
0
 /**
  * @param $product_array
  * @param $weight_array
  * @param $key
  * @param $value
  * @param $id_lang
  * @param $iso_code
  */
 protected static function fillProductArray(&$product_array, $weight_array, $key, $value, $id_lang, $iso_code)
 {
     if (strncmp($key, 'id_', 3) && isset($weight_array[$key])) {
         $words = explode(' ', Search::sanitize($value, (int) $id_lang, true, $iso_code));
         foreach ($words as $word) {
             if (!empty($word)) {
                 $word = Tools::substr($word, 0, PS_SEARCH_MAX_WORD_LENGTH);
                 // Remove accents
                 $word = Tools::replaceAccentedChars($word);
                 if (!isset($product_array[$word])) {
                     $product_array[$word] = 0;
                 }
                 $product_array[$word] += $weight_array[$key];
             }
         }
     }
 }
 static function cleaner($string)
 {
     return Tools::replaceAccentedChars($string);
 }
 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[] = '&nbsp;<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[] = '&nbsp;<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[] = '&nbsp;<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[] = '&nbsp;<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[] = '&nbsp;<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[] = '&nbsp;<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[] = '&nbsp;<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();
 }
Example #13
0
function smartyClassname($classname)
{
    $classname = Tools::replaceAccentedChars(strtolower($classname));
    $classname = preg_replace('/[^A-Za-z0-9]/', '-', $classname);
    $classname = preg_replace('/[-]+/', '-', $classname);
    return $classname;
}
Example #14
0
 public function displayAjax()
 {
     $query = Tools::getValue('search_query');
     $original_query = $query;
     $query = Tools::replaceAccentedChars(urldecode($query));
     $this->productSort();
     $this->n = abs((int) Tools::getValue('n', isset($this->context->cookie->nb_item_per_page) ? (int) $this->context->cookie->nb_item_per_page : Configuration::get('PS_PRODUCTS_PER_PAGE')));
     $this->p = abs((int) Tools::getValue('p', 1));
     $facets = Tools::getValue('cm_select');
     $search = Cmsearch::find($this->context->language->id, $query, $this->p, $this->n, $this->orderBy, $this->orderWay, false, true, null, $facets);
     if ($search) {
         $position = 1;
         foreach ($search['result'] as &$product) {
             $product['link'] .= (strpos($product['link'], '?') === false ? '?' : '&') . 'search_query=' . urlencode($query) . '&results=' . (int) $search['total'] . '&pid=' . (int) $product['id_product'] . '&position=' . $position . '&page=' . $this->p . '&num=' . $this->n;
             $position++;
         }
         Hook::exec('actionSearch', array('expr' => $query, 'total' => $search['total']));
         $nbProducts = $search['total'];
         $this->pagination($nbProducts);
         if (version_compare(_PS_VERSION_, '1.6.0', '>=') === true) {
             $this->addColorsToProductList($search['result']);
         }
         if (stripos($search['cm_result']->State, 'nothing')) {
             $cm_message = 'nothing found';
         } elseif (!empty($search['cm_result']->Corrections) && $search['cm_result']->Corrections[0]->Apply) {
             if (!empty($search['cm_result']->Query)) {
                 $cm_message = 'your request has been corrected to ' . $search['cm_result']->Query;
             } else {
                 $cm_message = 'nothing found';
             }
         } else {
             $cm_message = false;
         }
         $this->context->smarty->assign(array('search_products' => $search['result'], 'nbProducts' => $search['total'], 'search_query' => !empty($search['cm_result']->OriginalQuery) ? $search['cm_result']->OriginalQuery : ' ', 'cm_message' => $cm_message, 'homeSize' => Image::getSize(ImageType::getFormatedName('home')), 'add_prod_display' => Configuration::get('PS_ATTRIBUTE_CATEGORY_DISPLAY'), 'comparator_max_item' => Configuration::get('PS_COMPARATOR_MAX_ITEM')));
         $list = $this->context->smarty->fetch(_PS_MODULE_DIR_ . 'convermax/views/templates/front/search.tpl');
         $this->context->smarty->assign(array('facets' => $search['cm_result']->Facets, 'query' => $search['cm_result']->Query, 'pagenumber' => $this->p, 'pagesize' => $this->n, 'col_img_dir' => _PS_COL_IMG_DIR_));
         $facets = $this->context->smarty->fetch(_PS_MODULE_DIR_ . 'convermax/views/templates/hook/facet.tpl');
         $vars = array('productList' => utf8_encode($list), 'facets' => $facets, 'redirect_url' => isset($search['cm_result']->Actions[0]->RedirectUrl) ? $search['cm_result']->Actions[0]->RedirectUrl : false);
     } else {
         $this->context->smarty->assign(array('search_products' => $search['result'], 'nbProducts' => $search['total'], 'search_query' => !empty($original_query) ? $original_query : ' ', 'homeSize' => Image::getSize(ImageType::getFormatedName('home'))));
         $list = $this->context->smarty->fetch(_PS_MODULE_DIR_ . 'convermax/views/templates/front/search.tpl');
         $vars = array('productList' => utf8_encode($list), 'facets' => array(), 'redirect_url' => false);
     }
     echo Tools::jsonEncode($vars);
 }
Example #15
0
 public function initContent()
 {
     include _PS_MODULE_DIR_ . 'blocksearch_mod' . DIRECTORY_SEPARATOR . 'IqitSearch.php';
     $query = Tools::replaceAccentedChars(urldecode(Tools::getValue('q')));
     $original_query = Tools::getValue('q');
     $search_query_cat = (int) Tools::getValue('search_query_cat');
     if ($this->ajax_search) {
         self::$link = new Link();
         $image = new Image();
         $searchResults = IqitSearch::find((int) Tools::getValue('id_lang'), $query, $search_query_cat, 1, 10, 'position', 'desc', true);
         $taxes = Product::getTaxCalculationMethod();
         $currency = (int) Context::getContext()->currency->id;
         $iso_code = $this->context->language->iso_code;
         if (is_array($searchResults)) {
             foreach ($searchResults as &$product) {
                 $imageID = $image->getCover($product['id_product']);
                 if (isset($imageID['id_image'])) {
                     $imgLink = $this->context->link->getImageLink($product['prewrite'], (int) $product['id_product'] . '-' . $imageID['id_image'], 'small_default');
                 } else {
                     $imgLink = _THEME_PROD_DIR_ . $iso_code . "-default-small_default.jpg";
                 }
                 $product['product_link'] = $this->context->link->getProductLink($product['id_product'], $product['prewrite'], $product['crewrite']);
                 $product['obr_thumb'] = $imgLink;
                 $product['product_price'] = Product::getPriceStatic((int) $product['id_product'], false, NULL, 2);
                 if ($taxes == 0 or $taxes == 2) {
                     $product['product_price'] = Tools::displayPrice(Product::getPriceStatic((int) $product['id_product'], true), $currency);
                 } elseif ($taxes == 1) {
                     $product['product_price'] = Tools::displayPrice(Product::getPriceStatic((int) $product['id_product'], false), $currency);
                 }
             }
         }
         $this->ajaxDie(Tools::jsonEncode($searchResults));
     }
     // Only controller content initialization when the user use the normal search
     parent::initContent();
     if ($this->instant_search && !is_array($query)) {
         $this->productSort();
         $this->n = abs((int) Tools::getValue('n', $product_per_page));
         $this->p = abs((int) Tools::getValue('p', 1));
         $search = IqitSearch::find($this->context->language->id, $query, $search_query_cat, 1, 10, 'position', 'desc');
         Hook::exec('actionSearch', array('expr' => $query, 'total' => $search['total']));
         $nbProducts = $search['total'];
         $this->pagination($nbProducts);
         $this->addColorsToProductList($search['result']);
         if (method_exists('Product', 'getProductsImgs')) {
             $image_array = array();
             for ($i = 0; $i < $nbProducts; $i++) {
                 if (isset($search['result'][$i]['id_product'])) {
                     $image_array[$search['result'][$i]['id_product']] = Product::getProductsImgs($search['result'][$i]['id_product']);
                 }
             }
             $this->context->smarty->assign('productimg', (isset($image_array) and $image_array) ? $image_array : NULL);
         }
         $this->context->smarty->assign(array('products' => $search['result'], 'search_products' => $search['result'], 'nbProducts' => $search['total'], 'search_query' => $original_query, 'instant_search' => $this->instant_search, 'homeSize' => Image::getSize(ImageType::getFormatedName('home'))));
     } elseif (($query = Tools::getValue('search_query', Tools::getValue('ref'))) && !is_array($query)) {
         $this->productSort();
         $this->n = abs((int) Tools::getValue('n', Configuration::get('PS_PRODUCTS_PER_PAGE')));
         $this->p = abs((int) Tools::getValue('p', 1));
         $original_query = $query;
         $query = Tools::replaceAccentedChars(urldecode($query));
         $search = IqitSearch::find($this->context->language->id, $query, $search_query_cat, $this->p, $this->n, $this->orderBy, $this->orderWay);
         if (is_array($search['result'])) {
             foreach ($search['result'] as &$product) {
                 $product['link'] .= (strpos($product['link'], '?') === false ? '?' : '&') . 'search_query=' . urlencode($query) . '&results=' . (int) $search['total'];
             }
         }
         Hook::exec('actionSearch', array('expr' => $query, 'total' => $search['total']));
         $nbProducts = $search['total'];
         $this->pagination($nbProducts);
         $this->addColorsToProductList($search['result']);
         /************************* /Images Array ******************************/
         if (method_exists('Product', 'getProductsImgs')) {
             $image_array = array();
             for ($i = 0; $i < $nbProducts; $i++) {
                 if (isset($search['result'][$i]['id_product'])) {
                     $image_array[$search['result'][$i]['id_product']] = Product::getProductsImgs($search['result'][$i]['id_product']);
                 }
             }
             $this->context->smarty->assign('productimg', (isset($image_array) and $image_array) ? $image_array : NULL);
         }
         /************************* /Images Array ******************************/
         $this->context->smarty->assign(array('products' => $search['result'], 'search_products' => $search['result'], 'nbProducts' => $search['total'], 'search_query' => $original_query, 'homeSize' => Image::getSize(ImageType::getFormatedName('home'))));
     } elseif (($tag = urldecode(Tools::getValue('tag'))) && !is_array($tag)) {
         $nbProducts = (int) Search::searchTag($this->context->language->id, $tag, true);
         $this->pagination($nbProducts);
         $result = Search::searchTag($this->context->language->id, $tag, false, $this->p, $this->n, $this->orderBy, $this->orderWay);
         Hook::exec('actionSearch', array('expr' => $tag, 'total' => count($result)));
         $this->addColorsToProductList($result);
         /************************* /Images Array ******************************/
         if (method_exists('Product', 'getProductsImgs')) {
             $image_array = array();
             for ($i = 0; $i < $nbProducts; $i++) {
                 if (isset($result[$i]['id_product'])) {
                     $image_array[$result[$i]['id_product']] = Product::getProductsImgs($result[$i]['id_product']);
                 }
             }
             $this->context->smarty->assign('productimg', (isset($image_array) and $image_array) ? $image_array : NULL);
         }
         /************************* /Images Array ******************************/
         $this->context->smarty->assign(array('search_tag' => $tag, 'products' => $result, 'search_products' => $result, 'nbProducts' => $nbProducts, 'homeSize' => Image::getSize(ImageType::getFormatedName('home'))));
     } else {
         $this->context->smarty->assign(array('products' => array(), 'search_products' => array(), 'pages_nb' => 1, 'nbProducts' => 0));
     }
     $this->context->smarty->assign(array('add_prod_display' => Configuration::get('PS_ATTRIBUTE_CATEGORY_DISPLAY'), 'comparator_max_item' => Configuration::get('PS_COMPARATOR_MAX_ITEM')));
     $this->setTemplate(_PS_THEME_DIR_ . 'search.tpl');
 }
 /**
  * Assign template vars related to page content
  * @see FrontController::initContent()
  */
 public function initContent()
 {
     parent::initContent();
     $this->context->smarty->assign(array('HOOK_LEFT_COLUMN' => Hook::exec('displayLeftColumn')));
     $query = Tools::replaceAccentedChars(urldecode(Tools::getValue('q')));
     $original_query = Tools::getValue('q');
     if ($this->ajax_search) {
         $searchResults = Search::find((int) Tools::getValue('id_lang'), $query, 1, 10, 'position', 'desc', true);
         foreach ($searchResults as &$product) {
             $product['product_link'] = $this->context->link->getProductLink($product['id_product'], $product['prewrite'], $product['crewrite']);
         }
         die(Tools::jsonEncode($searchResults));
     }
     if ($this->instant_search && !is_array($query)) {
         $this->productSort();
         $this->n = abs((int) Tools::getValue('n', Configuration::get('PS_PRODUCTS_PER_PAGE')));
         $this->p = abs((int) Tools::getValue('p', 1));
         $search = Search::find($this->context->language->id, $query, 1, 10, 'position', 'desc');
         Hook::exec('actionSearch', array('expr' => $query, 'total' => $search['total']));
         $nbProducts = $search['total'];
         $this->pagination($nbProducts);
         $this->addColorsToProductList($search['result']);
         $products = $search['result'];
         $this->context->smarty->assign(array('products' => $search['result'], 'search_products' => $search['result'], 'nbProducts' => $search['total'], 'search_query' => $original_query, 'instant_search' => $this->instant_search, 'homeSize' => Image::getSize(ImageType::getFormatedName('home'))));
     } elseif (($query = Tools::getValue('search_query', Tools::getValue('ref'))) && !is_array($query)) {
         $this->productSort();
         $this->n = abs((int) Tools::getValue('n', Configuration::get('PS_PRODUCTS_PER_PAGE')));
         $this->p = abs((int) Tools::getValue('p', 1));
         $original_query = $query;
         $query = Tools::replaceAccentedChars(urldecode($query));
         $search = Search::find($this->context->language->id, $query, $this->p, $this->n, $this->orderBy, $this->orderWay);
         foreach ($search['result'] as &$product) {
             $product['link'] .= (strpos($product['link'], '?') === false ? '?' : '&') . 'search_query=' . urlencode($query) . '&results=' . (int) $search['total'];
         }
         Hook::exec('actionSearch', array('expr' => $query, 'total' => $search['total']));
         $nbProducts = $search['total'];
         $this->pagination($nbProducts);
         $this->addColorsToProductList($search['result']);
         $products = $search['result'];
         $this->context->smarty->assign(array('products' => $search['result'], 'search_products' => $search['result'], 'nbProducts' => $search['total'], 'search_query' => $original_query, 'homeSize' => Image::getSize(ImageType::getFormatedName('home'))));
     } elseif (($tag = urldecode(Tools::getValue('tag'))) && !is_array($tag)) {
         $nbProducts = (int) Search::searchTag($this->context->language->id, $tag, true);
         $this->pagination($nbProducts);
         $result = Search::searchTag($this->context->language->id, $tag, false, $this->p, $this->n, $this->orderBy, $this->orderWay);
         Hook::exec('actionSearch', array('expr' => $tag, 'total' => count($result)));
         $this->addColorsToProductList($result);
         $products = $result;
         $this->context->smarty->assign(array('search_tag' => $tag, 'products' => $result, 'search_products' => $result, 'nbProducts' => $nbProducts, 'homeSize' => Image::getSize(ImageType::getFormatedName('home'))));
     } else {
         $products = array();
         $this->context->smarty->assign(array('products' => array(), 'search_products' => array(), 'pages_nb' => 1, 'nbProducts' => 0));
     }
     $this->context->smarty->assign(array('add_prod_display' => Configuration::get('PS_ATTRIBUTE_CATEGORY_DISPLAY'), 'comparator_max_item' => Configuration::get('PS_COMPARATOR_MAX_ITEM')));
     if ($this->ajax) {
         $product_list = $this->context->smarty->fetch(_PS_THEME_DIR_ . 'product-list.tpl');
         $pagination = $this->context->smarty->fetch(_PS_THEME_DIR_ . 'pagination.tpl');
         $nbLeftProducts = $nbProducts - ($this->n * ($this->p - 1) + count($products));
         $nbLeftProductsPercentage = ($nbProducts - $nbLeftProducts) / $nbProducts * 100;
         echo Tools::jsonEncode(array('productList' => utf8_encode($product_list), 'pagination' => $pagination, 'nbRenderedProducts' => $nbProducts, 'nbLeftProducts' => $nbLeftProducts, 'nbLeftProductsPercentage' => $nbLeftProductsPercentage));
         die;
     } else {
         $this->setTemplate(_PS_THEME_DIR_ . 'search.tpl');
     }
 }
Example #17
0
 public function hookHeader()
 {
     if ($this->_isInMaintenance() || $this->_isMobileTheme()) {
         return;
     }
     if (version_compare(_PS_VERSION_, '1.5.0.0', '<')) {
         if (isset($_SERVER['PHP_SELF']) && preg_match('#' . preg_quote('best-sales.php') . '#', $_SERVER['PHP_SELF'])) {
             self::$productFilterListSource = 'best-sales';
         } else {
             if (isset($_SERVER['PHP_SELF']) && preg_match('#' . preg_quote('new-products.php') . '#', $_SERVER['PHP_SELF'])) {
                 self::$productFilterListSource = 'new-products';
             } else {
                 if (isset($_SERVER['PHP_SELF']) && preg_match('#' . preg_quote('prices-drop.php') . '#', $_SERVER['PHP_SELF'])) {
                     self::$productFilterListSource = 'prices-drop';
                 } else {
                     if (isset($_SERVER['PHP_SELF']) && preg_match('#' . preg_quote('search.php') . '#', $_SERVER['PHP_SELF']) && Tools::getIsset('q') && Tools::getValue('q')) {
                         self::$productFilterListData = urldecode(Tools::getValue('q'));
                         self::$productFilterListSource = 'search';
                     }
                 }
             }
         }
     } else {
         if (version_compare(_PS_VERSION_, '1.5.0.0', '>=') && isset($this->_context->controller) && is_object($this->_context->controller) && isset($this->_context->controller->php_self)) {
             if (in_array($this->_context->controller->php_self, array('best-sales', 'new-products', 'prices-drop', 'search'))) {
                 self::$productFilterListSource = $this->_context->controller->php_self;
                 if ($this->_context->controller->php_self == 'search' && Tools::getIsset('search_query') && Tools::getValue('search_query')) {
                     self::$productFilterListData = Tools::replaceAccentedChars(urldecode(Tools::getValue('search_query')));
                 }
             }
         }
     }
     $this->setProductFilterContext();
     $this->_addCSS(__PS_BASE_URI__ . 'modules/' . $this->name . '/css/' . $this->name . '.css', 'all');
     $this->_addCSS(__PS_BASE_URI__ . 'modules/' . $this->name . '/' . self::DYN_CSS_FILE, 'all');
     $this->_addCSS(__PS_BASE_URI__ . 'modules/' . $this->name . '/js/jqueryui/ui_theme_front/theme1/jquery-ui-1.8.13.custom.css', 'all');
     $this->_addJS(__PS_BASE_URI__ . 'modules/' . $this->name . '/js/jquery.min.js');
     $this->_addJS(__PS_BASE_URI__ . 'modules/' . $this->name . '/js/jqueryui/1.8.9/jquery-ui-1.8.9.custom.min.js');
     $this->_addJS(__PS_BASE_URI__ . 'modules/' . $this->name . '/js/jqueryui/jquery.ui.touch-punch.min.js');
     $this->_addJS(__PS_BASE_URI__ . 'modules/' . $this->name . '/js/loadjqPm.js');
     $this->_addJS(__PS_BASE_URI__ . 'modules/' . $this->name . '/js/jquery.actual.min.js');
     $this->_addJS(__PS_BASE_URI__ . 'modules/' . $this->name . '/js/jquery.history/jquery.history.js');
     $this->_addJS(__PS_BASE_URI__ . 'modules/' . $this->name . '/js/jquery.history/jquery.observehashchange.pack.js');
     $this->_addJS(__PS_BASE_URI__ . 'modules/' . $this->name . '/js/pm_advancedsearch.js');
     $this->_addJS(__PS_BASE_URI__ . 'modules/' . $this->name . '/js/jquery.form.js');
     if (Configuration::get('PS_COMPARATOR_MAX_ITEM') > 0) {
         $this->_addJS(_THEME_JS_DIR_ . 'products-comparison.js');
     }
     if (version_compare(_PS_VERSION_, '1.5.0.0', '>=')) {
         $ASSearchUrl = $this->_context->link->getModuleLink('pm_advancedsearch4', 'advancedsearch4');
     } else {
         $ASSearchUrl = __PS_BASE_URI__ . 'modules/pm_advancedsearch4/advancedsearch4.php';
     }
     $this->_smarty->assign('ASSearchUrlForm', $ASSearchUrl);
     if (!Tools::getValue('ajaxMode')) {
         $this->assignSearchVar();
     }
     return $this->display(__FILE__, (version_compare(_PS_VERSION_, '1.5.0.0', '<') ? '/views/templates/hook/' : '') . 'pm_advancedsearch_header.tpl');
 }
    /**
     * Assign template vars related to page content
     * @see FrontController::initContent()
     */
    public function initContent()
    {
        $query = Tools::replaceAccentedChars(urldecode(Tools::getValue('q')));
        $query_loc = Tools::replaceAccentedChars(urldecode(Tools::getValue('search_loc')));
        $query_state = Tools::replaceAccentedChars(urldecode(Tools::getValue('search_state')));
        $query_city = Tools::replaceAccentedChars(urldecode(Tools::getValue('search_city')));
        $query_cat = Tools::replaceAccentedChars(urldecode(Tools::getValue('search_cat')));
        $query_words = Tools::replaceAccentedChars(urldecode(Tools::getValue('search_words')));
        $original_query = Tools::getValue('q');
        $original_query_loc = Tools::getValue('search_original');
        $query_original = Tools::getValue('search_original');
        $original_query_cat = Tools::getValue('search_cat');
        $original_query_words = Tools::getValue('search_words');
        if ($this->ajax_search) {
            // die(Tools::jsonEncode(array('key' => 'value')));
            $searchresult = array();
            $sqlcountry = 'SELECT *, country as countryflg FROM ' . _DB_PREFIX_ . 'product_lang where country LIKE "' . $query . '%" Group by country';
            $resultcountry = Db::getInstance()->ExecuteS($sqlcountry);
            $sqlstate = 'SELECT *, state as stateflg FROM ' . _DB_PREFIX_ . 'product_lang where state LIKE "' . $query . '%" Group by state';
            $resultstate = Db::getInstance()->ExecuteS($sqlstate);
            $sqlcity = 'SELECT *, city as cityflg FROM ' . _DB_PREFIX_ . 'product_lang where city LIKE "' . $query . '%" Group by city ';
            $resultcity = Db::getInstance()->ExecuteS($sqlcity);
            array_push($searchresult, $resultcountry);
            array_push($searchresult, $resultstate);
            array_push($searchresult, $resultcity);
            if ($resultcity == null && $resultstate == null && $resultcountry == null) {
                $sqlplace = 'SELECT *, concat_ws(" ",country,state) as allflg,country as country FROM ' . _DB_PREFIX_ . 'product_lang	
					where concat_ws(" ",country,state) LIKE "' . $query . '%" AND id_lang = 1 Group by state limit 5 ';
                $resultplace = Db::getInstance()->ExecuteS($sqlplace);
                $sqlplacecity = 'SELECT *, city as cityflg,country as country FROM ' . _DB_PREFIX_ . 'product_lang	
					where concat_ws(" ",country,city) LIKE "' . $query . '%" AND id_lang = 1 Group by city limit 5 ';
                $resultplacecity = Db::getInstance()->ExecuteS($sqlplacecity);
                array_push($searchresult, $resultplace);
                array_push($searchresult, $resultplacecity);
            }
            $searchresult = array_filter($searchresult);
            $searchresult = array_values($searchresult);
            // foreach ($results as $key => $values){
            // 	$results[$key]['cityflag'] = $resultscity;
            // }
            die(Tools::jsonEncode($searchresult));
            // die('<pre>'.print_r($searchresult,true));
        }
        //Only controller content initialization when the user use the normal search
        parent::initContent();
        if ($this->instant_search && !is_array($query)) {
            $this->productSort();
            $this->n = abs((int) Tools::getValue('n', Configuration::get('PS_PRODUCTS_PER_PAGE')));
            $this->p = abs((int) Tools::getValue('p', 1));
            $search = Search::find($this->context->language->id, $query, 1, 10, 'position', 'desc');
            Hook::exec('actionSearch', array('expr' => $query, 'total' => $search['total']));
            $nbProducts = $search['total'];
            $this->pagination($nbProducts);
            $this->addColorsToProductList($search['result']);
            $this->context->smarty->assign(array('products' => $search['result'], 'search_products' => $search['result'], 'nbProducts' => $search['total'], 'search_query' => $original_query, 'instant_search' => $this->instant_search, 'homeSize' => Image::getSize(ImageType::getFormatedName('home'))));
        } elseif (($query = Tools::getValue('search_query', Tools::getValue('ref'))) && !is_array($query)) {
            $this->productSort();
            $this->n = abs((int) Tools::getValue('n', Configuration::get('PS_PRODUCTS_PER_PAGE')));
            $this->p = abs((int) Tools::getValue('p', 1));
            $original_query = $query;
            $query = Tools::replaceAccentedChars(urldecode($query));
            $search = Search::find($this->context->language->id, $query, $this->p, $this->n, $this->orderBy, $this->orderWay);
            foreach ($search['result'] as &$product) {
                $product['link'] .= (strpos($product['link'], '?') === false ? '?' : '&') . 'search_query=' . urlencode($query) . '&results=' . (int) $search['total'];
            }
            Hook::exec('actionSearch', array('expr' => $query, 'total' => $search['total']));
            $nbProducts = $search['total'];
            $this->pagination($nbProducts);
            $this->addColorsToProductList($search['result']);
            $this->context->smarty->assign(array('products' => $search['result'], 'search_products' => $search['result'], 'nbProducts' => $search['total'], 'search_query' => $original_query, 'homeSize' => Image::getSize(ImageType::getFormatedName('home'))));
        } elseif (($tag = urldecode(Tools::getValue('tag'))) && !is_array($tag)) {
            $nbProducts = (int) Search::searchTag($this->context->language->id, $tag, true);
            $this->pagination($nbProducts);
            $result = Search::searchTag($this->context->language->id, $tag, false, $this->p, $this->n, $this->orderBy, $this->orderWay);
            Hook::exec('actionSearch', array('expr' => $tag, 'total' => count($result)));
            $this->addColorsToProductList($result);
            $this->context->smarty->assign(array('search_tag' => $tag, 'products' => $result, 'search_products' => $result, 'nbProducts' => $nbProducts, 'homeSize' => Image::getSize(ImageType::getFormatedName('home'))));
        } elseif ($query_loc !== "" || $query_cat !== "" || $query_words !== "" || $query_state !== "" || $query_city !== "" || $query_original !== "") {
            $this->productSort();
            $this->n = abs((int) Tools::getValue('n', Configuration::get('PS_PRODUCTS_PER_PAGE')));
            $this->p = abs((int) Tools::getValue('p', 1));
            $query_arr = array('words' => $query_words, 'location' => $query_loc, 'city' => $query_city, 'state' => $query_state, 'original' => $query_original, 'category' => $query_cat);
            $search = Search::find($this->context->language->id, $query_arr, $this->p, $this->n, $this->orderBy, $this->orderWay);
            foreach ($search['result'] as &$product) {
                $product['link'] .= (strpos($product['link'], '?') === false ? '?' : '&') . 'search_query=' . urlencode($query) . '&results=' . (int) $search['total'];
            }
            Hook::exec('actionSearch', array('expr' => $query, 'total' => $search['total']));
            $nbProducts = $search['total'];
            $this->pagination($nbProducts);
            /*foreach($search['result'] as $k => $v) {
            			$country = $v['country'];
            			$flagId = Country::getIdByName(1, $country);
            			$search['result'][$k]['img_exist']	= file_exists(_PS_ROOT_DIR_ . DS . 'flag' . DS . 'mini'. DS . $flagId . '.jpg')? 1 : 0;
            			$search['result'][$k]['img_name']	= $flagId . '.jpg';
            		}*/
            foreach ($search['result'] as $key => $value) {
                $seller_id = $value['id_seller'];
                $flagIds = self::getFlagsId($seller_id);
                foreach ($flagIds as $k => $flgId) {
                    $search['result'][$key]['img_exist'][$k] = file_exists(_PS_ROOT_DIR_ . DS . 'flag' . DS . 'mini' . DS . $flgId . '.jpg') ? 1 : 0;
                    $search['result'][$key]['img_name'][$k] = $flgId . '.jpg';
                }
            }
            // die('<pre>' . print_r($search['result'], true));
            $this->addColorsToProductList($search['result']);
            $original_query = array();
            if ($query_loc != "") {
                array_push($original_query, $query_original);
            }
            if ($query_words != "") {
                array_push($original_query, $query_words);
            }
            $original_query_text = implode(" ", $original_query);
            $cat_name = $original_query_cat == 0 ? 'All Categories' : self::getCategoryName($original_query_cat);
            $this->context->smarty->assign(array('products' => $search['result'], 'search_words' => $original_query_words, 'search_products' => $search['result'], 'cat_id' => $original_query_cat, 'cat_name' => $cat_name, 'nbProducts' => $search['total'], 'search_query' => @$query_loc . ' ' . @$query_state . ' ' . @$query_city, 'homeSize' => Image::getSize(ImageType::getFormatedName('home'))));
        } else {
            $this->context->smarty->assign(array('products' => array(), 'search_products' => array(), 'pages_nb' => 1, 'nbProducts' => 0));
        }
        $this->context->smarty->assign(array('add_prod_display' => Configuration::get('PS_ATTRIBUTE_CATEGORY_DISPLAY'), 'comparator_max_item' => Configuration::get('PS_COMPARATOR_MAX_ITEM')));
        $this->setTemplate(_PS_THEME_DIR_ . 'search.tpl');
    }
 public static function sanitize($string, $id_lang, $indexation = false)
 {
     $string = trim($string);
     if (empty($string)) {
         return '';
     }
     $string = Tools::strtolower(strip_tags($string));
     $string = html_entity_decode($string, ENT_NOQUOTES, 'utf-8');
     $string = preg_replace('/([' . PREG_CLASS_NUMBERS . ']+)[' . PREG_CLASS_PUNCTUATION . ']+(?=[' . PREG_CLASS_NUMBERS . '])/u', '\\1', $string);
     $string = preg_replace('/[' . PREG_CLASS_SEARCH_EXCLUDE_THAI . ']+/u', ' ', $string);
     if ($indexation) {
         $string = preg_replace('/[._-]+/', '', $string);
     } else {
         $string = preg_replace('/[._]+/', '', $string);
         $string = ltrim(preg_replace('/([^ ])-/', '$1', ' ' . $string));
         $string = preg_replace('/[._]+/', '', $string);
         $string = preg_replace('/[^\\s]-+/', '', $string);
     }
     $blacklist = Tools::strtolower(Configuration::get('PS_SEARCH_BLACKLIST', $id_lang));
     if (!empty($blacklist)) {
         $string = preg_replace('/(?<=\\s)(' . $blacklist . ')(?=\\s)/Su', '', $string);
         $string = preg_replace('/^(' . $blacklist . ')(?=\\s)/Su', '', $string);
         $string = preg_replace('/(?<=\\s)(' . $blacklist . ')$/Su', '', $string);
         $string = preg_replace('/^(' . $blacklist . ')$/Su', '', $string);
     }
     if (!$indexation) {
         $words = explode(' ', $string);
         $processed_words = array();
         // search for aliases for each word of the query
         foreach ($words as $word) {
             $alias = new Alias(null, $word);
             if (Validate::isLoadedObject($alias)) {
                 $processed_words[] = $alias->search;
             } else {
                 $processed_words[] = $word;
             }
         }
         $string = implode(' ', $processed_words);
     }
     if ($indexation) {
         // If the language is constituted with symbol and there is no "words", then split every chars
         if (in_array($iso_code, array('zh', 'tw', 'ja')) && function_exists('mb_strlen')) {
             // Cut symbols from letters
             $symbols = '';
             $letters = '';
             foreach (explode(' ', $string) as $mb_word) {
                 if (strlen(Tools::replaceAccentedChars($mb_word)) == mb_strlen(Tools::replaceAccentedChars($mb_word))) {
                     $letters .= $mb_word . ' ';
                 } else {
                     $symbols .= $mb_word . ' ';
                 }
             }
             if (preg_match_all('/./u', $symbols, $matches)) {
                 $symbols = implode(' ', $matches[0]);
             }
             $string = $letters . $symbols;
         } else {
             $minWordLen = (int) Configuration::get('PS_SEARCH_MINWORDLEN');
             if ($minWordLen > 1) {
                 $minWordLen -= 1;
                 $string = preg_replace('/(?<=\\s)[^\\s]{1,' . $minWordLen . '}(?=\\s)/Su', ' ', $string);
                 $string = preg_replace('/^[^\\s]{1,' . $minWordLen . '}(?=\\s)/Su', '', $string);
                 $string = preg_replace('/(?<=\\s)[^\\s]{1,' . $minWordLen . '}$/Su', '', $string);
                 $string = preg_replace('/^[^\\s]{1,' . $minWordLen . '}$/Su', '', $string);
             }
         }
     }
     $string = trim(preg_replace('/\\s+/', ' ', $string));
     return $string;
 }
Example #20
0
 /**
  * Assign search template
  */
 public function assign()
 {
     $query = Tools::replaceAccentedChars(urldecode(Tools::getValue('q')));
     $original_query = Tools::getValue('q');
     $id_category = Tools::getValue('id_category');
     if (Tools::getValue('ajax_Search')) {
         $searchResults = Search::find((int) Tools::getValue('id_lang'), $query, 1, (int) Tools::getValue('limit', 10), 'position', 'desc', true);
         $results = array();
         foreach ($searchResults as $product) {
             $cover = Product::getCover($product['id_product']);
             $product['product_link'] = $this->context->link->getProductLink($product['id_product'], $product['prewrite'], $product['crewrite']);
             $product['product_image'] = $this->context->link->getImageLink($product['prewrite'], $cover['id_image'], 'home_default');
             $product['id_category'] = $id_category;
             $product['categories'] = Product::getProductCategories($product['id_product']);
             if ($id_category == 'all' || in_array((int) $id_category, Product::getProductCategories($product['id_product']))) {
                 $results[] = $product;
             }
         }
         die(Tools::jsonEncode($results));
     }
     if (Tools::getValue('instantSearch') && !is_array($query)) {
         $this->productSort();
         $this->n = abs((int) Tools::getValue('n', Configuration::get('PS_PRODUCTS_PER_PAGE')));
         $this->p = abs((int) Tools::getValue('p', 1));
         $search = Search::find($this->context->language->id, $query, 1, 10, 'position', 'desc');
         Hook::exec('actionSearch', array('expr' => $query, 'total' => $search['total']));
         $results = array();
         $index = 0;
         foreach ($search['result'] as $product) {
             $categories_id = Product::getProductCategories($product['id_product']);
             if (in_array((int) $id_category, Product::getProductCategories($product['id_product']))) {
                 if (($this->p - 1) * $this->n <= $index && $index < $this->p * $this->n) {
                     $results[] = $product;
                 }
                 $index++;
             }
         }
         $nbProducts = $index;
         $this->pagination($nbProducts);
         $this->addColorsToProductList($results);
         $this->context->smarty->assign(array('products' => $results, 'search_products' => $search['result'], 'nbProducts' => $search['total'], 'search_query' => $original_query, 'instant_search' => $this->instant_search, 'request' => $this->context->link->getModuleLink('categorysearch', 'catesearch'), 'homeSize' => Image::getSize(ImageType::getFormatedName('home'))));
     } elseif (($query = Tools::getValue('search_query', Tools::getValue('ref'))) && !is_array($query)) {
         $this->productSort();
         $this->n = abs((int) Tools::getValue('n', Configuration::get('PS_PRODUCTS_PER_PAGE')));
         $this->p = abs((int) Tools::getValue('p', 1));
         $original_query = $query;
         $query = Tools::replaceAccentedChars(urldecode($query));
         $search = Search::find($this->context->language->id, $query, $this->p, $this->n, $this->orderBy, $this->orderWay);
         //if($this->orderBy == 'price') $search['result'] = Tools::orderbyPrice($search['result'], $this->orderWay);
         //print_r($search['result']);
         //die;
         foreach ($search['result'] as &$product) {
             $product['link'] .= (strpos($product['link'], '?') === false ? '?' : '&') . 'search_query=' . urlencode($query) . '&results=' . (int) $search['total'];
         }
         $results = array();
         $id_category = Tools::getValue('search_category', 'all');
         Hook::exec('actionSearch', array('expr' => $query, 'total' => $search['total']));
         $nbProducts = $search['total'];
         $this->context->smarty->assign(array('search_query' => $original_query, 'homeSize' => Image::getSize(ImageType::getFormatedName('home'))));
         if ($id_category == 'all') {
             $this->pagination($nbProducts);
             $this->addColorsToProductList($search['result']);
             $this->context->smarty->assign(array('products' => $search['result'], 'search_products' => $search['result'], 'nbProducts' => $search['total'], 'nbp' => $this->p, 'nbn' => $this->n, 'orderby' => $this->orderBy, 'orderWay' => $this->orderWay, 'request' => $this->context->link->getModuleLink('categorysearch', 'catesearch')));
         } else {
             $search = Search::find($this->context->language->id, $query, 1, $nbProducts, $this->orderBy, $this->orderWay);
             $results = array();
             $index = 0;
             foreach ($search['result'] as $product) {
                 $categories_id = Product::getProductCategories($product['id_product']);
                 if (in_array((int) $id_category, Product::getProductCategories($product['id_product']))) {
                     if (($this->p - 1) * $this->n <= $index && $index < $this->p * $this->n) {
                         $results[] = $product;
                     }
                     $index++;
                 }
             }
             $nbProducts = $index;
             foreach ($results as &$product) {
                 $product['link'] .= (strpos($product['link'], '?') === false ? '?' : '&') . 'search_query=' . urlencode($query) . '&results=' . (int) $nbProducts;
             }
             $this->pagination($nbProducts);
             $this->addColorsToProductList($results);
             $this->context->smarty->assign(array('products' => $results, 'search_products' => $results, 'nbProducts' => $nbProducts, 'nbp' => $this->p, 'nbn' => $this->n, 'orderby' => $this->orderBy, 'orderWay' => $this->orderWay, 'request' => $this->context->link->getModuleLink('categorysearch', 'catesearch')));
         }
     } else {
         $this->context->smarty->assign(array('products' => array(), 'search_products' => array(), 'pages_nb' => 1, 'nbProducts' => 0));
     }
     $this->context->smarty->assign(array('add_prod_display' => Configuration::get('PS_ATTRIBUTE_CATEGORY_DISPLAY'), 'comparator_max_item' => Configuration::get('PS_COMPARATOR_MAX_ITEM')));
     $this->setTemplate('searchresult.tpl');
 }
<?php

include_once '../../config/config.inc.php';
include_once '../../init.php';
//$this->instant_search = Tools::getValue('instantSearch');
//$this->ajax_search = Tools::getValue('ajaxSearch');
//parent::initContent();
$query = Tools::replaceAccentedChars(urldecode(Tools::getValue('q')));
$original_query = Tools::getValue('q');
$searchResults = Search::find((int) Tools::getValue('id_lang'), $query, 1, 10, 'position', 'desc', true);
foreach ($searchResults as &$product) {
    //$product['product_link'] = $this->context->link->getProductLink($product['id_product'], $product['prewrite'], $product['crewrite']);
    $links = new Link();
    $product['product_link'] = $links->getProductLink($product['id_product'], $product['prewrite'], $product['crewrite']);
    /**
                *Get product cover
                */
    $tdgetpover = Product::getCover($product['id_product']);
    $cproduct_image = new Image($tdgetpover['id_image']);
    $cproductimg_url = $cproduct_image->getExistingImgPath() . '-small_default.jpg';
    $product['ajaxsearchimage'] = $cproductimg_url;
}
die(Tools::jsonEncode($searchResults));
Example #22
0
 private function _setProductFilterList()
 {
     $productFilterListSource = Tools::getValue('productFilterListSource');
     if (in_array($productFilterListSource, array('best-sales', 'new-products', 'prices-drop', 'search'))) {
         PM_AdvancedSearch4::$productFilterListSource = $productFilterListSource;
         if ($productFilterListSource == 'search') {
             $productFilterListData = @base64_decode(Tools::getValue('productFilterListData'));
             if ($productFilterListData !== false) {
                 if (version_compare(_PS_VERSION_, '1.5.0.0', '>=')) {
                     PM_AdvancedSearch4::$productFilterListData = Tools::replaceAccentedChars(urldecode($productFilterListData));
                 } else {
                     PM_AdvancedSearch4::$productFilterListData = urldecode($productFilterListData);
                 }
                 Module::getInstanceByName('pm_advancedsearch4')->setProductFilterContext();
             }
         }
     }
 }
Example #23
0
    public static function indexation($full = false, $id_product = false)
    {
        $db = Db::getInstance();
        if ($id_product) {
            $full = false;
        }
        if ($full) {
            $db->execute('TRUNCATE ' . _DB_PREFIX_ . 'search_index');
            $db->execute('TRUNCATE ' . _DB_PREFIX_ . 'search_word');
            ObjectModel::updateMultishopTable('Product', array('indexed' => 0));
        } else {
            // Do it even if you already know the product id in order to be sure that it exists and it needs to be indexed
            $products = $db->executeS('
				SELECT p.id_product
				FROM ' . _DB_PREFIX_ . 'product p
				' . Shop::addSqlAssociation('product', 'p') . '
				WHERE product_shop.visibility IN ("both", "search")
				AND ' . ($id_product ? 'p.id_product = ' . (int) $id_product : 'product_shop.indexed = 0'));
            $ids = array();
            if ($products) {
                foreach ($products as $product) {
                    $ids[] = (int) $product['id_product'];
                }
            }
            if (count($ids)) {
                $db->execute('DELETE FROM ' . _DB_PREFIX_ . 'search_index WHERE id_product IN (' . implode(',', $ids) . ')');
                ObjectModel::updateMultishopTable('Product', array('indexed' => 0), 'a.id_product IN (' . implode(',', $ids) . ')');
            }
        }
        // Every fields are weighted according to the configuration in the backend
        $weight_array = array('pname' => Configuration::get('PS_SEARCH_WEIGHT_PNAME'), 'reference' => Configuration::get('PS_SEARCH_WEIGHT_REF'), 'ean13' => Configuration::get('PS_SEARCH_WEIGHT_REF'), 'upc' => Configuration::get('PS_SEARCH_WEIGHT_REF'), 'description_short' => Configuration::get('PS_SEARCH_WEIGHT_SHORTDESC'), 'description' => Configuration::get('PS_SEARCH_WEIGHT_DESC'), 'cname' => Configuration::get('PS_SEARCH_WEIGHT_CNAME'), 'mname' => Configuration::get('PS_SEARCH_WEIGHT_MNAME'), 'tags' => Configuration::get('PS_SEARCH_WEIGHT_TAG'), 'attributes' => Configuration::get('PS_SEARCH_WEIGHT_ATTRIBUTE'), 'features' => Configuration::get('PS_SEARCH_WEIGHT_FEATURE'));
        // Those are kind of global variables required to save the processed data in the database every X occurrences, in order to avoid overloading MySQL
        $count_words = 0;
        $query_array3 = array();
        // Every indexed words are cached into a PHP array
        $word_ids = $db->executeS('
			SELECT id_word, word, id_lang, id_shop
			FROM ' . _DB_PREFIX_ . 'search_word', false);
        $word_ids_by_word = array();
        while ($word_id = $db->nextRow($word_ids)) {
            if (!isset($word_ids_by_word[$word_id['id_shop']][$word_id['id_lang']])) {
                $word_ids_by_word[$word_id['id_shop']][$word_id['id_lang']] = array();
            }
            $word_ids_by_word[$word_id['id_shop']][$word_id['id_lang']]['_' . $word_id['word']] = (int) $word_id['id_word'];
        }
        // Retrieve the number of languages
        $total_languages = count(Language::getLanguages(false));
        // Products are processed 50 by 50 in order to avoid overloading MySQL
        while (($products = Search::getProductsToIndex($total_languages, $id_product, 50)) && count($products) > 0) {
            $products_array = array();
            // Now each non-indexed product is processed one by one, langage by langage
            foreach ($products as $product) {
                $product['tags'] = Search::getTags($db, (int) $product['id_product'], (int) $product['id_lang']);
                $product['attributes'] = Search::getAttributes($db, (int) $product['id_product'], (int) $product['id_lang']);
                $product['features'] = Search::getFeatures($db, (int) $product['id_product'], (int) $product['id_lang']);
                // Data must be cleaned of html, bad characters, spaces and anything, then if the resulting words are long enough, they're added to the array
                $product_array = array();
                foreach ($product as $key => $value) {
                    if (strncmp($key, 'id_', 3) && isset($weight_array[$key])) {
                        $words = explode(' ', Search::sanitize($value, (int) $product['id_lang'], true, $product['iso_code']));
                        foreach ($words as $word) {
                            if (!empty($word)) {
                                $word = Tools::substr($word, 0, PS_SEARCH_MAX_WORD_LENGTH);
                                // Remove accents
                                $word = Tools::replaceAccentedChars($word);
                                if (!isset($product_array[$word])) {
                                    $product_array[$word] = 0;
                                }
                                $product_array[$word] += $weight_array[$key];
                            }
                        }
                    }
                }
                // If we find words that need to be indexed, they're added to the word table in the database
                if (count($product_array)) {
                    $query_array = $query_array2 = array();
                    foreach ($product_array as $word => $weight) {
                        if ($weight && !isset($word_ids_by_word['_' . $word])) {
                            $query_array[$word] = '(' . (int) $product['id_lang'] . ', ' . (int) $product['id_shop'] . ', \'' . pSQL($word) . '\')';
                            $query_array2[] = '\'' . pSQL($word) . '\'';
                            $word_ids_by_word[$product['id_shop']][$product['id_lang']]['_' . $word] = 0;
                        }
                    }
                    if ($query_array2) {
                        $existing_words = $db->executeS('
						SELECT DISTINCT word FROM ' . _DB_PREFIX_ . 'search_word
							WHERE word IN (' . implode(',', $query_array2) . ')
						AND id_lang = ' . (int) $product['id_lang'] . '
						AND id_shop = ' . (int) $product['id_shop']);
                        foreach ($existing_words as $data) {
                            unset($query_array[Tools::replaceAccentedChars($data['word'])]);
                        }
                    }
                    if (count($query_array)) {
                        // The words are inserted...
                        $db->execute('
						INSERT IGNORE INTO ' . _DB_PREFIX_ . 'search_word (id_lang, id_shop, word)
						VALUES ' . implode(',', $query_array));
                    }
                    if (count($query_array2)) {
                        // ...then their IDs are retrieved and added to the cache
                        $added_words = $db->executeS('
						SELECT sw.id_word, sw.word
						FROM ' . _DB_PREFIX_ . 'search_word sw
						WHERE sw.word IN (' . implode(',', $query_array2) . ')
						AND sw.id_lang = ' . (int) $product['id_lang'] . '
						AND sw.id_shop = ' . (int) $product['id_shop'] . '
						LIMIT ' . count($query_array2));
                        // replace accents from the retrieved words so that words without accents or with differents accents can still be linked
                        foreach ($added_words as $word_id) {
                            $word_ids_by_word[$product['id_shop']][$product['id_lang']]['_' . Tools::replaceAccentedChars($word_id['word'])] = (int) $word_id['id_word'];
                        }
                    }
                }
                foreach ($product_array as $word => $weight) {
                    if (!$weight) {
                        continue;
                    }
                    if (!isset($word_ids_by_word[$product['id_shop']][$product['id_lang']]['_' . $word])) {
                        continue;
                    }
                    if (!$word_ids_by_word[$product['id_shop']][$product['id_lang']]['_' . $word]) {
                        continue;
                    }
                    $query_array3[] = '(' . (int) $product['id_product'] . ',' . (int) $word_ids_by_word[$product['id_shop']][$product['id_lang']]['_' . $word] . ',' . (int) $weight . ')';
                    // Force save every 200 words in order to avoid overloading MySQL
                    if (++$count_words % 200 == 0) {
                        Search::saveIndex($query_array3);
                    }
                }
                if (!in_array($product['id_product'], $products_array)) {
                    $products_array[] = (int) $product['id_product'];
                }
            }
            Search::setProductsAsIndexed($products_array);
            // One last save is done at the end in order to save what's left
            Search::saveIndex($query_array3);
        }
        return true;
    }
 public function postProcess()
 {
     //create manual inventory
     if (Tools::isSubmit('submitAction') && Tools::getValue('submitAction') == 'submitCreateInventory') {
         $this->processCreateInventory();
     } else {
         if (isset($_FILES['file']) && Tools::isSubmit('submitAction') && Tools::getValue('submitAction') == 'submitCreateInventoryFromCsv') {
             // ASA - Security Audit
             $_FILES['file']['name'] = str_replace("", "", $_FILES['file']['name']);
             // get extention file
             $file_extension = strrchr($_FILES['file']['name'], '.');
             // allowed exention
             $allowed_extensions = array('.csv');
             $file_name = basename($_FILES['file']['name']);
             if (!in_array($file_extension, $allowed_extensions)) {
                 $this->errors[] = Tools::displayError($this->l('The uploaded file is not a CSV !'));
                 return;
             }
             // max file size
             $max_file_size = 1048576;
             //1 Mo
             //file size
             $file_size = filesize($_FILES['file']['tmp_name']);
             if ($file_size > $max_file_size) {
                 $this->errors[] = Tools::displayError($this->l('Your CSV file should not weight more than 1Mo !'));
                 return;
             }
             // if error
             if (!empty($_FILES['file']['error'])) {
                 switch ($_FILES['file']['error']) {
                     case UPLOAD_ERR_INI_SIZE:
                         $this->errors[] = Tools::displayError($this->l('The uploaded file exceeds the upload_max_filesize directive in php.ini. If your server configuration allows it, you may add a directive in your .htaccess.'));
                         break;
                     case UPLOAD_ERR_FORM_SIZE:
                         $this->errors[] = Tools::displayError($this->l('The uploaded file exceeds the post_max_size directive in php.ini.
                                                                                 If your server configuration allows it, you may add a directive in your .htaccess, for example:')) . '<br/><a target="_blank" href="' . $this->context->link->getAdminLink('AdminMeta') . '" >
                                                 <code>php_value post_max_size 20M</code> ' . ($this->errors[] = Tools::displayError($this->l('(click to open "Generators" page)')) . '</a>');
                         break;
                     case UPLOAD_ERR_PARTIAL:
                         $this->errors[] = Tools::displayError($this->l('The uploaded file was only partially uploaded. Please try again.'));
                         break;
                     case UPLOAD_ERR_NO_FILE:
                         $this->errors[] = Tools::displayError($this->l('No file was uploaded'));
                         break;
                 }
             }
             // if no error
             if (count($this->errors) == 0) {
                 //we format file name
                 // $file_name = strtr($file_name,
                 // 'ÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÒÓÔÕÖÙÚÛÜÝàáâãäåçèéêëìíîïðòóôõöùúûüýÿ',
                 // 'AAAAAACEEEEIIIIOOOOOUUUUYaaaaaaceeeeiiiioooooouuuuyy');
                 $file_name = Tools::replaceAccentedChars($file_name);
                 $file_name = preg_replace('/([^.a-z0-9]+)/i', '-', $file_name);
                 $file_name = str_replace('.csv', '-' . date('Y_m_d_his') . '.csv', $file_name);
                 // try to upload
                 if (@move_uploaded_file($_FILES['file']['tmp_name'], _PS_MODULE_DIR_ . 'erpillicopresta/imports/' . $file_name)) {
                     $directory = explode("_", Tools::getValue('id_inventory'));
                     $id_erpip_inventory = $directory[0];
                     // if directory has only one element, mean it s a new directory and we get the name in the dedicated field
                     if (count($directory) > 1) {
                         $name = $directory[1];
                     } else {
                         $name = Tools::getValue('new_inventory');
                     }
                     $id_warehouse = Tools::getValue('selected_warehouse');
                     $id_employee = $this->context->employee->id;
                     $firstname = $this->context->employee->firstname;
                     $lastname = $this->context->employee->lastname;
                     $inventory_values = '';
                     /* ------------------ TREATMENT CSV ------------*/
                     // 2 - open file
                     $handle = $this->openCsvFile($file_name);
                     // 3 - Browse file
                     $i = 0;
                     while ($data = fgetcsv($handle, 0, ";")) {
                         // 4 - reconstruct inventory_values
                         /*
                         $id_product = $data[0];
                         $id_product_attribute = $data[1];
                         $area = $data[5];
                         $subarea = $data[6];
                         $location = $data[7];
                         $physical_quantity = $data[8];
                         $found_quantity = $data[9];
                         */
                         //idproduct==6|idproductattribute==0|idreason==109|area==null|subarea==null|location==|physicalquantity==61|foundquantity==20_
                         // don't use the first line : headers
                         if ($i > 0) {
                             $inventory_values .= 'idproduct==' . $data[0] . '|';
                             $inventory_values .= 'idproductattribute==' . $data[1] . '|';
                             //$inventory_values .= 'idreason==|area=='.$data[-1].'|';
                             $inventory_values .= 'area==' . $data[5] . '|';
                             $inventory_values .= 'subarea==' . $data[6] . '|';
                             $inventory_values .= 'location==' . $data[7] . '|';
                             if (isset($data[8])) {
                                 $inventory_values .= 'physicalquantity==' . $data[8] . '|';
                             }
                             if (isset($data[9])) {
                                 $inventory_values .= 'foundquantity==' . (int) $data[9] . '_';
                             }
                         }
                         $i++;
                     }
                     // 5 - prepare inventory
                     $this->id_erpip_inventory = $id_erpip_inventory;
                     $this->name = $name;
                     $this->id_warehouse = $id_warehouse;
                     $this->id_employee = $id_employee;
                     $this->firstname = $firstname;
                     $this->lastname = $lastname;
                     $this->advanced_stock_management = $this->advanced_stock_management;
                     $this->inventory_values = $inventory_values;
                     $this->createContainer();
                 } else {
                     $this->errors[] = $this->l('An error occurred while uploading and copying the file. Please try again or contact the customer service.');
                 }
             }
         }
     }
     // Export CSV
     if (Tools::isSubmit('export_csv')) {
         $this->renderCSV();
     }
     // Export PDF
     if (Tools::isSubmit('submitAction') && Tools::getValue('submitAction') == 'generateInventoryPDF') {
         $this->processGenerateInventoryPDF();
     }
     parent::postProcess();
 }