<?php
class VGrab_youporn
{
    var $url;
    var $page;
    var $curl;
    function __construct()
    {
        $this->curl = new VCurl();
    }
    
    function VGrab_youporn()
    {
        $this->__construct();
    }

    function getPage( $url ) {
        $this->url  = $url;
        if ( $this->page = $this->curl->saveToString($url, 'age_check=1;') ) {
            $this->page = trim($this->page);
            $this->page = str_replace("\n", '', $this->page);
            $this->page = str_replace("\r", '', $this->page);
            $this->page = preg_replace('/\s\s+/', ' ', $this->page);
            return true;
        }
        
        return false;
    }
    
    function getVideoTitle()
    {
        preg_match('/<h1>(.*?)<\/h1>/', $this->page, $matches);        
        if ( isset($matches['0']) ) {
            $title  = str_replace('<h1>', '', $matches['0']);
            $title  = str_replace('</h1>', '', $title);
            
            return trim(strip_tags($title));
        }
    }
    
    function getVideoTags()
    {
        $tags   = $this->getVideoTitle();
        $tags   = ereg_replace('[^ 0-9a-zA-Z]', ' ', $tags);
        $tags   = preg_replace('/\s\s+/', ' ', $tags);
        
        return trim($tags);
    }
    
    function getVideoCategory()
    {
        return NULL;
    }
    
    function getVideoId()
    {
        $url_array      = explode('/', $this->url);
        foreach ( $url_array as $key => $value ) {
            if ( $value == 'watch' ) {                
                return $url_array[$key+1];
            }
        }
    }
    
    function getVideoUrl()
    {
        preg_match('/<h2>Download:<\/h2>(.*?)<\/ul>/', $this->page, $matches);
        if ( isset($matches['0']) ) {
            preg_match('/<p>(.*?).<\/p>/', $matches['0'], $matches_url);
            if ( isset($matches_url['0']) ) {
                $url    = str_replace('<p><a href="', '', $matches_url['0']);
                $pos    = strpos($url, '"');
                return substr($url, 0, $pos);
            }
        }
    }
    
    function getVideos( $items=0 )
    {
        $items              = intval($items);
        $videos             = 0;
        $page               = 1;
        $this->categories   = get_categories();
        while ( $videos <= $items ) {
            echo 'Items: ' .$items. "\n";
            echo 'Video: ' .$videos. "\n";
            echo 'http://www.youporn.com/?page=' .$page. "\n";
            $this->getPage('http://www.youporn.com/?page=' .$page, 'age_check=1;');
            preg_match_all('/<a href="\/watch\/(.*?)\/(.*?)\/">/', $this->page, $matches);
            if ( isset($matches['1']) ) {
                foreach ( $matches['1'] as $video_id ) {
                    if ( $this->getVideo($video_id) ) {
                        ++$videos;
                        if ( $videos >= $items ) {
                            break;
                        }
                    }
                }
            }
            ++$page;
        }
    }
    
    function getVideo( $video_id )
    {
        global $conn, $config;

        $this->getPage('http://www.youporn.com/watch/' .$video_id. '/');
        if ( strlen($this->page) > 100 ) {
            $title         = $this->getVideoTitle();
            $tags          = $this->getVideoTags();
            $category      = $this->getVideoCategory();
            foreach ( $this->categories as $category_site ) {
                if ( $category_site['name']. 's' == $category or $category_site['name'] == $category ) {
                    $category = $category_site['CHID'];
                    break;
                }
            }
            if ( !is_int($category) ) {
                $category = 0;
            }
            $v_site_id              = $this->getVideoId();
            $sql                    = "SELECT site FROM grab WHERE site = 'pornhub' AND id = '" .mysql_real_escape_string($v_site_id). "' LIMIT 1";
            $conn->execute($sql);
            if ( $conn->Affected_Rows() == 0 ) {
                $url       = $this->getVideoUrl();
                if ( $url ) {
                    $sql        = "SELECT UID FROM signup WHERE username = 'anonymous' LIMIT 1";
                    $rs         = $conn->execute($sql);
                    $uid        = intval($rs->fields['UID']);
                    $type       = 'public';
                    $sql        = "INSERT INTO video (UID, title, channel, vkey, keyword, type, addtime, adddate, active)  
                                   VALUES (" .$uid. ", '" .mysql_real_escape_string($title). "', channel = " .$category. ", 
                                           '" .mt_rand(). "', '" .mysql_real_escape_string($tags). "',  
                                           '" .$type. "', '" .time(). "', '" .date('Y-m-d'). "', '0')";
                    $conn->execute($sql);
                    $vid        = mysql_insert_id();
                    $dst        = $config['BASE_DIR']. '/media/videos/flv/' .$vid. '.flv';
                    echo var_dump($url). "\n";
                    if ( !$this->curl->saveToFile($url, $dst) ) {
                        $sql        = "DELETE FROM video WHERE VID = " .$vid. " LIMIT 1";
                        $conn->execute($sql);
                        return false;
                    } else {
                        extract_video_thumbs($dst, $vid);
                        $duration   = get_video_duration($dst, $vid);
                        $size       = filesize($dst);
                        $vkey       = substr(md5($vid),11,20);
                        $vdoname    = $vid. '.flv';
                        $flvdoname  = $vid. '.flv';
                        $sql        = "UPDATE video SET duration = '" .mysql_real_escape_string($duration). "', vkey = '" .$vkey. "',  
                                                        vdoname = '" .mysql_real_escape_string($vdoname). "', flvdoname = '" .mysql_real_escape_string($flvdoname). "',
                                                        space = " .$size. ", active = '1' 
                                       WHERE VID = " .intval($vid). " LIMIT 1";
                        $conn->execute($sql);
                        $sql        = "UPDATE channel SET total_videos = total_videos+1 WHERE CHID = " .$category. " LIMIT 1";
                        $conn->execute($sql);
                        $sql        = "INSERT INTO grab (site, id) VALUES ('pornhub', '" .mysql_real_escape_string($v_site_id). "')";
                        $conn->execute($sql);
                        return true;
                    }
                } else {
                    return false;
                }
            } else {
                return false;
            }
        } else {
            return false;
        }                                                                                                                                                                               
    }
}
