<?php

if (version_compare('15', $config['version_id'], '<=')) {
    include_once ENGINE_DIR . '/classes/composer/vendor/autoload.php';
}

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

if (!function_exists('xfieldsdatasave')) {
    function xfieldsdatasave($xfields) {
        $filecontents = [];
        foreach ($xfields as $xfielddataname => $xfielddatavalue) {
            if ($xfielddatavalue === '') continue;
            $xfielddataname = str_replace( "|", "&#124;", $xfielddataname);
            $xfielddataname = str_replace( "\r\n", "__NEWL__", $xfielddataname);
            $xfielddatavalue = str_replace( "|", "&#124;", $xfielddatavalue);
            $xfielddatavalue = str_replace( "\r\n", "__NEWL__", $xfielddatavalue);
            $filecontents[] = "$xfielddataname|$xfielddatavalue";
        }
        $filecontents = join('||', $filecontents );
        return $filecontents;
    }
}


if (!function_exists('xfcompile')) {
    function xfcompile( $in ) {
        if ( $in == "" ) return $in;

        foreach ( $in as $name => $value ) {
            if ( trim($name) == "" || trim($value) == "" ) continue;

            $name = str_replace( "|", "&#124;", $name );
            $name = str_replace( "\r\n", "__NEWL__", $name );
            $value = str_replace( "|", "&#124;", $value );
            $value = str_replace( "\r\n", "__NEWL__", $value );

            $out[] = "{$name}|{$value}";
        }

        return implode("||", $out);
    }
}


if (!function_exists('CheckDir')) {
    function CheckDir($dir){
        if( !is_dir( $dir ) ) {
            @mkdir( $dir, 0777 );
            @chmod( $dir, 0777 );
        }
    }
}


if (!function_exists('request')) {
    function request($url, $file = false){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60 );
        curl_setopt($ch, CURLOPT_TIMEOUT, 60 );
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);

        $headers = array(
            'User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.2924.87 Safari/537.36',
            'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
            'Accept-Language: ru-RU,ru;q=0.8,en-US;q=0.5,en;q=0.3',
            'Connection: keep-alive',
            'Cache-Control: max-age=0',
            'Upgrade-Insecure-Requests: 1'
        );
        if($file){
            $fp = fopen($file, "wb");
            curl_setopt($ch, CURLOPT_FILE, $fp);
        }
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        $res = curl_exec($ch);
        curl_close($ch);
        if($file) {
            fclose($fp);
            @chmod($file, 0666);
            $info = @getimagesize($file);
            if(is_array($info)){
                if( $info[2] == 2 ) {
                    $ext = 'jpg';
                } elseif( $info[2] == 3 ) {
                    $ext =  'png';
                } elseif( $info[2] == 1 ) {
                    $ext = 'gif';
                } elseif($info['mime'] == 'image/webp' or $info['mime'] == 'image/x-webp') {
                    $ext = 'webp';    
                } else $ext = 'jpg';
                $GLOBALS['EXT'] = $ext;
                rename($file, $file.'.'.$ext);
                return $file.'.'.$ext;
            } else {
                @unlink($file);
                return false;
            }
        }
        return $res;
    }
}


