<?php


if(!defined('DATALIFEENGINE')) {
    header( "HTTP/1.1 403 Forbidden" );
    header ( 'Location: ../../' );
    die( "Hacking attempt!" );
}

ini_set("memory_limit","256M");
ini_set('max_execution_time',200);
ignore_user_abort(true);
set_time_limit(200);
session_write_close();


require_once (ENGINE_DIR . '/classes/plugins.class.php');


if (version_compare('15', $config['version_id'], '<=')) {
    define('DLE15', true);
}


if (defined('DLE15')) {
    include_once ENGINE_DIR . '/classes/composer/vendor/autoload.php';
}

else {
    include_once ENGINE_DIR . '/classes/thumb.class.php';
}

require_once DLEPlugins::Check(ENGINE_DIR . '/modules/alloha.func.php');



$config_mod = unserialize( file_get_contents( ENGINE_DIR . '/data/' . $mod . '.config' ) );

if ( !$config_mod ) $config_mod = array();


$qual_list = [
	'TS 720p'         => 0,
	'TS '             => 1,	
	'CAMRip'          => 2,
	'Workprint-AVC'   => 3,
	'WEB-DLRip 720p'  => 4,
	'WEB-DLRip 1080p' => 5,
	'WEB-DLRip 1080p' => 6,
	'WEB-DLRip'       => 7,
	'WEBRip'       => 7,
	'VHSRip'          => 8,
	'TVRip 720p'      => 9,
	'TVRip'           => 10,
	'SuperTS'         => 11,
	'SATRip'          => 12,
	'Laserdisc-RIP'   => 13,
	'IPTVRip'         => 14,
	'DVDSrc'          => 15,
	'DVDRip'          => 16,
	'DVBRip 720p'     => 17,
	'DVBRip'          => 18,
	'DVB'          => 18,
	'HDDVDRip 720p'   => 19,
	'HDDVDRip 1080p'  => 20,
	'HDDVDRip'        => 21,
	'HDTVRip 720p'    => 22,
	'HDTVRip 1080p'   => 23,
	'HDTVRip'         => 24,
	'HDRip 720p'      => 25,
	'HDRip 1080p'     => 26,
	'HDRip'           => 27,
	'D-VHS'           => 28,
	'BDRip 720p'      => 29,
	'BDRip 1080p'     => 30,
	'BDRip'           => 31
];


class Alloha {
	
	function __construct($type, $db) {
		$this->log  = $this->getLog();
		$this->next = empty($this->log[$type]['next']) ? '' : $this->log[$type]['next'];
		
		$this->db   = $db;
		$this->type = $type;
	}

    public function start($url, $iframe_movie_check = false){
      
    	$request_url = $url;

        for ($i=0; $i < 5; $i++) { 
echo $request_url."<br>";
        	$result = request($request_url);
        	$res = json_decode($result, true);
          
            if(! empty($res['data']) && true === $iframe_movie_check)
            {
              
                foreach($res['data'] as $resKey => $resData)
                {
                 
                  	if(!empty($resData['iframe_movie']))
                    {
                       unset($res['data'][$resKey]); 
                    }
                  
                }
                
            }
     
        	if(!$res) {
        		die($result);
        	}

        	if ($res['status']=='error') {
        		die($res['error_info']);
        	}

        	if(empty($res['data'])) {
        		$this->setLog($this->type, 'next', '');
        		die('empty results');
        	}

            $this->render($res['data']);

            if($i==0 && $this->next) {
            	$request_url = $url.'&page='.$this->next;
            } else {
            	$request_url = $res['next_page'] ? $url.'&page='.$res['next_page'] : '';
            }

      	    $this->setLog($this->type, 'next', $res['next_page'] ? $res['next_page'] : '');
            if(!$request_url) break;

        }

    }


