<?php

if (basename($_SERVER['PHP_SELF']) == basename(__FILE__)) {
    die('Error , cannot Access To this File .');
}

function get_host() {
    if ($host = $_SERVER['HTTP_X_FORWARDED_HOST'])
    {
        $elements = explode(',', $host);

        $host = trim(end($elements));
    }
    else
    {
        if (!$host = $_SERVER['HTTP_HOST'])
        {
            if (!$host = $_SERVER['SERVER_NAME'])
            {
                $host = !empty($_SERVER['SERVER_ADDR']) ? $_SERVER['SERVER_ADDR'] : '';
            }
        }
    }

    // Remove port number from host
    $host = preg_replace('/:\d+$/', '', $host);

    return trim($host);
}
function getRealIP(){
    if( isset($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR'] != '' ){
        $client_ip =
            ( !empty($_SERVER['REMOTE_ADDR']) ) ?
                $_SERVER['REMOTE_ADDR']
                :
                ( ( !empty($_ENV['REMOTE_ADDR']) ) ?
                    $_ENV['REMOTE_ADDR']
                    :
                    "unknown" );

        $entries = preg_split('[, ]', $_SERVER['HTTP_X_FORWARDED_FOR']);

        reset($entries);
        while (list(, $entry) = each($entries)){
            $entry = trim($entry);
            if ( preg_match("/^([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)/", $entry, $ip_list) ){
                // http://www.faqs.org/rfcs/rfc1918.html
                $private_ip = array(
                    '/^0\./',
                    '/^127\.0\.0\.1/',
                    '/^192\.168\..*/',
                    '/^172\.((1[6-9])|(2[0-9])|(3[0-1]))\..*/',
                    '/^10\..*/');

                $found_ip = preg_replace($private_ip, $client_ip, $ip_list[1]);

                if ($client_ip != $found_ip){
                    $client_ip = $found_ip;
                    break;
                }
            }
        }
    } else {
        $client_ip =
            ( !empty($_SERVER['REMOTE_ADDR']) ) ?
                $_SERVER['REMOTE_ADDR']
                :
                ( ( !empty($_ENV['REMOTE_ADDR']) ) ?
                    $_ENV['REMOTE_ADDR']
                    :
                    "unknown" );
    }
    return $client_ip;
}
function getcontent($file){
    $tmp = explode('.',$file);
    $extension = strtolower(end($tmp));
    /* List of File Types */
    $fileTypes['swf'] = 'application/x-shockwave-flash';
    $fileTypes['pdf'] = 'application/pdf';
    $fileTypes['exe'] = 'application/octet-stream';
    $fileTypes['zip'] = 'application/zip';
    $fileTypes['7z'] = 'application/x-7z-compressed';
    $fileTypes['ace'] = 'application/x-ace-compressed';
    $fileTypes['apk'] = 'application/vnd.android.package-archive';
    $fileTypes['tar'] = 'application/x-tar';

    $fileTypes['doc'] = 'application/msword';
    $fileTypes['xls'] = 'application/vnd.ms-excel';
    $fileTypes['ppt'] = 'application/vnd.ms-powerpoint';
    $fileTypes['gif'] = 'image/gif';
    $fileTypes['png'] = 'image/png';
    $fileTypes['jpeg'] = 'image/jpg';
    $fileTypes['jpg'] = 'image/jpg';
    $fileTypes['rar'] = 'application/x-rar-compressed';

    $fileTypes['ra'] = 'audio/x-pn-realaudio';
    $fileTypes['ram'] = 'audio/x-pn-realaudio';
    $fileTypes['ogg'] = 'audio/x-pn-realaudio';

    $fileTypes['wav'] = 'video/x-msvideo';
    $fileTypes['wmv'] = 'video/x-msvideo';
    $fileTypes['avi'] = 'video/x-msvideo';
    $fileTypes['asf'] = 'video/x-msvideo';
    $fileTypes['divx'] = 'video/x-msvideo';

    $fileTypes['mp3'] = 'audio/mpeg';
    $fileTypes['mp4'] = 'audio/mpeg';
    $fileTypes['mpeg'] = 'video/mpeg';
    $fileTypes['mpg'] = 'video/mpeg';
    $fileTypes['mpe'] = 'video/mpeg';
    $fileTypes['mov'] = 'video/quicktime';
    $fileTypes['swf'] = 'video/quicktime';
    $fileTypes['3gp'] = 'video/quicktime';
    $fileTypes['m4a'] = 'video/quicktime';
    $fileTypes['aac'] = 'video/quicktime';
    $fileTypes['m3u'] = 'video/quicktime';

    $contentType = $fileTypes[$extension];
    return $contentType;
}
if( !function_exists('apache_request_headers') ) {

    function apache_request_headers() {
        $arh = array();
        $rx_http = '/\AHTTP_/';
        foreach($_SERVER as $key => $val) {
            if( preg_match($rx_http, $key) ) {
                $arh_key = preg_replace($rx_http, '', $key);
                $rx_matches = array();
                // do some nasty string manipulations to restore the original letter case
                // this should work in most cases
                $rx_matches = explode('_', $arh_key);
                if( count($rx_matches) > 0 and strlen($arh_key) > 2 ) {
                    foreach($rx_matches as $ak_key => $ak_val) $rx_matches[$ak_key] = ucfirst($ak_val);
                    $arh_key = implode('-', $rx_matches);
                }
                $arh[$arh_key] = $val;
            }
        }
        return( $arh );
    }

}
function smartReadFile($location,  $mimeType='application/octet-stream'){
    if(!file_exists($location))
    { header ("HTTP/1.0 404 Not Found");
        return;
    }

    $size=filesize($location);
    $time=date('r',filemtime($location));

    $fm=@fopen($location,'rb');
    if(!$fm)
    { header ("HTTP/1.0 505 Internal server error");
        return;
    }

    $begin=0;
    $end=$size;

    if(isset($_SERVER['HTTP_RANGE']))
    { if(preg_match('/bytes=\h*(\d+)-(\d*)[\D.*]?/i', $_SERVER['HTTP_RANGE'], $matches))
    { $begin=intval($matches[0]);
        if(!empty($matches[1]))
            $end=intval($matches[1]);
    }
    }

    if($begin>0||$end<$size)
        header('HTTP/1.0 206 Partial Content');
    else
        header('HTTP/1.0 200 OK');

    header("Content-Type: $mimeType");
    header('Cache-Control: public, must-revalidate, max-age=0');
    header('Pragma: no-cache');
    header('Accept-Ranges: bytes');
    header('Content-Length:'.($end-$begin));
    header("Content-Range: bytes $begin-$end/$size");
    header('Content-Disposition: inline; filename="'.basename($location).'"');
    header("Content-Transfer-Encoding: binary\n");
    header("Last-Modified: $time");
    header('Connection: close');

    $cur=$begin;
    fseek($fm,$begin,0);

    while(!feof($fm)&&$cur<$end&&(connection_status()==0))
    { print fread($fm,min(1024*16,$end-$cur));
        $cur+=1024*16;
    }
}
function serve_file_resumable ($file, $contenttype) {

    @error_reporting(0);

    if (!file_exists($file)) {
        header("HTTP/1.1 404 Not Found");
        exit;
    }

    if (isset($_SERVER['HTTP_RANGE'])) $range = $_SERVER['HTTP_RANGE'];
    else if ($apache = apache_request_headers()) {
        $headers = array();
        foreach ($apache as $header => $val) $headers[strtolower($header)] = $val;
        if (isset($headers['range'])) $range = $headers['range'];
        else $range = FALSE; // We can't get the header/there isn't one set
    } else $range = FALSE; // We can't get the header/there isn't one set

    $filesize = filesize($file);
    if ($range) {
        $partial = true;
        list($param,$range) = explode('=',$range);
        if (strtolower(trim($param)) != 'bytes') { // Bad request - range unit is not 'bytes'
            header("HTTP/1.1 400 Invalid Request");
            exit;
        }
        $range = explode(',',$range);
        $range = explode('-',$range[0]); // We only deal with the first requested range
        if (count($range) != 2) { // Bad request - 'bytes' parameter is not valid
            header("HTTP/1.1 400 Invalid Request");
            exit;
        }
        if ($range[0] === '') { // First number missing, return last $range[1] bytes
            $end = $filesize - 1;
            $start = $end - intval($range[0]);
        } else if ($range[1] === '') { // Second number missing, return from byte $range[0] to end
            $start = intval($range[0]);
            $end = $filesize - 1;
        } else { // Both numbers present, return specific range
            $start = intval($range[0]);
            $end = intval($range[1]);
            if ($end >= $filesize || (!$start && (!$end || $end == ($filesize - 1)))) $partial = false; // Invalid range/whole file specified, return whole file
        }
        $length = $end - $start + 1;
    } else $partial = false; // No range requested

    // Send standard headers
    header("Content-Type: $contenttype");
    header("Content-Length: $filesize");
    header('Content-Disposition: attachment; filename="'.basename($file).'"');
    header('Accept-Ranges: bytes');

    // if requested, send extra headers and part of file...
    if ($partial) {

        header('HTTP/1.1 206 Partial Content');
        header("Content-Range: bytes $start-$end/$filesize");
        if (!$fp = fopen($file, 'r')) { // Error out if we can't read the file
            header("HTTP/1.1 500 Internal Server Error");
            exit;
        }


        if ($start) fseek($fp,$start);
        while ($length) { // Read in blocks of 8KB so we don't chew up memory on the server
            $read = ($length > 8192) ? 8192 : $length;
            $length -= $read;
            print(fread($fp,$read));
        }
        fclose($fp);

    } else {
        //readfile($file); // ...otherwise just send the whole file
        smartReadFile($file,$contenttype);

    }
    // Exit here to avoid accidentally sending extra content on the end of the file


    exit;
}


function getdomain(){
    $regex = '@WordPress/(?P<version>\d[^;]*?);\s+(?P<url>https?://.+?)(?:\s|;|$)@i';
    if ( isset($_SERVER['HTTP_USER_AGENT']) && preg_match($regex, $_SERVER['HTTP_USER_AGENT'], $matches) ) {
        $registered_domain = $matches['url'];
    }


    // in case scheme relative URI is passed, e.g., //www.google.com/
    $input = trim($registered_domain, '/');

    // If scheme not included, prepend it
    if (!preg_match('#^http(s)?://#', $input)) {
        $input = 'http://' . $input;
    }

    $urlParts = parse_url($input);

    // remove www
    $registered_domain= preg_replace('/^www\./', '', $urlParts['host']);
    return $registered_domain;
}
function clean_url($url){
    // in case scheme relative URI is passed, e.g., //www.google.com/
    $input = trim($url, '/');
    // If scheme not included, prepend it
    if (!preg_match('#^http(s)?://#', $input)) {
        $input = 'http://' . $input;
    }
    $urlParts = parse_url($input);
    $urlParts = preg_replace('/^www\./', '', $urlParts['host']);
    return $urlParts;
}
function wpcar_sanitize_data($input_data) {
    $tmp = stripslashes($input_data);
    return htmlentities($tmp, ENT_QUOTES);
}
function createtable($mysqlserver,$dbusername,$dbpassword='',$dbname,$table){
    error_reporting(0);
    $result = 'FALSE' ;
    $resDB    = mysqli_connect($mysqlserver,$dbusername,$dbpassword,$dbname);
    if (!$resDB) return $result =  "Error Mysql Conenction  :".mysqli_connect_error();

    $strSQL   = "CREATE TABLE  IF NOT EXISTS " . $table . "
    (
    autoin INT NOT NULL AUTO_INCREMENT,
    PRIMARY KEY(autoin),
    downloadkey varchar(32),
    file varchar(255),
    downloads int default '0',
    expires int default '0',
    usermail varchar(255) ,
    dllimit int  default '0',
    linkfile varchar(255),
    downloadid int default '0',
    filenum int default '0',
    priceid int default '0' ,
    lockip varchar(36),
    ip VARCHAR(20) default '0') DEFAULT CHARSET=utf8 ;";
    $resCheck = mysqli_query($resDB, $strSQL) ;
    if (!$resCheck) return $result =  "Error Mysql Query .";

    if( ! mysqli_query($resDB,  'SELECT EXISTS(SELECT * FROM `'.$table.'` WHERE lockip)' ) === 1 ){

        mysqli_query($resDB, 'ALTER TABLE  `'.$table.'` ADD  `lockip` VARCHAR( 36 ) NULL DEFAULT NULL  ;' );
    }

    $result = "TRUE";
    return $result ;

}