if (!function_exists('template')) {
    function template($config, $data) {
        $find = array();
        $replace = array();

        foreach ($data as $name => $value) {
            if ( is_array($value) ) $value = implode(", ", $value);

            $find[] = "'{{$name}}'i";
            $replace[] = $value;
            $find[] = "'\\[if_{$name}\\](.*?)\\[/if_{$name}\\]'is";
            $replace[] = $value ? '\1' : '';
            $find[] = "'\\[ifnot_{$name}\\](.*?)\\[/ifnot_{$name}\\]'is";
            $replace[] = $value ? '' : '\1';
        }

        foreach ($config as $key => $value) {
            $value = preg_replace($find, $replace, $value);

            $value = preg_replace_callback('#\\[(if|ifnot)? (.+?)\\](.*?)\\[/\1\\]#isuU', function($matches) use($data) {
                foreach (explode("||", $matches[2]) as $key => $value) {
                    $value = explode("=", $value);
                    $name = array_shift($value);
                    $value = implode("=", $value);
                    $value = explode("|", $value);

                    if ( isset($data[$name]) ) {
                        $val = $data[$name];
                        if ( !is_array($val) ) $val = explode(",", $val);
                        if ( array_intersect($value, $val) ) {
                            if ( $matches[1] == "ifnot" ) return '';
                        } elseif( $matches[1] == "if" ) return '';
                    }
                }

                return $matches[3];
            }, $value);

            $value = preg_replace('#\\[ifnot_(.+)\\](.*)\\[/ifnot_\1\\]#isuU', '\2', $value);
            $value = preg_replace('#\\[if_(.+)\\](.*)\\[/if_\1\\]#isuU', '', $value);
            $value = preg_replace("'{[a-zA-Z0-9-_:]+}'i", '', $value);

            if ( $value ) $config[$key] = preg_replace('#\s{2,}#', ' ', $value);
            else unset($config[$key]);
        }

        return $config;
    }
}



if (!function_exists('fixGenres')) {
    
    function fixGenres(array $genres) {

        $replaces = array(
            'арт-хаус' => 'арт-хаус',
            'зарубежные' => 'зарубежный',
            'блокбастеры' => 'блокбастер',
            'русский' => 'русский',
            'биографический' => 'биография',
            'боевики' => 'боевик',
            'блокбастер' => 'блокбастер',
            'вестерны' => 'вестерн',
            'военные' => 'военный',
            'детективы' => 'детектив',
            'детский' => 'детский',
            'документальные' => 'документальный',
            'драмы' => 'драма',
            'игры' => 'игра',
            'история' => 'история',
            'комедии' => 'комедия',
            'концерты' => 'концерт',
            'короткометражный' => 'короткометражка',
            'полнометражный' => 'полнометражный',
            'криминал' => 'криминал',
            'мелодрамы' => 'мелодрама', 
            'музыкальные' => 'музыка',
            'мультфильмы' => 'мультфильм',
            'мультсериалы' => 'мультсериал',
            'мюзикл' => 'мюзикл',
            'новости' => 'новости',
            'путешествия' => 'путешествия',
            'приключения' => 'приключения',
            'развлекательный' => 'развлекательный',
            'семейные' => 'семейный',
            'спортивный' => 'спортивный',
            'триллеры' => 'триллер',
            'ужасы' => 'ужасы',
            'церемонии' => 'церемония',
            'для взрослых' => 'для взрослых',
        );

        foreach ($genres as $key => $genre) {
            $genre = mb_strtolower($genre, 'UTF-8');

            if (!empty($replaces[$genre])) {
                $genres[$key] = $replaces[$genre];
            } else {
                $genres[$key] = $genre;
            }
        }

        return $genres;
    }
}





if (!function_exists('db_query')) {
    function db_query($query, $data = false) {
        return preg_replace_callback('":([a-z0-9_\\-]+)"is', function($match) use($data) {
            if ( isset($data[$match[1]]) ) {
                if ($data[$match[1]] !== null) {
                    return "'" . addslashes($data[$match[1]]) . "'";
                } else {
                    return "NULL";
                }

            } else {
                return "NULL";
            }
        }, $query);
    }    
}



if (!function_exists('xfparamload')) {
    function xfparamload( $xfname ) {
        $path = ENGINE_DIR . '/data/xfields.txt';
        $filecontents = file( $path );
        
        foreach ( $filecontents as $name => $value ) {
            $filecontents[$name] = explode( "|", trim( $value ) );
            if($filecontents[$name][0] == $xfname ) return $filecontents[$name];
        }
        return false;
    }    
}


