<?php
// ini_set('display_errors', 1);
// ini_set('display_startup_errors', 1);
// error_reporting(E_ALL);
if(phpversion() > "7.4") {
	set_error_handler(function(int $errno, string $errstr) {
		if ((strpos($errstr, 'Undefined array key') === false) || (strpos($errstr, 'Undefined variable') === false)) {
			return false;
		} else {
			return true;
		}
	}, E_WARNING);
}

function remove_cdnm_files() {
	@unlink(ROOT_DIR . '/cdnm_install.php');
	@unlink(ROOT_DIR . '/cdnm_admin_install.php');
	@unlink(ROOT_DIR . '/cdnm_cron.php');
	@unlink(ENGINE_DIR . '/ajax/cdnm.php');
	@unlink(ENGINE_DIR . '/classes/cdnm.class.php');
	@unlink(ENGINE_DIR . '/data/cdnmconfig.php');
	@unlink(ENGINE_DIR . '/inc/cdnm.php');
	@unlink(ENGINE_DIR . '/skins/images/cdnm.png');
	@listdir(ENGINE_DIR . '/inc/cdnm');
	@listdir(ENGINE_DIR . '/skins/cdnm');
}

class cdnm {
	public $config;
	public $dle_config;
	public $dle_db;
	public $dle_tpl;

	public $copyright = '<b>CDN Movies v231122</b><br>';

	// Массив с типами видео
	public $video_type = array(
		'movie' => 'Фильм',
		'serial' => 'Сериал',
	);

	// Мыссивы доступных полей
	public $fields = array(
		'title' => array(
			'' => '----',
			'title' => 'Заголовок статьи',
		),
		'output' => array(
			'' => '----',
			'short_story' => 'Краткое описание',
			'full_story' => 'Полное описание',
		),
		'xf' => array(
			'' => '----',
		)
	);
	
	public $ganres = array(
		'аниме', 'биография', 'боевик', 'вестерн', 'военный', 'детектив', 'детский', 'для взрослых', 'документальный', 'драма', 'игра', 'история', 'комедия', 'концерт', 'короткометражка', 'криминал', 'мелодрама', 'музыка', 'мультфильм', 'мюзикл', 'новости', 'приключения', 'реальное ТВ', 'семейный', 'спорт', 'ток-шоу', 'триллер', 'ужасы', 'фантастика', 'фильм-нуар', 'фэнтези', 'церемония'
	);

	public function __construct($dle_config, $dle_db, $dle_tpl = null) {
		// Подключаем конфигурацию модуля
		if (file_exists(ENGINE_DIR . '/data/cdnmconfig.php'))
			$this->config = require ENGINE_DIR . '/data/cdnmconfig.php';
		else $this->config = array ();
		
		if (empty($this->config['cdnm_cache'])) $this->config['cdnm_cache'] = '21600';

		// Подключаем конфигурацию скрипта
		$this->dle_config = $dle_config;
		
		// Подключение к базе
		$this->dle_db = $dle_db;
		
		// Шаблонизатор скрипта
		$this->dle_tpl = $dle_tpl;

		// Переменная с ссылкой на видео
		$this->iframe = array('', '');
		
		// Загружаем доп. поля
		$this->xfields = xfieldsload();
		if (!empty($this->xfields)) foreach ($this->xfields as $key => $value) {
			$this->fields['title']["{$value[0]}|xfield|{$value[3]}"] = "Доп. поле &raquo; {$value[1]}";
			$this->fields['xf']["{$value[0]}|xfield|{$value[3]}"] = "Доп. поле &raquo; {$value[1]}";
			$this->fields['output']["{$value[0]}|xfield|{$value[3]}"] = "Доп. поле &raquo; {$value[1]}";
		}
	}
	
	public function doSettings() {
		
		// Сохранение настроек модуля
		if (isset($_POST['settings']) AND is_array($_POST['settings'])) {

			// Собираем настройки
			$save_con = $_POST['settings'];
			// print_r($_POST);
			// exit();
			
			// Замена качества
			$save_con['replace_q'] = array();
			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']);
			
			// Замена озвучки
			$save_con['replace_s'] = array();
			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']);
			
			$save_con['ganres_cat_1'] = implode(",", $save_con['ganres_cat_1']);
			$save_con['ganres_cat_2'] = implode(",", $save_con['ganres_cat_2']);
			$save_con['ganres_cat_3'] = implode(",", $save_con['ganres_cat_3']);
			$save_con['ganres_cat_4'] = implode(",", $save_con['ganres_cat_4']);
			$save_con['ganres_cat_5'] = implode(",", $save_con['ganres_cat_5']);
			$save_con['ganres_cat_6'] = implode(",", $save_con['ganres_cat_6']);
			
			$data = "<?php \r\n if (!defined('DATALIFEENGINE')) die('Hacking attempt!');";
			$data .= "\n\n//cdnm Plugin Configuration";
			$data .= "\r\n return array(";
			foreach ($save_con as $key => $value) {
				if ($key == 'allowgroups' || $key == 'cron_cats' || $key == 'cdnm_cat_trailer' || $key == 'cdnm_cats' || $key == 'grouptoken')
					$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);";
			
			// Записываем настройки в файл
			if (!empty($data)) {
				$fh = fopen(ENGINE_DIR . '/data/cdnmconfig.php', 'w');
				fwrite($fh, $data);
				fclose($fh);
			}
			
			if (!is_writable(ENGINE_DIR . '/data/cdnmconfig.php')) 
				header("Location: /{$this->dle_config['admin_path']}?mod=cdnm&action=settings&a_failed=1");
			else 
				header("Location: /{$this->dle_config['admin_path']}?mod=cdnm&action=settings&a_success=1");
		}

		// Подключаем шаблон страницы настроек модуля
		include_once ENGINE_DIR . '/inc/cdnm/templates/settings.php';
	}

	public function doReplace() {
		// Получаем количество записей в базе
		$post = $this->dle_db->super_query("SELECT COUNT(*) as count FROM " . PREFIX . "_post");
		
		// Подключаем шаблон страницы массового проставления ссылок на видео/сериал
		include_once ENGINE_DIR . '/inc/cdnm/templates/replace.php';
	}

	public function in_array_arr($find, $arr) {
		foreach ($find as $v) {
			if (in_array($v, $arr)) return true;
		}
		return false;
	}
	public function fix_separations($text, $arr = false) {
		$text = preg_replace('/(^,?\s?|\s?,?$)/', '', $text);
		$text = str_replace(array(',,', ', '), ',', $text);
		$text = str_replace(',', ', ', $text);
		
		if ($arr) return explode(', ', $text);
		else return $text;
	}
	
	public function arr_to_string($arr, $key = false, $key2 = false, $slice = false) {
		if (empty($arr)) return '';

		$text = array();
		foreach ($arr as $v) {
			if (empty($key) && empty($key2))
				$text[] = $v;
			elseif (!empty($key)) {
				if (empty($key2))
					$text[] = $v[$key];
				elseif ($v[$key2[0]] == $key2[1]) {
					if (!empty($v[$key]))
						$text[] = $v[$key];
					elseif (!empty($v['en_name']))
						$text[] = $v['en_name'];
						
				}
			}
			
		}
		
		if (!empty($slice) && !empty($text)) {
			$text = array_slice($text, 0 , intval($slice));
		}

		return implode(', ', $text);
	}
	public function date_to_cyr($d) {
		return preg_replace_callback('/_([0-9]{1,2})_/', function($match){
			$m = array( 1  => 'января', 2  => 'февраля', 3  => 'марта',	4  => 'апреля',	5  => 'мая', 6  => 'июня', 7  => 'июля', 8  => 'августа', 9  => 'сентября', 10 => 'октября', 11 => 'ноября', 12 => 'декабря');
			
			return $m[$match[1]];
			
		}, $d );
	}
	public function check_quality($q) {
		
		$quality_price = array( 
			"cam" => "1",
			"ts" => "2",
			"sat" => "3",
			"dvd" => "4",
			"iptv" => "5",
			"web" => "6",
			"hdtv" => "7",
			"hd" => "8",
			"webdl" => "9",
			"bd" => "10" 
		);
		$q = strtolower($q);
		$q = str_replace(array('rip', ' ', '-'), '', $q);
		
		if (empty( $quality_price[$q] ))
			return '8';
		
		return $quality_price[$q];
		
	}
	
