<?php

/**
 * Description of Vimeo
 *
 * @author Nexthon
 */
/*
  {source_info}{"name":"Vimeo.com","website":"https:\/\/www.vimeo.com\/"}{end_source_info}
 */
class Vimeo
{

    public function getVimeoVideoIdFromUrl($url = '')
    {

        $regs = array();

        $id = '';

        if (preg_match('%^https?:\/\/(?:www\.|player\.)?vimeo.com\/(?:channels\/(?:\w+\/)?|groups\/([^\/]*)\/videos\/|album\/(\d+)\/video\/|video\/|)(\d+)(?:$|\/|\?)(?:[?]?.*)$%im', $url, $regs))
        {
            $id = $regs[3];
        }

        return $id;
    }

    /*     * * Get Vimeo Video Info ** */

    public function getMediaInfo($url)
    {
        $data = array();
		
        $data['found'] = 0;
		
        $id = $this->getVimeoVideoIdFromUrl($url);
		
        if (is_numeric($id))
        {
            $result = getRemoteContents("https://vimeo.com/api/v2/video/" . $id . ".json");
			
            if ($result)
            {
                $result = json_decode($result, true);
                $data['id'] = $id;
                $data['found'] = 1;
                $title = (isset($result[0]['title']) ? htmlentities($result[0]['title'], ENT_QUOTES) : "Video By Vimeo");
                $data['title'] = $title;
                if (isset($result[0]['description']) && !empty($result[0]['description']))
                {
                    $data['description'] = htmlentities(truncate(trim(preg_replace('/[\s]+/', ' ', preg_replace("/\r|\n/", " ", $result[0]['description']))), 250), ENT_QUOTES);
                } else
                {
                    $data['description'] = "Download " . $title . " From Vimeo";
                }
                $data['image'] = (isset($result[0]['thumbnail_large']) ? $result[0]['thumbnail_large'] : $result[0]['thumbnail_medium']);
                $duration = $result[0]['duration'];
                $data['time'] = gmdate(($duration > 3600 ? "H:i:s" : "i:s"), $duration);
                $data['embedIframeDirect'] = "false";
                $embedIframe = '<div id="loader-iframe" class="p-t-40 p-b-40 text-center"><img src="' . base_url("assets/images/loader.svg") . '" /></div><iframe class="hide" id="player-id" src="https://player.vimeo.com/video/' . $id . '?title=0&byline=0&portrait=0&badge=0&api=1" width="100%" height="360" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>';
                $data['embedIframe'] = $embedIframe;
                $data['scriptFiles'] = '<script src="' . base_url("assets/js/vimeo-player.min.js") . '"></script>';
                $data['script'] = '$("#embedModal").one("show.bs.modal",function() { $("#player-body").html(\'' . $embedIframe . '\'); $("#player-id").on("load", function() { $("#loader-iframe").remove(); $(this).removeClass("hide"); }); }); $("#embedModal").on("hide.bs.modal",function(){ var iframe = $("#player-id")[0]; var player = $f(iframe); player.api("pause");});';
                $formatCodes = array(
                    "270p" => array("order" => "1", "height" => "270", "ext" => "mp4", "resolution" => "270p", "video" => "true", "video_only" => "false"),
                    "360p" => array("order" => "2", "height" => "360", "ext" => "mp4", "resolution" => "360p", "video" => "true", "video_only" => "false"),
                    "540p" => array("order" => "3", "height" => "540", "ext" => "mp4", "resolution" => "540p", "video" => "true", "video_only" => "false"),
                    "720p" => array("order" => "4", "height" => "720", "ext" => "mp4", "resolution" => "720p", "video" => "true", "video_only" => "false"),
                    "1080p" => array("order" => "5", "height" => "1080", "ext" => "mp4", "resolution" => "1080p", "video" => "true", "video_only" => "false")
                );
                
                $videoFormatsData = getRemoteContents("https://player.vimeo.com/video/" . $id);
                
                $videoFormatsData = getStringBetween($videoFormatsData, '"request":{"files":', ',"lang":"en"');
				
                $videoFormatsData = json_decode($videoFormatsData, true);

                $videoStreams = $videoFormatsData['progressive'];
                
                $videos = array();
				
                foreach ($videoStreams as $stream)
                {
                    $formatId = $stream['quality'];
                    if (array_key_exists($formatId, $formatCodes))
                    {
                        $link = array();
                        $formatData = $formatCodes[$formatId];
                        $link['data'] = $formatData;
                        $link['formatId'] = $formatId;
                        $link['order'] = $formatData['order'];
                        $link['url'] = $stream['url'];
                        $link['title'] = $title . "." . $formatData['ext'];
                        $link['size'] = "unknown";
                        
                        if(!isset($videos[$link['formatId']]))
                        {
                            $videos[$link['formatId']] = $link;
                        }
                        
                    }
                }
                
                $orders = array();
				
                foreach ($videos as $key => $row)
                {
                    $orders[$key] = $row['order'];
                }
				
                array_multisort($orders, SORT_DESC, $videos);
				
                $data['videos'] = $videos;
            }
        }
        return $data;
    }

}