if (!function_exists('upload_image')) {
    function upload_image($image_url, $file, $xfparam) {
        global $config;

        $folder = ROOT_DIR . "/uploads/posts/" . FOLDER_PREFIX;

        $image = request($image_url, $file);

        $old_image = $image;

        if ( !$image ) return false;

        if ( $xfparam[9] ) {

            $t_seite = intval($config['t_seite']);
            $t_size = $xfparam[9];
            
            $thumb = new thumbnail( $image );
            
            if( $thumb->size_auto( $t_size, $t_seite ) ) {
                               
                if (version_compare('15', $config['version_id'], '<=')) {
                    
                    $newFile = $thumb->save(str_replace(ROOT_DIR."/uploads/" , '', $image));

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

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

                }

            }

            else if (version_compare('15', $config['version_id'], '<=')) {
                $newFile = $thumb->save(str_replace(ROOT_DIR."/uploads/" , '', $image));
                $image = ROOT_DIR . "/uploads/posts/" . FOLDER_PREFIX . '/' . $newFile;
            }

            @chmod( $image, 0666 );

        }    

        else if (version_compare('15', $config['version_id'], '<=')) {
            $thumb = new thumbnail( $image );
            $newFile = $thumb->save(str_replace(ROOT_DIR."/uploads/" , '', $image));
            $image = ROOT_DIR . "/uploads/posts/" . FOLDER_PREFIX . '/' . $newFile;
        }

        if ( $xfparam[13] ) {

            $t_seite = intval($config['t_seite']);
            $t_size = $xfparam[13];

            $thumb = new thumbnail( $image );

            if( $thumb->size_auto( $t_size, $t_seite ) ) {

                if (version_compare('15', $config['version_id'], '<=')) {
                    
                    $newFile = $thumb->save(thumb_path($image));

                    $image = $folder . '/thumbs/' . $newFile;

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

                }

                $filename = basename($image);

            }

            else if (version_compare('15', $config['version_id'], '<=')) {
                $newFile = $thumb->save(thumb_path($image));
                $image = $folder . '/thumbs/' . $newFile;
            }

            @chmod( $image, 0666 );

        }

        else if (version_compare('15', $config['version_id'], '<=')) {
            $newFile = $thumb->save(thumb_path($image));
            $image = $folder . '/thumbs/' . $newFile;
        }


        if ($config['force_webp'] && $GLOBALS['EXT']!='webp' ) {
           @unlink($old_image);
        }

        $filename = basename($image);

        return FOLDER_PREFIX . '/' . $filename;
    }    
}


function thumb_path($image) {
    $image = str_replace(ROOT_DIR."/uploads/" , '', $image);
    $image = preg_replace('#posts/(\d\d\d\d)-(\d\d)/#', 'posts/\\1-\\2/thumbs/', $image);
    return $image;
}


if (!function_exists('allow_country')) {
    function allow_country($country, $allow_country){
        if (count($allow_country)) {
            $country2 = [];
            foreach ($country as $value) {
                $country2[] = mb_strtolower($value, 'utf-8');
            }
            if (count(array_intersect($country2, $allow_country))) {
                return true;
            } else {
                return false;
            }
        }
        return true;
    }    
}



if (!function_exists('disallow_country')) {
    function disallow_country($country, $allow_country){
        if (count($allow_country)) {
            $country2 = [];
            foreach ($country as $value) {
                $country2[] = mb_strtolower($value, 'utf-8');
            }
            if (count(array_intersect($country2, $allow_country))) {
                return true;
            } else {
                return false;
            }
        }
        return false;
    }    
}



if (!function_exists('upload_screenshots')) {
   function upload_screenshots($res, $kp_id = false) {
       $xfparam = xfparamload('screenshots');
       $screenshots = [];
       $max_screens = $xfparam[16] ? intval($xfparam[16]) : 0;

       $kp_id = $kp_id ? $kp_id : uniqid();

       foreach ($res['screenshots'] as $k => $screenshot) {
           $index = $k+1;
           if ($max_screens && $index>$max_screens) {
               break;
           }
           $name = $kp_id.'_'.(time()+rand( 1, 100 ));
           $screen = upload_image($screenshot, ROOT_DIR . "/uploads/posts/" . FOLDER_PREFIX.'/' .$name, $xfparam);
           if($screen){
               $screenshots[] = $screen;
           }
       }

       return $screenshots;
   } 
}


