<?php

@error_reporting(E_ALL ^ E_WARNING ^ E_NOTICE);
@ini_set('display_errors', true);
@ini_set('html_errors', false);
@ini_set('error_reporting', E_ALL ^ E_WARNING ^ E_NOTICE);

define('DATALIFEENGINE', true);
define('ROOT_DIR', substr(dirname(__FILE__), 0, -12));
define('ENGINE_DIR', ROOT_DIR . '/engine');

@include_once ENGINE_DIR . '/classes/plugins.class.php';
include ENGINE_DIR.'/data/config.php';

if ($config['http_home_url'] == '') {
	$config['http_home_url'] = explode('engine/ajax/profile.php', $_SERVER['PHP_SELF']);
	$config['http_home_url'] = reset($config['http_home_url']);
	$config['http_home_url'] = 'http://' . $_SERVER['HTTP_HOST'] . $config['http_home_url'];
}

require_once ENGINE_DIR . '/classes/mysql.php';
require_once ENGINE_DIR . '/data/dbconfig.php';
if (file_exists(ROOT_DIR . '/language/'.$config['langs'].'/website.lng')) 
	require_once ROOT_DIR . '/language/'.$config['langs'].'/website.lng';
require_once ENGINE_DIR . '/modules/functions.php';

date_default_timezone_set ( $config['date_adjust'] );

if (function_exists("dle_session"))
	dle_session();

require_once ENGINE_DIR . '/modules/sitelogin.php';

// Инициализация базового функционала модуля
require_once ENGINE_DIR . '/inc/cdnm/init.php';

// Обрабатываем входящие параметры
$action = isset($_GET['action']) ? $_GET['action'] : null;
$out_base = isset($_GET['out_base']) ? explode(',', $_GET['out_base']) : null;
$title = isset($_GET['title']) ? urldecode(trim($_GET['title'])) : null;
$output = isset($_GET['output']) ? urldecode(trim($_GET['output'])) : null;
$type = isset($_GET['type']) ? intval($_GET['type']) : null;
$threads = isset($_GET['threads']) ? intval($_GET['threads']) : null;
$last_post_id = isset($_GET['last_post_id']) ? intval($_GET['last_post_id']) : null;
$category = isset($_GET['category']) ? preg_replace("#[^0-9,]+#i", '', $_GET['category']) : '';
$category_inverse = isset($_GET['category_inverse']) ? intval($_GET['category_inverse']) : 0;
$post_id = isset($_GET['post_id']) ? intval($_GET['post_id']) : null;
$post_ids = isset($_GET['post_ids']) ? preg_replace("#[^0-9,]+#i", '', $_GET['post_ids']) : null;
$fields = isset($_GET['fields']) ? explode('|', $_GET['fields']) : array();
$rewrite = isset($_GET['rewrite']) ? intval($_GET['rewrite']) : null;

$parsetype = isset($_GET['parsetype']) ? $_GET['parsetype'] : '';
$continue = isset($_GET['continue']) ? preg_replace("#[^0-9,]+#i", '', $_GET['continue']) : 0;
$approve = isset($_GET['approve']) ? preg_replace("#[^0-9,]+#i", '', $_GET['approve']) : 0;
$noposter = isset($_GET['noposter']) ? preg_replace("#[^0-9,]+#i", '', $_GET['noposter']) : 0;
$nodesc = isset($_GET['nodesc']) ? preg_replace("#[^0-9,]+#i", '', $_GET['nodesc']) : 0;
$imageurl = isset($_GET['image_url']) ? $_GET['image_url'] : '';
$imagetype = isset($_GET['image_type']) ? $_GET['image_type'] : '';
$author = isset($_GET['author']) ? $_GET['author'] : '';

// Список категорий
$cat_info = get_vars("category");

if (!is_array($cat_info)) {
	$cat_info = array();
	
	$db->query("SELECT * FROM " . PREFIX . "_category ORDER BY posi ASC");

	while ($row = $db->get_row()) {
		$cat_info[$row['id']] = array();
		
		foreach ($row as $key => $value) {
			$cat_info[$row['id']][$key] = stripslashes($value);
		}
	}

	set_vars("category", $cat_info);

	$db->free();
}

