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

    function getPage( $url ) {
        if ( $this->page = $this->curl->saveToString($url) ) {
            $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>/ms', $this->page, $matches);
        if ( isset($matches['0']) ) {
            $title  = $matches['0'];
            $title  = str_replace('<h1>', '', $title);
            $title  = str_replace('</h1>', '', $title);
            return $title;
        }
    }
    
    function getVideoTags()
    {
        preg_match_all('/<a href\="\/video\/search\?search\=(.*?)\">(.*?)<\/a>/ms', $this->page, $matches);
        if ( isset($matches['0']) ) {
            $tag_links  = $matches['0'];
            $tags       = array();
            foreach ( $tag_links as $link ) {
                preg_match('/>(.*?)<\/a>/ms', $link, $matches_tag);
                if ( isset($matches_tag['0']) ) {
                    $tag    = str_replace('>', '', $matches_tag['0']);
                    $tag    = str_replace('</a', '', $tag);
                    $tags[] = $tag;
                }
            }
            
            return implode(' ', $tags);
        }
    }
    
    function getVideoCategory()
    {
        return true;
    }
    
    function getVideoId()
    {
        preg_match('/pornhub.com\/watch_player.php\?id\=(.*?)\"\);/ms', $this->page, $matches);
        if ( isset($matches['0']) ) {
            $video_id   = str_replace('pornhub.com/watch_player.php?id=', '', $matches['0']);
            $video_id   = str_replace('");', '', $video_id);            
            
            return $video_id;
        }
    }
    
    function getPlayerConfigUrl()
    {
        preg_match('/http:\/\/www.pornhub.com\/watch_player_with_related_videos.php\?id=(.*?)\"/ms', $this->page, $matches);
        if ( isset($matches['0']) ) {
            return str_replace('"', '', $matches['0']);
        } else {
            preg_match('/http:\/\/www.pornhub.com\/watch_player.php\?id=(.*?)\"/ms', $this->page, $matches);
            if ( isset($matches['0']) ) {
                return str_replace('"', '', $matches['0']);
            } else {
				preg_match('/to.addVariable\(\"options\"\, \"http%3A%2F%2Fwww.pornhub.com%2Fmx_player_config.php(.*?)\"\)\;/ms', $this->page, $matches);
				if ( isset($matches['0']) ) {
					$player_config = str_replace('to.addVariable("options", "', '', $matches['0']);
					$player_config = str_replace('");', '', $player_config);
					return urldecode($player_config);
				}
			}
        }
    }
    
    function getVideoUrl()
    {
        $player_config_url  = $this->getPlayerConfigUrl();
        $this->getPage($player_config_url);
        preg_match('/<flv_url>(.*?)<\/flv_url>/ms', $this->page, $matches);
        if ( isset($matches['0']) ) {
            $url    = str_replace('<flv_url>', '', $matches['0']);
            $url    = str_replace('</flv_url>', '', $url);
            
            return $url;
        }
    }
    
    function getVideos( $items=0 )
    {
        $videos             = 0;
        $page               = 1;
        $this->categories   = get_categories();
        while ( $videos <= $items ) {
    	    echo 'Video: ' .$videos. "\n";
    	    echo 'http://www.pornhub.com/video?o=mr&page=' .$page. "\n";
            $this->getPage('http://www.pornhub.com/video?o=mr&page=' .$page);
            preg_match_all('/\/view_video.php\?viewkey=(.*?)">/', $this->page, $matches);
            if ( isset($matches['1']) ) {
                foreach ( $matches['1'] as $vkey ) {
                    if ( $this->getVideo($vkey) ) {
                        if ( $videos >= $items ) {
                            break;
                        }
                        ++$videos;
                    }
                }
            }
            ++$page;                
        }
    }
    
    function getVideo( $vkey )
    {
        global $conn, $config;
    
        $this->getPage('http://www.pornhub.com/view_video.php?viewkey=' .$vkey);
        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';
                    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;
        }
    }
}