if (!function_exists('upload_kadr')) {

   function upload_kadr($url, $name) {

       $xfparam = xfparamload('kadr');

       $kadr = upload_image($url, ROOT_DIR . "/uploads/posts/" . FOLDER_PREFIX.'/' .$name, $xfparam);

       return $kadr;
   } 

}



if (!function_exists('upload_poster')) {
    function upload_poster($res, $kp_id) {

        global $config, $config_kodik;

        $poster_file = $kp_id.'_'.time();

        $poster = request($res['material_data']['poster_url'], ROOT_DIR . "/uploads/posts/" . FOLDER_PREFIX.'/' .$poster_file);

        $old_poster = $poster;

        if (!$poster) {
            return false;
        }

        $t_seite = intval($config['t_seite']);
        $t_size = $config_kodik['poster_size'];

        $thumb = new thumbnail( $poster );

        if( $thumb->size_auto( $t_size, $t_seite ) ) {

           if (version_compare('15', $config['version_id'], '<=')) {
               
                $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 );

            }

        }

        else if (version_compare('15', $config['version_id'], '<=')) {
            $newFile = $thumb->save(str_replace(ROOT_DIR."/uploads/" , '', $poster));
            $poster = ROOT_DIR . "/uploads/posts/" . FOLDER_PREFIX . '/' . $newFile;
        }

        if ($config['force_webp'] && $GLOBALS['EXT']!='webp' ) {
            @unlink($old_poster);
        }

        @chmod( $poster, 0666 );

        return $poster;
    }    
}



function formatize_kodik($number, $type) {
    if ( $type == 1 ) $result = $number." сезон";
    elseif ( $type == 2 ) {
        if ( $number == 1 ) $result = $number." сезон";
        elseif ( $number > 1 ) $result = "1-".$number." сезон";
    }
    elseif ( $type == 3 ) {
        if ( $number == 1 ) $result = $number." сезон";
        elseif ( $number > 1 ) {
            $number_mas = array();
            for ($i = 1; $i <= $number; $i++) {
                $number_mas[] = $i;
            }
            $result = implode(",", $number_mas)." сезон";
        }
    }
    elseif ( $type == 4 ) $result = $number." серия";
    elseif ( $type == 5 ) {
        if ( $number == 1 ) $result = $number." серия";
        elseif ( $number > 1 ) $result = "1-".$number." серия";
    }
    elseif ( $type == 6 ) {
        if ( $number == 1 ) $result = $number." серия";
        elseif ( $number > 1 ) {
            $number_mas = array();
            for ($i = 1; $i <= $number; $i++) {
                $number_mas[] = $i;
            }
            $result = implode(",", $number_mas)." серия";
        }
    }
    elseif ( $type == 7 ) {
        if ( $number == 1 ) $result = "1,2 серия";
        elseif ( $number == 2 ) $result = "1,2,3 серия";
        elseif ( $number > 2 ) {
            $number_mas = array();
            for ($i = $number-1; $i <= $number+1; $i++) {
                $number_mas[] = $i;
            }
            $result = implode(",", $number_mas)." серия";
        }
    }
    elseif ( $type == 71 ) {
        if ( $number == 1 ) $result = "1 серия";
        elseif ( $number == 2 ) $result = "1,2 серия";
        elseif ( $number >= 3 ) {
            $number_mas = array();
            for ($i = $number-2; $i <= $number; $i++) {
                $number_mas[] = $i;
            }
            $result = implode(",", $number_mas)." серия";
        }
    }
    elseif ( $type == 8 ) {
        if ( $number == 1 ) $result = "1 серия";
        elseif ( $number > 1 AND $number <= 5 ) {
            $number_mas = array();
            for ($i = 1; $i <= $number; $i++) {
                $number_mas[] = $i;
            }
            $result = implode(",", $number_mas)." серия";
        }
        elseif ( $number > 5 ) {
            $number_mas = array();
            for ($i = $number-1; $i <= $number+1; $i++) {
                $number_mas[] = $i;
            }
            $result = "1-".implode(",", $number_mas)." серия";
        }
    }
    elseif ( $type == 81 ) {
        if ( $number == 1 ) $result = "1 серия";
        elseif ( $number > 1 AND $number <= 5 ) {
            $number_mas = array();
            for ($i = 1; $i <= $number; $i++) {
                $number_mas[] = $i;
            }
            $result = implode(",", $number_mas)." серия";
        }
        elseif ( $number > 5 ) {
            $number_mas = array();
            for ($i = $number-2; $i <= $number; $i++) {
                $number_mas[] = $i;
            }
            $result = "1-".implode(",", $number_mas)." серия";
        }
    }
    return $result;
}

