public function convert($args) { if (isset($args[0])) { $vc47d187067c6cf953245f128b5fde62a = $args[0]; $vc47d187067c6cf953245f128b5fde62a = iconv("UTF-8", "CP1251", $vc47d187067c6cf953245f128b5fde62a); $ve730db5c29b7ba34f4d465b01bd33c5e = new Lingua_Stem_Ru(); $result = $ve730db5c29b7ba34f4d465b01bd33c5e->stem_word($vc47d187067c6cf953245f128b5fde62a); return iconv("CP1251", "UTF-8", $result); } else { return $args; } }
public function get($string) { require INC_DIR . 'stemmer.class.php'; $stemmer = new Lingua_Stem_Ru(); $str = $stemmer->stem_word($string); if (!empty($str) && mb_strlen($string) >= 3) { $rows = array(); $rows = array_merge($rows, $this->get_from_db($str, 'Ishop', 'ishop/product', TABLE_PRODUCTS, array('title', 'opisanie', 'param_polnoeopisanie', 'artikul', 'tsena', 'foto', 'vlink', 'enabled'))); $rows = array_merge($rows, $this->get_from_db($str, 'Ishop', 'ishop', TABLE_CATEGORIES, array('title', 'text', 'text2', 'foto', 'vlink', 'enabled'))); $rows = array_merge($rows, $this->get_from_db($str, 'Site', 'page', TABLE_SITEMENU, array('title', 'html', 'vlink', 'enabled'))); $rows = array_merge($rows, $this->get_from_db($str, 'News', 'news', TABLE_NEWS, array('t', 'txt', 'vlink'))); $html = $this->form_content($rows, $string); } elseif (empty($str) || mb_strlen($str) < 3) { $html = 'Запрос должен состоять как минимум из 3-х символов!'; } if (!isset($html) || empty($html)) { $html = 'По запросу "<u>' . $str . '</u>" ничего не найдено.'; } $content = array('html' => $html, 'meta_title' => 'Поиск', 'meta_keys' => 'Поиск', 'meta_desc' => 'Поиск', 'path' => 'Поиск'); return $content; }
function search_eshop($params) { global $tpl, $template, $twig, $mysql, $SYSTEM_FLAGS, $config, $userROW, $CurrentHandler, $lang; $url = pluginGetVariable('eshop', 'url'); switch ($CurrentHandler['handlerParams']['value']['pluginName']) { case 'core': if (isset($url) && !empty($url)) { return redirect_eshop(generateLink('eshop', 'search')); } break; case 'eshop': if (empty($url)) { return redirect_eshop(generateLink('core', 'plugin', array('plugin' => 'eshop'))); } break; } $SYSTEM_FLAGS['info']['title']['group'] = $lang['eshop']['name_plugin']; $SYSTEM_FLAGS['info']['title']['others'] = $lang['eshop']['name_search']; $SYSTEM_FLAGS['template.main.name'] = pluginGetVariable('eshop', 'main_template') ? pluginGetVariable('eshop', 'main_template') : 'main'; $SYSTEM_FLAGS['meta']['description'] = pluginGetVariable('eshop', 'description') ? pluginGetVariable('eshop', 'description') : $SYSTEM_FLAGS['meta']['description']; $SYSTEM_FLAGS['meta']['keywords'] = pluginGetVariable('eshop', 'keywords') ? pluginGetVariable('eshop', 'keywords') : $SYSTEM_FLAGS['meta']['keywords']; $tpath = locatePluginTemplates(array('search_eshop'), 'eshop', pluginGetVariable('eshop', 'localsource'), pluginGetVariable('eshop', 'localskin')); $xt = $twig->loadTemplate($tpath['search_eshop'] . 'search_eshop.tpl'); if (isset($_REQUEST['keywords']) && $_REQUEST['keywords']) { $keywords = filter_var($_REQUEST['keywords'], FILTER_SANITIZE_STRING); /* $cat_id = intval($_REQUEST['cat_id']); if(empty($cat_id)) $cat_id = 0; $search_in = secure_search_eshop($_REQUEST['search_in']); if(empty($search_in)) $search_in = 'all'; */ $search = substr($keywords, 0, 64); if (strlen($search) < 3) { $output = msg(array("type" => "error", "text" => "Слишком короткое слово"), 1, 2); } $keywords = array(); $get_url = $search; $search = str_replace(" +", " ", $search); $stemmer = new Lingua_Stem_Ru(); $tmp = explode(" ", $search); foreach ($tmp as $wrd) { $keywords[] = $stemmer->stem_word($wrd); } $string = implode("* ", $keywords); $string = $string . '*'; $text = implode('|', $keywords); $conditions = array(); if (isset($text) && !empty($text)) { array_push($conditions, "MATCH (p.name, p.annotation, p.body) AGAINST ('{$string}' IN BOOLEAN MODE) "); array_push($conditions, "p.active = 1 "); } $limitCount = pluginGetVariable('eshop', 'count_search'); $pageNo = intval($params['page']) ? intval($params['page']) : intval($_REQUEST['page']); if ($pageNo < 1) { $pageNo = 1; } if (!$limitStart) { $limitStart = ($pageNo - 1) * $limitCount; } $fSort = " GROUP BY p.id ORDER BY p.id DESC"; $sqlQPart = "FROM " . prefix . "_eshop_products p LEFT JOIN " . prefix . "_eshop_products_categories pc ON p.id = pc.product_id LEFT JOIN " . prefix . "_eshop_categories c ON pc.category_id = c.id " . (count($conditions) ? "WHERE " . implode(" AND ", $conditions) : '') . $fSort; $sqlQ = "SELECT p.id AS id, p.url as url, p.code AS code, p.name AS name, p.annotation AS annotation, p.body AS body, p.active AS active, p.featured AS featured, p.position AS position, p.meta_title AS meta_title, p.meta_keywords AS meta_keywords, p.meta_description AS meta_description, p.date AS date, p.editdate AS editdate, p.views AS views, c.id AS cid, c.url as curl, c.name AS category " . $sqlQPart; $sqlQCount = "SELECT COUNT(*) as CNT FROM (" . $sqlQ . ") AS T "; $count = $mysql->result($sqlQCount); //if($count == 0) // return msg(array("type" => "error", "text" => "В данной категории пока что нету продукции")); $countPages = ceil($count / $limitCount); //if($countPages < $pageNo) // return msg(array("type" => "error", "text" => "Подстраницы не существует")); if ($countPages > 1 && $countPages >= $pageNo) { $paginationParams = checkLinkAvailable('eshop', '') ? array('pluginName' => 'eshop', 'pluginHandler' => 'search', 'params' => array('keywords' => $get_url ? $get_url : ''), 'xparams' => array('keywords' => $get_url ? $get_url : ''), 'paginator' => array('page', 0, false)) : array('pluginName' => 'core', 'pluginHandler' => 'plugin', 'params' => array('plugin' => 'eshop'), 'xparams' => array('keywords' => $get_url ? $get_url : ''), 'paginator' => array('page', 1, false)); $navigations = LoadVariables(); $pages = generatePagination($pageNo, 1, $countPages, 10, $paginationParams, $navigations); } $cmp_array = array(); foreach ($SYSTEM_FLAGS["eshop"]["compare"]["entries"] as $cmp_row) { $cmp_array[] = $cmp_row['linked_fld']; } foreach ($mysql->select($sqlQ . ' LIMIT ' . $limitStart . ', ' . $limitCount) as $row) { $fulllink = checkLinkAvailable('eshop', 'show') ? generateLink('eshop', 'show', array('alt' => $row['url'])) : generateLink('core', 'plugin', array('plugin' => 'eshop', 'handler' => 'show'), array('alt' => $row['url'])); $catlink = checkLinkAvailable('eshop', '') ? generateLink('eshop', '', array('alt' => $row['curl'])) : generateLink('core', 'plugin', array('plugin' => 'eshop'), array('alt' => $row['curl'])); $cmp_flag = in_array($row['id'], $cmp_array); $entries[$row['id']] = array('id' => $row['id'], 'code' => $row['code'], 'name' => $row['name'], 'annotation' => $row['annotation'], 'body' => $row['body'], 'active' => $row['active'], 'featured' => $row['featured'], 'meta_title' => $row['meta_title'], 'meta_keywords' => $row['meta_keywords'], 'meta_description' => $row['meta_description'], 'fulllink' => $fulllink, 'date' => empty($row['date']) ? '' : $row['date'], 'editdate' => empty($row['editdate']) ? '' : $row['editdate'], 'views' => $row['views'], 'cat_name' => $row['category'], 'cid' => $row['cid'], 'catlink' => $catlink, 'compare' => $cmp_flag, 'home' => home, 'tpl_url' => home . '/templates/' . $config['theme']); } $entries_array_ids = array_keys($entries); if (isset($entries_array_ids) && !empty($entries_array_ids)) { $entries_string_ids = implode(',', $entries_array_ids); foreach ($mysql->select('SELECT * FROM ' . prefix . '_eshop_images i WHERE i.product_id IN (' . $entries_string_ids . ') ORDER BY i.position, i.id') as $irow) { $entries[$irow['product_id']]['images'][] = $irow; } foreach ($mysql->select('SELECT * FROM ' . prefix . '_eshop_variants v WHERE v.product_id IN (' . $entries_string_ids . ') ORDER BY v.position, v.id') as $vrow) { $entries[$vrow['product_id']]['variants'][] = $vrow; } } } $tVars = array('search_request' => $get_url, 'info' => isset($info) ? $info : '', 'entries' => isset($entries) ? $entries : '', 'pages' => array('true' => isset($pages) && $pages ? 1 : 0, 'print' => isset($pages) ? $pages : ''), 'prevlink' => array('true' => !empty($limitStart) ? 1 : 0, 'link' => str_replace('%page%', "\$1", str_replace('%link%', checkLinkAvailable('eshop', '') ? generatePageLink(array('pluginName' => 'eshop', 'pluginHandler' => 'search', 'params' => array('keywords' => $get_url ? $get_url : ''), 'xparams' => array('keywords' => $get_url ? $get_url : ''), 'paginator' => array('page', 0, false)), $prev = floor($limitStart / $limitCount)) : generatePageLink(array('pluginName' => 'core', 'pluginHandler' => 'plugin', 'params' => array('plugin' => 'eshop'), 'xparams' => array('keywords' => $get_url ? $get_url : ''), 'paginator' => array('page', 1, false)), $prev = floor($limitStart / $limitCount)), isset($navigations['prevlink']) ? $navigations['prevlink'] : ''))), 'nextlink' => array('true' => $prev + 2 <= $countPages ? 1 : 0, 'link' => str_replace('%page%', "\$1", str_replace('%link%', checkLinkAvailable('eshop', '') ? generatePageLink(array('pluginName' => 'eshop', 'pluginHandler' => 'search', 'params' => array('keywords' => $get_url ? $get_url : ''), 'xparams' => array('keywords' => $get_url ? $get_url : ''), 'paginator' => array('page', 0, false)), $prev + 2) : generatePageLink(array('pluginName' => 'core', 'pluginHandler' => 'plugin', 'params' => array('plugin' => 'eshop'), 'xparams' => array('keywords' => $get_url ? $get_url : ''), 'paginator' => array('page', 1, false)), $prev + 2), isset($navigations['nextlink']) ? $navigations['nextlink'] : ''))), 'tpl_url' => home . '/templates/' . $config['theme'], 'tpl_home' => admin_url); $template['vars']['mainblock'] .= $xt->render($tVars); }
/** * Подготавливает строку поиска для sql запроса * формирует $this->against и $this->words * @return bool */ protected function getAgainst() { // если уже получали, возвращаемся if (!empty($this->against) && !empty($this->words)) { return true; } $this->against = array(); $this->words = array(); // Подключаем стеммер Портера cmsCore::includeFile('includes/stemmer/stemmer.php'); $stemmer = new Lingua_Stem_Ru(); // формируем массив слов $words = preg_split('/[\s,-]+/', $this->query, null, PREG_SPLIT_NO_EMPTY); if ($this->look == 'anyword' || $this->look == 'allwords') { foreach($words as $w) { $w = trim($w); if (mb_strlen($w) > 3) { if (mb_strlen($w) == 4) { $this->against[] = '('. $w .' | *'. $w .'*)'; $this->words[] = $w; } else { $w = $stemmer->stem_word($w); $this->against[] = '('. $w .' | *'. $w .'*)'; $this->words[] = $w; } } } } // любое слово if ($this->look == 'anyword') { $this->against = implode(' | ', $this->against); } // все слова if ($this->look == 'allwords') { $this->against = implode(' & ', $this->against); } // фраза целиком if ($this->look == 'phrase') { $this->against = '*'. $this->query .'*'; $this->words = $words; } else { $this->words = implode(' ', $this->words); } return true; }
/** * Подготавливает строку поиска для sql запроса * формирует $this->against и $this->words * @return bool */ protected function getAgainst() { // если уже получали, возвращаемся if ($this->against && $this->words) { return true; } // Подключаем стеммер Портера $this->inCore->includeFile('includes/stemmer/stemmer.php'); $stemmer = new Lingua_Stem_Ru(); // формируем массив слов $words = explode(' ', $this->query); // любое слово if ($this->look == 'anyword') { foreach($words as $w) { $w = trim($w); if (mb_strlen($w) > 3) { if (mb_strlen($w) == 4) { $this->against .= $w .'* '; $this->words .= $w .' '; } else { $this->against .= $stemmer->stem_word($w) .'* '; $this->words .= $stemmer->stem_word($w) .' '; } } } } // все слова if ($this->look == 'allwords') { $this->against = '>\"'. $this->query .'\" '; $this->against .= '<('; foreach ($words as $w) { $w = trim($w); if (mb_strlen($w) > 3) { if (mb_strlen($w) == 4) { $this->against .= '+'. $w .'* '; $this->words .= $w .' '; } else { $this->against .= '+'. $stemmer->stem_word($w) .'* '; $this->words .= $stemmer->stem_word($w) .' '; } } } $this->against .= ')'; } // фраза целиком if ($this->look == 'phrase') { $this->against = '\"'. $this->query .'\"'; $this->words = $this->query; } return true; }
$aMatchNews = getMatchNews($q); // Сливаем результаты $aOutMatch = array_merge($aMatch, $aMatchNews); // Сортируем по релевантности uasort($aOutMatch, 'relcmp'); // Выводим foreach ($aOutMatch as $k => $v) { $tplSearchResults = $tpl->fetchBlock('SearchResults'); $tplSearchResults->assign($v); $tplSearchResults->assign('path', $k); $tpl->assign('SearchResults', $tplSearchResults); $tplSearchResults->reset(); } // Формируем стемминг-запрос $stem = ''; $Stem = new Lingua_Stem_Ru(); foreach ($aWords as $k => $v) { $stem .= $Stem->stem_word($v) . '* '; } $tpl->assign('stem', $stem); // Ищем в страницах $aStem = getStem($stem); // Ищем в новостях $aStemNews = getStemNews($stem); // Сливаем результаты $aOutStem = array_merge($aStem, $aStemNews); // Сортируем по релевантности uasort($aOutStem, 'relcmp'); // Выводим foreach ($aOutStem as $k => $v) { $tplSearchStemResults = $tpl->fetchBlock('SearchStemResults');
function search() { //debug($this->params); $this->subheaderTitle = 'РЕЗУЛЬТАТЫ ПОИСКА'; // function vars ini. $searchCleanString = null; $searchCleanType = null; $categoryToSearch = array(); $CategoryToSearchNew = array(); $CategoryToSearchFinal = array(); $searchBlockTrimed = null; $searchResult = array(); $giftsSet = array(); $giftsSetUnique = array(); $paramNamedToPass = array(); $inputCheck = null; //datas cleaning. $this->params = Sanitize::clean($this->params); //to activate late $searchClean = Sanitize::paranoid( ( $this->data['Gift']['string'] ), array(' ',',', '.','-', 'абвгдеёжзийклмнопрстуфхцчшщъыьэюяАБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ') ); //checking of presents of the params for search if (!empty($this->data)) { $case = 0; } elseif (empty($this->data) && !empty($this->passedArgs)) { $case = 1; } else { // nothing in form, nothing in url, so : $this->render('noresult'); $case = 2; } switch ($case) { case 0: //echo 'case 0'; if ($this->data['Gift']['string'] != null) { $searchCleanString = $this->data['Gift']['string']; $paramConditions[] = 'string:' . $searchCleanString; $inputCheck = 1; } if ($this->data['Gift']['type'] != null) { $searchCleanType = $this->data['Gift']['type']; $paramConditions[] = 'type:' . $searchCleanType; //$inputCheck = 1; } if (isset($this->data['priceMin']) && $this->data['priceMin'] != null) { //$this->Gift->set($this->data['priceMin']); if (is_numeric($this->data['priceMin'])) { $seachCleanPriceMin = $this->data['priceMin']; $paramConditions[] = 'priceMin:' . $seachCleanPriceMin; $inputCheck = 1; } else { $this->data['priceMin'] = null; $this->Session->setFlash('Неправильная минимальная цена товара!'); $this->redirect(array('controller' => 'Gifts', 'action' => 'extsearch')); } } if (isset($this->data['priceMax']) && $this->data['priceMax'] != null) { if (is_numeric($this->data['priceMax'])) { $seachCleanPriceMax = $this->data['priceMax']; $paramConditions[] = 'priceMax:' . $seachCleanPriceMax; $inputCheck = 1; } else { $this->data['priceMax'] = null; $this->Session->setFlash('Неправильная максимальная цена товара!'); $this->redirect(array('controller' => 'Gifts', 'action' => 'extsearch')); } } if (isset($this->data['priceOrder']) && $this->data['priceOrder'] != null) { $seachCleanPriceOrder = $this->data['priceOrder']; $paramConditions[] = 'sort:Gift.price/direction:' . $seachCleanPriceOrder; //sort:name/direction:asc $this->paginate['Gift']['order']['price'] = $seachCleanPriceOrder; $this->paginate['Gift']['limit'] = 9; } $categoryToSearch = array(); // Making array of selected categories if (isset($this->data['Checkbox']['oasisBG']) && $this->data['Checkbox']['oasisBG'] == 1) { $categoryToSearch[] = $this->data['Cat']['oasisBG']; $searchCleanOasisBG = $this->data['Cat']['oasisBG']; $paramConditions[] = 'oasisBG:' . $searchCleanOasisBG; $inputCheck = 1; } if (isset($this->data['Checkbox']['oasisEX']) && $this->data['Checkbox']['oasisEX'] == 1) { $categoryToSearch[] = $this->data['Cat']['oasisEX']; $searchCleanOasisEX = $this->data['Cat']['oasisEX']; $paramConditions[] = 'oasisEX:' . $searchCleanOasisEX; $inputCheck = 1; } if (isset($this->data['Checkbox']['penoteka']) && $this->data['Checkbox']['penoteka'] == 1) { $categoryToSearch[] = $this->data['Cat']['penoteka']; $searchCleanPenoteka = $this->data['Cat']['penoteka']; $paramConditions[] = 'penoteka:' . $searchCleanPenoteka; $inputCheck = 1; } if (isset($this->data['Checkbox']['ferre']) && $this->data['Checkbox']['ferre'] == 1) { $categoryToSearch[] = $this->data['Cat']['ferre']; $searchCleanFerre = $this->data['Cat']['ferre']; $paramConditions[] = 'ferre:' . $searchCleanFerre; $inputCheck = 1; } if (isset($this->data['Checkbox']['15days']) && $this->data['Checkbox']['15days'] == 1) { $categoryToSearch[] = $this->data['Cat']['15days']; $searchClean15days = $this->data['Cat']['15days']; $paramConditions[] = '15days:' . $searchClean15days; $inputCheck = 1; } if (isset($this->data['Checkbox']['proekt111']) && $this->data['Checkbox']['proekt111'] == 1) { $categoryToSearch[] = $this->data['Cat']['proekt111']; $searchCleanProekt111 = $this->data['Cat']['proekt111']; $paramConditions[] = 'proekt111:' . $searchCleanProekt111; $inputCheck = 1; } if (isset($this->data['Checkbox']['usb']) && $this->data['Checkbox']['usb'] == 1) { $categoryToSearch[] = $this->data['Cat']['usb']; $searchCleanUsb = $this->data['Cat']['usb']; $paramConditions[] = 'usb:' . $searchCleanUsb; $inputCheck = 1; } if (isset($this->data['Checkbox']['toys']) && $this->data['Checkbox']['toys'] == 1) { $categoryToSearch[] = $this->data['Cat']['toys']; $searchCleanToys = $this->data['Cat']['toys']; $paramConditions[] = 'toys:' . $searchCleanToys; $inputCheck = 1; } //rendering the nessesary view if ($inputCheck == null) { //$renderOuput = 'extsearch'; $this->Session->setFlash('Вы не ввели ни одного параметра!'); $this->redirect(array('controller' => 'Gifts', 'action' => 'extsearch')); } $renderOuput = 'search'; debug($paramConditions); $this->set('toSearch', $paramConditions); break; case 1: //echo 'case 1'; if (isset($this->params['named']['string'])) { $searchCleanString = $this->params['named']['string']; $paramNamedToPass['string'] = $this->params['named']['string']; } if (isset($this->params['named']['type'])) { $searchCleanType = $this->params['named']['type']; $paramNamedToPass['type'] = $this->params['named']['type']; } if (isset($this->params['named']['priceMin'])) { $seachCleanPriceMin = $this->params['named']['priceMin']; $paramNamedToPass['priceMin'] = $this->params['named']['priceMin']; } if (isset($this->params['named']['priceMax'])) { $seachCleanPriceMax = $this->params['named']['priceMax']; $paramNamedToPass['priceMax'] = $this->params['named']['priceMax']; } if (isset($this->params['named']['oasisBG'])) { $categoryToSearch[] = $this->params['named']['oasisBG']; $paramNamedToPass['oasisBG'] = $this->params['named']['oasisBG']; } if (isset($this->params['named']['oasisEX'])) { $categoryToSearch[] = $this->params['named']['oasisEX']; $paramNamedToPass['oasisEX'] = $this->params['named']['oasisEX']; } if (isset($this->params['named']['penoteka'])) { $categoryToSearch[] = $this->params['named']['penoteka']; $paramNamedToPass['penoteka'] = $this->params['named']['penoteka']; } if (isset($this->params['named']['ferre'])) { $categoryToSearch[] = $this->params['named']['ferre']; $paramNamedToPass['ferre'] = $this->params['named']['ferre']; } if (isset($this->params['named']['15days'])) { $categoryToSearch[] = $this->params['named']['15days']; $paramNamedToPass['15days'] = $this->params['named']['15days']; } if (isset($this->params['named']['proekt111'])) { $categoryToSearch[] = $this->params['named']['proekt111']; $paramNamedToPass['proekt111'] = $this->params['named']['proekt111']; } if (isset($this->params['named']['usb'])) { $categoryToSearch[] = $this->params['named']['usb']; $paramNamedToPass['usb'] = $this->params['named']['usb']; } if (isset($this->params['named']['toys'])) { $categoryToSearch[] = $this->params['named']['toys']; $paramNamedToPass['toys'] = $this->params['named']['toys']; } $renderOuput = 'search'; //To show the values in the input fields. $this->data['Gift']['string'] = $searchCleanString; $this->data['Gift']['type'] = $searchCleanType; //debug($paramNamedToPass); $this->set('toSearch', $paramNamedToPass); break; case 2: //debug($this->data); $renderOuput = 'extsearch'; $this->redirect(array('controller' => 'Gifts', 'action' => 'extsearch')); break; } // preparation of the array of the categories for searching debug($categoryToSearch); if ($categoryToSearch != array()) { foreach ($categoryToSearch as $allCategoryToSearch) { if (in_array($allCategoryToSearch, array(143, 137, 149, 228, 210, 6))) { $CategoryToSearchNew = $this->Category->children($allCategoryToSearch, false); foreach ($CategoryToSearchNew as $CategoryToSearchNew2) { $CategoryToSearchFinal[] = $CategoryToSearchNew2['Category']['id']; } } else { $CategoryToSearchFinal[] = $allCategoryToSearch; } } //debug($CategoryToSearchFinal); $tt = $this->CategoriesGift->find('all', array('conditions' => array('category_id' => $CategoryToSearchFinal))); $giftsScope = array(); if ($tt != array()) { foreach ($tt as $v) { $temGiff[] = $v['CategoriesGift']['gift_id']; } //debug(count($temGiff)); $giftsScope = array_unique($temGiff); //all Gifts id's belong to the selected categories. } } //debug($giftsScope); //$a = preg_split("/[\s,]+/" , $searchCleanString ); //separation cleaned string by the ','; $searchBlocks = explode(',', $searchCleanString); //Trimming of the search Blocks. foreach ($searchBlocks as $searchBlockTemp) { if (trim($searchBlockTemp) != null) { $searchBlockTrimed[] = trim($searchBlockTemp); } } //cleaning the array. if user add the same word: ex. 'word,word' $searchBlockTrimed = array_unique((array) $searchBlockTrimed); foreach ($searchBlockTrimed as $searchBlock) { if ($searchCleanType == 1) { //gift's code search mode if (strpos($searchBlock, '.') == strlen($searchBlock) - 1) { $searchBlock = str_replace('.', '', $searchBlock); //cut out the last point if it exists. case the code is corecet, but no extention. } if (strpos($searchBlock, '.')) { //we have point, but not at the last position. we take all the extentions $this->Gift->recursive = -1; $searchResult = $this->Gift->find('all', array('conditions' => array('Gift.code like' => $searchBlock . '%'), 'fields' => array('Gift.id', 'Gift.code', 'Gift.name'))); } else { // no point in the request. // looking for the exact code without point $this->Gift->recursive = -1; $searchResult = $this->Gift->find('all', array('conditions' => array('Gift.code like' => $searchBlock), 'fields' => array('Gift.id', 'Gift.code', 'Gift.name'))); if ($searchResult == null) { //no code without point at the end. User hasn't made a mistake. We add point back and looking again. $this->Gift->recursive = -1; $searchResult = $this->Gift->find('all', array('conditions' => array('Gift.code like' => $searchBlock . '.%'), 'fields' => array('Gift.id', 'Gift.code', 'Gift.name'))); } } foreach ($searchResult as $giftSet) { $giftsSet[] = $giftSet['Gift']['id']; } } else { //case seaching Gifts name. $searchLine = null; $searchLine2 = array(); $searchCondFulltext = null; $searchCondThreeLetter = null; //importing stemmer, cutting out the words ends. App::import('Vendor', array('Stem', 'stem')); $stemmer = new Lingua_Stem_Ru(); //extracting words out of the search block. $words = explode(' ', $searchBlock); foreach ($words as $word) { if ($word == null) { unset($word); continue; } $word = trim($word); $wordLower = mb_strtolower($word, 'utf8'); $wordResult = $stemmer->stem_word($wordLower); //debug($wordResult); //debug($word); if (mb_strlen($word, 'utf8') > 3) { if ($wordResult == $word) { $searchLine .= '+' . $wordResult; // we haven't cut the end of the word( ex: футбол футболк } else { $searchLine .= '+' . $wordResult . '* '; } } else { $searchLine2[] = $word; } // AND ( `name` LIKE '% òîï %' OR `name` LIKE 'òîï %' ) } if ($searchLine2 != null) { $searchCondThreeLetter = " (`name` LIKE '% " . $searchLine2[0] . " %' OR `name` LIKE '" . $searchLine2[0] . "%' )"; for ($i = 1; $i < count($searchLine2); $i++) { $searchCondThreeLetter .= " AND ( `name` LIKE '% " . $searchLine2[$i] . " %' OR `name` LIKE '" . $searchLine2[$i] . "%' )"; } } //`name` LIKE '%женс%' AND ( `name` LIKE '% топ %' OR `name` LIKE 'топ %' ) And ( `name` LIKE '%син%' or `name` like '%бел%') if ($searchLine != null) { $searchCondFulltext = " MATCH (name, material) AGAINST ('" . $searchLine . "' IN BOOLEAN MODE) "; } if ($searchCondFulltext != null && $searchCondThreeLetter != null) { $toSearchCond = $searchCondFulltext . ' AND ' . $searchCondThreeLetter; } elseif ($searchCondFulltext != null && $searchCondThreeLetter == null) { $toSearchCond = $searchCondFulltext; } elseif ($searchCondFulltext == null && $searchCondThreeLetter != null) { $toSearchCond = $searchCondThreeLetter; } else { $toSearchCond = null; } debug($toSearchCond); //adding the rest of conditions: price, order... } // end of case seaching Gifts name. } // More conditions preparation if ($searchCleanType == 0) { $this->Gift->recursive = -1; //$searchResult = $this->Gift->find('all', array( 'conditions' => array( " concat(`name`,`material`) LIKE '%ручка%' AND concat(`name`,`material`) LIKE '%рез%' " ), 'fields' => array('Gift.id', 'Gift.code', 'Gift.name') ) ) ; // Preparation of the final conditions for the pagination $toSerachCondFinal = array(); if (isset($toSearchCond)) { $toSerachCondFinal = array($toSearchCond); } if (isset($giftsScope) && $giftsScope != array()) { $toSerachCondFinal = array_merge($toSerachCondFinal, array('Gift.id' => $giftsScope)); } if (isset($seachCleanPriceMin) && $seachCleanPriceMin != null) { $toSerachCondFinal = array_merge($toSerachCondFinal, array('Gift.price >=' => $seachCleanPriceMin)); } if (isset($seachCleanPriceMax) && $seachCleanPriceMax != null) { $toSerachCondFinal = array_merge($toSerachCondFinal, array('Gift.price <=' => $seachCleanPriceMax)); } //debug($toSerachCondFinal); if ($toSerachCondFinal != array()) { $searchResult = $this->Gift->find('all', array('conditions' => $toSerachCondFinal, 'fields' => array('Gift.id', 'Gift.code', 'Gift.name', 'Gift.price'))); } else { $searchResult = null; } //debug( $searchResult ); if ($searchResult != null) { // looking if match to whole frase foreach ($searchResult as $giftSet) { $giftsSet[] = $giftSet['Gift']['id']; } } } $giftsSetUnique = array_unique($giftsSet); // to replace by the condition DINSTINCT $this->Gift->recursive = 1; // the result output. if ($giftsSetUnique != array()) { $this->set('gifts', $this->paginate('Gift', array('Gift.id' => $giftsSetUnique))); $renderOuput = 'search'; } else { //echo 'hhi'; $renderOuput = 'noresult'; } $this->render($renderOuput); }
$search = switcher($search); foreach ($arraySpecialChars as $item) { $search = str_replace($item, '', $search); } $search = preg_replace('/ {2,}/', ' ', $search); $search = trim($search); $searchKeywordArray = explode(' ', $search); if (count($searchKeywordArray) <= 1) { preg_match_all('/([A-Za-zА-Яа-я]{1,})|([0-9]{1,})/', $search, $searchKeywordArray); $searchKeywordArray = $searchKeywordArray[0]; } $usdCurs = 0; $sqlCurrency = "SELECT f1 FROM " . $module_name . " WHERE id=107"; $usdCurs = mysql_result($Q->query($DB, $sqlCurrency), 0, 0); $usdCurs = (double) $usdCurs; $stemLang = new Lingua_Stem_Ru(); $sqlQuery = 'FROM ' . $module_name . ' WHERE '; $sqlQueryPrefix = 'id<> 74 AND aname=\'e4\''; $sqlQueryTerm1 = ''; $sqlQueryTerm2 = ''; $writeTerm2 = false; foreach ($searchKeywordArray as $key => $value) { if (!empty($value)) { if ($value == '###') { $writeTerm2 = true; } else { $searchKeywordArray[$key] = $stemLang->stem_word($value); if ($writeTerm2) { if ($sqlQueryTerm2 != '') { $sqlQueryTerm2 .= ' AND '; }
function bench_porter($words, $encoding) { echo "Bench snowball[{$encoding}]: "; convert_words($words, $encoding, MB_CASE_LOWER); $stemmer = new Lingua_Stem_Ru($encoding, true); $b = microtime(true); foreach ($words as $word) { $lemma = $stemmer->stem_word($word); //var_dump($word, $lemma); } $e = microtime(true); printf("time = %0.2f sec, words per second = %0.2f\n", $e - $b, count($words) / ($e - $b)); }