
Есть два модуля http://blockpro.ru/ Подключаються на одной страницы сразу два таких модуля. 1 ташит информацию с базы основного сайта где он установлен. 2 ташит информацию с другой базы данных. При подключении обоих сразу допустим в main.tpl, ташит информацию только с 1 базы. В общем очень нужна помошь. Как заставить работать два таких модуля сразу, и допустим ташить с разных баз информацию? Пример первый {include file="engine/modules/block_pro_1/sort.php?&sort=date&template=block1&sort=date&startFrom=0&limit=5"} Второй {include file="engine/modules/block_pro_2/sort.php?&sort=date&template=block1&sort=date&startFrom=0&limit=5"} Прикладываю код одно из них.. Не судите строго, php плохо знаю. Подправтьте где ошибся, и подскажите как сделать что бы они работали.
connect($news_user, $news_pass, $news_bd, $news_host); if($showstat) $start = microtime(true); if(!class_exists('BlockPro')) { class BlockPro { protected static $_instance; // Конструктор конфига модуля private function __construct() { global $config; // Получаем конфиг DLE $this->dle_config = &$config; } public function __clone(){} private function __wakeup() {} /** * Статическая функция, которая возвращает * экземпляр класса или создает новый при * необходимости * * @return SingletonTest */ public static function getInstance() { if (null === self::$_instance) { self::$_instance = new self(); } return self::$_instance; } /* * Новый конфиг */ public function set_config($cfg) { // Задаем конфигуратор класса $this->config = $cfg; } /* * Обновление даных */ public function get_category() { global $category, $category_id; $this->category_id = $category_id; $this->category = $category; } /* * Главный метод класса BlockPro */ public function runBlockPro($BlockProConfig) { global $db, $cat_info, $lang; $this->get_category(); $this->set_config($BlockProConfig); // Защита от фашистов)))) (НУЖНА ЛИ?) $this->config['postId'] = @$db->safesql(strip_tags(str_replace('/', '', $this->config['postId']))); $this->config['notPostId'] = @$db->safesql(strip_tags(str_replace('/', '', $this->config['notPostId']))); $this->config['author'] = @$db->safesql(strip_tags(str_replace('/', '', $this->config['author']))); $this->config['notAuthor'] = @$db->safesql(strip_tags(str_replace('/', '', $this->config['notAuthor']))); $this->config['xfilter'] = @$db->safesql(strip_tags(str_replace('/', '', $this->config['xfilter']))); $this->config['notXfilter'] = @$db->safesql(strip_tags(str_replace('/', '', $this->config['notXfilter']))); // Определяем сегодняшнюю дату $tooday = date("Y-m-d H:i:s", (time() + $this->dle_config['date_adjust'] * 60)); // Проверка версии DLE if ($this->dle_config['version_id'] >= 9.6) $newVersion = true; // Пробуем подгрузить содержимое модуля из кэша $output = false; // Назначаем суффикс кеша, если имеются переменные со значениями this, иначе для разных мест будет создаваться один и тот же файл кеша $cache_suffix = ''; if ($this->config['catId'] == 'this') $cache_suffix .= $this->category_id.'cId_'; if ($this->config['notCatId'] == 'this') $cache_suffix .= $this->category_id.'nCId_'; if ($this->config['postId'] == 'this') $cache_suffix .= $_REQUEST["newsid"].'pId_'; if ($this->config['notPostId'] == 'this') $cache_suffix .= $_REQUEST["newsid"].'nPId_'; if ($this->config['author'] == 'this') $cache_suffix .= $_REQUEST["user"].'a_'; if ($this->config['notAuthor'] == 'this') $cache_suffix .= $_REQUEST["user"].'nA_'; if ($this->config['tags'] == 'this') $cache_suffix .= $_REQUEST["tag"].'t_'; if ($this->config['notTags'] == 'this') $cache_suffix .= $_REQUEST["tag"].'nT_'; if ($this->config['related'] == 'this') $cache_suffix .= $_REQUEST["newsid"].'r_'; // Если установлено время жизи кеша - убираем префикс news_ чтобы кеш не чистился автоматом // и задаём настройки времени жизни кеша в секундах if ($this->config['cacheLive']) { $this->config['prefix'] = ''; $filedate = ENGINE_DIR.'/cache/'.$this->config['prefix'].'bp_'.md5($cache_suffix.implode('_', $this->config)).'.tmp'; if(@file_exists($filedate)) $cache_time=time()-@filemtime ($filedate); else $cache_time = $this->config['cacheLive']*60; if ($cache_time>=$this->config['cacheLive']*60) $clear_time_cache = 1; } // Если nocache не установлен - добавляем префикс (по умолчанию news_) к файлу кеша. if(!$this->config['nocache']) { $output = dle_cache($this->config['prefix'].'bp_'.md5($cache_suffix.implode('_', $this->config))); } if ($clear_time_cache) { $output = false; } // Если значение кэша для данной конфигурации получено, выводим содержимое кэша if($output !== false) { $this->showOutput($output); return; } // Если в кэше ничего не найдено, генерируем модуль заново $wheres = array(); // Условие для отображения только постов, прошедших модерацию $wheres[] = 'approve'; if ($this->config['fixed']) { $fixedType = ($this->config['fixed'] == 'y') ? '' : 'NOT '; $wheres[] = $fixedType.'fixed'; } // Фильтрация КАТЕГОРИЙ по их ID if ($this->config['catId'] == 'this') $this->config['catId'] = $this->category_id; if ($this->config['notCatId'] == 'this') $this->config['notCatId'] = $this->category_id; if ($this->config['catId'] || $this->config['notCatId']) { $ignore = ($this->config['notCatId']) ? 'NOT ' : ''; $catArr = ($this->config['notCatId']) ? $this->getDiapazone($this->config['notCatId']) : $this->getDiapazone($this->config['catId']); $wheres[] = $ignore.'category regexp "[[:<:]]('.str_replace(',', '|', $catArr).')[[:>:]]"'; } // Фильтрация НОВОСТЕЙ по их ID if ($this->config['postId'] == 'this') $this->config['postId'] = $_REQUEST["newsid"]; if ($this->config['notPostId'] == 'this') $this->config['notPostId'] = $_REQUEST["newsid"]; if (($this->config['postId'] || $this->config['notPostId']) && $this->config['related'] == '') { $ignorePosts = ($this->config['notPostId']) ? 'NOT ' : ''; $postsArr = ($this->config['notPostId']) ? $this->getDiapazone($this->config['notPostId']) : $this->getDiapazone($this->config['postId']); $wheres[] = $ignorePosts.'id regexp "[[:<:]]('.str_replace(',', '|', $postsArr).')[[:>:]]"'; } // Фильтрация новостей по АВТОРАМ if ($this->config['author'] == 'this') $this->config['author'] = $_REQUEST["user"]; if ($this->config['notAuthor'] == 'this') $this->config['notAuthor'] = $_REQUEST["user"]; if ($this->config['author'] || $this->config['notAuthor']) { $ignoreAuthors = ($this->config['notAuthor']) ? 'NOT ' : ''; $authorsArr = ($this->config['notAuthor']) ? $this->config['notAuthor'] : $this->config['author']; $wheres[] = $ignoreAuthors.'autor regexp "[[:<:]]('.str_replace(',', '|', $authorsArr).')[[:>:]]"'; } // Фильтрация новостей по ДОПОЛНИТЕЛЬНЫМ ПОЛЯМ if ($this->config['xfilter'] || $this->config['notXfilter']) { $ignoreXfilters = ($this->config['notXfilter']) ? 'NOT ' : ''; $xfiltersArr = ($this->config['notXfilter']) ? $this->config['notXfilter'] : $this->config['xfilter']; $wheres[] = $ignoreXfilters.'xfields regexp "[[:<:]]('.str_replace(',', '|', $xfiltersArr).')[[:>:]]"'; } // Фильтрация новостей по ТЕГАМ if ($this->config['tags'] == 'this') $this->config['tags'] = $_REQUEST["tag"]; if ($this->config['notTags'] == 'this') $this->config['notTags'] = $_REQUEST["tag"]; if ($this->config['tags'] || $this->config['notTags']) { $ignoreTags = ($this->config['notTags']) ? 'NOT ' : ''; $tagsArr = ($this->config['notTags']) ? $this->config['notTags'] : $this->config['tags']; $wheres[] = $ignoreTags.'tags regexp "[[:<:]]('.str_replace(',', '|', $tagsArr).')[[:>:]]"'; } // Если включен режим вывода похожих новостей: if ($this->config['related'] != '') { if ($this->config['related'] == 'this' && $_REQUEST["newsid"] =='') { echo 'Переменная related=this работает только в полной новости и не работает с ЧПУ 3 типа.'; return; } $relatedId = ($this->config['related'] == 'this') ? $_REQUEST["newsid"] : $this->config['related']; $wheresRelated = array(); $relatedRows = 'title, short_story, full_story, xfields'; $wheresRelated[] = 'approve'; $wheresRelated[] = 'id = '.$relatedId; $whereRlated = implode(' AND ', $wheresRelated); $relatedBody = $this->load_table (PREFIX . '_post', $relatedRows, $whereRlated, false, '0', '1', '', ''); $bodyToRelated = (strlen($relatedBody['full_story']) < strlen($relatedBody['short_story'])) ? $relatedBody['short_story'] : $relatedBody['full_story']; $bodyToRelated = $db->safesql(strip_tags(stripslashes($relatedBody['title'] . " " . $bodyToRelated))); $wheres[] = 'MATCH ('.$relatedRows.') AGAINST ("'.$bodyToRelated.'") AND id !='.$relatedId; } // Определяем переменные, чтоб сто раз не писать одно и тоже $bDay = intval($this->config['day']); $bDayCount = intval($this->config['dayCount']); // Разбираемся с временными рамками отбора новостей, если кол-во дней указано - ограничиваем выборку, если нет - выводим без ограничения даты if($bDay) $wheres[] = 'date >= "'.$tooday.'" - INTERVAL '.$bDay.' DAY'; // Если задана переменная dayCount и day, а так же day больше dayCount - отбираем новости за указанный интервал от указанного периода if($bDay && $bDayCount && ($bDayCount < $bDay)) { $wheres[] = 'date < "'.$tooday.'" - INTERVAL '.($bDay-$bDayCount).' DAY'; } else { // Условие для отображения только тех постов, дата публикации которых уже наступила $wheres[] = 'date < "'.$tooday.'"'; } // Складываем условия $where = implode(' AND ', $wheres); // Направление сортировки по убыванию или возрастанию $ordering = $this->config['order'] == 'new'?'DESC':'ASC'; // Сортировка новостей switch ($this->config['sort']) { case 'none': // Не сортировать (можно использовать для вывода похожих новостей, аналогично стандарту DLE) $sort = false; break; case 'date': // Дата $sort = 'date '; break; case 'rating': // Рейтинг $sort = 'rating '; break; case 'comms': // Комментарии $sort = 'comm_num '; break; case 'views': // Просмотры $sort = 'news_read '; break; case 'random': // Случайные $sort = 'RAND() '; break; case 'title': // По алфавиту $sort = 'title '; break; case 'hit': // Правильный топ (экспериментально) $sort = '(rating + (comm_num*0,6) + (news_read*0,2)) '; break; default: // Топ как в DLE (сортировка по умолчанию) $sort = 'rating '.$ordering.', comm_num '.$ordering.', news_read '; break; } // Формирование запроса в зависимости от версии движка if ($newVersion) { // 9.6 и выше $selectRows = 'p.id, p.autor, p.date, p.short_story, p.full_story, p.xfields, p.title, p.category, p.alt_name, p.allow_comm, p.comm_num, p.fixed, p.tags, e.news_read, e.allow_rate, e.rating, e.vote_num, e.votes'; } else { // старые версии идут лесом echo 'Модуль поддерживает только DLE 9.6 и выше.'; return; } /** * Service function - take params from table * @param $table string - название таблицы * @param $fields string - необходимые поля через запятйю или * для всех * @param $where string - условие выборки * @param $multirow bool - забирать ли один ряд или несколько * @param $start int - начальное значение выборки * @param $limit int - количество записей для выборки, 0 - выбрать все * @param $sort string - поле, по которому осуществляется сортировка * @param $sort_order - направление сортировки * @return array с данными или false если mysql вернуль 0 рядов */ $news = $this->load_table (PREFIX . '_post p LEFT JOIN ' . PREFIX . '_post_extras e ON (p.id=e.news_id)', $selectRows, $where, true, $this->config['startFrom'], $this->config['limit'], $sort, $ordering); if(empty($news)) $news = array(); // Задаём переменную, в котоую будем всё складывать $output = ''; // Если в выборке нет новостей - сообщаем об этом if (empty($news)) { $output .= 'По заданным критериям материалов нет, попробуйте изменить параметры строки подключения'; return; } // Пробегаем по массиву с новостями и формируем список foreach ($news as $newsItem) { $xfields = xfieldsload(); $newsItem['date'] = strtotime($newsItem['date']); $newsItem['short_story'] = stripslashes($newsItem['short_story']); $newsItem['full_story'] = stripslashes($newsItem['full_story']); // Формируем ссылки на категории и иконки категорий $my_cat = array(); $my_cat_icon = array(); $my_cat_link = array(); $cat_list = explode(',', $newsItem['category']); foreach($cat_list as $element) { if(isset($cat_info[$element])) { $my_cat[] = $cat_info[$element]['name']; if ($cat_info[$element]['icon']) $my_cat_icon[] = ''; else $my_cat_icon[] = ''; if($this->dle_config['allow_alt_url'] && $this->dle_config['allow_alt_url'] != 'no') $my_cat_link[] = ''.$cat_info[$element]['name'].''; else $my_cat_link[] = ''.$cat_info[$element]['name'].''; } } $categoryUrl = ($newsItem['category']) ? $this->dle_config['http_home_url'] . get_url(intval($newsItem['category'])) . '/' : '/'; // Ссылка на профиль юзера if($this->dle_config['allow_alt_url'] && $this->dle_config['allow_alt_url'] != 'no') { $go_page = $this->dle_config['http_home_url'].'user/'.urlencode($newsItem['autor']).'/'; } else { $go_page = $PHP_SELF.'?subaction=userinfo&user='.urlencode($newsItem['autor']); } // Выводим картинку switch($this->config['image']) { // Первое изображение из краткой новости case 'short_story': $imgArray = $this->getImage($newsItem['short_story'], $newsItem['date']); break; // Первое изображение из полного описания case 'full_story': $imgArray = $this->getImage($newsItem['full_story'], $newsItem['date']); break; // Изображение из дополнительного поля default: $xfieldsdata = xfieldsdataload($newsItem['xfields']); $imgArray = $this->getImage($xfieldsdata[$this->config['image']], $newsItem['date']); break; } // Определяем переменные, выводящие картинку $image = ($imgArray['imgResized']) ? $imgArray['imgResized'] : '{THEME}/blockpro/'.$this->config['noimage']; if (!$imgArray['imgResized']) { $imageFull = '{THEME}/blockpro/'.$this->config['noimageFull']; } else { $imageFull = $imgArray['imgOriginal']; } // Формируем вид даты новости для вывода в шаблон if(date('Ymd', $newsItem['date']) == date('Ymd')) { $showDate = $lang['time_heute'].langdate(', H:i', $newsItem['date']); } elseif(date('Ymd', $newsItem['date']) == date('Ymd') - 1) { $showDate = $lang['time_gestern'].langdate(', H:i', $newsItem['date']); } else { $showDate = langdate($this->dle_config['timestamp_active'], $newsItem['date']); } // Формируем вывод облака тегов if($this->dle_config['allow_tags'] && $newsItem['tags']) { $showTagsArr = array(); $newsItem['tags'] = explode(",", $newsItem['tags']); foreach ($newsItem['tags'] as $value) { $value = trim($value); if($this->dle_config['allow_alt_url'] && $this->dle_config['allow_alt_url'] != 'no') $showTagsArr[] = "dle_config['http_home_url']."tags/".urlencode($value)."/">".$value.""; else $showTagsArr[] = "".$value.""; $showTags = implode(', ', $showTagsArr); } } else { $showTags = ''; } // Выводим аватарку пользователя, если включен вывод (добавляет один запрос на каждую новость). $avatar = '{THEME}/images/noavatar.png'; if ($this->config['avatar']) { $userAvatar = $this->load_table(PREFIX . '_users', 'foto', 'name="'.$newsItem['autor'].'"', false, '0', '1', '', ''); if($userAvatar['foto']) { $avatar = $this->dle_config['http_home_url'].'uploads/fotos/'.$userAvatar['foto']; } } /** * Код, формирующий вывод шаблона новости */ // проверяем существует ли файл шаблона, если есть - работаем дальше if (file_exists(TEMPLATE_DIR.'/'.$this->config['template'].'.tpl')) { $xfieldsdata = xfieldsdataload($newsItem['xfields']); $newsTitle = htmlspecialchars(strip_tags(stripslashes($newsItem['title'])), ENT_QUOTES, $this->dle_config['charset']); $output .= $this->applyTemplate($this->config['template'], array( '{title}' => $this->textLimit($newsTitle, $this->config['titleLimit']), '{full-title}' => $newsTitle, '{full-link}' => $this->getPostUrl($newsItem, $newsItem['date']), '{image}' => $image, '{full-image}' => $imageFull, '{short-story}' => $this->textLimit($newsItem['short_story'], $this->config['textLimit']), '{full-story}' => $this->textLimit($newsItem['full_story'], $this->config['textLimit']), '{link-category}' => implode(', ', $my_cat_link), '{category}' => implode(', ', $my_cat), '{category-icon}' => implode('', $my_cat_icon), '{category-url}' => $categoryUrl, '{news-id}' => $newsItem['id'], '{author}' => "" . $newsItem['autor'] . "", '{login}' => $newsItem['autor'], '[profile]' => '', '[/profile]' => '', '[com-link]' => $newsItem['allow_comm']?'':'', '[/com-link]' => $newsItem['allow_comm']?'':'', '{comments-num}' => $newsItem['allow_comm']?$newsItem['comm_num']:'', '{views}' => $newsItem['news_read'], '{date}' => $showDate, '{tags}' => $showTags, '{rating}'  
Источник: dle-faq.pro
Источник: alexgut
Другие материалы на сайте b.Z - Записки о гаджетах, людях и музыке