// Обрабатываем AJAX запросы
switch ($action) {
	// Поиск фильма/сериала через API cdnm
	case 'find':
		// Проверяем включен ли модуль
		if (!$cdnm->config['on'] && !$cdnm->config['api_token'])
			break;

		if (!in_array($member_id['user_group'], explode(',', $cdnm->config['allowgroups'])))
			break;
		
		if (empty($out_base)) {
			die(json_encode(array(
				'status' => 'error',
				'error' => '#01',
			)));
		} else {
			
			// Получаем поля Kinopoisk, IMDM, World-Art...
			// $out_base = array();
			$response = $cdnm->find(true, $out_base, null);
			
			// Если кодировка не utf-8
			if ($cdnm->dle_config['charset'] == 'windows-1251') {
				array_walk_recursive($response, function(&$r_val,$r_key){
					$r_val = iconv('windows-1251','utf-8', $r_val);
				});
			}
				
			if ($response['error'])
				die(json_encode(array(
					'status' => 'error',
					'error' => $response['error'],
				)));
				
			if ($response)
				die(json_encode(array(
					'status' => 'ok',
					'result' => $response,
				)));
			else
				die(json_encode(array(
					'status' => 'error',
					'error' => '#02',
				)));
		}
		break;
	
	// Получение id постов для потоков
	case 'get_replace_threads':
		if ($member_id['user_group'] != 1)
			break;

		if ($cdnm->config['on'] and $type and $threads) {
			if (is_array($fields)) $fields[] = 'replace';
			else $fields = array('replace');
			
			$result = $cdnm->get_replace_threads($type, $threads, $last_post_id, $category, $category_inverse, $fields);
			if ($result)
				die(json_encode($result));
			else
				die(json_encode(array(
					'status' => 'end',
					'code' => '#02',
				)));
		} else
			die(json_encode(array(
				'status' => 'end',
				'code' => '#01',
			)));
		break;
		
	// Проставление ссылки по полю Кинопоиск ID
	case 'replace_thread':
		if ($member_id['user_group'] != 1)
			break;

		if ($cdnm->config['on'] and $post_id) {
			if (is_array($fields)) $fields[] = 'replace';
			else $fields = array('replace');
			
			$result = $cdnm->replace_thread($post_id, $fields, $rewrite, false, false);
			if ($result) {
				die(json_encode($result));
			} else
				die(json_encode(array(
					'status' => 'end',
					'code' => '#02',
				)));
		} else
			die(json_encode(array(
				'status' => 'end',
				'code' => '#01',
			)));
		break;
	
	// Загрузка постера
	case 'upload':
		// Проверяем включен ли модуль
		if (!$cdnm->config['on'] || !$cdnm->config['api_token'] || !$cdnm->config['output_poster'] || !$imageurl)
			break;

		if (!in_array($member_id['user_group'], explode(',', $cdnm->config['allowgroups'])))
			break;

		if ($imagetype == 'screen') {

			$screens = array();
			$screens_str = array();
			$imageurl = explode(',', $imageurl);
			foreach($imageurl as $screen_url) {
				$screen_url = $cdnm->poster($screen_url, $post_id, $author);
				
				$screen_url['link'] = preg_replace('/^(.*)\/uploads\/posts\//', '', $screen_url['link']);
				
				if (!empty($screen_url['link'])) {
					$screen_url['link_md5'] = md5($screen_url['link']);
					$screens[] = $screen_url;
					$screens_str[] = $screen_url['link'];
				}
			}

		} else {
			if ($cdnm->config['output_poster'] != '') 
				$_field_poster = explode('|', $cdnm->config['output_poster']);
			
			$result = $cdnm->poster($imageurl, $post_id, $author);
		}
		
		if ($result['link'] || !empty($screens)) {
			$edit_time = time();
			
			if ($imagetype == 'screen') {
				
				$db_image = implode('|||', $screens_str);
				$screens_str = implode(',', $screens_str);
				
				$result = array(
					'links' => $screens,
					'links_str' => $screens_str
				);
				
			} else {
				
				if ($_field_poster[2] == 'image') $result['link'] = preg_replace('/^(.*)\/uploads\/posts\//', '', $result['link']);
				else $result['link'] = preg_replace('/^(.*)\/uploads\//', '/uploads/', $result['link']);
				
				$db_image = preg_replace('/^(.*)?\/uploads\/posts\//', '', $result['link']);
				
			}			
			
			$row = $db->super_query( "SELECT images  FROM " . PREFIX . "_images WHERE author = '{$author}' AND news_id = '$post_id'" );
			
			
			if (empty($row['images'])) {
				$db->query( "INSERT INTO " . PREFIX . "_images (images, author, news_id, date) values ('{$db_image}', '{$author}', '{$post_id}', '{$edit_time}')" );
			} else {
				$listimages = explode( "|||", $row['images'] );
				$listimages[] = $db_image;
				$row['images'] = implode( "|||", $listimages );
				
				$db->query( "UPDATE " . PREFIX . "_images set images='{$row['images']}' WHERE author = '{$author}' AND news_id = '$post_id'" );
			}
			
			die(json_encode($result));
		}
		else 
			die(json_encode(array(
				'status' => 'error',
				'message' => $result
			)));

		break;
}
