<?php
function remove_videocdn_files() {
@unlink(ROOT_DIR . '/videocdn_install.php');
@unlink(ROOT_DIR . '/videocdn_admin_install.php');
@unlink(ROOT_DIR . '/videocdn_cron.php');
@unlink(ENGINE_DIR . '/ajax/videocdn.php');
@unlink(ENGINE_DIR . '/classes/videocdn.class.php');
@unlink(ENGINE_DIR . '/data/videocdnconfig.php');
@unlink(ENGINE_DIR . '/inc/videocdn.php');
@unlink(ENGINE_DIR . '/skins/images/videocdn.png');
@listdir(ENGINE_DIR . '/inc/videocdn');
@listdir(ENGINE_DIR . '/skins/videocdn');
}
class videocdn {
public $config;
public $dle_config;
public $dle_db;
public $dle_tpl;
public $copyright = '<b>VideoCDN+ v1.2.6 от Sanjarmen</b><br>Для доработок и благодарностей <b>Telegram: <a href="https://t.me/sanjarmen" target="_blank">@sanjarmen</a></b><br>';
// Массив с типами видео
public $video_type = array(
'movie' => 'Фильм',
'serial' => 'Сериал',
);
// Мыссивы доступных полей
public $fields = array(
'title' => array(
'' => '----',
'title' => 'Заголовок статьи',
),
'kinopoisk' => array(
'' => '----',
),
'output' => array(
'' => '----',
'short_story' => 'Краткое описание',
'full_story' => 'Полное описание',
),
);
public function __construct($dle_config, $dle_db, $dle_tpl = null) {
// Подключаем конфигурацию модуля
if (file_exists(ENGINE_DIR . '/data/videocdnconfig.php'))
$this->config = require_once ENGINE_DIR . '/data/videocdnconfig.php';
else $this->config = array ();
// Подключаем конфигурацию скрипта
$this->dle_config = $dle_config;
// Подключение к базе
$this->dle_db = $dle_db;
// Шаблонизатор скрипта
$this->dle_tpl = $dle_tpl;
// Загружаем доп. поля
$xfields = xfieldsload();
if ($xfields) foreach ($xfields as $key => $value) {
$this->fields['title']["{$value[0]}|xfield|{$value[3]}"] = "Доп. поле » {$value[1]}";
$this->fields['kinopoisk']["{$value[0]}|xfield|{$value[3]}"] = "Доп. поле » {$value[1]}";
$this->fields['output']["{$value[0]}|xfield|{$value[3]}"] = "Доп. поле » {$value[1]}";
}
}
public function doMain() {
// Подключаем шаблон главной страницы админпанели модуля
include_once ENGINE_DIR . '/inc/videocdn/templates/main.php';
}
public function doUpdVoice () {
if($this->config['api_token'] == '') {
header('Location: ?mod=videocdn&action=settings&failed_api=1');
return false;
}
$source = file_get_contents('https://videocdn.tv/api/translations?api_token=' . $this->config['api_token']);
if ($source) {
$voice = json_decode($source, true);
if ($voice && $voice['result'] && $voice['data']) {
foreach ($voice['data'] as $item) {
$_voice = $this->dle_db->super_query("SELECT * FROM " . PREFIX . "_videocdn_voice WHERE voice_id = '{$item['id']}'");
if (!$_voice) {
if ($this->dle_config['charset'] == 'windows-1251')
$item['title'] = iconv('utf-8', 'windows-1251', $item['title']);
$voice_id = intval($item['id']);
$voice_name = $this->dle_db->safesql($item['title']);
$this->dle_db->query("INSERT INTO " . PREFIX . "_videocdn_voice (id, voice_id, voice_name) VALUES (null, '$voice_id', '$voice_name')");
}
}
}
}
header('Location: ?mod=videocdn&action=settings&t_success=1');
}
public function doSettings() {
if (isset($_GET['upd_translations'])) {
$this->doUpdVoice();
return false;
}
// Сохранение настроек модуля
if (isset($_POST['settings']) AND is_array($_POST['settings'])) {
// Сохраняем приоритеты озвучек для фильмов
if (isset($_POST['film_voice_save'])) {
$arr = explode(',', $_POST['film_voice_save']);
if ($arr) {
$this->dle_db->query("UPDATE " . PREFIX . "_videocdn_voice SET film_priority = '0'");
foreach ($arr as $key => $value) {
$val = explode('|', $value);
$val[0] = intval($val[0]);
$val[1] = intval($val[1]);
$this->dle_db->query("UPDATE " . PREFIX . "_videocdn_voice SET film_priority = '{$val[0]}' WHERE id = '{$val[1]}'");
}
}
}
// Сохраняем приоритеты озвучек для сериалов
if (isset($_POST['serial_voice_save'])) {
$arr = explode(',', $_POST['serial_voice_save']);
if ($arr) {
$this->dle_db->query("UPDATE " . PREFIX . "_videocdn_voice SET serial_priority = '0'");
foreach ($arr as $key => $value) {
$val = explode('|', $value);
$val[0] = intval($val[0]);
$val[1] = intval($val[1]);
$this->dle_db->query("UPDATE " . PREFIX . "_videocdn_voice SET serial_priority = '{$val[0]}' WHERE id = '{$val[1]}'");
}
}
}
// Собираем настройки
$save_con = $_POST['settings'];
foreach ($_POST['replace_q_arr'] as $key=>$value) {
if(!empty($value)) $save_con['replace_q'][] = "{$key};{$value}";
else $save_con['replace_q'][] = "{$key}";
}
$save_con['replace_q'] = implode("##", $save_con['replace_q']);
foreach ($_POST['replace_s_arr'] as $key=>$value) {
if(!empty($value)) $save_con['replace_s'][] = "{$key};{$value}";
else $save_con['replace_s'][] = "{$key}";
}
$save_con['replace_s'] = implode("##", $save_con['replace_s']);
$data = "<?php \r\n if (!defined('DATALIFEENGINE')) die('Hacking attempt!');";
$data .= "\n\n//VideoCDN Plugin Configuration";
$data .= "\r\n return array(";
foreach ($save_con as $key => $value) {
if ($key == 'allowgroups' || $key == 'cron_cats' || $key == 'uf_cat_trailer' || $key == 'uf_cats')
$value = implode(',', $value);
if ($key == 'fields')
$value = implode('|', $value);
$key = addslashes(trim($key));
$value = addslashes(trim($value));
$data .= "\r\n\t'{$key}' => '{$value}',";
}
$data .= "\r\n);";
// Записываем настройки в файл
$fh = fopen(ENGINE_DIR . '/data/videocdnconfig.php', 'w');
fwrite($fh, $data);
fclose($fh);
header('Location: ?mod=videocdn&action=settings&success=1');
}
$voice_settings = false;
//$cdnvoice = $this->dle_db->super_query("SELECT COUNT(*) as count FROM " . PREFIX . "_videocdn_voice");
if($cdnvoice['count']) {
$voice_settings = true;
$film_voice_use = array();
$voice_use_result = $this->dle_db->query("SELECT * FROM " . PREFIX . "_videocdn_voice WHERE film_priority > 0 ORDER BY film_priority ASC");
while ($voice_use_row = $voice_use_result->fetch_assoc()) {
$film_voice_use[] = $voice_use_row;
}
$film_voice_off = array();
$voice_off_result = $this->dle_db->query("SELECT * FROM " . PREFIX . "_videocdn_voice WHERE film_priority = 0 ORDER BY voice_id ASC");
while ($voice_off_row = $voice_off_result->fetch_assoc()) {
$film_voice_off[] = $voice_off_row;
}
$serial_voice_use = array();
$voice_use_result = $this->dle_db->query("SELECT * FROM " . PREFIX . "_videocdn_voice WHERE serial_priority > 0 ORDER BY serial_priority ASC");
while ($voice_use_row = $voice_use_result->fetch_assoc()) {
$serial_voice_use[] = $voice_use_row;
}
$serial_voice_off = array();
$voice_off_result = $this->dle_db->query("SELECT * FROM " . PREFIX . "_videocdn_voice WHERE serial_priority = 0 ORDER BY voice_id ASC");
while ($voice_off_row = $voice_off_result->fetch_assoc()) {
$serial_voice_off[] = $voice_off_row;
}
}
// Подключаем шаблон страницы настроек модуля
include_once ENGINE_DIR . '/inc/videocdn/templates/settings.php';
}
public function doReplace() {
// Получаем количество записей в базе
$post = $this->dle_db->super_query("SELECT COUNT(*) as count FROM " . PREFIX . "_post");
// Подключаем шаблон станицы массового проставления ссылок на видео/сериал
include_once ENGINE_DIR . '/inc/videocdn/templates/replace.php';
}
public function doDelete() {
global $db;
// Код подключения кнопки поиска на VideoCDN
$videocdn_code_button = "
// videocdn search begin
require_once ENGINE_DIR . '/inc/videocdn/init.php';
\$output .= \$videocdn->get_button();
";
// Код подключения вывода плеера VideoCDN
$videocdn_code_player = "
// videocdn player begin
require_once ENGINE_DIR . '/inc/videocdn/init.php';
\$videocdn->add_player(\$row);
";
$addnews_source = file_get_contents(ENGINE_DIR . '/inc/addnews.php');
$editnews_source = file_get_contents(ENGINE_DIR . '/inc/editnews.php');
$showfull_source = file_get_contents(ENGINE_DIR . '/modules/show.full.php');
$addnews_source = str_replace($videocdn_code_button, '', $addnews_source);
$editnews_source = str_replace($videocdn_code_button, '', $editnews_source);
$showfull_source = str_replace($videocdn_code_player, '', $showfull_source);
file_put_contents(ENGINE_DIR . '/inc/addnews.php', $addnews_source);
file_put_contents(ENGINE_DIR . '/inc/editnews.php', $editnews_source);
file_put_contents(ENGINE_DIR . '/modules/show.full.php', $showfull_source);
$db->query("DROP TABLE IF EXISTS " . PREFIX . "_videocdn_voice");
require_once ENGINE_DIR . '/api/api.class.php';
$dle_api->uninstall_admin_module('videocdn');
register_shutdown_function('remove_videocdn_files');
die("<p>Модуль <b>VideoCDN</b> успешно удалён из вашего сайта!</p>");
}
public function in_array_arr($find, $arr) {
foreach ($find as $v) {
if (in_array($v, $arr)) return true;
}
return false;
}
/**
* Формат сезона/серии
*
* @param string $type (season,episode)
* @param int $format номер формата
* @param int $data номер сезона/серии
* @param string $format_def номер формата по умолчанию
* @param int $plus +1 к серии
* @return string
*/
public function serials_format($type, $format, $data, $format_def = false, $plus = 0) {
if ($format_def !== false && $format == '') $format = $format_def;
if ($format != '' && $format > 0 && $data != '') {
//season
if ($type == 'season') {
$text_season = '';
$season = $data;
switch ($format) {
case '1': //1 сезон, 2 сезон, 3 сезон
$text_season = $season; break;
case '2': //1 сезон, 1-2 сезон, 1-3 сезон
$text_season = $season > 1 ? '1-'.$season:$season; break;
case '3': //1 сезон, 1,2 сезон, 1,2,3 сезон, 1,2,3,4 сезон
for ($i = 1; $i <= $season ; $i++) {
$text_season .= $i . ",";
}
$text_season = substr($text_season, 0, - 1);
}
return $text_season . ' сезон';
}
//episode
if ($type == 'episode') {
if ($plus == 1) $data++;
$text_episod = '';
$ep = $data;
switch ($format) {
case '1': //1 серия, 2 серия, 3 серия
$text_episod = $ep; break;
case '2': //1 серия, 1-2 серия, 1-3 серия
$text_episod = $ep > 1 ? '1-'.$ep:$ep; break;
case '3': //1 серия, 1,2 серия, 1,2,3 серия, 1,2,3,4 серия
for ($i = 1; $i <= $ep ; $i++) {
$text_episod .= $i . ",";
}
$text_episod = substr($text_episod, 0, - 1);
break;
case '4': //1 серия, 1,2 серия, 1,2,3 серия, 2,3,4 серия
if ($ep > 2 ) $text_episod = ($ep - 2) .','. ($ep - 1) .','. $ep;
elseif ($ep == 2 ) $text_episod = ($ep - 1) .','. $ep;
else $text_episod = $ep;
break;
case '5': //1,2 серия, 1,2,3 серия, 1,2,3,4,5 серия, 1-5,6,7 серия
if ($ep >= 6 ) $text_episod = '1-' . ($ep - 2) .','. ($ep - 1) .','. $ep;
else {
for ($i = 1; $i <= $ep ; $i++) {
$text_episod .= $i . ",";
}
$text_episod = substr($text_episod, 0, - 1);
}
}
return $text_episod . ' серия';
}
} else return $data;
}
/**
* Поиск через API videocdn
*
* @param int $out_base_id id видео в сторонней базе
* @param string $out_field_id имя поля для id видео в сторонней базе
* @param string $title оригинальное название фильма/сериала
* @return array список найденых фильмов/сериалов
*/
public function find($out_base_id = 0, $out_field_id = '', $title = '') {
// Проверяем включен ли модуль
if (!$this->config['on'])
return array('error' => 'module_is_disabled');
if ($title && $this->dle_config['charset'] == 'windows-1251')
$title = iconv('windows-1251', 'utf-8', $title);
$api_url = "https://videocdn.tv/api/short?api_token={$this->config['api_token']}";
if ($out_base_id && $out_field_id)
$api_url .= "&{$out_field_id}={$out_base_id}";
else
$api_url .= "&title=" . urlencode($title);
// Инициализируем cURL
if ($ch = curl_init($api_url)) {
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 4 );
curl_setopt($ch, CURLOPT_TIMEOUT, 8 );
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
if ($this->config['proxy_ip'] && $this->config['proxy_type'] != '') {
$curl_proxy_ip = $this->config['proxy_ip'];
$curl_proxy_pwd = $this->config['proxy_login'].':'.$this->config['proxy_pass'];
curl_setopt($ch, CURLOPT_PROXY, $curl_proxy_ip);
curl_setopt($ch, CURLOPT_PROXYUSERPWD, $curl_proxy_pwd);
switch ($this->config['proxy_type']) {
case 'CURLPROXY_HTTP':
curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP); break;
case 'CURLPROXY_SOCKS4':
curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4); break;
case 'CURLPROXY_SOCKS5':
curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5); break;
}
}
$output = curl_exec($ch);
if(@curl_errno($ch)) {
return array('status'=>'error','error'=>"Error! cURL Failed, Request Error: ".@curl_error($ch));
}
curl_close($ch);
if ($output !== false) {
$response = json_decode($output, true);
// Если кодировка не utf-8
if ($this->dle_config['charset'] == 'windows-1251') {
array_walk_recursive($response, function(&$r_val,$r_key){
$r_val = iconv('utf-8', 'windows-1251', $r_val);
});
}
$data = $response['data'];
foreach ($data as $key => $item) {
// delete domain
// $data[$key]['iframe_src'] = preg_replace("#^//(.*)/#U", '', $item['iframe_src']);
if ($this->config['domain'] && $item['iframe_src'])
$data[$key]['iframe_src'] = preg_replace("#//[^/]+#i", $this->config['domain'], $item['iframe_src']);
//change translations
$data[$key]['translations_orig'][$key2] = $item['translations'];
$replace_s = explode("##", $this->config['replace_s']);
$replace_s_name = array();
$replace_s_change = array();
foreach ($replace_s as $item2) {
$s_arr = explode(";", $item2);
$replace_s_name[] = $s_arr[0];
$replace_s_change[] = $s_arr[1];
}
foreach($item['translations'] as $key2 => $item2) {
//$item2 = str_replace($replace_s_name, $replace_s_change, $item2);
if (strpos( $item2, ') (' ) !== false) {
preg_match('/\) \((.*)\)/U', $item2, $tmp);
$data[$key]['translations'][$key2] = $tmp[1];
}
else {
$data[$key]['translations'][$key2] = str_replace(array('(',')'), '', $item2);
}
}
$data[$key]['translations'] = str_replace($replace_s_name, $replace_s_change, $data[$key]['translations']);
// Обрезка пробела
foreach($data[$key]['translations'] as $key2 => $item2) {
$data[$key]['translations'][$key2] = trim($item2);
}
// Оставляем уникальные
$data[$key]['translations'] = array_unique($data[$key]['translations']);
//change quality
if ($item['quality']) {
$data[$key]['quality_orig'][$key2] = $item['quality'];
$data[$key]['quality'] = strtoupper($item['quality']);
if ($this->config['replace_q'] != '') {
$replace_q = explode("##", $this->config['replace_q']);
foreach ($replace_q as $item2) {
$q_arr = explode(";", $item2);
if (strtoupper($item['quality']) == strtoupper($q_arr[0])) {
$data[$key]['quality'] = $q_arr[1];
break;
}
}
}
}
else {
if ($this->config['output_no_quality'] != '') $data[$key]['quality'] = $this->config['output_no_quality'];
else $data[$key]['quality'] = 'HD';
}
if ($this->config['output_quality_res'] == '1') $data[$key]['quality'] .= ' 720p';
if (isset($item['seasons_count']) && isset($item['episodes'])) {
//seasons_count
$data[$key]['seasons_count_orig'] = $item['seasons_count'];
if ($this->config['output_season_format'] != '')
$data[$key]['seasons_count'] = $this->serials_format('season', $this->config['output_season_format'], $item['seasons_count']);
//episodes_count
//episodes
$data[$key]['episodes_orig'] = $item['episodes'];
$output_episode_plus = $this->config['output_episode_plus'] ? $this->config['output_episode_plus'] : 0 ;
if ($this->config['output_episode_format'] != '')
$data[$key]['episodes'] = $this->serials_format('episode', $this->config['output_episode_format'], $item['episodes'], false, $output_episode_plus);
}
//year
$data[$key]['year_full'] = $item['year'];
$data[$key]['year'] = explode('-', $item['year'])[0];
}
$data[0]['result'] = $response['result'];
return $data;
} else
return array('status'=>'error','error'=>"Error! cURL result empty");
} else
return array('status'=>'error','error'=>"Error! cURL not found");
}
public function get_replace_threads($type, $threads, $last_post_id = array(), $category = '', $category_inverse = false) {
if ($type == 2)
$approve = ' AND approve = 1';
elseif ($type == 3)
$approve = ' AND approve = 0';
if ($category) {
$searchcategory = array();
$category = explode(',', $category);
foreach ($category as $category_id) {
$searchcategory[] = get_sub_cats($category_id);
}
$searchcategory = implode('|', $searchcategory);
if ($searchcategory) {
// Для dle 13.2 и mysql8
if ($this->dle_config['version_id'] >= 13.2) {
if ($category_inverse) {
$stop_list = "p.id NOT IN ( SELECT DISTINCT(" . PREFIX . "_post_extras_cats.news_id) FROM " . PREFIX . "_post_extras_cats WHERE cat_id IN ({$searchcategory})) AND ";
} else {
$cat_join = "INNER JOIN (SELECT DISTINCT(" . PREFIX . "_post_extras_cats.news_id) FROM " . PREFIX . "_post_extras_cats WHERE cat_id IN ({$searchcategory})) c ON (p.id=c.news_id) ";
}
$searchcategory = '';
} else
$searchcategory = " AND category" . ($category_inverse ? ' not' : '') . " regexp '[[:<:]]($searchcategory)[[:>:]]'";
}
}
if ($last_post_id) {
$next_posts_id = array();
$post_result = $this->dle_db->query("SELECT p.id FROM " . PREFIX . "_post p {$cat_join}WHERE {$stop_list}p.id < {$last_post_id}{$searchcategory}{$approve} ORDER BY p.id DESC LIMIT {$threads}");
while ($post_row = $post_result->fetch_assoc()) {
$next_posts_id[] = $post_row['id'];
}
if ($next_posts_id) {
$result = array(
'status' => 'ok',
'next_posts_id' => $next_posts_id,
);
} else
$result = array(
'status' => 'end',
);
}
else {
$post = $this->dle_db->super_query("SELECT COUNT(p.id) as count FROM " . PREFIX . "_post p {$cat_join}WHERE {$stop_list}p.id <> 0 {$searchcategory}{$approve}");
if ($post['count']) {
$next_posts_id = array();
$post_result = $this->dle_db->query("SELECT p.id FROM " . PREFIX . "_post p {$cat_join}WHERE {$stop_list}p.id <> 0 {$searchcategory}{$approve} ORDER BY p.id DESC LIMIT {$threads}");
while ($post_row = $post_result->fetch_assoc()) {
$next_posts_id[] = $post_row['id'];
}
if ($next_posts_id) {
$result = array(
'status' => 'ok',
'next_posts_id' => $next_posts_id,
'count' => $post['count'],
);
} else
$result = array(
'status' => 'end',
);
} else
$result = array(
'status' => 'end',
'code' => '#00',
);
}
return $result;
}
public function replace_thread($post_id, $fields, $rewrite = 0, $post = false, $xfieldsdata = false, $only_url = false) { //1.2
$out_base_name = false;
$out_base_id = false;
$allow_title_search = false;
//если массив не передается, делаем запрос в БД
if ($post == false)
$post = $this
->dle_db
->super_query("SELECT * FROM " . PREFIX . "_post WHERE id = {$post_id}");
// Получаем данные доп. полей
if ($xfieldsdata == false)
$xfieldsdata = xfieldsdataload($post['xfields']);
// Получаем ссылку
$_field_output = explode('|', $this->config['output']);
if (count($_field_output) == 3) {
$output = ''.$xfieldsdata[$_field_output[0]];
}
elseif (count($_field_output) == 1) {
$output = ''.$post[$_field_output[0]];
}
// Получаем основные поля
if ($this->config['output_quality'] != '') {
$_field_quality = explode('|', $this->config['output_quality']);
$output_quality = ''.$xfieldsdata[$_field_quality[0]];
}
if ($this->config['output_season'] != '') {
$_field_season = explode('|', $this->config['output_season']);
$output_season = ''.$xfieldsdata[$_field_season[0]];
}
if ($this->config['output_episode'] != '') {
$_field_episode = explode('|', $this->config['output_episode']);
$output_episode = ''.$xfieldsdata[$_field_episode[0]];
}
if ($this->config['output_voice'] != '') {
$_field_voice = explode('|', $this->config['output_voice']);
$output_voice = ''.$xfieldsdata[$_field_voice[0]];
}
if ($this->config['output_voiceall'] != '') {
$_field_voiceall = explode('|', $this->config['output_voiceall']);
$output_voiceall = ''.$xfieldsdata[$_field_voiceall[0]];
}
// Получаем поля Kinopoisk, IMDM, World-Art, ID-vcdn, Заголовок
if ($this->config['kinopoisk_id'] != '') {
$_field_kinopoisk = explode('|', $this->config['kinopoisk_id']);
$out_base['kinopoisk_id'] = ''.$xfieldsdata[$_field_kinopoisk[0]];
}
if ($this->config['imdb_id'] != '') {
$_field_imdb = explode('|', $this->config['imdb_id']);
$out_base['imdb_id'] = ''.$xfieldsdata[$_field_imdb[0]];
}
if ($this->config['world_art_id'] != '') {
$_field_world_art = explode('|', $this->config['world_art_id']);
$out_base['world_art_id'] = ''.$xfieldsdata[$_field_world_art[0]];
}
/*
// //3.videocdn.pw/woUMiRe8xJf4/tv-series/39
$out_base_vcdn = explode('?', $output);
$out_base['id'] = end(explode('/', $out_base_vcdn[0]));
*/
/*
// Поиск по title
$_field = explode('|', $this->config['title']);
if (count($_field) == 3) {
$out_base['title'] = ''.$xfieldsdata[$_field[0]];
}
elseif (count($_field) == 1) {
$out_base['title'] = ''.$post[$_field[0]];
}
*/
// Получаем дополнительные поля
if ($this->config['output_title'] != '') {
$_field_title = explode('|', $this->config['output_title']);
if (count($_field_title) == 3) {
$output_title = ''.$xfieldsdata[$_field_title[0]];
}
elseif (count($_field_title) == 1) {
$output_title = ''.$post[$_field_title[0]];
}
}
if ($this->config['output_otitle'] != '') {
$_field_orig_title = explode('|', $this->config['output_otitle']);
$output_otitle = ''.$xfieldsdata[$_field_orig_title[0]];
}
if ($this->config['output_year'] != '') {
$_field_year = explode('|', $this->config['output_year']);
$output_year = ''.$xfieldsdata[$_field_year[0]];
}
// Переменные UF
if ($this->config['uf_status'] != '' && $this->config['uf_status_value'] != '') {
$_field_uf_status = explode('|', $this->config['uf_status']);
$uf_status = ''.$xfieldsdata[$_field_uf_status[0]];
$uf_status_value = $this->config['uf_status_value'];
}
if ($this->config['uf_season'] != '') {
$_field_uf_season = explode('|', $this->config['uf_season']);
$uf_season = ''.$xfieldsdata[$_field_uf_season[0]];
}
$uf_stop = false; // Стоп-фактор для uf
if ($output != '') { // Если ссылка уже проставлена, проверяем остальные стоп-факторы
if (
($this->config['output_season'] != '' && $output_season == '') ||
($this->config['uf_season'] != '' && $uf_season == '')
) { //movie
// Проверка по качеству
if ($this->config['uf_stop_q'] != '' && $uf_stop == false) {
$stop_q = explode(',', $this->config['uf_stop_q']);
//if ($output_quality != '' && in_array($output_quality, $stop_q)) $uf_stop = true;
if ($output_quality != '')
foreach ($stop_q as $value) {
if (stripos($output_quality, $value) !== false) {
$uf_stop = true;
if ($this->config['uf_debug'] != '') echo "\r\n".'<!-- STOP QUALITY -->';
break;
}
}
}
// Проверка по озвучке
if ($this->config['uf_stop_s'] != '' && $uf_stop == false) {
$stop_s = explode(',', $this->config['uf_stop_s']);
if ($output_voice != '' && in_array($output_voice, $stop_s)) $uf_stop = true;
elseif ($output_voiceall != '') {
$output_voiceall_arr = explode(', ', $output_voiceall);
foreach ($stop_s as $value) {
if (in_array($value, $output_voiceall_arr)) {
$uf_stop = true;
if ($this->config['uf_debug'] != '') echo "\r\n".'<!-- STOP SOUND -->';
break;
}
}
}
}
// Проверка по году
if ($this->config['uf_stop_y'] != '' && $uf_stop == false) {
$_field_year = explode('|', $this->config['uf_stop_y']);
$field_year = ''.$xfieldsdata[$_field_year[0]];
$stop_y = intval($this->config['uf_stop_y_value']);
if ($field_year != '' && $stop_y != 0 && (date('Y') - $field_year) > $stop_y) {
$uf_stop = true;
if ($this->config['uf_debug'] != '') echo "\r\n".'<!-- STOP YEAR -->';
}
}
}
else { //serial
// Проверка по статусу
if ($this->config['uf_status'] != '' && $this->config['uf_status_value'] != '' && $uf_status == $uf_status_value && $output_episode != '') {
if ($this->config['uf_episodes_end'] == '' || $output_episode == $this->config['uf_episodes_end'])
$uf_stop = true;
if ($this->config['uf_debug'] != '') echo "\r\n".'<!-- STOP STATUS -->';
}
}
} // Если ссылки нет, идем дальше и делаем запрос
// Если запрос от модуля uf
if (in_array('uf', $fields) && $uf_stop) return array('status' => 'stop');
// Определяем базу для поиска
foreach ($out_base as $base_name => $base_value) {
if ($out_base[$base_name] != '') {
$out_base_id = $base_value;
$out_base_name = $base_name;
break;
}
}
/*
//if (in_array("title_strict", $fields)) $allow_title_search = true;
foreach ($fields as $field_name) {
if ($field_name == "title_strict" || $field_name == "uf" || $field_name == 'cron') continue;
if ($out_base[$field_name] != '') {
$out_base_id = $out_base[$field_name];
$out_base_name = $field_name;
}
}
*/
if ($out_base_id && $out_base_name) {
if ($out_base_name == "title")
$response_query = $this->find(null, null, $out_base_id, false, true);
else
$response_query = $this->find($out_base_id, $out_base_name);
//$response = $response_query['result'];
$response = $response_query;
if ($response[0] and $response[0]['iframe_src']) {
$iframe_url = $response[0]['iframe_src'];
$iframe_title = $response[0]['title'];
$iframe_orig_title = $response[0]['orig_title'];
$iframe_kinopoisk_id = $response[0]['kp_id'];
$iframe_imdb_id = $response[0]['imdb_id'];
$iframe_world_art_id = $response[0]['world_art_id'];
$iframe_type = $response[0]['type'];
$iframe_voice = $response[0]['translations'];
$iframe_voiceall = implode(", ", $iframe_voice);
$iframe_quality = $response[0]['quality'];
$iframe_lastseason = isset($response[0]['seasons_count']) ? $response[0]['seasons_count'] : '';
$iframe_origseason = isset($response[0]['seasons_count_orig']) ? $response[0]['seasons_count_orig'] : '';
$iframe_lastepisode = isset($response[0]['episodes']) ? $response[0]['episodes'] : '';
$iframe_origepisode = isset($response[0]['episodes_orig']) ? $response[0]['episodes_orig'] : '';
if ( isset($response[0]['year']) ) $iframe_year = $response[0]['year'];
elseif ($this->config['uf_stop_y'] != '') {
$_field_year = explode('|', $this->config['uf_stop_y']);
$iframe_year = ''.$xfieldsdata[$_field_year[0]];
$iframe_year = explode('-', $iframe_year)[0];
} else $iframe_year = '';
//UF season and status
if ($this->config['uf_debug'] != '') echo "\r\n".'<!-- ONE SEASON TXT _ "'.$uf_season.'" -->';
if ($uf_season && $uf_season != '') {
preg_match('/^[0-9]{1,3}/', $uf_season, $uf_season_str);
$uf_season = $uf_season_str[0];
}
if ($this->config['uf_debug'] != '')
echo "\r\n".'<!-- ONE SEASON _ "'.$uf_season.'" - "'.$uf_season_str[0].'" - "'.$iframe_origseason.'" -->';
if ($uf_season && $uf_season != '' && $iframe_lastseason != '') {
// Меняем ссылку и сезон
$iframe_url .= '?season='.$uf_season;
if ($this->config['output_season_format'] != '') $iframe_lastseason = $uf_season.' сезон';
else $iframe_lastseason = $uf_season;
// Если сезон больше проставленного
if ($iframe_origseason > $uf_season && $this->config['uf_status'] != '' && $uf_status_value != '') {
// Меняем статус на "Завершенный"
$uf_status = $uf_status_value;
$xfieldsdata[$_field_uf_status[0]] = $uf_status_value;
$uf_stop = true; // Стоп-фактор для uf
}
}
// Меняем текст в сериях на "Все серии"
if (
$iframe_lastepisode != '' && //если сериал
$uf_status != '' &&
$uf_status_value != '' &&
$uf_status == $uf_status_value &&
$this->config['uf_episodes_end'] != ''
)
{
$iframe_lastepisode = $this->config['uf_episodes_end'];
}
if ($this->config['uf_debug'] != '') {
echo "\r\n".'<!-- BEFORE_SAVE _ "'.$iframe_url.'" - "'.$output.'" -->';
echo "\r\n".'<!-- BEFORE_SAVE _ "'.$iframe_quality.'" - "'.$output_quality.'" -->';
echo "\r\n".'<!-- BEFORE_SAVE _ "'.$iframe_voice[0].'" - "'.$output_voice.'" -->';
echo "\r\n".'<!-- BEFORE_SAVE _ "'.$iframe_voiceall.'" - "'.$output_voiceall.'" -->';
echo "\r\n".'<!-- BEFORE_SAVE _ "'.$iframe_lastseason.'" - "'.$output_season.'" -->';
echo "\r\n".'<!-- BEFORE_SAVE _ "'.$iframe_lastepisode.'" - "'.$output_episode.'" -->';
}
// Проставление только ссылки
if ($only_url && $iframe_url != '' && $iframe_url != $output) {
$field_set = array();
// this field is used
if ($this->config['output']) {
$_field = explode('|', $this->config['output']);
if (count($_field) == 1) $field_set[] = "{$_field[0]}='" . $this
->dle_db
->safesql($iframe_url) . "'";
elseif (count($_field) == 3) $xfieldsdata[$_field_output[0]] = $iframe_url;
}
$xfields = array();
foreach ($xfieldsdata as $key => $value) {
$value = str_replace('|', '|', $value);
$xfields[] = "$key|$value";
}
$xfields = implode('||', $xfields);
$xfields = addslashes($xfields);
$up_date = '';
//$thistime = date("Y-m-d H:i:s", time());
//$up_date = ", date='{$thistime}' ";
if (count($field_set)) $set_nativefields = ", " . implode(", ", $field_set);
$this->dle_db
->query("UPDATE " . PREFIX . "_post SET xfields = '{$xfields}'{$up_date}{$set_nativefields} WHERE id='{$post_id}'");
clear_cache( array('full_'.$post_id) );
$result = array(
'status' => 'ok',
);
}
// Проставление ссылки и данных
elseif (!$only_url && ((
($iframe_url != '' && $iframe_url != $output) or
($this->config['output_quality'] != '' && $iframe_quality != '' && $iframe_quality != $output_quality) or
($this->config['output_voice'] != '' && isset($output_voice) && $iframe_voice[0] != $output_voice) or
($this->config['output_voiceall'] != '' && isset($output_voiceall) && $iframe_voiceall != $output_voiceall) or
($this->config['output_season'] != '' && $iframe_lastseason != '' && $iframe_lastseason != $output_season) or
($this->config['output_season'] != '' && $iframe_lastseason == '' && $output_season != '') or
($this->config['output_episode'] != '' && $iframe_lastepisode != '' && $iframe_lastepisode != $output_episode) or
($this->config['output_episode'] != '' && $iframe_lastepisode == '' && $output_episode != '')
) or
// Если дебаг и nosave опция активна
($this->config['uf_debug'] != '' && $this->config['uf_debug_nosave']) or
// Если перезапись
$rewrite))
{
if ($this->config['uf_debug'] != '') echo "\r\n".'<!-- SAVE -->';
if ($this->config['uf_on']) {
$catTrailer = $this->config['uf_cat_trailer'];
$catTs = $this->config['uf_cat_ts'];
$catHD = $this->config['uf_cat_hd'];
$catHD_s = $this->config['uf_cat_hd_s'];
$catTrailer = (!empty($catTrailer) AND $catTrailer > 0) ? $catTrailer : false;
$catTs = (!empty($catCam) AND $catCam > 0) ? $catTs : false;
$catHD = (!empty($catHD) AND $catHD > 0) ? $catHD : false;
$catHD_s = (!empty($catHD_s) AND $catHD_s > 0) ? $catHD_s : false;
if ($catTrailer) $catTrailer = explode(',', $catTrailer);
$uf_cat = explode(',', $post['category']);
// Автообновление - ФИЛЬМ
if ($iframe_type == 'movie') {
// Переводим из плохого качества в HD, если был в плохом
if ($catTs && $catHD && in_array($catTs, $uf_cat) && stripos($iframe_quality, 'hd')) {
$uf_cat = array_diff ($uf_cat, array($catTs));
if ( !in_array($catHD, $uf_cat) ) $uf_cat[] = $catHD;
}
// Удаляем из трейлеров и переводим куда-то
elseif ($catTrailer && ($catTs || $catHD) && $this->in_array_arr($catTrailer, $uf_cat)) {
$uf_cat = array_diff($uf_cat, $catTrailer);
if ($catTs && $catHD) {
//если не HD
if (stripos($iframe_quality, 'hd') === false) {
if ( $catTs && !in_array($catTs, $uf_cat) ) $uf_cat[] = $catTs;
}
//если HD
elseif (stripos($iframe_quality, 'hd') !== false) {
$uf_cat = array_diff ($uf_cat, array($catTs));
if ( !in_array($catHD, $uf_cat) ) $uf_cat[] = $catHD;
}
} elseif ($catHD) {
if ( !in_array($catHD, $uf_cat) ) $uf_cat[] = $catHD;
}
}
// Просто удаляем из трейлеров
elseif ($catTrailer) $uf_cat = array_diff($uf_cat, $catTrailer);
} //end movie
// Автообновление - СЕРИАЛ
if ($iframe_type != 'movie') {
// Удаляем из трейлеров и переводим куда-то
if ($catTrailer && $catHD_s && $this->in_array_arr($catTrailer, $uf_cat)) {
$uf_cat = array_diff($uf_cat, $catTrailer);
if ( $catHD_s && !in_array($catHD_s, $uf_cat) ) $uf_cat[] = $catHD_s;
}
// Просто удаляем из трейлеров
elseif ($catTrailer) $uf_cat = array_diff($uf_cat, $catTrailer);
} //end serials
$uf_cat = array_unique($uf_cat); // удаляем дубли
$uf_cat_str = implode(',', $uf_cat);
$new_category = '';
//если есть изменения в категориях
if ($uf_cat_str != $post['category']) {
$new_category = ", category = '".$uf_cat_str."'";
// Запись ID категорий в отдельную таблицу для dle 13.2
if ($this->dle_config['version_id'] >= 13.2) {
$this
->dle_db
->query( "DELETE FROM " . PREFIX . "_post_extras_cats WHERE news_id = '{$post_id}'" );
if ($uf_cat_str != '') {
foreach ( $uf_cat as $value ) {
$cat_ids[] = "('" . $post_id . "', '" . trim( $value ) . "')";
}
$cat_ids = implode( ", ", $cat_ids );
$this
->dle_db
->query( "INSERT INTO " . PREFIX . "_post_extras_cats (news_id, cat_id) VALUES " . $cat_ids );
}
}
}
} //end uf_on
// Основные данные
$field_set = array(); // определяем, если использует поле, а не доп.поле
if ($this->config['output']) {
$_field = explode('|', $this->config['output']);
if (count($_field) == 1) $field_set[] = "{$_field[0]}='" . $this
->dle_db
->safesql($iframe_url) . "'";
elseif (count($_field) == 3) $xfieldsdata[$_field_output[0]] = $iframe_url;
}
if ($this->config['output_quality']) {
$_field = explode('|', $this->config['output_quality']);
$xfieldsdata[$_field[0]] = $iframe_quality;
}
if ($this->config['output_voice'] AND $this->config['output_voice'] != '') {
$_field = explode('|', $this->config['output_voice']);
$xfieldsdata[$_field[0]] = $iframe_voice[0];
}
if ($this->config['output_voiceall'] AND $this->config['output_voiceall'] != '') {
$_field = explode('|', $this->config['output_voiceall']);
$xfieldsdata[$_field[0]] = $iframe_voiceall;
}
if ($this->config['output_season'] && $iframe_lastseason != '') {
$_field = explode('|', $this->config['output_season']);
$xfieldsdata[$_field[0]] = $iframe_lastseason;
}
elseif ($this->config['output_season'] && $iframe_lastseason == '') {
$_field = explode('|', $this->config['output_season']);
if (isset($xfieldsdata[$_field[0]])) unset($xfieldsdata[$_field[0]]);
}
if ($this->config['output_episode'] && $iframe_lastepisode != '') {
$_field = explode('|', $this->config['output_episode']);
$xfieldsdata[$_field[0]] = $iframe_lastepisode;
}
elseif ($this->config['output_episode'] && $iframe_lastepisode == '') {
$_field = explode('|', $this->config['output_episode']);
if (isset($xfieldsdata[$_field[0]])) unset($xfieldsdata[$_field[0]]);
}
// Kinopoisk, IMDM, World-Art
if ($this->config['allow_autopaste']) {
if ($iframe_kinopoisk_id && $_field_kinopoisk && !$out_base['kinopoisk_id'])
$xfieldsdata[$_field_kinopoisk[0]] = $iframe_kinopoisk_id;
if ($iframe_imdb_id && $_field_imdb && !$out_base['imdb_id'])
$xfieldsdata[$_field_imdb[0]] = $iframe_imdb_id;
if ($iframe_world_art_id && $_field_world_art && !$out_base['world_art_id'])
$xfieldsdata[$_field_world_art[0]] = $iframe_world_art_id;
}
// Дополнительные данные
if ($iframe_title && $_field_title && (!$output_title || $this->config['output_title_rw'])) {
if(count($_field_title) == 1) $field_set[] = "{$_field_title[0]}='".$this->dle_db->safesql($iframe_title)."'";
elseif(count($_field_title) == 3) $xfieldsdata[$_field_title[0]] = $iframe_title;
}
if ($iframe_orig_title && $_field_orig_title && (!$output_otitle || $this->config['output_otitle_rw']))
$xfieldsdata[$_field_orig_title[0]] = $this->dle_db->safesql( $iframe_orig_title );
if ($iframe_year && $_field_year && (!$output_year || $this->config['output_year_rw']))
$xfieldsdata[$_field_year[0]] = $iframe_year;
//
// Shablons
$set_shablons = '';
$uf_metatitle = $this->config['uf_metatitle'];
$uf_title = $this->config['uf_title'];
$uf_chpu = $this->config['uf_chpu'];
if (
($iframe_type != 'movie' || $this->config['uf_shab_movie']) &&
($uf_metatitle != '' || $uf_title != '' || $uf_chpu != '')
)
{
$uf_from = array(
'{title}',
'{year}',
'{date}'
);
$uf_to_date = $this->config['uf_shab_date'] != ''?date($this->config['uf_shab_date']):'';
$uf_to = array(
$iframe_title,
$iframe_year,
$uf_to_date
);
$uf_shabs = $uf_metatitle.'#SEP#'.$uf_title.'#SEP#'.$uf_chpu;
preg_match_all( "/{xfvalue_(.*)}/U", $uf_shabs, $uf_shabs_match );
foreach ($uf_shabs_match[1] as $k => $v) {
// Добавляем в шаблоны если еще не было раньше
if (!in_array($uf_shabs_match[0][$k], $uf_from)) {
$uf_from[] = $uf_shabs_match[0][$k];
$uf_to[] = $xfieldsdata[$v];
}
}
$uf_from[] = ' ';
$uf_to[] = ' ';
if ($this->config['uf_debug'] != '') echo "\r\n".'<!-- SHAB before: '.$uf_shabs.'-->';
$uf_shabs = str_replace($uf_from, $uf_to, $uf_shabs);
if ($this->config['uf_debug'] != '') echo "\r\n".'<!-- SHAB after: '.$uf_shabs.'-->';
// Тег фильма
if (strpos($uf_shabs,'{if_movie}')) {
if ($iframe_type == 'movie')
$uf_shabs = str_replace(array('{if_movie}','{/if_movie}'), '', $uf_shabs);
else
$uf_shabs = preg_replace('/{if_movie}(.*){\/if_movie}/U', '', $uf_shabs);
}
// Тег сериал
if (strpos($uf_shabs,'{if_serial}')) {
if ($iframe_type == 'movie')
$uf_shabs = preg_replace('/{if_serial}(.*){\/if_serial}/U', '', $uf_shabs);
else
$uf_shabs = str_replace(array('{if_serial}','{/if_serial}'), '', $uf_shabs);
}
$uf_shabs = explode('#SEP#', $uf_shabs);
$uf_metatitle = $uf_shabs[0];
$uf_title = $uf_shabs[1];
$uf_chpu = $uf_shabs[2];
if ($iframe_type != 'movie') {
$uf_metatitle_season = $this->serials_format('season', $this->config['uf_metatitle_season_format'], $iframe_origseason, $this->config['output_season_format']);
$uf_metatitle_plus = $this->config['uf_metatitle_plus'] ? $this->config['uf_metatitle_plus'] : 0 ;
$uf_metatitle_episode = $this->serials_format('episode', $this->config['uf_metatitle_episode_format'], $iframe_origepisode, $this->config['output_episode_format'], $uf_metatitle_plus);
$uf_title_season = $this->serials_format('season', $this->config['uf_title_season_format'], $iframe_origseason, $this->config['output_season_format']);
$uf_title_plus = $this->config['uf_title_plus'] ? $this->config['uf_title_plus'] : 0 ;
$uf_title_episode = $this->serials_format('episode', $this->config['uf_title_episode_format'], $iframe_origepisode, $this->config['output_episode_format'], $uf_title_plus);
$uf_chpu_season = $this->serials_format('season', $this->config['uf_chpu_season_format'], $iframe_origseason, $this->config['output_season_format']);
$uf_chpu_plus = $this->config['uf_chpu_plus'] ? $this->config['uf_chpu_plus'] : 0 ;
$uf_chpu_episode = $this->serials_format('episode', $this->config['uf_chpu_episode_format'], $iframe_origepisode, $this->config['output_episode_format'], $uf_chpu_plus);
} else {
$uf_metatitle_season = $uf_metatitle_episode = $uf_title_season = $uf_title_episode = $uf_chpu_season = $uf_chpu_episode = '';
}
if ($uf_metatitle != '') {
$uf_metatitle = str_replace(
array('{season}','{episode}'),
array($uf_metatitle_season, $uf_metatitle_episode),
$uf_metatitle
);
$uf_metatitle = $this->dle_db->safesql( $uf_metatitle );
$uf_metatitle = ", metatitle = '{$uf_metatitle}'";
}
if ($uf_title != '') {
$uf_title = str_replace(
array('{season}','{episode}'),
array($uf_title_season, $uf_title_episode),
$uf_title
);
$uf_title = $this->dle_db->safesql( $uf_title );
$uf_title = ", title = '{$uf_title}'";
}
if ($uf_chpu != '') {
$uf_chpu = str_replace(
array('{season}','{episode}'),
array($uf_chpu_season, $uf_chpu_episode),
$uf_chpu
);
$uf_chpu = totranslit( stripslashes( $uf_chpu ), true, false );
$uf_chpu = $this->dle_db->safesql( $uf_chpu );
$uf_chpu = ", alt_name = '{$uf_chpu}'";
}
$set_shablons = $uf_metatitle.$uf_title.$uf_chpu;
if ($this->config['uf_debug'] != '') echo "\r\n".'<!-- SHAB sql: "'.$set_shablons.'" -->';
} //end shablons
$xfields = array();
foreach ($xfieldsdata as $key => $value) {
$value = str_replace('|', '|', $value);
$xfields[] = "$key|$value";
}
$xfields = implode('||', $xfields);
$xfields = addslashes($xfields);
$post['xfields'] = $xfields;
$up_date = '';
if (
$this->config['up_news'] && (
$uf_stop == false && //Стоп-фактор для uf
(
($this->config['output_quality'] != '' && $iframe_quality != $output_quality) ||
($this->config['output_season'] != '' && $iframe_lastseason != '' and $iframe_lastseason != $output_season) ||
($this->config['output_episode'] != '' && $iframe_lastepisode != '' and $iframe_lastepisode != $output_episode)
)
)
) {
if ($this->config['uf_debug'] != '') {
echo "\r\n".'<!-- UP_DATE _ '.$iframe_quality.' - '.$output_quality.' -->';
echo "\r\n".'<!-- UP_DATE _ '.$iframe_lastseason.' - '.$output_season.' -->';
echo "\r\n".'<!-- UP_DATE _ '.$iframe_lastepisode.' - '.$output_episode.' -->';
}
else {
$thistime = date("Y-m-d H:i:s", time());
$up_date = ", date='{$thistime}' ";
}
}
if (count($field_set))
{
$set_nativefields = ", " . implode(", ", $field_set);
}
if (
$this->config['uf_debug'] == '' || // Если не дебаг
($this->config['uf_debug'] != '' && !$this->config['uf_debug_nosave'])//Если дебаг и nosave опция не активна
)
{
$this->dle_db
->query("UPDATE " . PREFIX . "_post SET xfields = '{$xfields}'{$up_date}{$set_nativefields}{$new_category}{$set_shablons} WHERE id='{$post_id}'");
clear_cache( array('full_'.$post_id) );
if ($this->config['uf_debug'] != '') echo "\r\n".'<!-- SAVE DB -->';
}
$result = array( 'status' => 'ok' );
}
else $result = array( 'status' => 'exist' );
}
else {
if (
in_array('uf', $fields) && // Запрос от модуля UF
$response[0]['result'] == true && // Ответ был точно получен
$output != '' // Ссылка ранее была
) {
// Удаляем ссылку
if (count($_field_output) == 3) $xfieldsdata[$_field_output[0]] = '';
elseif (count($_field_output) == 1) $set_nativefields = ", {$_field[0]}=''";
// Прописываем качество - Трейлер
if ( $this->config['output_quality'] &&
$this->config['uf_trailer'] != '' && // Если в настройках поле Трейлер заполнено
$output_quality != $this->config['uf_trailer'] // Качестно не как трейлер
) {
$xfieldsdata[$_field_quality[0]] = $this->config['uf_trailer'];
}
$xfields = array();
foreach ($xfieldsdata as $key => $value) {
$value = str_replace('|', '|', $value);
$xfields[] = "$key|$value";
}
$xfields = implode('||', $xfields);
$xfields = addslashes($xfields);
$this->dle_db
->query("UPDATE " . PREFIX . "_post SET xfields = '{$xfields}'{$set_nativefields} WHERE id='{$post_id}'");
clear_cache( array('full_'.$post_id) );
}
$result = array(
'status' => 'error',
'code' => '#02', // Видео в базе не найдено
);
}
}
else $result = array(
'status' => 'error',
'code' => '#01', // Не указан ID базы видео или Название для поиска
);
if (in_array('uf', $fields)) $result['post'] = $post;
$result['response'] = $response[0];
$result['kinopoisk_id'] = $kinopoisk_id;
$result['out_base_id'] = $out_base_id;
$result['out_base_name'] = $out_base_name;
if ($this->dle_config['allow_alt_url']) {
if ($this->dle_config['seo_type'] == 1 || $this->dle_config['seo_type'] == 2) {
$result['post']['category'] = intval($result['post']['category']);
if ($result['post']['category'] && $this->dle_config['seo_type'] == 2) {
$full_link = $this->dle_config['http_home_url'] . get_url($result['post']['category']) . "/" . $result['post']['id'] . "-" . $result['post']['alt_name'] . ".html";
}
else {
$full_link = $this->dle_config['http_home_url'] . $result['post']['id'] . "-" . $result['post']['alt_name'] . ".html";
}
}
else {
$full_link = $this->dle_config['http_home_url'] . date('Y/m/d/', $result['post']['date']) . $result['post']['alt_name'] . ".html";
}
}
else {
$full_link = $this->dle_config['http_home_url'] . "index.php?newsid=" . $result['post']['id'];
}
$thistime = date('d.m.Y H:i:s', time());
if (in_array('cron', $fields)) {
$log_string = " $thistime [{$result['status']}] $full_link" . ($result['out_base_id'] ? " ({$result['out_base_name']}: {$result['out_base_id']}) { {$iframe_url} }" : '') . "\r\n";
file_put_contents(ENGINE_DIR . '/inc/videocdn/reports/cron.log', $log_string, FILE_APPEND | LOCK_EX);
}
elseif (in_array('uf', $fields)) {
}
else {
$log_string = " $thistime - $full_link" . ($result['out_base_id'] ? " ({$result['out_base_name']}: {$result['out_base_id']})" : '') . "\r\n";
if ($result['status'] == 'ok')
file_put_contents(ENGINE_DIR . '/inc/videocdn/reports/success.log', $log_string, FILE_APPEND | LOCK_EX);
if ($result['status'] == 'exist')
file_put_contents(ENGINE_DIR . '/inc/videocdn/reports/found.log', $log_string, FILE_APPEND | LOCK_EX);
if ($result['status'] == 'error')
file_put_contents(ENGINE_DIR . '/inc/videocdn/reports/not_found.log', $log_string, FILE_APPEND | LOCK_EX);
}
return $result;
}
/**
* Вывод кнопки поиска на videocdn
*
* @return string обработанный в зависимости от версии скрипта шаблон кнопки поиска
*/
public function get_button() {
global $member_id;
// Проверяем включен ли модуль
if (!$this->config['on'])
return '';
if (!in_array($member_id['user_group'], explode(',', $this->config['allowgroups'])))
return '';
// Загружаем шаблон кнопки поиска
ob_start();
include_once ENGINE_DIR . '/inc/videocdn/templates/button.php';
$button_template = ob_get_clean();
// Подключаем вывод кнопки с обработчиком в зависимости от версии DLE
if ($this->dle_config['version_id'] < 10.2) {
// для версий ниже 10.2
$button_template = "<tr>
<td width=\"140\" height=\"29\" style=\"padding-left:5px;\">VideoCDN:</td>
<td>
{$button_template}
</td>
</tr>";
} else {
// для версий 10.2 и выше
$button_template = "<div class=\"form-group\">
<label class=\"control-label col-lg-2\">VideoCDN:</label>
<div class=\"col-lg-10\">
{$button_template}
</div>
</div>";
}
return $button_template;
}
/**
* Вставка в основной шаблон кода плеера videocdn
*
* @param object $tpl шаблонизатор
* @param array $row текущая новость
*/
public function add_player($row, $return_data = false) {
// Проверяем включен ли модуль
if (!$this->config['on'])
return false;
else {
$xfieldsdata = false;
$uf_result = array();
if ($this->config['uf_debug'] != '') echo '<!-- DEBUG -->';
// Категории
if ($this->config['uf_cats'] != '') {
if ($this->config['uf_debug'] != '') echo "\r\n".'<!-- UF CATS -->';
$uf_cats = explode(',', $this->config['uf_cats']);
$cat_list = explode(',', $row['category']);
$uf_cat = $this->config['uf_cats_inverse'] ? true : false;
foreach($uf_cats as $cat) {
if (in_array( $cat, $cat_list)) {
$uf_cat = $this->config['uf_cats_inverse'] ? false : true; //меняем флаг
break;
}
}
} else $uf_cat = true; // если категории не выбраны
// Дебаг
$uf_debug = true;
if ($this->config['uf_debug'] != '' && !in_array($row['id'], explode(',', $this->config['uf_debug'])) ) $uf_debug = false;
// Автообновление, проверяем включено и указано ли время кеша
if ($this->config['uf_on'] && $this->config['uf_cache'] != '' && $uf_debug && $uf_cat) {
if ($this->config['uf_debug'] != '') echo "\r\n".'<!-- UF START -->';
$uf = dle_cache('uf_vcdn_'. $row['id'], false, false);
if ($uf === false || (time() - intval($uf)) > $this->config['uf_cache'] || $this->config['uf_debug'] != '') {
$fields = array( 'uf' );
$uf_result = $this->replace_thread($row['id'], $fields, $rewrite = 0, $row, $xfieldsdata);
switch ($uf_result['status']) {
case 'stop':
clear_cache(array( 'uf_vcdn_'. $row['id'] ));
break;
case 'ok':
case 'update':
case 'exist':
case 'error':
if ($uf_result['post']) {
$result = array( 'status' => $uf_result['status'],'row' => $uf_result['post']);
$row = $uf_result['post'];
}
create_cache('uf_vcdn_'. $row['id'], time());
}
};
}
if ($row and strpos($this->dle_tpl->copy_template, '{videocdn-player}') !== false) {
// Получаем данные доп. полей
if ($xfieldsdata == false)
$xfieldsdata = xfieldsdataload($row['xfields']);
// Получаем ссылку
$_field = explode('|', $this->config['output']);
if (count($_field) == 3) {
$videocdn_video_url = ''.$xfieldsdata[$_field[0]];
} elseif (count($_field) == 1) {
$videocdn_video_url = ''.$row[$_field[0]];
}
// Дополнительные параметры плеера
if ($this->config['player_params'] != '' && $videocdn_video_url != '') {
$player_params = str_replace('?','', $this->config['player_params']);
// Обработка доп.поля в доп.параметрах
if (strpos('xfvalue_')) {
preg_match_all( "/{xfvalue_(.*)}/U", $player_params, $player_params_match );
foreach ($player_params_match[1] as $k => $v) {
$player_params = str_replace($player_params_match[0][$k], $xfieldsdata[$v], $player_params);
}
}
// Добавляем к ссылке
$videocdn_video_url .= strpos($videocdn_video_url, '?') ? '&'.$player_params : '?'.$player_params;
}
// Замена домена
if ($this->config['domain'] && $videocdn_video_url != '')
$videocdn_video_url = preg_replace("#//[^/]+#i", $this->config['domain'], $videocdn_video_url);
// Если заполнена ссылка и в настройках задана ширина и высота видео
if ($videocdn_video_url && $this->config['video_width'] && $this->config['video_height']) {
// Строим код видео плеера
$videocdn_player = "<iframe src=\"{$videocdn_video_url}\" width=\"{$this->config['video_width']}\" height=\"{$this->config['video_height']}\" frameborder=\"0\" allowfullscreen></iframe>";
// Заменяем {videocdn-player} на код плеера
$this->dle_tpl->copy_template = str_replace('{videocdn-player}', $videocdn_player, $this->dle_tpl->copy_template);
// Всё что будет в тегах [videocdn-player]...[/videocdn-player] будет отображаться только если выводится код плеера
$this->dle_tpl->copy_template = str_replace('[videocdn-player]', '', $this->dle_tpl->copy_template);
$this->dle_tpl->copy_template = str_replace('[/videocdn-player]', '', $this->dle_tpl->copy_template);
// Если заполнены не все необходимые параметры
}
else {
// Удаляем тег плеера из шаблона
$this->dle_tpl->copy_template = str_replace('{videocdn-player}', '', $this->dle_tpl->copy_template);
// Так же удаляем блок кода плеера, то есть всё что будет в эти тегах [videocdn-player]...[/videocdn-player]
$this->dle_tpl->copy_template = preg_replace("'\\[videocdn-player\\](.*?)\\[/videocdn-player\\]'is", '', $this->dle_tpl->copy_template);
}
}
if ($return_data) return $uf_result;
}
}
}