	/**
	 * Формат сезона/серии
	 *
	 * @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;
	}

	public function poster($imageurl, $news_id, $author) {
		if ($imageurl && $this->config['output_poster'] ) {
			// $path = $this->config['output_poster_path'];
			$path = 'uploads/posts/';
			$o_size = $this->dle_config['max_up_side'];
			
			$t_size = 0;
			$make_thumb = false;

			$uploader = new cdnm_PosterUploader($imageurl, $news_id, $author, $path, $o_size, $t_size, $make_thumb);			
			$result = $uploader->FileUpload();
			
			$data = json_decode($result, true);
			if ($result) return $data;
		}

		return false;
	}

	/**
	 * CURL запрос
	 *
	 * @param string $url имя поля для id видео в сторонней базе
	 * @return array ответ с результатом или ошибкой
	 */
	public function get_api($api_url, $search_time = 30) {
		if ($ch = curl_init($api_url)) {
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10 );
			curl_setopt($ch, CURLOPT_TIMEOUT, $search_time );
			curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
			
			// if (empty($this->config['tls'])) $this->config['tls'] = 7; // CURL_SSLVERSION_TLSv1_3
			if (!empty($this->config['tls'])) {
				curl_setopt($ch, CURLOPT_SSLVERSION, $this->config['tls']); 
			}
			
			$result = curl_exec($ch);
			if(@curl_errno($ch)) {
				return json_encode( array('status'=>'error','error'=>"Error! cURL Failed, Request Error: ".@curl_error($ch)) );
			}
			
			return $result;
			
		} else
			return json_encode( array('status'=>'error','error'=>"Error! cURL not found") );
	}
	 /**
	 * Поиск через API cdnm
	 *
	 * @param array $out_base список для поиска видео в базе
	 * @param string $title оригинальное название фильма/сериала
	 * @return array список найденых фильмов/сериалов
	 */
	public function find($btn, $out_base, $title = '', $search_time = 30) {
		// Проверяем включен ли модуль
		if (!$this->config['on'] && !$this->config['api_token'])
			return array('error' => 'module_is_disabled');
		
		if ($title && $this->dle_config['charset'] == 'windows-1251')
			$title = iconv('windows-1251', 'utf-8', $title);
		
		// Инициализируем cURL
		$query_time = microtime(true);
		// echo $api_url ."\r\n";
			
		foreach ($out_base as $base) {
			preg_match('/=(.*)/', $base, $base_id);
			if (empty($base) || empty($base_id[1])) continue;
			
			$api_url = 'https://api.cdnmovies.net/v1/contents?'. $base .'&token='. $this->config['api_token'];

			$data = $this->get_api($api_url, $search_time);
			$data = json_decode($data, true);
			
			if (!isset($data['error'])) break;
		}
		
		// print_r($output);
		if (!empty($data)) {
			$api_time = microtime(true) - $query_time;
			//echo $data."\r\n";
			
			if (isset($data['error'])) return array('status'=>'error','error'=>$data['error']);
			if (isset($data['status']) && $data['status'] == 'error') return $data;
			
			// Если кодировка не utf-8
			if ($this->dle_config['charset'] == 'windows-1251') {
				array_walk_recursive($data, function(&$r_val,$r_key){
					$r_val = iconv('utf-8', 'windows-1251//IGNORE', $r_val);
				});
			}
			
			$translate_all = array();
			$data = $data['data'];
			// print_r($data); 
			
			foreach ($data as $key => $item) {

				// print_r($data[$key]);
				
				// Время запроса
				$data[$key]['api_time'] = $api_time;
				
				// $data[$key]['id']
				
				// persons (director|actor|producer|voice_director|translator|writer|operator|composer|design|editor)
				//         (режисер|актер|продюсер|режисер дубляжа|переводчик|сценарист|оператор|композитор|художник|монтаж)
				// https://api.cdnmovies.net/v1/contents/persons?token=f0a33b99cd8410a52defb9a820a46c5b&content_id=31b01da440e7b4970cb5185e33e797ca
				$persons = $this->get_api('https://api.cdnmovies.net/v1/contents/persons?token='. $this->config['api_token'] .'&content_id='. $data[$key]['id'], $search_time);
				$persons = json_decode($persons, true);
				if (!empty($persons['data'])) {
					$persons = $persons['data'];
					
					$director_count = empty($this->config['output_directors_count']) ? 3 : $this->config['output_directors_count'];
					$data[$key]['director'] = $this->arr_to_string($persons, 'ru_name', array('en_type', 'director'), $director_count);
					
					$actors_count = empty($this->config['output_actors_count']) ? 10 : $this->config['output_actors_count'];
					$data[$key]['actors'] = $this->arr_to_string($persons, 'ru_name', array('en_type', 'actor'), $actors_count);
					
					$producers_count = empty($this->config['output_producers_count']) ? 3 : $this->config['output_producers_count'];
					$data[$key]['producer'] = $this->arr_to_string($persons, 'ru_name', array('en_type', 'producer'), $producers_count);
					
					$voice_directors_count = empty($this->config['output_voice_directors_count']) ? 3 : $this->config['output_voice_directors_count'];
					$data[$key]['voice_director'] = $this->arr_to_string($persons, 'ru_name', array('en_type', 'voice_director'), $voice_directors_count);
					
					$translators_count = empty($this->config['output_translators_count']) ? 3 : $this->config['output_translators_count'];
					$data[$key]['translator'] = $this->arr_to_string($persons, 'ru_name', array('en_type', 'translator'), $translators_count);
					
					$writers_count = empty($this->config['output_writers_count']) ? 3 : $this->config['output_writers_count'];
					$data[$key]['writer'] = $this->arr_to_string($persons, 'ru_name', array('en_type', 'writer'), $writers_count);
					
					$operators_count = empty($this->config['output_operators_count']) ? 3 : $this->config['output_operators_count'];
					$data[$key]['operator'] = $this->arr_to_string($persons, 'ru_name', array('en_type', 'operator'), $operators_count);
					
					$composers_count = empty($this->config['output_composers_count']) ? 3 : $this->config['output_composers_count'];
					$data[$key]['composer'] = $this->arr_to_string($persons, 'ru_name', array('en_type', 'composer'), $composers_count);
					
					$designs_count = empty($this->config['output_designs_count']) ? 3 : $this->config['output_designs_count'];
					$data[$key]['design'] = $this->arr_to_string($persons, 'ru_name', array('en_type', 'design'), $designs_count);
					
					$editors_count = empty($this->config['output_editors_count']) ? 3 : $this->config['output_editors_count'];
					$data[$key]['editor'] = $this->arr_to_string($persons, 'ru_name', array('en_type', 'editor'), $editors_count);

				} else {
					$data[$key]['director'] = $data[$key]['actors'] = $data[$key]['producer'] = $data[$key]['voice_director'] = $data[$key]['translator'] = $data[$key]['writer'] = $data[$key]['operator'] = $data[$key]['composer'] = $data[$key]['design'] = $data[$key]['editor'] = '';
				}
				
				// $data[$key]['iframe_src']
				// $data[$key]['content_type']
				switch ($item['content_type']) {
					case ('сериал'):
						$item['category'] = '2';
						break;
					case ('аниме'):
						$item['category'] = '3';
						break;
					case ('аниме сериал'):
						$item['category'] = '4';
						break;
					case ('тв телепередача'):
						$item['category'] = '5';
						break;
					case ('фильм'):
					default:
						$item['category'] = '1';
				}
				$data[$key]['category'] = $item['category'];
				
				// $data[$key]['ru_title']
				$data[$key]['title'] = $item['ru_title'];
				unset($data[$key]['ru_title']);
				
				// $data[$key]['orig_title']
				$data[$key]['title_orig'] = $item['orig_title'];
				unset($data[$key]['orig_title']);
				
				// $data[$key]['ua_title']
				$data[$key]['title_ua'] = $item['ua_title'];
				unset($data[$key]['ua_title']);
				
				// $data[$key]['other_title']
				$data[$key]['title_alt'] = $item['other_title'];
				unset($data[$key]['other_title']);

				// $data[$key]['year']
				// $data[$key]['rating_age']
				$data[$key]['age'] = empty($item['rating_age']) ? '' : $item['rating_age'];
				unset($data[$key]['rating_age']);
				
				// $data[$key]['rating_mpaa']
				$data[$key]['mpaa'] = empty($item['rating_mpaa']) ? '' : $item['rating_mpaa'];
				unset($data[$key]['rating_mpaa']);
				
				// $data[$key]['kinopoisk_id']
				// $data[$key]['kinopoisk_rating']
				$data[$key]['kinopoisk_rate'] = empty($item['kinopoisk_rating']) ? '' : $item['kinopoisk_rating'];
				unset($data[$key]['kinopoisk_rating']);
				
				// $data[$key]['kinopoisk_rating_votes']
				$data[$key]['kinopoisk_rate_votes'] = empty($item['kinopoisk_rating_votes']) ? '' : $item['kinopoisk_rating_votes'];
				unset($data[$key]['kinopoisk_rating_votes']);
				
				// $data[$key]['imdb_id']
				// chek correct ID
				preg_match('/[0-9]{7,}/', $item['imdb_id'], $imdb_match);
				if (empty($imdb_match[0])) {
					unset($item['imdb_id']);
					unset($data[$key]['imdb_id']);
				} else { // tt or not tt
					// clear tt
					$item['imdb_id'] = $imdb_match[0];
					$data[$key]['imdb_id'] = $imdb_match[0];
					
					// add tt
					if (empty($this->config['imdb_no_tt'])) $data[$key]['imdb_id'] = 'tt'.$item['imdb_id'];
				}
				
				// $data[$key]['imdb_rating']
				$data[$key]['imdb_rate'] = empty($item['imdb_rating']) ? '' : $item['imdb_rating'];
				unset($data[$key]['imdb_rating']);
				
				// $data[$key]['imdb_rating_votes']
				$data[$key]['imdb_rate_votes'] = empty($item['imdb_rating_votes']) ? '' : $item['imdb_rating_votes'];
				unset($data[$key]['imdb_rating_votes']);
				
				// $data[$key]['world_art_id']
				$data[$key]['world_art_id'] = $item['worldart_id'];
				unset($data[$key]['worldart_id']);
				
				// $data[$key]['tmdb_id']
				// $data[$key]['tmdb_rating']
				$data[$key]['tmdb_rate'] = empty($item['tmdb_rating']) ? '' : $item['tmdb_rating'];
				unset($data[$key]['tmdb_rating']);
				
				// $data[$key]['tmdb_rating_votes']
				$data[$key]['tmdb_rate_votes'] = empty($item['tmdb_rating_votes']) ? '' : $item['tmdb_rating_votes'];
				unset($data[$key]['tmdb_rating_votes']);
				
				// $data[$key]['kinorium_id']
				// $data[$key]['mdl_id']
				// $data[$key]['shikimori_id']
				
				// $data[$key]['slogan']
				// $data[$key]['duration']
				// $data[$key]['description']
				if (!empty($data[$key]['description'])) {
					$data[$key]['description'] = preg_replace('/"(.*)"/U', '«$1»', $data[$key]['description']);
					$description = str_replace(PHP_EOL, PHP_EOL .'<br>', $data[$key]['description']);
					
					$description_count = dle_strlen( $description, $this->dle_config['charset'] );
					$description_limit = intval($this->config['output_shortstory_limit']);

					if ($description_limit == 0) 
						$data[$key]['description_short'] = '';
					else {
						// обрезаем
						if ($description_count > $description_limit) 
							$data[$key]['description_short'] = dle_substr( $description, 0, $description_limit, $this->dle_config['charset'] );
						else 
							$data[$key]['description_short'] = $description;
						
						$data[$key]['description_short'] .= $this->config['output_shortstory_end'];
					}
				} else 
					$data[$key]['description'] = $data[$key]['description_short'] = '';
				
				// $data[$key]['budget']
				// $data[$key]['feels_world']
				// $data[$key]['feels_usa']
				// $data[$key]['feels_russia']
				
				// $data[$key]['premiere_world']
				if (!empty($item['premiere_world']))
					$data[$key]['premier_mir'] = $this->date_to_cyr( date('j _n_ Y', strtotime($item['premiere_world'])) );
				else
					$data[$key]['premier_mir'] = '';
				unset($data[$key]['premiere_world']);
				
				// $data[$key]['premiere_russia']
				if (!empty($item['premiere_russia']))
					$data[$key]['premier_rf'] = $this->date_to_cyr( date('j _n_ Y', strtotime($item['premiere_russia'])) );
				else
					$data[$key]['premier_rf'] = '';
				unset($data[$key]['premiere_russia']);
				
				// $data[$key]['countries']
				$data[$key]['country'] = $this->arr_to_string($item['countries'], 'ru_name');
				unset($data[$key]['countries']);
				
				// $data[$key]['genres']
				$data[$key]['ganre'] = $this->arr_to_string($item['genres'], 'ru_name');
				
				$data[$key]['ganres_cats'] = array();
				if (!empty($this->config['output_cat_'.$item['category']]))
						$data[$key]['ganres_cats'][] = $this->config['output_cat_'.$item['category']];
					
				if (!empty($item['category']) && !empty($data[$key]['ganre'])) {
					$ganres_cat = explode(',', $this->config['ganres_cat_'.$item['category']]);
					
					$ganres = explode(', ', $data[$key]['ganre']);
					
					foreach ($this->ganres as $key2 => $cat) {
						if (empty($ganres_cat[$key2])) continue;
						// если категория есть в жанрах
						if (in_array($cat, $ganres)) $data[$key]['ganres_cats'][] = $ganres_cat[$key2];
					}
				}
				$data[$key]['ganres_cats'] = array_unique($data[$key]['ganres_cats']);
				$data[$key]['ganres_cats'] = implode(',', $data[$key]['ganres_cats']);
				unset($data[$key]['genres']);
				
				// $data[$key]['collections']
				$data[$key]['collections'] = $this->arr_to_string($item['collections']);
				
				// $data[$key]['facts']
				$data[$key]['trivia'] = '';
				if (!empty($item['facts'])) {
					$item['facts'] = array_slice($item['facts'], 0, $this->config['output_trivia_count']);
					
					$t_prefix = $this->config['output_trivia_prefix'];
					$t_sufix = $this->config['output_trivia_sufix'];
					$t_spacer = $this->config['output_trivia_spacer'];
					$data[$key]['trivia'] = $t_prefix . implode($t_sufix.$t_spacer.$t_prefix, $item['facts']) . $t_sufix;
					if ($btn)
						$data[$key]['trivia'] = str_replace(
							array('<b>', '</b>', '<i>', '</i>', '<u>', '</u>','<ul>', '</ul>', '<li>', '</li>', '<br>'), 
							array('[b]', '[/b]', '[i]', '[/i]', '[u]', '[/u]','[list]', '[/list]', '[*]', '', "\r\n"), 
							$data[$key]['trivia']
						);
				}
				unset($data[$key]['facts']);
				
				// $data[$key]['posters']
				if (empty($this->config['output_poster_size']))
					$this->config['output_poster_size'] = 'large';

				$data[$key]['poster'] = $data[$key]['posters'][0][$this->config['output_poster_size']];
				unset($data[$key]['posters']);

				// $data[$key]['screens']
				if (empty($this->config['output_screen_size']))
					$this->config['output_screen_size'] = 'large';
				
				$data[$key]['screen'] = array();
				foreach($data[$key]['screens'] as $s) {
					$data[$key]['screen'][] = $s[$this->config['output_screen_size']];
				}
				unset($data[$key]['screens']);
				
				// // //
				if (empty($item['last_season'])) $data[$key]['type'] = 'movie';
				else $data[$key]['type'] = 'serial';
				
				// Serials_format
				if (!empty($item['last_season']) && !empty($item['last_episode'])) {
					//seasons
					$data[$key]['seasons_orig'] = $item['last_season'];
					$data[$key]['seasons'] = $this->serials_format('season', $this->config['output_season_format'], $item['last_season']);
					//episodes_count
					//episodes
					$data[$key]['episodes_orig'] = $item['last_episode'];
					$output_episode_plus = $this->config['output_episode_plus'] ? $this->config['output_episode_plus'] : 0 ;
					$data[$key]['episodes'] = $this->serials_format('episode', $this->config['output_episode_format'], $item['last_episode'], false, $output_episode_plus);
				}

				// $data[$key]['translations'] - $item['translations']
				$data[$key]['translate'] = $item['translations'][0]['format_name'];
				$data[$key]['translate_all'] = $this->arr_to_string($item['translations'], 'format_name');
				
				// replace translation
				if ($this->config['replace_s']) {
					$replace_s = explode("##", $this->config['replace_s']);
					$replace_s_name = array();
					$replace_s_change = array();
					foreach ($replace_s as $replace_s_item) {
						$s_arr = explode(";", $replace_s_item);
						$replace_s_name[] = $s_arr[0];
						$replace_s_change[] = $s_arr[1];
					}
					$data[$key]['translate'] = str_replace($replace_s_name, $replace_s_change, $data[$key]['translate']);
					$data[$key]['translate_all'] = str_replace($replace_s_name, $replace_s_change, $data[$key]['translate_all']);
					
					// Оставляем уникальные
					$item['translate_all'] = explode(', ', $data[$key]['translate_all']);
					$item['translate_all'] = array_unique($item['translate_all']);
					$data[$key]['translate_all'] = $this->arr_to_string($item['translate_all']);
				}
				if (!empty($this->config['output_voice_all']) && !empty($data[$key]['translate_all']))
					$data[$key]['translate'] = $data[$key]['translate_all'];
				unset($data[$key]['translations']);
				
				//quality
				$quality = '';
				$quality_index = 0;
				$max_quality = 0;

				foreach($item['translations'] as $t) {
					if ($t['max_quality'] >= $max_quality) {
						$q = $this->check_quality($t['quality']);
						
						if ($q >= $quality_index)
							$quality = $t['quality'];
							$quality_index = $q;
							$max_quality = $t['max_quality'];
					}
				}
				
				if (empty($quality))
					$quality = 'HD';
				
				if (empty($max_quality))
					$max_quality = 1080;
				
				$data[$key]['quality'] = $quality;
				$item['quality_orig'] = $max_quality;
				if ($this->config['output_quality_res'] == '1' && isset($item['quality_orig'])) $data[$key]['quality'] .= ' '.$item['quality_orig'].'p';
				
				// Replace quality
				if ($this->config['replace_q'] != '') {
					$replace_q = explode("##", $this->config['replace_q']);
					foreach ($replace_q as $item2) {
						$q_arr = explode(";", $item2);
						if ($data[$key]['quality'] == $q_arr[0]) {
							$data[$key]['quality'] = $q_arr[1];
							break;
						}
					}
				}
				
				// print_r($data[$key]);
				// exit();
				// // //
				$data[$key]['api_time'] = round($api_time, 3);
				
			}
			
			if (!is_array($data)) $data = array();
			return $data;
			
		} else
			return array('status'=>'error','error'=>"Error! cURL result empty");

	}
	
	public function get_replace_threads($type, $threads, $last_post_id = array(), $category = '', $category_inverse = false, $fields = array()) {
		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) {
				$sub_cats = get_sub_cats($category_id);
				if ($this->dle_config['version_id'] >= 13.2) $sub_cats = str_replace('|', ',', $sub_cats);
				$searchcategory[] = $sub_cats;
			}
			if ($this->dle_config['version_id'] >= 13.2) $searchcategory = implode(',', $searchcategory);
			else $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)[[:>:]]'";
				
			}
		}
		
		$only_no_url = in_array('only_no_url', $fields) ? true : false;
		$big_query = in_array('big_query', $fields) ? true : false;
		
		if ($only_no_url) {
			$_field_output = explode('|', $this->config['output']);
			if (count($_field_output) == 3)	{
				$not_like = " AND xfields NOT LIKE '%{$_field_output[0]}|%'";
			}
		}
		
		if ($big_query) $threads = "";
		else $threads = " LIMIT {$threads}";
		
		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}$not_like{$searchcategory}{$approve} ORDER BY p.id DESC{$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 {$not_like}{$searchcategory}{$approve}");
			if ($post['count']) {
				$next_posts_id = array();
				// echo "SELECT p.id FROM " . PREFIX . "_post p {$cat_join}WHERE {$stop_list}p.id <> 0 {$not_like}{$searchcategory}{$approve} ORDER BY p.id DESC{$threads}";
				$post_result = $this->dle_db->query("SELECT p.id FROM " . PREFIX . "_post p {$cat_join}WHERE {$stop_list}p.id <> 0 {$not_like}{$searchcategory}{$approve} ORDER BY p.id DESC{$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 xfsearch($xfields, $post_id) {
		$xf_search_words = array ();			
		$xfieldsLoad = xfieldsload();
		if (is_array($xfields)) $postedxfields = $xfields;
		else $postedxfields = xfieldsdataload($xfields);
		
		if(!empty($postedxfields)) {
			if (!empty($this->config['output_xfsearch_translit'])) {
				if ($this->dle_config['version_id'] >= 13.0) 
					$xf_file = file_get_contents(DLEPlugins::Check(ENGINE_DIR . '/inc/xfields.php'));
				else
					$xf_file = file_get_contents(ENGINE_DIR . '/inc/xfields.php');
				
				//($value[31]) ? $db->safesql(totranslit
				preg_match('/\(\$value\[([0-9]{2})\]\) \? \$db->safesql\(totranslit/', $xf_file, $xf_translit);
			}
			
			foreach ($xfieldsLoad as $name => $value3) {
				if ( $value3[6] AND !empty( $postedxfields[$value3[0]] ) ) {
					$temp_array = explode( ",", stripslashes($postedxfields[$value3[0]]) );
					
					foreach ($temp_array as $value2) {
						$value2 = trim($value2);
						if(!empty($value2)) {
							if (!empty($this->config['output_xfsearch_translit'])) 
								$xf_search_words[] = array( $this->dle_db->safesql($value[0]), $this->dle_db->safesql($value2), ($value[$xf_translit[1]]) ? $this->dle_db->safesql(totranslit(preg_replace('/&.*;/U', '', $value2), true, false)) : '' );
							else
								$xf_search_words[] = array( $this->dle_db->safesql($value3[0]), $this->dle_db->safesql($value2) );
						}
					}
				}
			}
			
			if ( count($xf_search_words) ) {
				$temp_array = array();
			
				if ($this->config['output_xfsearch_translit']) {
					foreach ( $xf_search_words as $value3 ) {
						$temp_array[] = "('" . $post_id . "', '" . $value3[0] . "', '" . $value3[1] . "', '" . $value3[2] . "')";
					}
				} else {
					foreach ( $xf_search_words as $value3 ) {
						$temp_array[] = "('" . $post_id . "', '" . $value3[0] . "', '" . $value3[1] . "')";
					}
				}
				
				$xf_search_words = implode( ", ", $temp_array );
				
				$this->dle_db->query( "DELETE FROM " . PREFIX . "_xfsearch WHERE news_id = '{$post_id}'" );
				
				// print_r($xf_search_words);
				if ($this->config['output_xfsearch_translit'])
					$this->dle_db->query( "INSERT INTO " . PREFIX . "_xfsearch (news_id, tagname, tagvalue, tagvalue_translit) VALUES " . $xf_search_words );
				else
					$this->dle_db->query( "INSERT INTO " . PREFIX . "_xfsearch (news_id, tagname, tagvalue) VALUES " . $xf_search_words );
				
			}
		}
	}
	public function replace_thread($post_id, $fields, $rewrite = 0, $post = false, $xfieldsdata = false, $parser_params = false) {

		$out_base_name = false;
		$out_base_id = false;
		$allow_title_search = false;
		
		$parser = false;
		if (in_array('parser', $fields)) $parser = true;

		//если не парсинг и массив не передается, делаем запрос в БД
		if (!$parser) {
			if ($post == false) 
				$post = $this
					->dle_db
					->super_query("SELECT * FROM " . PREFIX . "_post WHERE id = {$post_id}");
		} else $post = array();
		
		// Получаем данные доп. полей
		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]];
		}
		
		// Получаем поля cdnm ID, Kinopoisk, IMDM, World-Art
		if (!empty($output) && strpos($output, '/view/') !== false) {
			preg_match('/[0-9]{1,50}$/', $output, $cdnm_id);
			if (!empty($cdnm_id[0])) 
				$out_base['cdnm'] = $cdnm_id[0];
		}
		
		if ($this->config['kinopoisk_id'] != '') {
			$_field_kinopoisk = explode('|', $this->config['kinopoisk_id']);
			if ($_field_kinopoisk[0] == 'pspvolt_id') {
				$pspvolt = $this
					->dle_db
					->super_query("SELECT kp_id_movie FROM " . PREFIX . "_post WHERE id = {$post_id}");
				$out_base['kinopoisk_id'] = ''.$pspvolt['kp_id_movie'];
			} else {
				$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['worldart_id'] = ''.$xfieldsdata[$_field_world_art[0]];
		}
		if ($this->config['kinorium_id'] != '') {
			$_field_kinorium = explode('|', $this->config['kinorium_id']);
			$out_base['kinorium_id'] = ''.$xfieldsdata[$_field_kinorium[0]];
		}
		if ($this->config['shikimori_id'] != '') {
			$_field_shikimori = explode('|', $this->config['shikimori_id']);
			$out_base['shikimori_id'] = ''.$xfieldsdata[$_field_shikimori[0]];
		}
		if ($this->config['mdl_id'] != '') {
			$_field_mdl = explode('|', $this->config['mdl_id']);
			$out_base['mdl_id'] = ''.$xfieldsdata[$_field_mdl[0]];
		}
		if ($this->config['tmdb_id'] != '') {
			$_field_tmdb = explode('|', $this->config['tmdb_id']);
			$out_base['tmdb_id'] = ''.$xfieldsdata[$_field_tmdb[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_title_orig'] != '') {
			$_field_title_orig = explode('|', $this->config['output_title_orig']);
			$output_title_orig = ''.$xfieldsdata[$_field_title_orig[0]];
		}
		if ($this->config['output_title_ua'] != '') {
			$_field_title_ua = explode('|', $this->config['output_title_ua']);
			$output_title_ua = ''.$xfieldsdata[$_field_title_ua[0]];
		}
		if ($this->config['output_title_alt'] != '') {
			$_field_title_alt = explode('|', $this->config['output_title_alt']);
			$output_title_alt = ''.$xfieldsdata[$_field_title_alt[0]];
		}
		if ($this->config['output_year'] != '') {
			$_field_year = explode('|', $this->config['output_year']);
			$output_year = ''.$xfieldsdata[$_field_year[0]];
		}
		if ($this->config['output_duration'] != '') {
			$_field_duration = explode('|', $this->config['output_duration']);
			$output_duration = ''.$xfieldsdata[$_field_duration[0]];
		}
		if ($this->config['output_ganre'] != '') {
			$_field_ganre = explode('|', $this->config['output_ganre']);
			$output_ganre = ''.$xfieldsdata[$_field_ganre[0]];
		}
		if ($this->config['output_collections'] != '') {
			$_field_collections = explode('|', $this->config['output_collections']);
			$output_collections = ''.$xfieldsdata[$_field_collections[0]];
		}
		if ($this->config['output_country'] != '') {
			$_field_country = explode('|', $this->config['output_country']);
			$output_country = ''.$xfieldsdata[$_field_country[0]];
		}
		// persons
		if ($this->config['output_director'] != '') {
			$_field_director = explode('|', $this->config['output_director']);
			$output_director = ''.$xfieldsdata[$_field_director[0]];
		}
		if ($this->config['output_actors'] != '') {
			$_field_actors = explode('|', $this->config['output_actors']);
			$output_actors = ''.$xfieldsdata[$_field_actors[0]];
		}
		if ($this->config['output_producer'] != '') {
			$_field_producer = explode('|', $this->config['output_producer']);
			$output_producer = ''.$xfieldsdata[$_field_producer[0]];
		}
		if ($this->config['output_voice_director'] != '') {
			$_field_voice_director = explode('|', $this->config['output_voice_director']);
			$output_voice_director = ''.$xfieldsdata[$_field_voice_director[0]];
		}
		if ($this->config['output_translator'] != '') {
			$_field_translator = explode('|', $this->config['output_translator']);
			$output_translator = ''.$xfieldsdata[$_field_translator[0]];
		}
		if ($this->config['output_writer'] != '') {
			$_field_writer = explode('|', $this->config['output_writer']);
			$output_writer = ''.$xfieldsdata[$_field_writer[0]];
		}
		if ($this->config['output_operator'] != '') {
			$_field_operator = explode('|', $this->config['output_operator']);
			$output_operator = ''.$xfieldsdata[$_field_operator[0]];
		}
		if ($this->config['output_composer'] != '') {
			$_field_composer = explode('|', $this->config['output_composer']);
			$output_composer = ''.$xfieldsdata[$_field_composer[0]];
		}
		if ($this->config['output_design'] != '') {
			$_field_design = explode('|', $this->config['output_design']);
			$output_design = ''.$xfieldsdata[$_field_design[0]];
		}
		if ($this->config['output_editor'] != '') {
			$_field_editor = explode('|', $this->config['output_editor']);
			$output_editor = ''.$xfieldsdata[$_field_editor[0]];
		}
		//
		
		if ($this->config['output_kinopoisk_rate'] != '') {
			$_field_kinopoisk_rate = explode('|', $this->config['output_kinopoisk_rate']);
			$output_kinopoisk_rate = ''.$xfieldsdata[$_field_kinopoisk_rate[0]];
		}
		if ($this->config['output_kinopoisk_rate_votes'] != '') {
			$_field_kinopoisk_rate_votes = explode('|', $this->config['output_kinopoisk_rate_votes']);
			$output_kinopoisk_rate_votes = ''.$xfieldsdata[$_field_kinopoisk_rate_votes[0]];
		}
		if ($this->config['output_imdb_rate'] != '') {
			$_field_imdb_rate = explode('|', $this->config['output_imdb_rate']);
			$output_imdb_rate = ''.$xfieldsdata[$_field_imdb_rate[0]];
		}
		if ($this->config['output_imdb_rate_votes'] != '') {
			$_field_imdb_rate_votes = explode('|', $this->config['output_imdb_rate_votes']);
			$output_imdb_rate_votes = ''.$xfieldsdata[$_field_imdb_rate_votes[0]];
		}
		if ($this->config['output_tmdb_rate'] != '') {
			$_field_tmdb_rate = explode('|', $this->config['output_tmdb_rate']);
			$output_tmdb_rate = ''.$xfieldsdata[$_field_tmdb_rate[0]];
		}
		if ($this->config['output_tmdb_rate_votes'] != '') {
			$_field_tmdb_rate_votes = explode('|', $this->config['output_tmdb_rate_votes']);
			$output_tmdb_rate_votes = ''.$xfieldsdata[$_field_tmdb_rate_votes[0]];
		}

		if ($this->config['output_age'] != '') {
			$_field_age = explode('|', $this->config['output_age']);
			$output_age = ''.$xfieldsdata[$_field_age[0]];
		}
		if ($this->config['output_mpaa'] != '') {
			$_field_mpaa = explode('|', $this->config['output_mpaa']);
			$output_mpaa = ''.$xfieldsdata[$_field_mpaa[0]];
		}
		if ($this->config['output_premier_mir'] != '') {
			$_field_premier_mir = explode('|', $this->config['output_premier_mir']);
			$output_premier_mir = ''.$xfieldsdata[$_field_premier_mir[0]];
		}
		if ($this->config['output_premier_rf'] != '') {
			$_field_premier_rf = explode('|', $this->config['output_premier_rf']);
			$output_premier_rf = ''.$xfieldsdata[$_field_premier_rf[0]];
		}
		if ($this->config['output_budget'] != '') {
			$_field_budget = explode('|', $this->config['output_budget']);
			$output_budget = ''.$xfieldsdata[$_field_budget[0]];
		}
		if ($this->config['output_feels_usa'] != '') {
			$_field_feels_usa = explode('|', $this->config['output_feels_usa']);
			$output_feels_usa = ''.$xfieldsdata[$_field_feels_usa[0]];
		}
		if ($this->config['output_feels_world'] != '') {
			$_field_feels_world = explode('|', $this->config['output_feels_world']);
			$output_feels_world = ''.$xfieldsdata[$_field_feels_world[0]];
		}
		if ($this->config['output_feels_russia'] != '') {
			$_field_feels_russia = explode('|', $this->config['output_feels_russia']);
			$output_feels_russia = ''.$xfieldsdata[$_field_feels_russia[0]];
		}
		if ($this->config['output_slogan'] != '') {
			$_field_slogan = explode('|', $this->config['output_slogan']);
			$output_slogan = ''.$xfieldsdata[$_field_slogan[0]];
		}
		if ($this->config['output_trivia'] != '') {
			$_field_trivia = explode('|', $this->config['output_trivia']);
			$output_trivia = ''.$xfieldsdata[$_field_trivia[0]];
		}
		if ($this->config['output_poster'] != '') {
			$_field_poster = explode('|', $this->config['output_poster']);
			$output_poster = ''.$xfieldsdata[$_field_poster[0]];
		}
		if ($this->config['output_screen'] != '') {
			$_field_screen = explode('|', $this->config['output_screen']);
			$output_screen = ''.$xfieldsdata[$_field_screen[0]];
		}

		$output_short_story = ''.$post['short_story'];
		$output_full_story = ''.$post['full_story'];
		
		// Переменные UF
		if ($this->config['cdnm_status'] != '' && $this->config['cdnm_statcdnm_value'] != '') {
			$_field_cdnm_status = explode('|', $this->config['cdnm_status']);
			$cdnm_status = ''.$xfieldsdata[$_field_cdnm_status[0]];
			$cdnm_statcdnm_value = $this->config['cdnm_statcdnm_value'];
		}
		
		$cdnm_stop = false; // Стоп-фактор для us
		if ($output != '') { // Если ссылка уже проставлена, проверяем остальные стоп-факторы
			if ($this->config['output_season'] != '' && $output_season == '' && $this->config['output_episode'] != '' && $output_episode == '') { //movie
				
				// Проверка по качеству
				if ($this->config['cdnm_stop_q'] != '' && $cdnm_stop == false) {
					$stop_q = explode(',', $this->config['cdnm_stop_q']);
						
					//if ($output_quality != '' && in_array($output_quality, $stop_q)) $cdnm_stop = true;
					if ($output_quality != '') 
						foreach ($stop_q as $value) {
							if (stripos($output_quality, $value) !== false) {
								$cdnm_stop = true;
								if ($this->config['cdnm_debug'] != '') echo "\r\n".'<!-- STOP QUALITY -->';
								break;
							}
									
						}	
				}
						
				// Проверка по озвучке
				if ($this->config['cdnm_stop_s'] != '' && $cdnm_stop == false) {
					$stop_s = explode(',', $this->config['cdnm_stop_s']);
						
					if ($output_voice != '' && in_array($output_voice, $stop_s)) $cdnm_stop = true;
					elseif ($output_voiceall != '') {
						$output_voiceall_arr = explode(', ', $output_voiceall);
						foreach ($stop_s as $value) {
							if (in_array($value, $output_voiceall_arr)) {
								$cdnm_stop = true;
								if ($this->config['cdnm_debug'] != '') echo "\r\n".'<!-- STOP SOUND -->';
								break;
							}
						}
					}
				}
					
				// Проверка по году
				if ($this->config['cdnm_stop_y'] != '' && $cdnm_stop == false) {
					$_uf_field_year = explode('|', $this->config['cdnm_stop_y']);
					$uf_field_year = ''.$xfieldsdata[$_uf_field_year[0]];
					$stop_y = intval($this->config['cdnm_stop_y_value']);

					if ($uf_field_year != '' && $stop_y != 0 && (date('Y') - $uf_field_year) > $stop_y) {
						$cdnm_stop = true;
						if ($this->config['cdnm_debug'] != '') echo "\r\n".'<!-- STOP YEAR -->';
					}
				} 
					
			}
			else { //serial
					
				// Проверка по статусу
				if ($this->config['cdnm_status'] != '' && $this->config['cdnm_statcdnm_value'] != '' && $cdnm_status == $cdnm_statcdnm_value && $output_episode != '') {
					if ($this->config['cdnm_episodes_end'] == '' || $output_episode == $this->config['cdnm_episodes_end']) 
						$cdnm_stop = true; 
					if ($this->config['cdnm_debug'] != '') echo "\r\n".'<!-- STOP STATUS -->';
				} 
					
			}
				
		} // Если ссылки нет, идем дальше и делаем запрос
			
		// Если запрос от модуля us
		if (in_array('us', $fields) && $cdnm_stop) return array('status' => 'stop');

		// Если ссылка уже проставлена
		$only_url = in_array('only_url', $fields) ? true : false;
		$only_no_url = in_array('only_no_url', $fields) ? true : false;
		if ($only_no_url && !$rewrite && !empty($output)) return array('status' => 'exist');
		
		// Определяем базу для поиска 
		$bases = array();
		foreach ($out_base as $base_name => $base_value) {
			if ($out_base[$base_name] != '') {
				$bases[] = $base_name.'='.$base_value;
				
				if (in_array('us', $fields)) break; // autoupdate
			}
		}

		if (!empty($bases)) {
			
			if (in_array('us', $fields)) $search_time = 2; else $search_time = 30;
			// public function find($btn, $out_base, $title = '', $search_time = 20) {
			$response = $this->find(true, $bases, null, $search_time);
				
			$r_key = 0;
	
			// если массив и (есть фрейм или (парсер и есть данные кинопоиска))
			if (is_array($response) && (!empty($response[$r_key]['iframe_src']) )) {
				$iframe_type = $response[$r_key]['type'];
				$iframe_url = $response[$r_key]['iframe_src'];
				
				$iframe_quality = !empty($response[$r_key]['quality']) ? $response[$r_key]['quality'] : '';
				$iframe_voice = !empty($response[$r_key]['translate']) ? $response[$r_key]['translate'] : '';
				// if ($this->config['output_voice_all'])
					// $iframe_voice = !empty($response[$r_key]['translate_all']) ? $response[$r_key]['translate_all'] : $iframe_voice;
				
				$iframe_lastseason = $response[$r_key]['seasons'] > 0 ? $response[$r_key]['seasons'] : '';
				$iframe_origseason = isset($response[$r_key]['seasons_orig']) ? $response[$r_key]['seasons_orig'] : '';
				$iframe_lastepisode = $response[$r_key]['episodes'] > 0 ? $response[$r_key]['episodes'] : '';
				$iframe_origepisode = isset($response[$r_key]['episodes_orig']) ? $response[$r_key]['episodes_orig'] : '';
				$iframe_serial_end = isset($response[$r_key]['serial_end']) ? $response[$r_key]['serial_end'] : '0';
				
				$iframe_kinopoisk_id = $response[$r_key]['kinopoisk_id'];
				$iframe_imdb_id = $response[$r_key]['imdb_id'];
				$iframe_world_art_id = isset($response[$r_key]['world_art_id']) ? $response[$r_key]['world_art_id'] : '';
				$iframe_kinorium_id = isset($response[$r_key]['kinorium_id']) ? $response[$r_key]['kinorium_id'] : '';
				$iframe_tmdb_id = isset($response[$r_key]['tmdb_id']) ? $response[$r_key]['tmdb_id'] : '';
				$iframe_shikimori_id = isset($response[$r_key]['shikimori_id']) ? $response[$r_key]['shikimori_id'] : '';
				$iframe_mdl_id = isset($response[$r_key]['mdl_id']) ? $response[$r_key]['mdl_id'] : '';

				$iframe_title = $response[$r_key]['title'];
				$iframe_title_orig = $response[$r_key]['title_orig'];
				$iframe_title_ua = $response[$r_key]['title_ua'];
				$iframe_title_alt = $response[$r_key]['title_alt'];
				$iframe_year = $response[$r_key]['year'];
				
				$iframe_duration = $response[$r_key]['duration'];
				$iframe_ganre = $response[$r_key]['ganre'];
				$iframe_collections = $response[$r_key]['collections'];
				$iframe_country = $response[$r_key]['country'];
				$iframe_actors = $response[$r_key]['actors'];
				$iframe_producer = $response[$r_key]['producer'];
				
				$iframe_voice_director = $response[$r_key]['voice_director'];
				$iframe_translator = $response[$r_key]['translator'];
				$iframe_writer = $response[$r_key]['writer'];
				$iframe_operator = $response[$r_key]['operator'];
				$iframe_composer = $response[$r_key]['composer'];
				$iframe_composer = $response[$r_key]['composer'];
				$iframe_editor = $response[$r_key]['editor'];
				
				$iframe_kinopoisk_rate = $response[$r_key]['kinopoisk_rate'];
				$iframe_kinopoisk_rate_votes = $response[$r_key]['kinopoisk_rate_votes'];
				$iframe_imdb_rate = $response[$r_key]['imdb_rate'];
				$iframe_imdb_rate_votes = $response[$r_key]['imdb_rate_votes'];
				$iframe_tmdb_rate = $response[$r_key]['tmdb_rate'];
				$iframe_tmdb_rate_votes = $response[$r_key]['tmdb_rate_votes'];
				
				$iframe_poster = $response[$r_key]['poster']; 
				$iframe_screen = $response[$r_key]['screen']; 
				$iframe_age = $response[$r_key]['age']; 
				$iframe_mpaa = $response[$r_key]['mpaa']; 
				$iframe_premier_rf = $response[$r_key]['premier_rf'];
				$iframe_premier_mir = $response[$r_key]['premier_mir'];
				$iframe_budget = $response[$r_key]['budget'];
				$iframe_feels_usa = $response[$r_key]['feels_usa'];
				$iframe_feels_russia = $response[$r_key]['feels_russia'];
				$iframe_feels_world = $response[$r_key]['feels_world'];

				$iframe_director = $response[$r_key]['director'];
				$iframe_trivia = $response[$r_key]['trivia'];
				$iframe_description = $response[$r_key]['description'];
				$iframe_description_short = $response[$r_key]['description_short'];
				$iframe_slogan = $response[$r_key]['slogan'];
				$iframe_ganres_cats = $response[$r_key]['ganres_cats'];
				
				//UF status
				// Если сезон завершен
				if ($iframe_serial_end == '1' && $this->config['cdnm_status'] != '' && $cdnm_statcdnm_value != '') { 
					// Меняем статус на "Завершенный"
					$cdnm_status = $cdnm_statcdnm_value;
					$xfieldsdata[$_field_cdnm_status[0]] = $cdnm_statcdnm_value;

					$cdnm_stop = true; // Стоп-фактор для us
				} 
					
				// Меняем текст в сериях на "Все серии"
				if (
					$iframe_lastseason != '' && //если сериал
					$cdnm_status != '' && 
					$cdnm_statcdnm_value != '' && 
					$cdnm_status == $cdnm_statcdnm_value &&
					$this->config['cdnm_episodes_end'] != ''
				   ) 
				{
				   $iframe_lastepisode = $this->config['cdnm_episodes_end'];
				}

				if ($this->config['cdnm_debug'] != '')
					echo "\r\n".'<!-- END_SERIAL _ "'.$cdnm_status.'" - "'.$cdnm_statcdnm_value.'" - "'.$this->config['cdnm_episodes_end'].'" - "'.$iframe_lastepisode.'" -->';
				
				if ($this->config['cdnm_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.'" - "'.$output_voice.'" -->';
					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) || $rewrite)) {
					if ($this->config['cdnm_debug'] != '') echo "\r\n".'<!-- SAVE_ONLY_URL -->';
					
					$field_set = array();
					// this field is used
					if ($this->config['output'] && $iframe_url != '') {
						$_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;
					} elseif ($xfieldsdata[$_field_output[0]] == '') unset($xfieldsdata[$_field_output[0]]);
					
					$xfields = array();
					foreach ($xfieldsdata as $key => $value) {
						// if ((isset($xfieldsdata[$key]) && $xfieldsdata[$key] == '') || (!isset($xfieldsdata[$key]))) continue;
						$value = str_replace('|', '&#124;', $value);
						$xfields[] = "$key|$value";
					}
					$xfields = implode('||', $xfields);
					$xfields = addslashes($xfields);

					if (count($field_set)) $set_nativefields = ", " . implode(", ", $field_set);

					$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' => '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 != $output_voice) or
					($this->config['output_season'] != '' && $iframe_lastseason != '' && $iframe_lastseason != $output_season) or
					($this->config['output_episode'] != '' && $iframe_lastepisode != '' && $iframe_lastepisode != $output_episode)
					) or 
					// Если дебаг и nosave опция активна
					($this->config['cdnm_debug'] != '' && $this->config['cdnm_debug_nosave']) or
					// Если перезапись
					$rewrite))
				{

					if ($this->config['cdnm_debug'] != '') echo "\r\n".'<!-- SAVE -->';
					
					// cats
					if ($this->config['cdnm_on'] && !empty($iframe_url)) {
						$catTrailer = $this->config['cdnm_cat_trailer'];
						$catTs = $this->config['cdnm_cat_ts'];
						$catHD = $this->config['cdnm_cat_hd'];
						$catHD_s = $this->config['cdnm_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);
						$cdnm_cat = explode(',', $post['category']);
						
						// Автообновление - ФИЛЬМ
						if ($iframe_type == 'movie') {
							// Переводим из плохого качества в HD, если был в плохом 
							if ($catTs && $catHD && in_array($catTs, $cdnm_cat)) {
								if (stripos($iframe_quality, 'ts') === false || stripos($iframe_quality, 'camrip') === false) {
									$cdnm_cat = array_diff ($cdnm_cat, array($catTs));
									if ( !in_array($catHD, $cdnm_cat) ) $cdnm_cat[] = $catHD;
								}
							} 
							// Удаляем из трейлеров и переводим куда-то
							elseif ($catTrailer && ($catTs || $catHD) && $this->in_array_arr($catTrailer, $cdnm_cat)) {
								$cdnm_cat = array_diff($cdnm_cat, $catTrailer);
							
								if ($catTs && $catHD) {
									//если не HD
									if (stripos($iframe_quality, 'ts') !== false || stripos($iframe_quality, 'camrip') !== false) {
										if ( $catTs && !in_array($catTs, $cdnm_cat) ) $cdnm_cat[] = $catTs;
									} 
									//если HD
									elseif (stripos($iframe_quality, 'ts') === false || stripos($iframe_quality, 'camrip') === false) {
										$cdnm_cat = array_diff ($cdnm_cat, array($catTs));					
										if ( !in_array($catHD, $cdnm_cat) ) $cdnm_cat[] = $catHD;
									}
								} elseif ($catHD) {
									if ( !in_array($catHD, $cdnm_cat) ) $cdnm_cat[] = $catHD;
								}
							}
							// Просто удаляем из трейлеров
							elseif ($catTrailer) $cdnm_cat = array_diff($cdnm_cat, $catTrailer);
						} //end movie
							
						// Автообновление - СЕРИАЛ
						if ($iframe_type == 'serial') {
							// Удаляем из трейлеров и переводим куда-то
							if ($catTrailer && $catHD_s && $this->in_array_arr($catTrailer, $cdnm_cat)) {
								$cdnm_cat = array_diff($cdnm_cat, $catTrailer);
								if ( $catHD_s && !in_array($catHD_s, $cdnm_cat) ) $cdnm_cat[] = $catHD_s;
							}
							// Просто удаляем из трейлеров
							elseif ($catTrailer) $cdnm_cat = array_diff($cdnm_cat, $catTrailer);
						} //end serials
						
						$cdnm_cat = array_unique($cdnm_cat); // удаляем дубли
						$cdnm_cat_str = implode(',', $cdnm_cat);
						//если есть изменения в категориях
						if ($cdnm_cat_str != $post['category']) {
							$post['category']  = $cdnm_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 ($cdnm_cat_str != '') {
									$cat_ids = array();
									foreach ( $cdnm_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 cdnm_on
										
					// Основные данные
					$field_set = array(); // определяем, если использует поле, а не доп.поле
					if ($this->config['output'] && $iframe_url != '') {
						$_field = explode('|', $this->config['output']);
						if (count($_field) == 1) 
							$field_set[$_field[0]] = $iframe_url;
						elseif (count($_field) == 3) $xfieldsdata[$_field_output[0]] = $iframe_url;
					} elseif ($xfieldsdata[$_field_output[0]] == '') unset($xfieldsdata[$_field_output[0]]);

					if ($this->config['output_quality'] && $iframe_quality != '') {
						$_field = explode('|', $this->config['output_quality']);
						$xfieldsdata[$_field[0]] = $iframe_quality;
					} elseif ($xfieldsdata[$_field_quality[0]] == '') unset($xfieldsdata[$_field_quality[0]]);
					
					if ($this->config['output_voice'] && $this->config['output_voice'] != '' && $iframe_voice != '') {
						$_field = explode('|', $this->config['output_voice']);
						$xfieldsdata[$_field[0]] = $iframe_voice;
					} elseif ($xfieldsdata[$_field_voice[0]] == '') unset($xfieldsdata[$_field_voice[0]]);
											
					if ($this->config['output_season'] && $iframe_lastseason != '') {
						$_field = explode('|', $this->config['output_season']);
						$xfieldsdata[$_field[0]] = $iframe_lastseason;
					} 

					if ($this->config['output_episode'] && $iframe_lastepisode != '') {
						$_field = explode('|', $this->config['output_episode']);
						$xfieldsdata[$_field[0]] = $iframe_lastepisode;
					}
					
					// Kinopoisk, IMDM, World-Art....
					if ($this->config['allow_autopaste']) {
						if ($iframe_kinopoisk_id && $_field_kinopoisk && !$out_base['kinopoisk_id'] && $_field_kinopoisk[0] != 'pspvolt_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_kinorium_id && $_field_kinorium && !$out_base['kinorium_id'])
							$xfieldsdata[$_field_kinorium[0]] = $iframe_kinorium_id;
						
						if ($iframe_tmdb_id && $_field_tmdb && !$out_base['tmdb_id'])
							$xfieldsdata[$_field_tmdb[0]] = $iframe_tmdb_id;
						
						if ($iframe_shikimori_id && $_field_shikimori && !$out_base['shikimori_id'])
							$xfieldsdata[$_field_shikimori[0]] = $iframe_shikimori_id;
						
						if ($iframe_mdl_id && $_field_mdl && !$out_base['mdl_id'])
							$xfieldsdata[$_field_mdl[0]] = $iframe_mdl_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_title_orig && $_field_title_orig && (!$output_title_orig || $this->config['output_title_orig_rw']))
						$xfieldsdata[$_field_title_orig[0]] = $this->dle_db->safesql( $iframe_title_orig );
					
					if ($iframe_title_ua && $_field_title_ua && (!$output_title_ua || $this->config['output_title_ua_rw']))
						$xfieldsdata[$_field_title_ua[0]] = $this->dle_db->safesql( $iframe_title_ua );
					
					if ($iframe_title_alt && $_field_title_alt && (!$output_title_alt || $this->config['output_title_orig_rw']))
						$xfieldsdata[$_field_title_alt[0]] = $this->dle_db->safesql( $iframe_title_alt );
					
					if ($iframe_year && $_field_year && (!$output_year || $this->config['output_year_rw']))
						$xfieldsdata[$_field_year[0]] = $iframe_year;
					
					if ($iframe_duration && $_field_duration && (!$output_duration || $this->config['output_duration_rw']))
						$xfieldsdata[$_field_duration[0]] = $iframe_duration;
					
					if ($iframe_ganre && $_field_ganre && (!$output_ganre || $this->config['output_ganre_rw']))
						$xfieldsdata[$_field_ganre[0]] = $iframe_ganre;
					
					if ($iframe_collections && $_field_collections) 
						if (!$output_collections)
							$xfieldsdata[$_field_collections[0]] = $iframe_collections;
						elseif ($this->config['output_collections_rw']) {
							$output_collections_arr = explode(',', $output_collections .','. $iframe_collections);
							foreach($output_collections_arr as $k => $c) {
								$output_collections_arr[$k] = trim($c);
							}
							$output_collections_arr = array_unique($output_collections_arr);
							$iframe_collections = implode(', ', $output_collections_arr);
							$xfieldsdata[$_field_collections[0]] = $iframe_collections;
						}
					
					if ($iframe_country && $_field_country && (!$output_country || $this->config['output_country_rw']))
						$xfieldsdata[$_field_country[0]] = $iframe_country;
					
					if ($iframe_actors && $_field_actors && (!$output_actors || $this->config['output_actors_rw']))
						$xfieldsdata[$_field_actors[0]] = $iframe_actors;
					
					if ($iframe_producer && $_field_producer && (!$output_producer || $this->config['output_producer_rw']))
						$xfieldsdata[$_field_producer[0]] = $iframe_producer;

					if ($iframe_voice_director && $_field_voice_director && (!$output_voice_director || $this->config['output_voice_director_rw']))
						$xfieldsdata[$_field_voice_director[0]] = $iframe_voice_director;
					
					if ($iframe_translator && $_field_translator && (!$output_translator || $this->config['output_translator_rw']))
						$xfieldsdata[$_field_translator[0]] = $iframe_translator;
					
					if ($iframe_writer && $_field_writer && (!$output_writer || $this->config['output_writer_rw']))
						$xfieldsdata[$_field_writer[0]] = $iframe_writer;
					
					if ($iframe_operator && $_field_operator && (!$output_operator || $this->config['output_operator_rw']))
						$xfieldsdata[$_field_operator[0]] = $iframe_operator;
					
					if ($iframe_composer && $_field_composer && (!$output_composer || $this->config['output_composer_rw']))
						$xfieldsdata[$_field_composer[0]] = $iframe_composer;
					
					if ($iframe_design && $_field_design && (!$output_design || $this->config['output_design_rw']))
						$xfieldsdata[$_field_design[0]] = $iframe_design;
					
					if ($iframe_editor && $_field_editor && (!$output_editor || $this->config['output_editor_rw']))
						$xfieldsdata[$_field_editor[0]] = $iframe_editor;

					if ($iframe_kinopoisk_rate && $_field_kinopoisk_rate && (!$output_kinopoisk_rate || $this->config['output_kinopoisk_rate_rw']))
						$xfieldsdata[$_field_kinopoisk_rate[0]] = $iframe_kinopoisk_rate;
					
					if ($iframe_kinopoisk_rate_votes && $_field_kinopoisk_rate_votes && (!$output_kinopoisk_rate_votes || $this->config['output_kinopoisk_rate_votes_rw']))
						$xfieldsdata[$_field_kinopoisk_rate_votes[0]] = $iframe_kinopoisk_rate_votes;
					
					if ($iframe_imdb_rate && $_field_imdb_rate && (!$output_imdb_rate || $this->config['output_imdb_rate_rw']))
						$xfieldsdata[$_field_imdb_rate[0]] = $iframe_imdb_rate;
					
					if ($iframe_imdb_rate_votes && $_field_imdb_rate_votes && (!$output_imdb_rate_votes || $this->config['output_imdb_rate_votes_rw']))
						$xfieldsdata[$_field_imdb_rate_votes[0]] = $iframe_imdb_rate_votes;
					
					if ($iframe_tmdb_rate && $_field_tmdb_rate && (!$output_tmdb_rate || $this->config['output_tmdb_rate_rw']))
						$xfieldsdata[$_field_tmdb_rate[0]] = $iframe_tmdb_rate;
					
					if ($iframe_tmdb_rate_votes && $_field_tmdb_rate_votes && (!$output_tmdb_rate_votes || $this->config['output_tmdb_rate_votes_rw']))
						$xfieldsdata[$_field_tmdb_rate_votes[0]] = $iframe_tmdb_rate_votes;
					
					// ratingAge
					if ($iframe_age && $_field_age && (!$output_age || $this->config['output_age_rw']))
						$xfieldsdata[$_field_age[0]] = $iframe_age;
					
					if ($iframe_mpaa && $_field_mpaa && (!$output_mpaa || $this->config['output_mpaa_rw']))
						$xfieldsdata[$_field_mpaa[0]] = $iframe_mpaa;
					
					// premier
					if ($iframe_premier_rf && $_field_premier_rf && (!$output_premier_rf || $this->config['output_premier_rf_rw']))
						$xfieldsdata[$_field_premier_rf[0]] = $iframe_premier_rf;
					
					if ($iframe_premier_mir && $_field_premier_mir && (!$output_premier_mir || $this->config['output_premier_mir_rw']))
						$xfieldsdata[$_field_premier_mir[0]] = $iframe_premier_mir;
					
					if ($iframe_budget && $_field_budget && (!$output_budget || $this->config['output_budget_rw']))
						$xfieldsdata[$_field_budget[0]] = $iframe_budget;
					
					if ($iframe_feels_usa && $_field_feels_usa && (!$output_feels_usa || $this->config['output_feels_usa_rw']))
						$xfieldsdata[$_field_feels_usa[0]] = $iframe_feels_usa;
					
					if ($iframe_feels_world && $_field_feels_world && (!$output_feels_world || $this->config['output_feels_world_rw']))
						$xfieldsdata[$_field_feels_world[0]] = $iframe_feels_world;
					
					if ($iframe_feels_russia && $_field_feels_russia && (!$output_feels_russia || $this->config['output_feels_russia_rw']))
						$xfieldsdata[$_field_feels_russia[0]] = $iframe_feels_russia;
					
					// director
					if ($iframe_director && $_field_director && (!$output_director || $this->config['output_director_rw']))
						$xfieldsdata[$_field_director[0]] = $iframe_director;
					// trivia
					if ($iframe_trivia && $_field_trivia && (!$output_trivia || $this->config['output_trivia_rw']))
						$xfieldsdata[$_field_trivia[0]] = $iframe_trivia;
					
					// description
					if (empty($output_full_story) && !$this->config['output_not_fullstory']) 
						$field_set['full_story'] = $this->dle_db->safesql($iframe_description);
					if (empty($output_short_story)) 
						$field_set['short_story'] = $this->dle_db->safesql($iframe_description_short);
					
					// slogan
					if ($iframe_slogan && $_field_slogan && (!$output_slogan || $this->config['output_slogan_rw']))
						$xfieldsdata[$_field_slogan[0]] = $iframe_slogan;
					
					// poster
					if ($iframe_poster && $_field_poster && (!$output_poster || ($this->config['output_poster_no'] && $output_poster == $this->config['output_poster_no']) || in_array('poster_rewrite', $fields))) {
						// if ($this->config['output_poster_no_upload'] && $_field_poster[2] == 'text') $poster_url['link'] = $iframe_poster;
						// else $poster_url = $this->poster($iframe_poster, 0);	
						$poster_url = $this->poster($iframe_poster, $post['id'], $post['author']);	
						
						if ($_field_poster[2] == 'image') $poster_url['link'] = preg_replace('/^(.*)\/uploads\/posts\//', '', $poster_url['link']);
						else $poster_url['link'] = preg_replace('/^(.*)\/uploads\//', '/uploads/', $poster_url['link']);
						
						if (!empty($poster_url['link'])) $xfieldsdata[$_field_poster[0]] = $poster_url['link'];
						
					} elseif (!$iframe_poster && $_field_poster && !$output_poster && $this->config['output_poster_no']  && $_field_poster[2] == 'text') {
						$xfieldsdata[$_field_poster[0]] = $this->config['output_poster_no'];
					}
					// screens
					if (!empty($iframe_screen) && $_field_screen && !$output_screen) {
						$screens = array();
						foreach($iframe_screen as $screen_url) {
							$screen_url = $this->poster($screen_url, $post['id'], $post['author']);	
							
							$screen_url['link'] = preg_replace('/^(.*)\/uploads\/posts\//', '', $screen_url['link']);
							
							if (!empty($screen_url['link'])) $screens[] = $screen_url['link'];
						}
						if (!empty($screens)) {
							$screen_url = implode(',', $screens);
							$xfieldsdata[$_field_screen[0]] = $screen_url;
						}
					}

					//ganres-catogory
					if (!empty($iframe_ganres_cats)) {
						$ganre_cat = explode(',', $iframe_ganres_cats);
						$g_cat = explode(',', $post['category']);

						$g_cat = array_merge($ganre_cat,$g_cat);
						$g_cat = array_unique($g_cat); // удаляем дубли
						$g_cat_str = implode(',', $g_cat);
						//если есть изменения в категориях
						if ($g_cat_str != $post['category']) {
							$post['category'] = $g_cat_str;
								
							// Запись ID категорий в отдельную таблицу для dle 13.2
							if ($this->dle_config['version_id'] >= 13.2 && !$parser) {
								$this
									->dle_db
									->query( "DELETE FROM " . PREFIX . "_post_extras_cats WHERE news_id = '{$post_id}'" );
											
								if ($g_cat_str != '') {
									$cat_ids = array();
									foreach ( $g_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 );
								}
							}
						}
					}
					
					// Shablons
					$set_shablons = '';
					$cdnm_metatitle = $this->config['cdnm_metatitle'];
					$cdnm_title = $this->config['cdnm_title'];
					$cdnm_chpu = $this->config['cdnm_chpu'];
					$cdnm_metadescription = $this->config['cdnm_metadescription'];
					
					if (($cdnm_metatitle != '' || $cdnm_title != '' || $cdnm_chpu != '' || $cdnm_metadescription != '') && $iframe_type != 'my_base') {
						$cdnm_from = array(
							'{title}',
							'{year}',
							'{date}',
							'{description}'
						);
						$cdnm_to_date = $this->config['cdnm_shab_date'] != ''?date($this->config['cdnm_shab_date']):'';
						$cdnm_to = array(
							$iframe_title,
							$iframe_year,
							$cdnm_to_date,
							$iframe_description
						);
						
						$cdnm_shabs = $cdnm_metatitle.'#SEP#'.$cdnm_metadescription.'#SEP#'.$cdnm_title.'#SEP#'.$cdnm_chpu;
							
						preg_match_all( "/{xfvalue_(.*)}/U", $cdnm_shabs, $cdnm_shabs_match );
						foreach ($cdnm_shabs_match[1] as $k => $v) {
							// Добавляем в шаблоны если еще не было раньше
							if (!in_array($cdnm_shabs_match[0][$k], $cdnm_from)) {
								$cdnm_from[] = $cdnm_shabs_match[0][$k];
								$cdnm_to[] = $xfieldsdata[$v];
							}
						}
						$cdnm_from[] = '  ';
						$cdnm_to[] = ' ';
						if ($this->config['cdnm_debug'] != '') echo "\r\n".'<!-- SHAB before: '.$cdnm_shabs.'-->';
						$cdnm_shabs = str_replace($cdnm_from, $cdnm_to, $cdnm_shabs);
						if ($this->config['cdnm_debug'] != '') echo "\r\n".'<!-- SHAB after: '.$cdnm_shabs.'-->';
							
						// Тег фильма
						if (strpos($cdnm_shabs,'{if_movie}') !== false) {
							if ($iframe_type == 'movie') 
								$cdnm_shabs = str_replace(array('{if_movie}','{/if_movie}'), '', $cdnm_shabs);
							else 
								$cdnm_shabs = preg_replace('/{if_movie}(.*){\/if_movie}/U', '', $cdnm_shabs);
						}
						// Тег сериал
						if (strpos($cdnm_shabs,'{if_serial}') !== false) {
							if ($iframe_type == 'movie') 
								$cdnm_shabs = preg_replace('/{if_serial}(.*){\/if_serial}/U', '', $cdnm_shabs);
							else 
								$cdnm_shabs = str_replace(array('{if_serial}','{/if_serial}'), '', $cdnm_shabs);
						}

						$cdnm_shabs = explode('#SEP#', $cdnm_shabs);
							
						$cdnm_metatitle = $cdnm_shabs[0];
						$cdnm_metadescription = $cdnm_shabs[1];
						$cdnm_title = $cdnm_shabs[2];
						$cdnm_chpu = $cdnm_shabs[3];
						
						if ($iframe_type == 'serial') {
							$cdnm_metatitle_season = $this->serials_format('season', $this->config['cdnm_metatitle_season_format'], $iframe_origseason, $this->config['output_season_format']);
							$cdnm_metatitle_plus = $this->config['cdnm_metatitle_plus'] ? $this->config['cdnm_metatitle_plus'] : 0 ;
							$cdnm_metatitle_episode = $this->serials_format('episode', $this->config['cdnm_metatitle_episode_format'], $iframe_origepisode, $this->config['output_episode_format'], $cdnm_metatitle_plus);
							
							$cdnm_metadescription_season = $this->serials_format('season', $this->config['cdnm_metadescription_season_format'], $iframe_origseason, $this->config['output_season_format']);
							$cdnm_metadescription_plus = $this->config['cdnm_metadescription_plus'] ? $this->config['cdnm_metadescription_plus'] : 0 ;
							$cdnm_metadescription_episode = $this->serials_format('episode', $this->config['cdnm_metadescription_episode_format'], $iframe_origepisode, $this->config['output_episode_format'], $cdnm_metadescription_plus);
							
							$cdnm_title_season = $this->serials_format('season', $this->config['cdnm_title_season_format'], $iframe_origseason, $this->config['output_season_format']);
							$cdnm_title_plus = $this->config['cdnm_title_plus'] ? $this->config['cdnm_title_plus'] : 0 ;
							$cdnm_title_episode = $this->serials_format('episode', $this->config['cdnm_title_episode_format'], $iframe_origepisode, $this->config['output_episode_format'], $cdnm_title_plus);
							
							$cdnm_chpu_season = $this->serials_format('season', $this->config['cdnm_chpu_season_format'], $iframe_origseason, $this->config['output_season_format']);
							$cdnm_chpu_season = str_replace(',', '-', $cdnm_chpu_season);
							$cdnm_chpu_plus = $this->config['cdnm_chpu_plus'] ? $this->config['cdnm_chpu_plus'] : 0 ;
							$cdnm_chpu_episode = $this->serials_format('episode', $this->config['cdnm_chpu_episode_format'], $iframe_origepisode, $this->config['output_episode_format'], $cdnm_chpu_plus);
							$cdnm_chpu_episode = str_replace(',', '-', $cdnm_chpu_episode);
						} else {
							$cdnm_metatitle_season = $cdnm_metatitle_episode = $cdnm_metadescription_season = $cdnm_metadescription_episode = $cdnm_title_season = $cdnm_title_episode = $cdnm_chpu_season = $cdnm_chpu_episode = '';
						}
							
						if ($cdnm_metatitle != '' && 
							(
							 $parser || // parser
							 ( // not parser
							  !$parser && !isset($this->config['cdnm_metatitle_onlyparse']) &&
							  ($iframe_type == 'serial' || $this->config['cdnm_metatitle_movie'])
							 )
							)
						   ) {
							$cdnm_metatitle = str_replace(
								array('{season}','{episode}'), 
								array($cdnm_metatitle_season, $cdnm_metatitle_episode),
								$cdnm_metatitle
							);
							$cdnm_metatitle_parse = $this->dle_db->safesql( $cdnm_metatitle );
							$cdnm_metatitle  = ", metatitle = '{$cdnm_metatitle_parse}'";
						} else $cdnm_metatitle = '';
						
						if ($cdnm_metadescription != '' && 
							(
							 $parser || // parser
							 ( // not parser
							  !$parser && !isset($this->config['cdnm_metadescription_onlyparse']) &&
							  ($iframe_type == 'serial' || $this->config['cdnm_metadescription_movie'])
							 )
							)
						   ) {
							$cdnm_metadescription = str_replace(
								array('{season}','{episode}'), 
								array($cdnm_metadescription_season, $cdnm_metadescription_episode),
								$cdnm_metadescription
							);
							$cdnm_metadescription = dle_substr( $cdnm_metadescription, 0, 300, $this->dle_config['charset'] );
							$cdnm_metadescription_parse = $this->dle_db->safesql( $cdnm_metadescription );
							$cdnm_metadescription  = ", descr = '{$cdnm_metadescription_parse}'";
						} else $cdnm_metadescription = '';
						
						if ($cdnm_title != '' && 
							(
							 $parser || // parser
							 ( // not parser
							  !$parser && !isset($this->config['cdnm_title_onlyparse']) &&
							  ($iframe_type == 'serial' || $this->config['cdnm_title_movie'])
							 )
							)
						   ) {
							$cdnm_title = str_replace(
								array('{season}','{episode}'), 
								array($cdnm_title_season, $cdnm_title_episode),
								$cdnm_title
							);
							$cdnm_title_parse = $this->dle_db->safesql( $cdnm_title );							
							$cdnm_title  = ", title = '{$cdnm_title_parse}'";
						} else $cdnm_title = '';
						
						if ($cdnm_chpu != '' && 
							(
							 $parser || // parser
							 ( // not parser
							  !$parser && !isset($this->config['cdnm_chpu_onlyparse']) &&
							  ($iframe_type == 'serial' || $this->config['cdnm_chpu_movie'])
							 )
							)
						   ) {
							$cdnm_chpu = str_replace(
								array('{season}','{episode}'),
								array($cdnm_chpu_season, $cdnm_chpu_episode),
								$cdnm_chpu
							);
							$cdnm_chpu = totranslit( stripslashes( $cdnm_chpu ), true, false, $this->dle_config['translit_url'] );
							$cdnm_chpu_parse = $this->dle_db->safesql( $cdnm_chpu );							
							$cdnm_chpu  = ", alt_name = '{$cdnm_chpu_parse}'";
						} else $cdnm_chpu = '';
						 
						$set_shablons = $cdnm_metatitle.$cdnm_metadescription.$cdnm_title.$cdnm_chpu;
						if ($this->config['cdnm_debug'] != '') echo "\r\n".'<!-- SHAB sql: "'.$set_shablons.'" -->';
						
					} //end shablons

					$xfields = array();
					foreach ($xfieldsdata as $key => $value) {
						// if ((isset($xfieldsdata[$key]) && $xfieldsdata[$key] == '') || (!isset($xfieldsdata[$key]))) continue;
						$value = str_replace('|', '&#124;', $value);
						$xfields[] = "$key|$value";
					}
					$xfields = implode('||', $xfields);
					$xfields = addslashes($xfields);
					$post['xfields'] = $xfields;
					
					if (!$parser) {
					// not parser
						$up_date = '';
						$update_time = date("Y-m-d H:i:s", time());
						$edit_time = time();
						if (
						  $iframe_type == 'movie' &&
						  $this->config['up_news'] && (
							$cdnm_stop == false && //Стоп-фактор для us
							($this->config['output_quality'] != '' && $iframe_quality != $output_quality)
						  )
						) {
							if ($this->config['cdnm_debug'] != '') {
								echo "\r\n".'<!-- UP_DATE _ '.$iframe_quality.' - '.$output_quality.' -->';
							}
							else {
							  $up_date = ", date='{$update_time}' ";
							}
						}
						elseif (
						  $iframe_type == 'serial' &&
						  $this->config['up_news_serial'] && (
							$cdnm_stop == false && //Стоп-фактор для us
							(
							($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['cdnm_debug'] != '') {
								echo "\r\n".'<!-- UP_DATE _ '.$iframe_lastseason.' - '.$output_season.' -->';
								echo "\r\n".'<!-- UP_DATE _ '.$iframe_lastepisode.' - '.$output_episode.' -->';
							}
							else {
							  $up_date = ", date='{$update_time}' ";
							}
						}

						if (count($field_set)) {
							foreach($field_set as $k => $v) {
								$field_res[] = "{$k}='" . $this
									->dle_db
									->safesql($v) . "'";
							}
							$set_nativefields = ", " . implode(", ", $field_res);
						}
						// echo $set_nativefields;
						$new_category  = ", category = '".$post['category']."'";

						if (
							empty($this->config['cdnm_debug']) || // Если не дебаг
							(!empty($this->config['cdnm_debug']) && empty($this->config['cdnm_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}'");

							if (!empty($up_date)) {
								$reason = $this->config['up_news_noreason'] == 1 ? '' : ", editor='cdnm', reason='cdnm'";
								$this->dle_db
									->query("UPDATE " . PREFIX . "_post_extras SET editdate='{$edit_time}'{$reason} WHERE news_id='{$post_id}'");
							}
							
							// log 25 = edit_news
							if (in_array('cron', $fields)) 
								$admin_log_name = 'CDNM_Cron';
							elseif (in_array('us', $fields)) 
								$admin_log_name = 'CDNM_Autoupdate';
							else 
								$admin_log_name = 'CDNM_Replace';
							
							$this->dle_db->query("INSERT INTO " . PREFIX . "_admin_logs (date, name, action, extras) VALUES ('{$edit_time}', '{$admin_log_name}', '25', '{$post_id} - {$post['title']}');");
							
							if (!empty($poster_url['link']) || !empty($screens)) {
								
								if (empty($screens))
									$db_image = preg_replace('/^(.*)?\/uploads\/posts\//', '', $poster_url['link']);
								else {
									if (!empty($poster_url['link'])) {
										$db_image = preg_replace('/^(.*)?\/uploads\/posts\//', '', $poster_url['link']);
										$screens[] = $db_image;
									}
									
									$db_image = implode('|||', $screens);
									
								}
								
								$row_poster = $this->dle_db->super_query( "SELECT images FROM " . PREFIX . "_images WHERE author = '{$post['autor']}' AND news_id = '$post_id'" );
								if (empty($row_poster['images'])) {
									$this->dle_db->query( "INSERT INTO " . PREFIX . "_images (images, author, news_id, date) values ('{$db_image}', '{$post['autor']}', '{$post_id}', '{$edit_time}')" );
								} else {
									$listimages = explode( "|||", $row_poster['images'] );
									$listimages[] = $db_image;
									$row_poster['images'] = implode( "|||", $listimages );
									
									$this->dle_db->query( "UPDATE " . PREFIX . "_images set images='{$row_poster['images']}' WHERE author = '{$post['autor']}' AND news_id = '$post_id'" );
								}
								
							}
								  
							if ($post['approve']) $this->xfsearch($xfields, $post_id);
							
							if ( empty($this->config['up_news_cache']) ) 
								clear_cache( array('full_'.$post_id) );
							else 
								clear_cache( array('full_'.$post_id, 'news') );
								
							if ($this->config['cdnm_debug'] != '') echo "\r\n".'<!-- SAVE DB -->';
							
							if ($this->config['subscribe_lazydev'] && file_exists (ENGINE_DIR . '/lazydev/dle_subscribe/lib/send.php')) {
								$arrContextOptions = [
									'ssl' => [
										'verify_peer' => false,
										'verify_peer_name' => false,
									]
								];
								file_get_contents($this->dle_config['http_home_url'] . 'engine/lazydev/dle_subscribe/lib/send.php?id=' . $post_id . '&action=send&news=doeditnews&author=Admin&uid=1', false, stream_context_create($arrContextOptions));
							}
							
						} else {
							if ($this->config['cdnm_debug'] != '') echo "\r\n".'<!-- SQL _ '. "UPDATE " . PREFIX . "_post SET xfields = '{$xfields}'{$up_date}{$set_nativefields}{$new_category}{$set_shablons} WHERE id='{$post_id}'" .' -->';
						}
					} 
					
					if (!$parser && !empty($iframe_url)) $result = array( 'status' => 'ok' );
					elseif (!$parser && empty($iframe_url)) $result = array('status' => 'error', 'code' => '#02_1');
					else $result = array('status' => 'added', 'all' => $parser_params['all'], 'last' => $parser_params['last'], 'xf' => $out_base);

				}
				else $result = array( 'status' => 'exist' );

			}
			else { 
				$result = array(
				'status' => 'error',
				'code' => '#02', // Видео в базе не найдено 
				);
			}
		}
		else $result = array(
			'status' => 'error',
			'code' => '#01', // Не указан ID базы видео или Название для поиска
		);

		if (in_array('cron', $fields) || in_array('us', $fields)) {
			$result['post'] = $post;
			$result['response'] = $response[$r_key];
		}

		$result['api_time'] = $response[$r_key]['api_time'];
		$result['out_base'] = $out_base;
		$result['id'] = $post['id'];
		$result['title'] = $post['title'];

		if ($this->dle_config['allow_alt_url']) {
			if ($this->dle_config['seo_type'] == 1 || $this->dle_config['seo_type'] == 2) {
				$post['category'] = intval($post['category']);
				if ($post['category'] && $this->dle_config['seo_type'] == 2) {
					$full_link = $this->dle_config['http_home_url'] . get_url($post['category']) . "/" . $post['id'] . "-" . $post['alt_name'] . ".html";
				}
				else {
					$full_link = $this->dle_config['http_home_url'] . $post['id'] . "-" . $post['alt_name'] . ".html";
				}
			}
			else {
				$full_link = $this->dle_config['http_home_url'] . date('Y/m/d/', $post['date']) . $post['alt_name'] . ".html";
			}
		}
		else {
			$full_link = $this->dle_config['http_home_url'] . "index.php?newsid=" . $post['id'];
		}
		$thistime = date('d.m.Y H:i:s', time());
		$log_out_base = '';
		foreach($out_base as $k => $v) {
			$sep = '';
			if (!empty($log_out_base)) $sep = ' .:. ';
			
			$log_out_base .= $sep . $k .' : "'. $v .'"';
		}
		$result['log'] = " {$thistime} - <a href=\"/{$this->dle_config['admin_path']}?mod=editnews&action=editnews&id={$post['id']}\" target=\"_blank\">[edit]</a> - <a href=\"{$full_link}\" target=\"_blank\">{$post['title']}</a> \r\n";
		$log_string = " {$thistime} [{$result['status']}] - [b:{$log_out_base}] - [q:{$response[$r_key]['api_time']}] - {$full_link} \r\n";
		
		if (in_array('cron', $fields)) {
			$this->save_reports($log_string, 'cron');
		}
		elseif (in_array('us', $fields)) {
			
		}
		elseif (in_array('parser', $fields)) {
			if ($result['status'] == 'added') 
				$this->save_reports($log_string, 'parser');
		}
		else {
			$this->save_reports($log_string, $result['status']);
		}
		
		return $result;
	}

	public function save_reports($data, $file) {
		if (!empty($data) && !empty($file)) {
			file_put_contents(ENGINE_DIR . '/inc/cdnm/reports/'. $file .'.log', $data, FILE_APPEND | LOCK_EX);
		}
	}
	/**
	 * Вывод кнопки поиска на cdnm
	 *
	 * @return string обработанный в зависимости от версии скрипта шаблон кнопки поиска
	 */
	public function get_button() {
		global $member_id;

		// Проверяем включен ли модуль
		if (!$this->config['on'] || !$this->config['api_token'])
			return '';

		if (!in_array($member_id['user_group'], explode(',', $this->config['allowgroups'])))
			return '';
		
		// Загружаем шаблон кнопки поиска
		ob_start();
		include_once ENGINE_DIR . '/inc/cdnm/templates/button.php';
		$button_template = ob_get_clean();

		// Подключаем вывод кнопки с обработчиком в зависимости от версии DLE
			// для версий 10.2 и выше
			$button_template = "<div class=\"form-group\">
				<label class=\"control-label col-lg-2\">cdnm:</label>
				<div class=\"col-lg-10\">
					{$button_template}
				</div>
			</div>";
		
		return $button_template;
	}

	/**
	 * Вставка в основной шаблон кода плеера cdnm
	 *
	 * @param object $tpl шаблонизатор
	 * @param array $row текущая новость
	 */
	public function add_player($row, $return_data = false, $usergroup = false) {
		// Проверяем включен ли модуль
		if (!$this->config['on'] || !$this->config['api_token'])
			return false;
		else {
			$xfieldsdata = false;

			$cdnm_result = array();
			
			if ($this->config['cdnm_debug'] != '') echo '<!-- DEBUG -->';
			// Категории
			if ($this->config['cdnm_cats'] != '') {
				if ($this->config['cdnm_debug'] != '') echo "\r\n".'<!-- UF CATS -->';
				
				$cdnm_cats = explode(',', $this->config['cdnm_cats']);
				$cat_list = explode(',', $row['category']);

				$cdnm_cat = $this->config['cdnm_cats_inverse'] ? true : false;
				foreach($cdnm_cats as $cat) {
					if (in_array( $cat, $cat_list)) {
						$cdnm_cat = $this->config['cdnm_cats_inverse'] ? false : true; //меняем флаг
						break;
					}
				}

			} else $cdnm_cat = true; // если категории не выбраны
			
			// Дебаг
			$cdnm_debug = true;
			if ($this->config['cdnm_debug'] != '' && !in_array($row['id'], explode(',', $this->config['cdnm_debug'])) ) $cdnm_debug = false;
			
			// Автообновление, проверяем включено и указано ли время кеша
			if ($this->config['cdnm_on'] && $this->config['cdnm_cache'] != '' && $cdnm_debug && $cdnm_cat)	{
				if ($this->config['cdnm_debug'] != '') echo "\r\n".'<!-- UF START -->';
				$cdnm = dle_cache('uf_cdnm_'. $row['id'], false, false);
					
				if ($cdnm === false || (time() - intval($cdnm)) > $this->config['cdnm_cache'] || $this->config['cdnm_debug'] != '') {
					$fields = array( 'us' );
					$cdnm_result = $this->replace_thread($row['id'], $fields, $rewrite = 0, $row, $xfieldsdata);
					
					switch ($cdnm_result['status']) {
						case 'stop':
							clear_cache(array( 'uf_cdnm_'. $row['id'] ));
							break;
						case 'ok':
						case 'update':
						case 'exist':
						case 'error':
							create_cache('uf_cdnm_'. $row['id'], time());
					}

					if ($cdnm_result['post']['id']) $row = $cdnm_result['post'];
				}
			}
			
			if ($row and (strpos($this->dle_tpl->copy_template, '{cdnm-player}') !== false || strpos($this->dle_tpl->copy_template, '{cdnm-link}') !== false)) {
				// Получаем данные доп. полей
				if ($xfieldsdata == false) 
					$xfieldsdata = xfieldsdataload($row['xfields']);
				
				// формируем актуальну ссылку на новость
				if ($this->dle_config['allow_alt_url']) {
					$alt_name = preg_replace('/^[0-9]{1,10}-/', '', $row['alt_name']);
					if ($this->dle_config['seo_type'] == 1 || $this->dle_config['seo_type'] == 2) {
						$row['category'] = intval($row['category']);
						if ($row['category'] && $this->dle_config['seo_type'] == 2) {
							$full_link = $this->dle_config['http_home_url'] . get_url($row['category']) . "/" . $row['id'] . "-" . $alt_name . ".html";
						}
						else {
							$full_link = $this->dle_config['http_home_url'] . $row['id'] . "-" . $alt_name . ".html";
						}
					}
					else {
						$full_link = $this->dle_config['http_home_url'] . date('Y/m/d/', $row['date']) . $alt_name . ".html";
					}
				}
				else {
					$full_link = $this->dle_config['http_home_url'] . "index.php?newsid=" . $row['id'];
				}

				$curent_link = $this->dle_config['http_home_url']. preg_replace('/^\//', '', $_SERVER['REQUEST_URI']);
				// echo $full_link . " - \r\n" . $curent_link;

				
				// Получаем ссылку
				$_field = explode('|', $this->config['output']);
				if (count($_field) == 3) {
					$cdnm_video_url = ''.$xfieldsdata[$_field[0]];
				} elseif (count($_field) == 1) {
					$cdnm_video_url = ''.$row[$_field[0]];
				}

				// Если заполнена ссылка
				if (!empty($cdnm_video_url)) {
					// Замена домена
					
					// original link
					$this->iframe[0] = $cdnm_video_url;
				
					// в настройках задана ширина и высота видео
					if (empty($this->config['video_width']) || empty($this->config['video_height'])) {
						$this->config['video_width'] = '100%';
						$this->config['video_height'] = '400';
					}
					
					// Строим код видео плеера
					$cdnm_player = "<iframe id=\"CDNMplay\" src=\"{$cdnm_video_url}\" width=\"{$this->config['video_width']}\" height=\"{$this->config['video_height']}\" frameborder=\"0\" allowfullscreen></iframe>";
					
					$this->dle_tpl->copy_template = str_replace('{cdnm-player}', $cdnm_player, $this->dle_tpl->copy_template);
					
					// Заменяем {cdnm-link} на ссылку плеера
					$this->dle_tpl->copy_template = str_replace('{cdnm-link}', $cdnm_video_url, $this->dle_tpl->copy_template);
					
					// Всё что будет в тегах [cdnm-player]...[/cdnm-player] будет отображаться только если выводится код плеера
					$this->dle_tpl->copy_template = str_replace(array('[cdnm-player]','[/cdnm-player]'), '', $this->dle_tpl->copy_template);
				// Если заполнены не все необходимые параметры
				} 
				else {
					// Удаляем тег плеера из шаблона
					$this->dle_tpl->copy_template = str_replace(array('{cdnm-player}','{cdnm-link}','{cdnm-adblock}'), '', $this->dle_tpl->copy_template);
					
					// Так же удаляем блок кода плеера, то есть всё что будет в эти тегах [cdnm-player]...[/cdnm-player]
					$this->dle_tpl->copy_template = preg_replace("'\\[cdnm-player\\](.*?)\\[/cdnm-player\\]'is", '', $this->dle_tpl->copy_template);
				}
			}

			if ($return_data) return $cdnm_result;
		}
	}
	
}


class cdnm_UploadFileFromURL {  

	private $from = "";

	function saveFile($path, $filename, $prefix=true) {

		if ( $prefix !== false ) {

			// $file_prefix = time() + rand( 1, 100 );
			$file_prefix = md5($this->from);
			$file_prefix .= "_". $prefix ."_";

		} else $file_prefix = "";

		$filename = totranslit( $file_prefix.$filename );

		if(!@copy($this->from, $path.$filename)){
			//echo "не удалось скопировать...\r\n";
			return false;
		}

		return $filename;
	}
	
	function getFileName() {
		global $config;

		if ( $config['charset'] == "windows-1251" AND $config['charset'] != detect_encoding($_POST['imageurl']) ) {

			if( function_exists( 'mb_convert_encoding' ) ) {
	
				$_POST['imageurl'] = mb_convert_encoding( $_POST['imageurl'], "windows-1251", "UTF-8" );
	
			} elseif( function_exists( 'iconv' ) ) {
	
				$_POST['imageurl'] = iconv( "UTF-8", "windows-1251//IGNORE", $_POST['imageurl'] );
	
			}

		}

		$imageurl = trim( htmlspecialchars( strip_tags( $_POST['imageurl'] ) ) );
		$imageurl = str_replace(chr(0), '', $imageurl);
		$imageurl = str_replace( "\\", "/", $imageurl );

		$url = @parse_url ( $imageurl );

		if (!array_key_exists('host', $url)) {
			return '';
		}

		if($url['scheme'] != 'http' AND $url['scheme'] != 'https') {

			return '';
		}

		if($url['host'] == 'localhost' OR $url['host'] == '127.0.0.1') {

			return '';
		}

		if( stripos (  $url['host'], $_SERVER['HTTP_HOST'] ) !== false ) {

			return '';

		}

		if( stripos( $imageurl, ".php" ) !== false ) return '';
		if( stripos( $imageurl, ".phtm" ) !== false ) return '';

		$this->from = $imageurl;

		$imageurl = explode( "/", $imageurl );
		$imageurl = end( $imageurl );

		return $imageurl;
	}
	
	function getFileSize() {

		$url = @parse_url( $this->from );
		
		if ( $url ) {
			if($url['scheme'] == "https" ) $port = 443; else $port = 80;
			$fp = @fsockopen( $url['host'], $port, $errno, $errstr, 10);

			if ($fp) {
				$x='';
	
				fputs($fp,"HEAD {$url['path']} HTTP/1.0\nHOST: {$url['host']}\n\n");
				while(!feof($fp)) $x.=fgets($fp,128);
				fclose($fp);

				if ( strpos($x, 'no-poster.gif') !== false) return 0;
				if ( strpos($x, 'Location: ') !== false) return 302;
				if ( preg_match("#Content-Length: ([0-9]+)#i",$x,$size) ) return intval($size[1]); else return 0;

			} else return 0;

		} else return 0;

	}

	function getErrorCode() {

		return false;

	}
}
class cdnm_PosterUploader {

	private $allowed_extensions = array ("gif", "jpg", "jpeg", "png", "webp" );
	private $allowed_files = array();
	private $author = "";
	private $news_id = "";
	private $o_size = "";
	private $t_size = "";
	private $t_seite = 2;
	private $make_thumb = false;
	private $m_size = "";
	private $m_seite = 2;
	private $make_medium = false;
	private $upload_path = "uploads/posts/";
	private $use_prefix = true;

	function __construct($imageurl, $news_id, $author, $path, $o_size, $t_size = 0, $make_thumb = false, $m_size = 0, $make_medium = false){        
	global $config, $db;

		if ( $config['charset'] == "windows-1251" AND $config['charset'] != detect_encoding($author) ) {

			if( function_exists( 'mb_convert_encoding' ) ) {
	
				$author = mb_convert_encoding( $author, "windows-1251", "UTF-8" );
	
			} elseif( function_exists( 'iconv' ) ) {
	
				$author = iconv( "UTF-8", "windows-1251//IGNORE", $author );
	
			}

		}

		$this->author = $author;
		$this->news_id = intval($news_id);
		$this->o_size = $o_size;
		$this->t_size = $t_size;
		$this->t_seite = 2;
		$this->make_thumb = $make_thumb;
		$this->m_size = $m_size;
		$this->m_seite = 2;
		$this->make_medium = $make_medium;
		$this->upload_path = $path;
	  
		if ( $imageurl != "" ) {

			$_POST['imageurl'] = $imageurl;
			$this->file = new cdnm_UploadFileFromURL();

		} else {

			$this->file = false; 

		}

		define( 'FOLDER_PREFIX', date( "Y-m" )."/" );

	}

	private function check_filename ( $filename ) {
		global $config;
		
		if( $filename != "" ) {

			$filename = str_replace( "\\", "/", $filename );
			$filename = preg_replace( '#[.]+#i', '.', $filename );
			$filename = str_replace( "/", "", $filename );
			$filename = str_ireplace( "php", "", $filename );

			$filename_arr = explode( ".", $filename );
			
			if(count($filename_arr) < 2) {
				return false;
			}
			
			$type = totranslit( end( $filename_arr ) );
			
			if( empty($type) ) return false;
			
			$curr_key = key( $filename_arr );
			unset( $filename_arr[$curr_key] );
 
			$filename = totranslit( implode( "_", $filename_arr ) );
			
			if( empty($filename) ) {
				$filename = time() + rand( 1, 100 );
			}
			
			$filename = $filename . "." . $type;

		} else return false;

		$filename = preg_replace( '#[.]+#i', '.', $filename );

		if( stripos ( $filename, ".php" ) !== false ) return false;
		if( stripos ( $filename, ".phtm" ) !== false ) return false;
		if( stripos ( $filename, ".shtm" ) !== false ) return false;
		if( stripos ( $filename, ".htaccess" ) !== false ) return false;
		if( stripos ( $filename, ".cgi" ) !== false ) return false;
		if( stripos ( $filename, ".htm" ) !== false ) return false;
		if( stripos ( $filename, ".ini" ) !== false ) return false;

		if( stripos ( $filename, "." ) === 0 ) return false;
		if( stripos ( $filename, "." ) === false ) return false;
		
		if( dle_strlen( $filename, $config['charset'] ) > 170 ) {
			return false;
		}

		return $filename;

	}

	private function msg_error($message, $code = 500) {
		global $config;

		return "{\"error\":\"{$message}\"}";
	}

	function FileUpload(){
		global $config, $db, $lang;

		if( !is_dir( ROOT_DIR . "/" . $this->upload_path . FOLDER_PREFIX ) ) {
			
			@mkdir( ROOT_DIR . "/" . $this->upload_path . FOLDER_PREFIX, 0777 );
			@chmod( ROOT_DIR . "/" . $this->upload_path . FOLDER_PREFIX, 0777 );
			
			@mkdir( ROOT_DIR . "/" . $this->upload_path . FOLDER_PREFIX . "thumbs", 0777 );
			@chmod( ROOT_DIR . "/" . $this->upload_path . FOLDER_PREFIX . "thumbs", 0777 );

			@mkdir( ROOT_DIR . "/" . $this->upload_path . FOLDER_PREFIX . "medium", 0777 );
			@chmod( ROOT_DIR . "/" . $this->upload_path . FOLDER_PREFIX . "medium", 0777 );

		}

		if( !is_writable( ROOT_DIR . "/" . $this->upload_path . FOLDER_PREFIX ) ) {
			
			return $this->msg_error( $lang['upload_error_1']." /{$this->upload_path}/" . FOLDER_PREFIX . " ".$lang['upload_error_2'], 403 );
		}

		if( !is_writable( ROOT_DIR . "/" . $this->upload_path . FOLDER_PREFIX . "thumbs" ) ) {
			
			return $this->msg_error( $lang['upload_error_1']." /{$this->upload_path}/" . FOLDER_PREFIX . "thumbs/ ".$lang['upload_error_2'], 403 );
		}

		if( !is_writable( ROOT_DIR . "/" . $this->upload_path . FOLDER_PREFIX . "medium" ) ) {
			
			return $this->msg_error( $lang['upload_error_1']." /{$this->upload_path}/" . FOLDER_PREFIX . "medium/ ".$lang['upload_error_2'], 403 );
		}

		if (!$this->file){
			return $this->msg_error( $lang['upload_error_3'], 405 );
		}

		$filename = $this->check_filename( $this->file->getFileName() );

		if (!$filename){
			return $this->msg_error( $lang['upload_error_4'], 405 );
		}

		$filename_arr = explode( ".", $filename );
		$type = end( $filename_arr );

		if (!$type){
			return $this->msg_error( $lang['upload_error_4'], 405 );
		}

		$error_code = $this->file->getErrorCode();

		if ( $error_code ){
			return $this->msg_error( $error_code, 405 );
		}

		$size = $this->file->getFileSize();
		
		if ($size == 0) {
			return $this->msg_error( $lang['upload_error_5'], 403 );
		}

		if ( in_array( $type, $this->allowed_extensions )) {
			
			$uploaded_filename = $this->file->saveFile(ROOT_DIR . "/" . $this->upload_path . FOLDER_PREFIX, $filename, $this->news_id);

			if ( $uploaded_filename ) {

				$added_time = time();

				@chmod( ROOT_DIR . "/" . $this->upload_path . FOLDER_PREFIX . $uploaded_filename, 0666 );

				$i_info = @getimagesize(ROOT_DIR . "/" . $this->upload_path . FOLDER_PREFIX . $uploaded_filename); 
		
				if( !in_array( $i_info[2], array (1, 2, 3, 18 ) ) )	{
					@unlink( ROOT_DIR . "/" . $this->upload_path . FOLDER_PREFIX . $uploaded_filename );
					return $this->msg_error( $lang['upload_error_6'], 500 );
				}

				$thumb = new cdnm_thumbnail( ROOT_DIR . "/" . $this->upload_path . FOLDER_PREFIX . $uploaded_filename );

				if( $this->make_thumb ) {
					
					if( $thumb->size_auto( $this->t_size, $this->t_seite ) ) {
						
						$thumb->jpeg_quality( $config['jpeg_quality'] );
						
						$thumb->save( ROOT_DIR . "/" . $this->upload_path . FOLDER_PREFIX . "thumbs/" . $uploaded_filename );
						
						@chmod( ROOT_DIR . "/" . $this->upload_path . FOLDER_PREFIX . "thumbs/" . $uploaded_filename, 0666 );
					}
				}

				if( $this->make_medium ) {

					$thumb = new cdnm_thumbnail( ROOT_DIR . "/" . $this->upload_path . FOLDER_PREFIX . $uploaded_filename );
					
					if( $thumb->size_auto( $this->m_size, $this->m_seite ) ) {
						
						$thumb->jpeg_quality( $config['jpeg_quality'] );
						
						$thumb->save( ROOT_DIR . "/" . $this->upload_path . FOLDER_PREFIX . "medium/" . $uploaded_filename );
						
						@chmod( ROOT_DIR . "/" . $this->upload_path . FOLDER_PREFIX . "medium/" . $uploaded_filename, 0666 );
					}
				}
	
				$thumb = new cdnm_thumbnail( ROOT_DIR . "/" . $this->upload_path . FOLDER_PREFIX . $uploaded_filename );
				$thumb->jpeg_quality( $config['jpeg_quality'] );
				
				if( $this->o_size ) $thumb->size_auto( $this->o_size, 2 );
				$thumb->save( ROOT_DIR . "/" . $this->upload_path . FOLDER_PREFIX . $uploaded_filename );
				

				if( $this->o_size ) $i_info = @getimagesize( ROOT_DIR . "/" . $this->upload_path . FOLDER_PREFIX . $uploaded_filename );

				$img_url = 	$config['http_home_url'] . $this->upload_path . FOLDER_PREFIX . $uploaded_filename;

				if( file_exists( ROOT_DIR . "/" . $this->upload_path . FOLDER_PREFIX . "medium/" . $uploaded_filename ) ) {
					$img_url = 	$config['http_home_url'] . $this->upload_path . FOLDER_PREFIX . "medium/" . $uploaded_filename;
					$medium_data = "yes";
					$tm_url = $img_url;
					
				} else {
					$medium_data = "no";

				}

				if( file_exists( ROOT_DIR . "/" . $this->upload_path . FOLDER_PREFIX . "thumbs/" . $uploaded_filename ) ) {
					$img_url = 	$config['http_home_url'] . $this->upload_path . FOLDER_PREFIX . "thumbs/" . $uploaded_filename;
					$thumb_data = "yes";
					$th_url = $img_url;
				} else {
					$thumb_data = "no";

				}

				$data_url = '/' . $this->upload_path . FOLDER_PREFIX . $uploaded_filename;
				
				$link = $data_url;
				$flink =", \"flink\":\"{$link}\"";
				
				if($medium_data == "yes" ) $link = $tm_url;
				elseif( $thumb_data == "yes" ) $link = $th_url;
				else {
					$flink ="";
				}

			} else return $this->msg_error( $lang['images_uperr_3'], 403 );

		} else return $this->msg_error( $lang['images_uperr_2'], 403 );

		$xfvalue = FOLDER_PREFIX . $uploaded_filename;
		$xf_id = md5($xfvalue);
		return htmlspecialchars("{\"success\":true, \"link\":\"{$data_url}\", \"filename\":\"{$filename}\", \"md5\":\"{$xf_id}\"}", ENT_NOQUOTES, $config['charset']);

	}

}
class cdnm_thumbnail {
	var $img;
	var $watermark_image_light;
	var $watermark_image_dark;
	var $re_save = false;
	
	function __construct($imgfile) {
		//detect image format

		$info = @getimagesize($imgfile); 
		$img_name_arr = explode( ".", $imgfile );
		$type = end( $img_name_arr );

		if( $info[2] == 2 ) {
			$this->img['format'] = "JPEG";
			$this->img['src'] = @imagecreatefromjpeg( $imgfile );

			if($this->img['src'] AND function_exists('exif_read_data') ) {
				$exif = exif_read_data( $imgfile, 0, true);
				
				if( !empty( $exif['IFD0']['Orientation'] ) ) {
					
					switch( $exif['IFD0']['Orientation'] ) {
						
						case 8:
							$this->img['src'] = imagerotate( $this->img['src'], 90, 0 );
							$this->re_save = true;
						break;
					
						case 3:
							$this->img['src'] = imagerotate( $this->img['src'], 180, 0);
							$this->re_save = true;
						break;
					
						case 6:
							$this->img['src'] = imagerotate( $this->img['src'], -90, 0);
							$this->re_save = true;
						break;
					}
				} 
				
			}
			
		} elseif( $info[2] == 3 ) {
			$this->img['format'] = "PNG";
			$this->img['src'] = @imagecreatefrompng( $imgfile );
		} elseif( $info[2] == 1 ) {
			$this->img['format'] = "GIF";
			$this->img['src'] = @imagecreatefromgif( $imgfile );
		} elseif( $info[2] == 18 ) {
			$this->img['format'] = "WEBP";
			$this->img['src'] = @imagecreatefromwebp( $imgfile );
		} else {
			
			if (!@unlink( $imgfile ) ) {
				@chmod( $imgfile, 0666 );
				@unlink( $imgfile );
			}
			
			echo "{\"error\":\"The file is not the image, or this file is damaged.\"}";
			exit();
		}

		if( !$this->img['src'] ) {
			
			if (!@unlink( $imgfile ) ) {
				@chmod( $imgfile, 0666 );
				@unlink( $imgfile );
			}
			
			echo "{\"error\":\"The file is not the image, or this file is damaged.\"}";
			exit();
		
		}

		$this->img['lebar'] = @imagesx( $this->img['src'] );
		$this->img['tinggi'] = @imagesy( $this->img['src'] );
		$this->img['lebar_thumb'] = $this->img['lebar'];
		$this->img['tinggi_thumb'] = $this->img['tinggi'];
		//default quality jpeg
		$this->img['quality'] = 90;

		if( $this->img['lebar'] < 10 OR  $this->img['tinggi'] < 10 ) {
			
			if (!@unlink( $imgfile ) ) {
				@chmod( $imgfile, 0666 );
				@unlink( $imgfile );
			}
			
			echo "{\"error\":\"The file is not the image, or this file is damaged.\"}";
			exit();
		
		}
		
	}
	
	function size_auto($size = 100, $site = 0) {

		$size = explode ("x", $size);

		if ( count($size) == 2 ) {
			$size[0] = intval($size[0]);
			$size[1] = intval($size[1]);

			if ( $size[0] < 10 ) $size[0] = 10;
			if ( $size[1] < 10 ) $size[1] = 10;

			return $this->crop( $size[0], $size[1] );

		} else {
			$size[0] = intval($size[0]);

			if ( $size[0] < 10 ) $size[0] = 10;

			return $this->scale( $size[0], $site);

		}

	}

	function crop($nw, $nh) {

		$w = $this->img['lebar'];
		$h = $this->img['tinggi'];

		if( $w <= $nw AND $h <= $nh ) {
			$this->img['lebar_thumb'] = $w;
			$this->img['tinggi_thumb'] = $h;
			return 0;
		}

		$nw = min($nw, $w);
		$nh = min($nh, $h);

		$size_ratio = max($nw / $w, $nh / $h);

		$src_w = ceil($nw / $size_ratio);
		$src_h = ceil($nh / $size_ratio);

		$sx = floor(($w - $src_w)/2);
		$sy = floor(($h - $src_h)/2);

		$this->img['des'] = imagecreatetruecolor($nw, $nh);

		if ( $this->img['format'] == "PNG" ) {
			imagealphablending( $this->img['des'], false);
			imagesavealpha( $this->img['des'], true);
		}

		if ( $this->img['format'] == "GIF" ) {

			$transparent_index=imagecolortransparent($this->img['src']);

			if($transparent_index!==-1){
				$transparent_color=imagecolorsforindex($this->img['src'], $transparent_index);
			 
				$transparent_destination_index=imagecolorallocate($this->img['des'], $transparent_color['red'], $transparent_color['green'], $transparent_color['blue']);
				imagecolortransparent($this->img['des'], $transparent_destination_index);
			 
				imagefill($this->img['des'], 0, 0, $transparent_destination_index);
			}


		}

		imagecopyresampled($this->img['des'],$this->img['src'],0,0,$sx,$sy,$nw,$nh,$src_w,$src_h);

		$this->img['src'] = $this->img['des'];
		return 1;
	}

	function scale($size = 100, $site = 0) {

		$site = intval( $site );
		
		if( $this->img['lebar'] <= $size and $this->img['tinggi'] <= $size ) {
			$this->img['lebar_thumb'] = $this->img['lebar'];
			$this->img['tinggi_thumb'] = $this->img['tinggi'];
			return 0;
		}
		
		switch ($site) {
			
			case "1" :
				if( $this->img['lebar'] <= $size ) {
					$this->img['lebar_thumb'] = $this->img['lebar'];
					$this->img['tinggi_thumb'] = $this->img['tinggi'];
					return 0;
				} else {
					$this->img['lebar_thumb'] = $size;
					$this->img['tinggi_thumb'] = ceil(($this->img['lebar_thumb'] / $this->img['lebar']) * $this->img['tinggi']);
				}
				
				break;
			
			case "2" :
				if( $this->img['tinggi'] <= $size ) {
					$this->img['lebar_thumb'] = $this->img['lebar'];
					$this->img['tinggi_thumb'] = $this->img['tinggi'];
					return 0;
				} else {
					$this->img['tinggi_thumb'] = $size;
					$this->img['lebar_thumb'] = ceil(($this->img['tinggi_thumb'] / $this->img['tinggi']) * $this->img['lebar']);
				}
				
				break;
			
			default :
				
				if( $this->img['lebar'] >= $this->img['tinggi'] ) {
					$this->img['lebar_thumb'] = $size;
					$this->img['tinggi_thumb'] = ceil(($this->img['lebar_thumb'] / $this->img['lebar']) * $this->img['tinggi']);
				
				} else {
					
					$this->img['tinggi_thumb'] = $size;
					$this->img['lebar_thumb'] = ceil(($this->img['tinggi_thumb'] / $this->img['tinggi']) * $this->img['lebar']);
				
				}
				
				break;
		}

		if ($this->img['lebar_thumb'] < 1 ) $this->img['lebar_thumb'] = 1;
		if ($this->img['tinggi_thumb'] < 1 ) $this->img['tinggi_thumb'] = 1;
		
		$this->img['des'] = imagecreatetruecolor( $this->img['lebar_thumb'], $this->img['tinggi_thumb'] );

		if ( $this->img['format'] == "PNG" ) {
			imagealphablending( $this->img['des'], false);
			imagesavealpha( $this->img['des'], true);
		}


		if ( $this->img['format'] == "GIF" ) {

			$transparent_index=imagecolortransparent($this->img['src']);

			if($transparent_index!==-1){
				$transparent_color=imagecolorsforindex($this->img['src'], $transparent_index);
			 
				$transparent_destination_index=imagecolorallocate($this->img['des'], $transparent_color['red'], $transparent_color['green'], $transparent_color['blue']);
				imagecolortransparent($this->img['des'], $transparent_destination_index);
			 
				imagefill($this->img['des'], 0, 0, $transparent_destination_index);
			}


		}

		@imagecopyresampled( $this->img['des'], $this->img['src'], 0, 0, 0, 0, $this->img['lebar_thumb'], $this->img['tinggi_thumb'], $this->img['lebar'], $this->img['tinggi'] );
		
		$this->img['src'] = $this->img['des'];
		return 1;

	}
	
	function jpeg_quality($quality = 90) {
		//jpeg quality
		$this->img['quality'] = $quality;
	}
	
	function save($save = "") {
		
		if( $this->img['format'] == "JPG" || $this->img['format'] == "JPEG" ) {
			//JPEG
			imagejpeg( $this->img['src'], $save, $this->img['quality'] );
		} elseif( $this->img['format'] == "PNG" ) {
			//PNG
			imagealphablending( $this->img['src'], false);
			imagesavealpha( $this->img['src'], true);
			imagepng( $this->img['src'], $save, 8 );
		} elseif( $this->img['format'] == "GIF" ) {
			//GIF
			imagegif( $this->img['src'], $save );
		}
		
		imagedestroy( $this->img['src'] );
	}
	
	function show() {
		if( $this->img['format'] == "JPG" || $this->img['format'] == "JPEG" ) {
			//JPEG
			imagejpeg( $this->img['src'], "", $this->img['quality'] );
		} elseif( $this->img['format'] == "PNG" ) {
			//PNG
			imagepng( $this->img['src'] );
		} elseif( $this->img['format'] == "GIF" ) {
			//GIF
			imagegif( $this->img['src'] );
		}
		
		imagedestroy( $this->img['src'] );
	}
	
	// *************************************************************************
	function insert_watermark($min_image) {
		global $config;
		$margin = 7;
		
		$this->watermark_image_light = ROOT_DIR . '/templates/' . $config['skin'] . '/dleimages/watermark_light.png';
		$this->watermark_image_dark = ROOT_DIR . '/templates/' . $config['skin'] . '/dleimages/watermark_dark.png';
		
		$image_width = imagesx( $this->img['src'] );
		$image_height = imagesy( $this->img['src'] );
		
		list ( $watermark_width, $watermark_height ) = getimagesize( $this->watermark_image_light );
		
		if($config['watermark_seite'] == 1) {
			
			$watermark_x = $margin;
			$watermark_y = $margin;
			
		} elseif($config['watermark_seite'] == 2) {
			
			$watermark_x = $image_width - $margin - $watermark_width;
			$watermark_y = $margin;
			
		} elseif($config['watermark_seite'] == 3) {
			
			$watermark_x = $margin;
			$watermark_y = $image_height - $margin - $watermark_height;
			
		} else {
	
			$watermark_x = $image_width - $margin - $watermark_width;
			$watermark_y = $image_height - $margin - $watermark_height;
		}
		
		$watermark_x2 = $watermark_x + $watermark_width;
		$watermark_y2 = $watermark_y + $watermark_height;
		
		if( $watermark_x < 0 OR $watermark_y < 0 OR $watermark_x2 > $image_width OR $watermark_y2 > $image_height OR $image_width < $min_image OR $image_height < $min_image ) {
			return;
		}
		
		$test = imagecreatetruecolor( 1, 1 );
		imagecopyresampled( $test, $this->img['src'], 0, 0, $watermark_x, $watermark_y, 1, 1, $watermark_width, $watermark_height );
		$rgb = imagecolorat( $test, 0, 0 );
		
		$r = ($rgb >> 16) & 0xFF;
		$g = ($rgb >> 8) & 0xFF;
		$b = $rgb & 0xFF;
		
		$max = min( $r, $g, $b );
		$min = max( $r, $g, $b );
		$lightness = ( double ) (($max + $min) / 510.0);
		imagedestroy( $test );
		
		$watermark_image = ($lightness < 0.5) ? $this->watermark_image_light : $this->watermark_image_dark;
		
		$watermark = imagecreatefrompng( $watermark_image );

		imagealphablending( $watermark, true );

		if( $this->img['format'] == "PNG") {
			imagealphablending( $this->img['src'], true );
			$temp_img = imagecreatetruecolor( $image_width, $image_height );
			imagealphablending ( $temp_img , true );
			imagesavealpha ( $temp_img , true );
			imagecopy( $temp_img, $this->img['src'], 0, 0, 0, 0, $image_width, $image_height );
			imagecopy( $temp_img, $watermark, $watermark_x, $watermark_y, 0, 0, $watermark_width, $watermark_height );
			imagecopy( $this->img['src'], $temp_img, 0, 0, 0, 0, $image_width, $image_height );
			imagedestroy( $temp_img );
		
		} elseif($this->img['format'] == "GIF") { 

			$temp_img = imagecreatetruecolor( $image_width, $image_height );

			$transparent_index=imagecolortransparent($this->img['src']);

			if($transparent_index!==-1){
				$transparent_color=imagecolorsforindex($this->img['src'], $transparent_index);
			 
				$transparent_destination_index=imagecolorallocate($temp_img, $transparent_color['red'], $transparent_color['green'], $transparent_color['blue']);
				imagecolortransparent($temp_img, $transparent_destination_index);
			 
				imagefill($temp_img, 0, 0, $transparent_destination_index);
			}

			imagecopy( $temp_img, $this->img['src'], 0, 0, 0, 0, $image_width, $image_height );
			imagecopy( $temp_img, $watermark, $watermark_x, $watermark_y, 0, 0, $watermark_width, $watermark_height );
			imagecopy( $this->img['src'], $temp_img, 0, 0, 0, 0, $image_width, $image_height );
			imagedestroy( $temp_img );

		} else {

			imagecopy( $this->img['src'], $watermark, $watermark_x, $watermark_y, 0, 0, $watermark_width, $watermark_height );

		}
	
		imagedestroy( $watermark );
	
	}

}