function check_if_kodik($check_value, $dataArray) {
    foreach($dataArray as $named => $zna4enie) {
        if (strpos($check_value, '[data_'.$named.']') !== false) {
            if ($zna4enie) $check_value = preg_replace(';\[data_'.$named.'\](.*?)\[\/data_'.$named.'\];ius', $dataArray[$named], $check_value);
            else $check_value = preg_replace(';\[data_'.$named.'\](.*?)\[\/data_'.$named.'\];ius', '', $check_value);
        }
        if (strpos($check_value, '[nodata_'.$named.']') !== false) {
            if ($zna4enie) $check_value = preg_replace(';\[nodata_'.$named.'\](.*?)\[\/nodata_'.$named.'\];ius', '', $check_value);
            else $check_value = preg_replace(';\[nodata_'.$named.'\](.*?)\[\/nodata_'.$named.'\];ius', '$1', $check_value);
        }
    }

    return $check_value;
}


function kodik_mass_series(&$kadry, $news_id, $res) {

    global $config_kodik, $db, $serials;

    if (!$config_kodik['mass_series']) {
        return;
    }

    set_time_limit(0);

    for ($sez=1; $sez <= $res['last_season']; $sez++) { 

        foreach ($serials[$sez] as $ser => $url_kadr) {

            $row = $db->super_query(" SELECT * FROM " . PREFIX . "_serials WHERE news_id='{$news_id}' AND season='{$sez}' AND episode='{$ser}'");

            $kadr = '';

            if (!$row && $config_kodik['upload_kadr']) {
                
                $name = 'kadr_'.$news_id.'_'.$sez.'_'.$ser;
                $kadr = upload_kadr($serials[$sez][$ser], $name);
                
                if ($kadr) {
                    $kadry[] = $kadr;
                }

            }

            $moder = $config_kodik['moder_series'] ? 1 : 0;

            $db->query( "INSERT IGNORE INTO " . PREFIX . "_serials (news_id, season, episode, kadr, moder) VALUES('{$news_id}', '{$sez}', '{$ser}', '{$kadr}', '{$moder}')" );

        }

        // for ($ser=1; $ser <= count($serials[$sez]); $ser++) { }

    }
    
}


function check_license_kodik() {
    global $config_kodik;
    preg_match('#[^.]+\.[^.]+$#', trim(getenv('HTTP_HOST')), $host);
    if(md5($host[0].'kodik_grab-v2.2.evo')!=$config_kodik['lickey']) {
       // die('{"error": "Требуется лицензионный ключ"}');
    }
}


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

CheckDir(ROOT_DIR . "/uploads/posts/" . FOLDER_PREFIX .'/');
CheckDir(ROOT_DIR . "/uploads/posts/" . FOLDER_PREFIX .'/thumbs/');
CheckDir(ROOT_DIR . "/uploads/posts/" . FOLDER_PREFIX .'/medium/');


?>