    private function render($data){
		

	    foreach ($data as $k => $value) {
			if($this->type!="trailer"){ //humbert
				
		  
	        $kp_id        = intval($value['id_kp']);
	        $year         = intval($value['year']);
	        $type         = $this->type;
	        $quality      = $this->db->safesql($value['quality']);
	        $episode      = $season = 0;

	        if($kp_id<10) continue;

	        if(in_array($this->type, ['serial', 'multserial', 'animeserial'])){
	        	$season  = (int)$value['seasons_count'];
	        	$episode = (int)$value['last_episode'];
	        }

	        global $qual_list;

	        $row = $this->db->super_query( "SELECT * FROM " . PREFIX . "_alloha WHERE kp_id='$kp_id'" );

	        if ($row) {
	            if($qual_list[$row['quality']]<$qual_list[$quality] or $row['season']<$season or $row['episode']<$episode)
	                $this->db->query( "UPDATE " . PREFIX . "_alloha SET status='1', quality='{$quality}', episode='{$episode}', season='{$season}' WHERE kp_id='$kp_id'" );
	            
	        } else {
	            $this->db->query( "INSERT INTO " . PREFIX . "_alloha (kp_id, year, quality, type, episode, season) VALUES('{$kp_id}', '{$year}', '{$quality}', '{$type}', '{$episode}', '{$season}')" );
	        }

	    }
	    else //humbert
	   { 
		   global $config_mod, $db, $config;
		   $global_config=$config_mod;
		   
		   $kl_next=0;
		   
		   foreach($data as $value_data)
		   {
			   $kl_next=1;
			   $config_mod=$global_config;
			   $value_data['country'] = str_replace(', ', ',', $value_data['country']);
               $value_data['genre'] = str_replace(', ', ',', $value_data['genre']);


               if( ($premiere = strtotime($value_data['premiere']))!==false && $value_data['premiere'] ){
                   $value_data['premiere'] = date('j', $premiere).' '.$langdate[date('F', $premiere)].' '.date('Y', $premiere);
               }
               
               if( ($premiere_ru = strtotime($value_data['premiere_ru']))!==false && $value_data['premiere_ru'] ){
                   $value_data['premiere_ru'] = date('j', $premiere_ru).' '.$langdate[date('F', $premiere_ru)].' '.date('Y', $premiere_ru);
               }

               $request = [];

               $is_serial = false;

               if($value_data['seasons_count']){
				   $request['last_season'] = $value_data['seasons_count'];
                   $request['last_episode'] = $value_data['last_episode'];

                   $episodes = array_shift($value_data['seasons']);
                   $episodes = count($episodes['episodes']);
                   $request['episode_count'] = $episodes;

                   $request['last_translate'] = trim( array_shift(explode(',', $value_data['translation'])) );

                   $is_serial = true;
               }

               $ex_genres = array();
               $ex_genres[] = "трейлер";
               $ex_genres[]=$value_data['category'];

               if ($value_data['category']=='1' && mb_stripos($value_data['genre'], 'мультфильм')===false) {
				   $ex_genres[] = "фильм"; $request['video_type'] = 'фильм';
    
               }

               if ($value_data['category']=='5') {
                   $ex_genres[] = "тв шоу"; $request['video_type'] = 'тв шоу';
               }

               
               if (mb_stripos($value_data['genre'], 'мультфильм')!==false) {
                   if ($is_serial) {
					   
					   $request['video_type'] = "мультсериал";
                       $ex_genres[] = "мультсериал";


                   } else {
					   $request['video_type'] = 'мультфильм';
                       $ex_genres[] = "мультфильм";


                   }
               }

               if (mb_stripos($value_data['country'], 'россия')===false && mb_stripos($value_data['country'], 'ссср')===false) {
				   $ex_genres[] = "зарубежный";
               }

               if ($value_data['category']=='4') {
				   $ex_genres[] = "аниме сериал"; $request['video_type'] = 'аниме сериал';
			   }

               if ($alloha['type']=='anime') {
				   $ex_genres[] = "аниме"; $request['video_type'] = 'аниме';
               }
               
               
               $genres = fixGenres(explode(',', $value_data['genre']));


               $inter = array_merge($ex_genres, $genres, explode(',', $value_data['country']), array($value_data['year']));

               if ($request['video_type'] == 'мультсериал') {
				   $inter = array_diff($inter, ['мультфильм']);
               }

               if ($value_data['category']=='3') {
				   $inter = array_diff($inter, ['зарубежный', 'мультфильм']);
               }

               if ($value_data['category']=='4') {
				   $inter = array_diff($inter, ['зарубежный', 'мультсериал', 'мультфильм', 'аниме']);
               }
               
              
    $cats=array();
               
     foreach ($config_mod['category'] as $cat_id => $values) {
    $f = true;

    foreach ($values as $value) {
        if ( !in_array($value, $inter) ) {
            $f = false;
            break;
        }
    }

    if ( $f ) $cats[] = $cat_id;
}
 
               $config_mod['category'] = implode(",", $cats); 
               
              
               if ($config_mod['max_actors']) {
				   
				   $value_data['actors'] = explode(',', $value_data['actors']);
                   $value_data['actors'] = array_slice($value_data['actors'], 0, intval($config_mod['max_actors']));
                   $value_data['actors'] = implode(',', $value_data['actors']);
               }

               if ($config_mod['max_directors']) {
				   
				   $value_data['directors'] = explode(',', $value_data['directors']);
                   $value_data['directors'] = array_slice($value_data['directors'], 0, intval($config_mod['max_directors']));
                   $value_data['directors'] = implode(',', $value_data['directors']);
               }

               $value_data['genre'] = preg_replace_callback('/,([^,]|\s+)/u', function($m){
				   
				   return ','.(strpos(' ', $m[1]) ? ' ' : ' '.$m[1]);
               }, $value_data['genre']);

               $value_data['country'] = preg_replace_callback('/,([^,]|\s+)/u', function($m){
				   return ','.(strpos(' ', $m[1]) ? ' ' : ' '.$m[1]);
			   }, $value_data['country']);

			   $request['title_ru']      = $value_data['name'];
               $request['title_en']      = $value_data['original_name'];
               $request['title_alt']     = $value_data['alternative_name'];
               $request['token_movie']  = $value_data['token_movie'];
  			   $request['year']          = $value_data['year'];
			   $request['description']   = html_entity_decode($value_data['description'], ENT_HTML5);
			   $request['countries']     = $value_data['country'];
               $request['genres']        = $value_data['genre'];
               $request['actors']        = $value_data['actors'];
			   $request['iframe_url']    = "";
			   $request['quality']       = $value_data['quality'];
			   $request['slogan']        = $value_data['tagline'];
			   $request['directors']     = $value_data['directors'];
			   $request['producer']      = $value_data['producers'];
			   $request['translator']    = $value_data['translation'];
			   $request['trailer']       = $value_data['iframe'];

			   $request['premiere_ru']    = $value_data['premiere_ru'];
			   $request['premiere_world'] = $value_data['premiere'];

			   $request['rating_kp']        = $value_data['rating_kp'];
			   $request['rating_imdb']      = $value_data['rating_imdb'];
			   $request['rating_world_art'] = $value_data['world_art'];
			   $request['rate_mpaa']        = $value_data['rating_mpaa'];

			   $request['kinopoisk_id']     = $value_data['id_kp'];
			   $request['imdb_id']          = $value_data['id_imdb'];
			   $request['tmdb_id']          = $value_data['id_tmdb'];
			   $request['world_art_id']     = $value_data['id_world_art'];

			   $request['age']          = $value_data['age_restrictions'];
			   $request['time']         = $value_data['time'];
			   $request['instream_ads'] = ($value_data['ads']=='') ? '' : 1;

			   if($request['title_en']==$request['title_ru']) $request['title_en']='';
			   
			   $kp_id        = intval($request['kinopoisk_id']);
	           $year         = intval($request['year']);
	           $type         = "trailer";
	           $quality      = $request['year'];
	           $episode      = $season = 1;


			   $post_row = $db->super_query( "SELECT id, title, xfields FROM " . PREFIX . "_post WHERE xfields LIKE '%kinopoisk_id|{$value_data['id_kp']}||%'" );

			   if(!$post_row) $alloha['news_id']=0;
			   else {$alloha['news_id']=$post_row['id'];}

			   if(!$alloha['news_id']){
				   
				   if ($config_mod['upload_poster']) {
					   
					   $poster_file = $value_data['id_kp'].'_'.time();
					   $poster = request($value_data['poster'], ROOT_DIR . "/uploads/posts/" . FOLDER_PREFIX.'/' .$poster_file);
					   if($poster){
						   
						   if ($config_mod['poster_size']) {
							   
							   $t_seite = intval($config['t_seite']);
							   $t_size = $config_mod['poster_size'];
							   
							   $thumb = new thumbnail( $poster );

							   if( $thumb->size_auto( $t_size, $t_seite ) ) {
								   
								   if (defined('DLE15')) {
									   $newFile = $thumb->save(str_replace(ROOT_DIR."/uploads/" , '', $poster));

									   $poster = ROOT_DIR . "/uploads/posts/" . FOLDER_PREFIX . '/' . $newFile; 

								   } else {
									   $thumb->jpeg_quality( $config['jpeg_quality'] );

									   $thumb->save( $poster );
							   }

							   @chmod( $poster, 0666 );

								/**************/


							}

						}

						$request['poster'] = str_replace(ROOT_DIR.'/' , $config['http_home_url'], $poster);
                        $poster = str_replace(ROOT_DIR."/uploads/posts/" , '', $poster);
					}
				} else {
					$request['poster'] = $value_data['poster'];
				}
			
			
			    $compile = template($config_mod, $request);
			    
			    $compile['metatitle'] = check_if_alloha($compile['metatitle'], $request);
			    $compile['metatitle'] = preg_replace('/\s{2,}/', ' ',  $compile['metatitle']);


			    if($compile['category']=='') $compile['category']=0;
			    if(!$compile['tags']) $compile['tags'] = '';


			    $compile['xfields'] = !$alloha['news_id'] ? xfcompile($compile['xfields']) : xfcompile($xfdata);
			    $compile['alt_name'] = totranslit( stripslashes( $compile['alt_name'] ), true, false );
			    $compile['date'] = date('Y-m-d H:i:s');


			    if (empty($compile['short_story'])) {
					$compile['short_story'] = '';
			    }

			    if (empty($compile['full_story'])) {
					$compile['full_story'] = '';
			    }

			    if (empty($compile['keywords'])) {
					$compile['keywords'] = '';
			    }

			    if (empty($compile['descr'])) {
					$compile['descr'] = '';
			    }


			    $approve =1;
			    if($config_mod['go_moder_trailer'])   $approve =0;



			    $disable_index = 0;
			    if (!empty($config_mod['disable_index'])
				    && (bool)$config_mod['disable_index'] === true
			    ) {
				    $disable_index = 1;
			    }

			    $updateNewsDate = false;
			    if (!empty($config_mod['update_news_date'])
				    && (bool)$config_mod['update_news_date'] === true
			    ) {
				   $updateNewsDate = true;
			    }

			    $last_season = $request['last_season'];
			    $last_episode = $request['last_episode'];
			    $user_row = $db->super_query(" SELECT user_id, name FROM " . PREFIX . "_users WHERE name='{$config_mod['author']}' ");


			
				$db->super_query( "INSERT INTO " . PREFIX . "_alloha (kp_id, year, status, quality, type, episode, season) VALUES('{$kp_id}', '{$year}', '1', '{$quality}', '{$type}', '{$episode}', '{$season}')" );
				
				$db->query(db_query("INSERT INTO `" . PREFIX . "_post` (`autor`, `date`, `short_story`, `full_story`, `xfields`, `title`, `descr`, `keywords`, `category`, `alt_name`, `comm_num`, `allow_comm`, `allow_main`, `approve`, `fixed`, `allow_br`, `symbol`, `tags`, `metatitle`) VALUES ('{$user_row['name']}', :date, :short_story, :full_story, :xfields, :title, :descr, :keywords, :category, :alt_name, 0, 1, 1, $approve, 0, 0, '', :tags, :metatitle);", $compile));


                
				$news_id = $db->insert_id();
				$db->query( "INSERT INTO " . PREFIX . "_post_extras (news_id,user_id,disable_index) VALUES('$news_id','{$user_row['user_id']}', '$disable_index')" );

				if($poster){
					$db->query( "INSERT INTO " . PREFIX . "_images (images,news_id,author,date) VALUES('{$poster}','$news_id','{$user_row['name']}','{$_TIME}')" );
				}

				alloha_mass_series($news_id, $result);

				echo "insert news --- $news_id --- {$value_data['name']}"; 
				
			
				
if( $news_id){
	$db->query(db_query("Update `" . PREFIX . "_post` set kinopoisk_id='".$request['kinopoisk_id']."' where id='".$news_id."'"));


                
    $ex_cats = explode(',', $compile['category']);
    foreach ($ex_cats as $ex_cat) {
        $ex_cat = intval($ex_cat);
        $db->query( "INSERT INTO " . PREFIX . "_post_extras_cats (news_id, cat_id) VALUES ('{$news_id}', '{$ex_cat}')" );
    }
}
			}

		   }
		   
		  if($kl_next) $res['next_page']++;
		  $config_mod=$global_config;
	   } 

	   }
	   
    }

    function getLog(){
    	$log = unserialize( file_get_contents( ENGINE_DIR . '/data/alloha.log' ) );
    	if (!$log) $log = array();
    	return $log;
    }

    function setLog($type, $name, $val){
    	$this->log[$type][$name] = $val;
    	file_put_contents( ENGINE_DIR . '/data/alloha.log', serialize($this->log));
    }

}


?>