<?php
/*
 * KodikSerials
 * =======================================================
 * Автор: kild, grey
 * =======================================================
 * Файл: kodikserials.php
 * -------------------------------------------------------
 * Версия: 2.0.5
 * =======================================================
 */

if( ! defined( 'DATALIFEENGINE' ) ) {
    die( "Hacking attempt!" );
}

include_once (ENGINE_DIR . '/data/kodikserials_options.php');

global $row;

if ($kodikserials_options['allow_module_on'] != 0) {

    $allow_cache = $config['allow_cache'];
    $config['allow_cache'] = 1;

    $cacheName = '_ks_' . $row['id'] . '_';
    // debug
    //$kodikSerials = false;
    $kodikSerials = dle_cache($kodikserials_options['cashe_prefix_dle'], $cacheName . $config['skin']);
    if ($kodikserials_options['module_debug']) $kodikSerials = false;

    if ($kodikSerials === false) {
      
        require_once (ENGINE_DIR . '/classes/ks.class.php');
    
        $post_id = $row['id'];
        $post_title = $row['title'];
        $xfieldsdata = xfieldsdataload($row['xfields']);
        
        $xfields_n = array();
                
        $seasonTemp = false;
        $seriesTemp = false;
        $seriesMax = false;         
        
        foreach($xfieldsdata as $xf_k=>$xf_v) {
          if(!is_null($xf_v) && $xf_v !== '' && $xf_k !== '') $xfields_n[$xf_k] = $xf_v;
        }
        
        $xfieldsdata = $xfields_n;
        //
        
        $kinopoisk_id = trim($xfieldsdata[$kodikserials_options['field_kpid']]);        
        $imdb_id = trim($xfieldsdata[$kodikserials_options['field_imdbid']]);
        $wordart_id = trim($xfieldsdata[$kodikserials_options['field_wordartid']]);
        $wordartanime_id = trim($xfieldsdata[$kodikserials_options['field_wordartanimeid']]);       
        $search_title = trim($xfieldsdata[$kodikserials_options['field_title']]);       
        $filter_translate = trim($xfieldsdata[$kodikserials_options['field_xtranslate']]);  
        if ($filter_translate != '') {
            $filter_translate_arr = explode(",", $filter_translate);
            $filter_translate_arr = array_map('trim',array_map('strtolower', $filter_translate_arr));
        }
                
        if ( $xfieldsdata[$kodikserials_options['field_season_num']] != '' AND $kodikserials_options['field_season_num'] ) {
            $seasonTemp = intval($xfieldsdata[$kodikserials_options['field_season_num']]);
        }
        
        if ( $xfieldsdata[$kodikserials_options['field_series_num']] != '' AND $kodikserials_options['field_series_num'] ) {
            $seriesTemp = intval($xfieldsdata[$kodikserials_options['field_series_num']]);
        }      
        
        if ( !$seasonTemp AND $kodikserials_options['field_season'] AND $xfieldsdata[$kodikserials_options['field_season']] AND $xfieldsdata[$kodikserials_options['field_season']] !== $kodikserials_options['if_series_ower'] ) {
            if(preg_match('/(\d+)/', $xfieldsdata[$kodikserials_options['field_season']], $matches)) $seasonTemp = $matches[1];
        }
        
        if ( !$seriesTemp AND $kodikserials_options['field_series'] AND $xfieldsdata[$kodikserials_options['field_series']]) {
            if(preg_match('/(\d+)/', $xfieldsdata[$kodikserials_options['field_series']], $matches)) $seriesTemp = $matches[1];
        }
        
        
        if ($kodikserials_options['module_debug']) {
          $seasonTemp = false;
          $seriesTemp = false;
        }
        
        
        // определение количества серий в сезоне
        if ( $kodikserials_options['field_series-max'] AND $xfieldsdata[$kodikserials_options['field_series-max']] AND $kodikserials_options['allow_module_new_series_max'] > 0 AND $xfieldsdata[$kodikserials_options['field_season_iframe']] )
            $seriesMax = $xfieldsdata[$kodikserials_options['field_series-max']];

        if ($kodikserials_options['allow_module_new']) {
            $tpl1 = new dle_template();
            $tpl1->dir = TEMPLATE_DIR;
                        
            $tpl1->load_template( '/kodikserials/kodikserials_iframe_modern.tpl' );
        }
        // если сериал закончен
        if ($kodikserials_options['field_status_name'] AND $xfieldsdata[$kodikserials_options['field_status_name']] == $kodikserials_options['field_status'] ) {
            if ( $kodikserials_options['field_season'] AND $kodikserials_options['allow_fields_spy'] ) {
                // поле сезон добавляем значение "если сериал закончен"
                $xfields_n[$kodikserials_options['field_season']] = $kodikserials_options['if_series_ower'];
                // если поле серия не пустое, чистим его
                if ($xfieldsdata[$kodikserials_options['field_series']]) unset($xfields_n[$kodikserials_options['field_series']]);
                // обрабатываем доп поля
                foreach($xfields_n as $key => &$value) {
                  $arr_field[] = $key . "|" . str_replace('|', '&#124;', $value);
                }
                
                $xfields_n = implode("||", $arr_field);
                unset($arr_field);
                $xfields_n = $db->safesql($xfields_n);
                // и в базу
                $db->query("UPDATE " . PREFIX . "_post SET `xfields` = '{$xfields_n}' WHERE id = '{$post_id}'");
            }
            if ($kodikserials_options['allow_module_new']) {
                $tpl1->set( '[ower]', "" );
                $tpl1->set( '[/ower]', "" );
                $tpl1->set_block( "'\\[not-ower\\](.*?)\\[/not-ower\\]'si", "" );
            }
        } else {
            if ($kodikserials_options['allow_module_new']) {
                $tpl1->set_block( "'\\[ower\\](.*?)\\[/ower\\]'si", "" );
                $tpl1->set_block( "'\\[not-ower\\](.*?)\\[/not-ower\\]'si", "\\1" );
            }
        }
        // получаем список переводов сериала
        
        $search_param = array();
        
        if ($kinopoisk_id != '') $search_param['kinopoisk_id'] = $kinopoisk_id;
        if ($imdb_id != '') $search_param['imdb_id'] = $imdb_id;
        if ($wordart_id != '') $search_param['worldart_cinema_id'] = $wordart_id;
        if ($wordartanime_id != '') $search_param['worldart_animation_id'] = $wordartanime_id;
        if ($search_title !='') { $search_param['title'] = $search_title; $search_param['strict'] = 'true'; }
        
        $search_param['with_episodes'] = "true";
                
        if($kodikserials_options['trans_prio_high'] != '') $search_param['prioritize_translations'] = $kodikserials_options['trans_prio_high'];
        if($kodikserials_options['trans_prio_low'] != '') $search_param['unprioritize_translations'] = $kodikserials_options['trans_prio_low'];
        if($kodikserials_options['trans_ignore'] != '') $search_param['block_translations'] = $kodikserials_options['trans_ignore'];
        
        $output_tr = get_api_ks( $search_param, $kodikserials_options );
                        
        if ( $config['charset'] == 'windows-1251' ) encoding_ks($output_tr, "UTF-8", "WINDOWS-1251");
        // если сервер не отвечает или ответ что видео нету                            
        if ($output_tr['total'] == 0 OR !count($output_tr['results']) OR $output_tr['status'] == 'error') {
            if ($kodikserials_options['allow_module_new']) {
                if (!$xfieldsdata[$kodikserials_options['field_season_iframe']]) {
                  $tpl1->set_block( "'\\[error\\](.*?)\\[/error\\]'si", "\\1" );
                  $tpl1->set_block( "'\\[not-error\\](.*?)\\[/not-error\\]'si", "" );
                } else {
                  $tpl1->set_block( "'\\[error\\](.*?)\\[/error\\]'si", "" );
                  $tpl1->set_block( "'\\[not-error\\](.*?)\\[/not-error\\]'si", "\\1" );
                }
                
              $tpl1->set_block( "'\\[soon\\](.*?)\\[/soon\\]'si", "" );
              $tpl1->set_block( "'\\[not-soon\\](.*?)\\[/not-soon\\]'si", "" );                
                
              if(isset($output_tr['error'])) var_dump($output_tr['error']);
              
            }
            
        } else {
        
            if ($kodikserials_options['allow_module_new']) {
                $tpl1->set_block( "'\\[error\\](.*?)\\[/error\\]'si", "" );
                $tpl1->set_block( "'\\[not-error\\](.*?)\\[/not-error\\]'si", "\\1" );
                $tpl1->set('{title}', $output_tr['results'][0]['title']);                
            }
            // получаем серии для каждого перевода
            
            $studios_sp = array();
                                 
            foreach ( (array)$output_tr['results'] as $vv ) {
				
				if($vv["type"] == "foreign-movie") break;
            
                $kinopoisk_id_result = $vv["kinopoisk_id"];
                $imdb_id_result = $vv["imdb_id"];
                $title_id_result = $vv["title"]; // $vv["title_orig"] $vv["other_title"] 
                $episodes_arr = array();    
            
                $seasonfound = 0;
                $seriesfound = 0;                

                $output_sr = $vv;

                $title_ru = $vv['title'];                                               
                
                // сокращаем названия озвучек
                if ( !isset($vv['translation']['title']) ) $vv['translation']['title'] = 'Неизвестно';
                elseif ( $vv['translation']['title'] == 'Проф. Двухголосый' ) $vv['translation']['title'] = 'Двухголосый';
                elseif ( $vv['translation']['title'] == 'Проф. Многоголосый' ) $vv['translation']['title'] = 'Многоголосый';
                elseif ( $vv['translation']['title'] == 'Проф. Одноголосый' ) $vv['translation']['title'] = 'Одноголосый';
                                
                //
                if ($filter_translate != '') {
                   if (in_array(strtolower($vv['translation']['title']), $filter_translate_arr) == false ) continue;
                }
                //                               
                
                // все озвучки для поля
                if ( $kodikserials_options['field_studios_sp'] ) $studios_sp[] = $vv['translation']['title'];
                
                                
                // ищем самую самую последнюю серию                        
                foreach ( (array)$output_sr["seasons"] as $kkk => $vvv ) {
                
					$seasonfound = 0;
					$seriesfound = 0;                    
                    // $kkk - сезон
                    // $vvv['episodes']
                    if ( $xfieldsdata[$kodikserials_options['field_season_iframe']]  != '') {
                        if ( $kkk == $xfieldsdata[$kodikserials_options['field_season_iframe']] ) {
                            $season = $kkk;
                            $seriesA = array_keys($vvv["episodes"]);
                            $seriesC = count($vvv["episodes"]);                            
                        }
                    } else {
                        if ( $kkk > $season ) {
                            $season = $kkk;
                            $seriesA = array_keys($vvv["episodes"]);
                            $seriesC = count($vvv["episodes"]);
                        }
                    }                                             
                                                                                    
                    //if ( $kodikserials_options['allow_module_new'] ) {
                        // есть ли сезон, который надо вывести                        
                        if ($xfieldsdata[$kodikserials_options['field_season_iframe']] != '') {
                        
                            if ($kkk == $xfieldsdata[$kodikserials_options['field_season_iframe']]) {
                                
                                $seasonfound = 1;
                                $s_link = $vvv['link'];                        
                                                                                      
                                if ( $xfieldsdata[$kodikserials_options['field_series_iframe']] != '') {
                                    foreach ( (array)$vvv["episodes"] as $kkkkk=>$vvvvv ) {
                                        if ( $kkkkk == $xfieldsdata[$kodikserials_options['field_series_iframe']] ) {
                                
                                            $seriesfound = 1;
                                            $e_link = $vvvvv;                                         
                                            
                                            break;
                                        
                                        }
                                    }                                    
                                }                                
                            }
                        }
                    //}                                        
                    
                    // может есть пилотная серия
                    foreach ( (array)$seriesA as $vvvv ) {
                        if ($vvvv == 0) $seriesT = -1;
                    }
                    
                    // если есть пилотная и серия только одна
                    if ($seriesT == -1 AND $seriesC == 1) $series = $kodikserials_options['if_pilot_series'];
                    else $series = max($seriesA);
                    
                    // get all episodes array
                    $episodes_arr = array();
                    foreach ( (array)$vvv["episodes"] as $kkkkk=>$vvvvv ) {
                      $episodes_arr[$kkk][$kkkkk] = $vvvvv . "?translations=false";
                      //$episodes_arr[$kkk] = $vvvvv;
                    }
                    
                   $tabs[] = array( 'translator_id' => $vv['translation']['id'], 'translator' => $vv['translation']['title'], 'iframe_url' => $vv['link'], 'season' => $kkk, 'series' => count($vvv["episodes"]), 'seasonfound' => $seasonfound, 's_link' => $s_link,'seriesfound' => $seriesfound, 'e_link' => $e_link, 'e_arr' => $episodes_arr);
                                
                }                
                
                unset($season);
                unset($series);
        }
                   
		$season = false;
		$series = false;        
                    
        // сортируем добро
        if (!$kodikserials_options['modern_style']) {
        
			  if ($kodikserials_options['trans_prio_high'] != '') $thighp = explode(",", $kodikserials_options['trans_prio_high']);
			  if ($kodikserials_options['trans_prio_low'] != '') $tlowp = explode(",", $kodikserials_options['trans_prio_low']);
			  
			  foreach ( (array)$tabs as $k => $v ){
				//if ( $v['series'] == $kodikserials_options['if_pilot_series'] ) $v['series'] = 0;
				//if ( $v['translator'] == "Субтитры" ) $v['series'] = $v['series'] - 0.5;
				
				if ( count($thighp) AND in_array($v['translator_id'], $thighp) ) $v['season'] = $v['season'] + 0.5;
				if ( count($tlowp) AND in_array($v['translator_id'], $tlowp) ) $v['series'] = $v['series'] - 0.5;
				
				$se[$k] = $v['season'];
				$ep[$k] = $v['series'];    			
			  }
                        
				array_multisort($se, SORT_NUMERIC, SORT_DESC, $ep, SORT_NUMERIC, SORT_DESC, $tabs); 		
				
    		}
    		
            
			$tplstudios = false;
			$hidese = "false";
																	
			// формируем табы
			foreach ( (array)$tabs as $tabskey => $tabsvalue ) {
					
						// если надо вывести сезон или серию
						if ( $xfieldsdata[$kodikserials_options['field_season_iframe']] != '' AND $xfieldsdata[$kodikserials_options['field_series_iframe']] != '' ) {
							if ( $tabsvalue['seasonfound'] > 0 AND $tabsvalue['seriesfound'] > 0 ) {
							
								$force_season = $tabsvalue['season'];
								$force_series = $tabsvalue['series'];
								$force_translator = $tabsvalue['translator'];                        
															
								$tmodern_arr["Сезон ".$xfieldsdata[$kodikserials_options['field_season_iframe']]." Серия ".$xfieldsdata[$kodikserials_options['field_series_iframe']]][$tabsvalue['translator']] = array(array($tabsvalue['e_link'].'?translations=false'));                            
								
								if ( !$tplstudios ) $tplstudios = $tabsvalue['translator'];
								
								$hidese = "true";
								
								$ifrm = $tabsvalue['e_link'] . ($kodikserials_options['hide_translations'] ? '?translations=false' : '');   
								
								if (!$kodikserials_options['modern_style']) break;
							}
							
						} elseif ( $xfieldsdata[$kodikserials_options['field_season_iframe']] != '' AND $xfieldsdata[$kodikserials_options['field_series_iframe']] == '' ) {
							if ($tabsvalue['seasonfound'] > 0) {
							
								$force_season = $tabsvalue['season'];
								$force_series = $tabsvalue['series'];
								$force_translator = $tabsvalue['translator'];
														
								$tmodern_arr["Сезон ". $xfieldsdata[$kodikserials_options['field_season_iframe']]][$tabsvalue['translator']] = $tabsvalue['e_arr'];
							
								if ( !$tplstudios ) $tplstudios = $tabsvalue['translator'];
								
								$hidese = "true";

								$ifrm = $tabsvalue['s_link'] . ($kodikserials_options['hide_translations'] ? '?translations=false' : '');
								
								if (!$kodikserials_options['modern_style']) break;
							}
							
						//} elseif ( !$xfieldsdata[$kodikserials_options['field_season_iframe']] AND !$xfieldsdata[$kodikserials_options['field_series_iframe']] ) {
						} else {
						
							$tmodern_arr["Сезон ". $tabsvalue['season']][$tabsvalue['translator']] = $tabsvalue['e_arr'];
																			
							if ( !$tplstudios ) $tplstudios = $tabsvalue['translator'];
													
							$ifrm = $tabsvalue['iframe_url'] . ($kodikserials_options['hide_translations'] ? '?translations=false' : '');
							
							if (!$kodikserials_options['modern_style']) break;
							
						}
						
					
			}
                
			if ( $kodikserials_options['allow_module_new'] ) {
                
                //
				// second sorting			
				if ($kodikserials_options['trans_prio_high'] != '') $thighp = explode(",", $kodikserials_options['trans_prio_high']);
				if ($kodikserials_options['trans_prio_low'] != '') $tlowp = explode(",", $kodikserials_options['trans_prio_low']);

				foreach ( (array)$tabs as $k => $v ){
					if ( count($thighp) AND in_array($v['translator_id'], $thighp) ) $v['season'] = $v['season'] + 0.5;
					if ( count($tlowp) AND in_array($v['translator_id'], $tlowp) ) $v['series'] = $v['series'] - 0.5;

					$se[$k] = $v['season'];
					$ep[$k] = $v['series'];    			
				}
					
				array_multisort($se, SORT_NUMERIC, SORT_DESC, $ep, SORT_NUMERIC, SORT_DESC, $tabs); 		
				//          
				//      
                
                if ( !$tplstudios ) $tplstudios = $tabs[0]['translator'];
                
                //                  
                ksort($tmodern_arr, SORT_STRING); // seasons sort        
                                
                $se_id = 0;
                $t_id = 0;
                $ep_id = 0;                
                
                foreach ($tmodern_arr as $sname=>$seasonarr) {
                
                  $se_id++;                  
                  $s_num[] = "<span onclick=\"kodikSlider.setseason('{$se_id}', this)\">{$sname}</span>";
                     
                  foreach ($seasonarr as $tname=>$seasonitem) {
                    
                   $t_id++;
                    
                   $z_num[] = "<span class=\"translatedseason_{$se_id}\" onclick=\"kodikSlider.season('{$t_id}', this)\" style=\"display:none;\">{$tname}</span>";
                   
                  
                   $temp_arr = array();
                     foreach ($seasonitem as $items) {
                     
                        ksort($items); // episodes sort    
                        
                        $ep_id = count($items) > $ep_id ? count($items) : $ep_id ;
                     
                        foreach ($items as $epnum=>$link) {
                          $temp_arr[] = "<span onclick=\"kodikSlider.player('{$link}', this);\"> {$epnum} серия</span>";
                        }
                     
                     }
                     
                   $e_num[] = "<li id=\"season{$t_id}\" style=\"display:none;\">" . implode($temp_arr) . "</li>";
                  }                
                }
                
                
                $tpl1->set('{snum}', implode($s_num));
                $tpl1->set('{znum}', implode($z_num));
                $tpl1->set('{enum}', implode($e_num));
                
                $hideep = "false";                
                if($ep_id == 1) $hideep = "true";                
                if($se_id == 1) $hidese = "true";
                
                $tpl1->set('{season}', $tabs[0]['season']);
                $tpl1->set('{studios}', $tplstudios);
                
                $tpl1->set('{iframe-player}', $ifrm);
                
                if ($kodikserials_options['modern_style']) {
                
                  $tpl1->set('{init-player}', "<script type=\"text/javascript\">var kodikserials_ready = true; var kodikserials_noseasons = {$hidese}; var kodikserials_noepisodes = {$hideep};</script>" );
                
                  $tpl1->set_block( "'\\[modern-player\\](.*?)\\[/modern-player\\]'si", "\\1" ); 
                  $tpl1->set_block( "'\\[classic-player\\](.*?)\\[/classic-player\\]'si", "" ); 
                
                } else {
                
                  $tpl1->set('{init-player}', "<script type=\"text/javascript\">var kodikserials_ready = false; var kodikserials_noseasons = false; var kodikserials_noepisodes = false;</script>" );
                
                  $tpl1->set_block( "'\\[modern-player\\](.*?)\\[/modern-player\\]'si", "" ); 
                  $tpl1->set_block( "'\\[classic-player\\](.*?)\\[/classic-player\\]'si", "\\1" ); 
                
                }
                
                if(!count($tabs)) {
                  $tpl1->set('{init-player}', "" );
                
                  $tpl1->set_block( "'\\[modern-player\\](.*?)\\[/modern-player\\]'si", "" );
                  $tpl1->set_block( "'\\[classic-player\\](.*?)\\[/classic-player\\]'si", "" );
                }
                
                if ( $kodikserials_options['add_series_one_tpl'] ) $tpl1->set('{series}', $tabs[0]['series'] + 1);
                else $tpl1->set('{series}', $tabs[0]['series']);
            
            }
                  
            if(count($tabs)) {
				$season = isset($force_season) ? $force_season : $tabs[0]['season'];
				$series = isset($force_series) ? $force_series : $tabs[0]['series'];
				$studios = isset($force_translator) ? $force_translator : $tabs[0]['translator'];
            }            
                        
            if ( $kodikserials_options['allow_module_new'] ) {
                // если надо вывести конкретные сезон или сезон/серию но они еще не вышли
                                
                if ( $season < $xfieldsdata[$kodikserials_options['field_season_iframe']] OR ($xfieldsdata[$kodikserials_options['field_season_iframe']] == $season AND $series < $xfieldsdata[$kodikserials_options['field_series_iframe']]) ) {                                    
                                    
                  $tpl1->set( '[soon]', "" );
                	$tpl1->set( '[/soon]', "" );
                	$tpl1->set_block( "'\\[not-soon\\](.*?)\\[/not-soon\\]'si", "" );
                	
                } else {
                
                  $tpl1->set_block( "'\\[soon\\](.*?)\\[/soon\\]'si", "" );
                  $tpl1->set_block( "'\\[not-soon\\](.*?)\\[/not-soon\\]'si", "\\1" );                	
                	
                }
            }
            
            // если конкретно указано сезон и серию
            if ( $xfieldsdata[$kodikserials_options['field_season_iframe']]  != '' ) {
                $season = $xfieldsdata[$kodikserials_options['field_season_iframe']];
                if ( $kodikserials_options['allow_module_new'] ) $tpl1->set('{season}', $xfieldsdata[$kodikserials_options['field_season_iframe']]);
            }
            
            if ( $xfieldsdata[$kodikserials_options['field_series_iframe']] != '' ) {
                $series = $xfieldsdata[$kodikserials_options['field_series_iframe']];
                if ( $kodikserials_options['allow_module_new'] ) $tpl1->set('{series}', $xfieldsdata[$kodikserials_options['field_series_iframe']]);
            }
            
            // вышел, поля пустые            
            if ( $season !== false AND !$seasonTemp AND $series !== false AND !$seriesTemp AND $xfieldsdata[$kodikserials_options['field_status_name']] !== $kodikserials_options['field_status'] )
                $notdateup = true;
            else
                $notdateup = false;
                                

            $exclude_news = false;
            if($kodikserials_options['exnews_module']) {
              $temp_exnews_module = explode(",", preg_replace('/\s+/', '', $kodikserials_options['exnews_module']));
              if(in_array($post_id, $temp_exnews_module)) $exclude_news = true;
            }
                                
            // отключаем автообновления полей если сезон или серия уже заполнены
            if (($kodikserials_options['without_updates'] AND $seasonTemp AND $seriesTemp) OR $exclude_news) {
                $seasonTemp = false;
                $season = false;
            }
                                
            // есть новая серия
            $newbetter = false;
            if ( $seasonTemp !== false AND $seriesTemp !== false) {
              if( (int)$season > (int)$seasonTemp ) {
                  $newbetter = true;
              } elseif ( (int)$season == (int)$seasonTemp AND (int)$series > (int)$seriesTemp) {
                  $newbetter = true;
              }
            }
                        
            if ( ($newbetter OR ($season !== false AND !$seasonTemp AND $series !== false AND !$seriesTemp)) AND $xfieldsdata[$kodikserials_options['field_status_name']] !== $kodikserials_options['field_status'] ) {
                

                // сезон цифрой серия цифрой
                if( $kodikserials_options['field_season_num'] ) {
                   $xfields_n[$kodikserials_options['field_season_num']] = $season;
                }
                
                if( $kodikserials_options['field_series_num'] ) {
                  if ( $kodikserials_options['add_series_one'] > 0 ) $xfields_n[$kodikserials_options['field_series_num']] = ($tabs[0]['series'] + 1);
                  else $xfields_n[$kodikserials_options['field_series_num']] = $series;
                }
                                
                $season = $season . " сезон";                
                $series = $series . " серия"; 

                // кинопоиск imdb
                if($kodikserials_options['fill_kpimdb']) {
                  if ($kinopoisk_id == '' AND $kinopoisk_id_result != '' AND $kodikserials_options['field_kpid'] != '') $xfields_n[$kodikserials_options['field_kpid']] = $kinopoisk_id_result;
                  if ($imdb_id == '' AND $imdb_id_result != '' AND $kodikserials_options['field_imdbid'] != '') $xfields_n[$kodikserials_options['field_imdbid']] = $imdb_id_result;                  
                  if ($search_title == '' AND $title_id_result != '' AND $kodikserials_options['field_title'] != '') $xfields_n[$kodikserials_options['field_title']] = $title_id_result;                
                }
                                
                // сезон
                if($kodikserials_options['field_season']) {
                   $xfields_n[$kodikserials_options['field_season']] = $season;
                }
                
                //серия. обычная и +1
                if($kodikserials_options['field_series']) {
                  if ( $kodikserials_options['add_series_one'] > 0 ) $xfields_n[$kodikserials_options['field_series']] = ($tabs[0]['series'] + 1) . ' серия';
                  else $xfields_n[$kodikserials_options['field_series']] = $series;                    
                }
                    
                //перевод
                if ( $studios AND $kodikserials_options['field_studios'] ) {
                    $xfields_n[$kodikserials_options['field_studios']] = $studios;
                }
                    
                //русское название
                if ( !$xfieldsdata[$kodikserials_options['field_title_ru']] AND $kodikserials_options['field_title_ru'] AND $title_ru ) {
                    $xfields_n[$kodikserials_options['field_title_ru']] = $title_ru;
                }
                    
                //все переводы
                if ( count($studios_sp) AND $kodikserials_options['field_studios_sp'] )
                    $xfields_n[$kodikserials_options['field_studios_sp']] = implode(", ", $studios_sp);
                    
                //форматированные сезон и серия
                if ( $kodikserials_options['season_mod'] ) {
                    $xfields_n[$kodikserials_options['season_mod']] = seform_ks($kodikserials_options['field_season_form'], $season, '0');
                }
                
                if ( $kodikserials_options['series_mod'] ) {
                    $xfields_n[$kodikserials_options['series_mod']] = seform_ks($kodikserials_options['field_series_form'], $series, $kodikserials_options['add_series_one']);
                }
                    
                // макс серий                
                if ( $kodikserials_options['field_series-max'] AND $xfieldsdata[$kodikserials_options['field_series-max']] < $tabs[0]['series'] AND $xfieldsdata[$kodikserials_options['field_season_iframe']] AND !$kodikserials_options['allow_module_new_series_max'] ) {
                    $xfields_n[$kodikserials_options['field_series-max']] = $tabs[0]['series'];
                }
                    
                // статус
                if ( $kodikserials_options['field_status'] AND $kodikserials_options['allow_module_new_series_max'] > 0 AND $seriesMax == $tabs[0]['series'] AND $xfieldsdata[$kodikserials_options['field_status_name']] !== $kodikserials_options['field_status'] ) {
                    $xfields_n[$kodikserials_options['field_status_name']] = $kodikserials_options['field_status'];
                }
                    
                // новая дата новости
                if ( $kodikserials_options['allow_news_update'] AND !$notdateup ) {
                    $myNewDate = ( $kodikserials_options['allow_news_update'] != 0 ) ? ", `date` = '" . date('Y-m-d H:i:s') . "'" : false;
                }                    
                    
                
                $exclude_title = false;
                if($kodikserials_options['exnews_title']) {
                  $temp_exnews_title = explode(",", preg_replace('/\s+/', '', $kodikserials_options['exnews_title']));
                  if(in_array($post_id, $temp_exnews_title)) $exclude_title = true;
                }
                
                // если включено обновлять тайтл
                if ( $kodikserials_options['allow_news_title_update'] AND !$exclude_title) {
                    $ms_title_date= !empty($kodikserials_options['ms_title_date']) ? langdate($kodikserials_options['ms_title_date'], false) : false;
                    $ms_title_preffix = !empty($kodikserials_options['ms_title_preffix']) ? $kodikserials_options['ms_title_preffix'] . " " : false;
                    $ms_title_year = !empty($kodikserials_options['ms_title_year']) ? $xfieldsdata[$kodikserials_options['ms_title_year']] . " " : false;
                    $ms_title_t1 = !empty($kodikserials_options['ms_title_t1']) ? $kodikserials_options['ms_title_t1'] . " " : false;
                    $ms_title_t2 = !empty($kodikserials_options['ms_title_t2']) ? $kodikserials_options['ms_title_t2'] . " " : false;
                    $ms_title_field = !empty($kodikserials_options['ms_title_field']) ? $xfieldsdata[$kodikserials_options['ms_title_field']] . " " : false;

                    if ( $kodikserials_options['ms_title_season'] ) {
                        if ( $kodikserials_options['ms_title_season_one'] AND $season == "1 сезон" )
                            $ms_title_season = false;
                        else
                            $ms_title_season = seform_ks($kodikserials_options['title_season_form'], $season, '0') . " ";
                    }

                    if ( $kodikserials_options['ms_title_series'] )
                        $ms_title_series = seform_ks($kodikserials_options['title_series_form'], $series, $kodikserials_options['ms_title_series_add']) . " ";

                    $myModule_title = $ms_title_season . $ms_title_series;
                    $ms_title_up = $ms_title_preffix . $title_ru . " " . $ms_title_year . $ms_title_t1 . $myModule_title . $ms_title_t2 . $ms_title_field . $ms_title_date;
                    $ms_title_up = $db->safesql(trim(strip_tags(stripslashes(preg_replace("/\s{2,}/"," ",$ms_title_up)))));
                    $ms_title_up = ", `metatitle`='" . $ms_title_up . "'";
                }
                
                $exclude_cpu = false;
                if($kodikserials_options['exnews_cpu']) {
                  $temp_exnews_cpu = explode(",", preg_replace('/\s+/', '', $kodikserials_options['exnews_cpu']));
                  if(in_array($post_id, $temp_exnews_cpu)) $exclude_cpu = true;
                }                
                
                // если включено обновлять ЧПУ
                if ($kodikserials_options['allow_news_cpu_update'] AND !$exclude_cpu) {
                    $ms_cpu_date = !empty($kodikserials_options['ms_cpu_date']) ? totranslit(langdate($kodikserials_options['ms_cpu_date'], false)) : false;
                    $ms_cpu_preffix = !empty($kodikserials_options['ms_cpu_preffix']) ? totranslit($kodikserials_options['ms_cpu_preffix']) . '-' : false;
                    $ms_cpu_year = !empty($kodikserials_options['ms_cpu_year']) ? totranslit($xfieldsdata[$kodikserials_options['ms_cpu_year']]) . '-' : false;
                    $ms_cpu_t1 = !empty($kodikserials_options['ms_cpu_t1']) ? totranslit($kodikserials_options['ms_cpu_t1']) . '-' : false;
                    $ms_cpu_t2 = !empty($kodikserials_options['ms_cpu_t2']) ? totranslit($kodikserials_options['ms_cpu_t2']) . '-' : false;
                    $ms_cpu_field = !empty($kodikserials_options['ms_cpu_field']) ? totranslit($xfieldsdata[$kodikserials_options['ms_cpu_field']]) . "-" : false;
                    $title_ru_cpu = totranslit($title_ru) . '-';
                    if ( $kodikserials_options['ms_cpu_season'] ) {
                        if ( $kodikserials_options['ms_cpu_season_one'] AND $season == "1 сезон" )
                            $ms_cpu_season = false;
                        else
                            $ms_cpu_season = seform_ks($kodikserials_options['cpu_season_form'], $season, '0') . '-';
                    }

                    if ( $kodikserials_options['ms_cpu_series'] )
                        $ms_cpu_series = seform_ks($kodikserials_options['cpu_series_form'], $series, $kodikserials_options['ms_cpu_series_add']) . '-';

                    $myModule_cpu = $ms_cpu_season . $ms_cpu_series;
                    $myModule_cpu = str_replace(",", "-", $myModule_cpu);
                    $myModule_cpu = totranslit($myModule_cpu);

                    $ms_cpu_up = $ms_cpu_preffix . $title_ru_cpu . $ms_cpu_year . $ms_cpu_t1 . $myModule_cpu . $ms_cpu_t2 . $ms_cpu_field . $ms_cpu_date;

                    $ms_cpu_up = $db->safesql(trim(strip_tags(stripslashes(preg_replace("/-{2,}/","-",$ms_cpu_up))),"-"));
                    $ms_cpu_up = ", `alt_name`='" . $ms_cpu_up . "'";
                }
                
                $exclude_title2 = false;
                if($kodikserials_options['exnews_title2']) {
                  $temp_exnews_title2 = explode(",", preg_replace('/\s+/', '', $kodikserials_options['exnews_title2']));
                  if(in_array($post_id, $temp_exnews_title2)) $exclude_title2 = true;
                }
                                
                // если включено обновлять заголовок
                if ( $kodikserials_options['allow_news_title2_update'] AND !$exclude_title2) {
                    $ms_title2_date	= !empty($kodikserials_options['ms_title2_date']) ? langdate($kodikserials_options['ms_title2_date'], false) . " " : false;
                    $ms_title2_preffix = !empty($kodikserials_options['ms_title2_preffix']) ? $kodikserials_options['ms_title2_preffix'] . " " : false;
                    $ms_title2_year = !empty($kodikserials_options['ms_title2_year']) ? $xfieldsdata[$kodikserials_options['ms_title2_year']] . " " : false;
                    $ms_title2_t1 = !empty($kodikserials_options['ms_title2_t1']) ? $kodikserials_options['ms_title2_t1'] . " " : false;
                    $ms_title2_t2 = !empty($kodikserials_options['ms_title2_t2']) ? $kodikserials_options['ms_title2_t2'] . " " : false;
                    $ms_title2_field = !empty($kodikserials_options['ms_title2_field']) ? $xfieldsdata[$kodikserials_options['ms_title2_field']] . " " : false;

                    if ( $kodikserials_options['ms_title2_season'] ) {
                        if ( $kodikserials_options['ms_title2_season_one'] AND $season == "1 сезон" )
                            $ms_title2_season = false;
                        else
                            $ms_title2_season = seform_ks($kodikserials_options['title2_season_form'], $season, '0') . " ";
                    }
                    if ( $kodikserials_options['ms_title2_series'] )
                        $ms_title2_series = seform_ks($kodikserials_options['title2_series_form'], $series, $kodikserials_options['ms_title2_series_add']) . " ";

                    $myModule_title2 = $ms_title2_season . $ms_title2_series;

                    $ms_title2_up = $ms_title2_preffix . $title_ru . " " . $ms_title2_year . $ms_title2_t1 . $myModule_title2 . $ms_title2_t2 . $ms_title2_field . $ms_title2_date;
                    $ms_title2_up = $db->safesql(trim(strip_tags(stripslashes(preg_replace("/\s{2,}/"," ",$ms_title2_up))))); 
                    $ms_title2_up = ", `title`='" . $ms_title2_up . "'";
                }
                
                // обрабатываем доп поля
                foreach($xfields_n as $key => &$value)
                    $arr_field[] = $key . "|" . str_replace('|', '&#124;', $value);
                    
                $xfields_n = implode("||", $arr_field);
                unset($arr_field);
                $xfields_n = $db->safesql($xfields_n);
                
                
                
                // вносим все это счастье в базу                                
                $db->query("UPDATE " . PREFIX . "_post SET `xfields` = '{$xfields_n}' {$myNewDate} {$ms_title_up} {$ms_title2_up} {$ms_cpu_up} WHERE id = '{$post_id}'");
                $db->query( "INSERT INTO " . USERPREFIX . "_admin_logs (name, date, ip, action, extras) values ('kodikserials', '{$_TIME}', '127.0.0.1', '25', '{$post_title}')" );
                clear_cache( array('news_', 'full_'.$post_id) );
                
                //
                //if ($kodikserials_options['module_debug']) {
                  if (file_exists(ENGINE_DIR . '/data/kodikserials.log') && filesize(ENGINE_DIR . '/data/kodikserials.log') > 2048*1024) {unlink(ENGINE_DIR . '/data/kodikserials.log');}
                  $log_string = "{$post_title} | {$xfields_n}" . "\r\n";
                  file_put_contents(ENGINE_DIR . '/data/kodikserials.log', $log_string, FILE_APPEND | LOCK_EX);
                //}
                //
                
                // если включено отправлять ЛС
                if ($kodikserials_options['sendpm'] > 0 AND !$xfieldsdata[$kodikserials_options['field_season_iframe']] AND intval($seriesTemp) > 0) {
                    $user_id = $kodikserials_options['sendpm'];
                    $user_id = (int)$user_id;
                    $now = time();
                    $subject = 'Вышла ' . $series . ' сериала ' . $title_ru . '';
                    $subject = $db->safesql($subject);
                    $from = 'kodikSerials';
                    $from = $db->safesql($from);
                    $text = '<h3>Вышла ' . $series . ' сериала ' . $title_ru . '</h3>';
                    $text .= '<p><b>Теперь можно:</b></p>';
                    $text .= '<ul><li><a href="'.$config['http_home_url'] . 'index.php?newsid=' . $post_id.'" target="_blank">Открыть новость на сайте</a></li>';
                    $text .= '<li><a href="'.$config['admin_path'] . '?mod=editnews&action=editnews&id=' . $post_id.'" target="_blank">Редактировать в админпанели</a></li>';
                    $text .= '<li><a href="'.$config['admin_path'] . '?mod=addnews&action=addnews" target="_blank">Добавить новую новость в админпанели</a></li></ul>';
                    $text = $db->safesql($text);
                    $db->query("INSERT into " . PREFIX . "_pm (subj, text, user, user_from, date, pm_read, folder) VALUES ('{$subject}', '{$text}', '{$user_id}', '{$from}', '{$now}', '0', 'inbox')");
                    $db->query("UPDATE " . USERPREFIX . "_users set pm_unread = pm_unread + 1, pm_all = pm_all+1 WHERE user_id = '{$user_id}'");                                        
                }
            }
        }
        if ($kodikserials_options['allow_module_new']) {
            
            //$tpl1->set("{tabs-title}", $kodikserials_options['shide_translations'] ? "" : $tpl2->result['tabs-title']); unset($tpl2);
            //$tpl1->set("{tabs-content}", $tpl3->result['tabs-content']); unset($tpl3);
            $tpl1->compile('myModule');            
            
            $kodikSerials = $tpl1->result['myModule'];
            
        } elseif ($xfieldsdata[$kodikserials_options['field_status_name']] !== $kodikserials_options['field_status']) {
            $echoseries = $kodikserials_options['add_series_one'] > 0 ? $tabs[0]['series'] + 1 : $tabs[0]['series'];
            if ($kodikserials_options['allow_module_new_season'] AND $kodikserials_options['allow_module_new_series'])
                $kodikSerials = $tabs[0]['season'] . " сезон " . $echoseries . " серия";
            elseif ($kodikserials_options['allow_module_new_season'] AND !$kodikserials_options['allow_module_new_series'])
                $kodikSerials = $tabs[0]['season'] . " сезон";
            elseif (!$kodikserials_options['allow_module_new_season'] AND $kodikserials_options['allow_module_new_series'])
                $kodikSerials = $echoseries . " серия";
        } else
            $kodikSerials = $kodikserials_options['if_series_ower'];

        create_cache($kodikserials_options['cashe_prefix_dle'], $kodikSerials, $cacheName . $config['skin']);

        if ($kodikserials_options['allow_module_new']) $tpl1->clear();
    }
    
    $config['allow_cache'] = $allow_cache;
    
    // Выводим результат работы модуля
    echo $kodikSerials;
}
?>