<?php

session_start();

class fb {
	public $url;
	public $fb_hd;
	public $fb_sd;
	public $fb_title;
	public $id;
	public $fb_url;
	public $image;

	function __construct( $url ) {
		$this->url = $url;
	}

	public function fbvideoid( $url ) {
		$url  = str_replace( ' ', '', $url );
		$pars = parse_url( $url );
		if ( isset( $pars['path'] ) ) {
			$path = $pars['path'];
			if ( $path[ strlen( $path ) - 1 ] == '/' ):
				$path = rtrim( $path, '/' );
			endif;

			$count   = count( explode( "/", $path ) );
			$urltype = "";
			if ( $pars['path'] == "/photo.php" || $pars['path'] == "/video.php"
			     || $pars['path'] == "/video/video.php"
			     || $pars['path'] == "/"
			) {
				$urltype = 2;
			} elseif ( $count == 4 ) {
				$urltype = 3;
			} elseif ( $count == 5 ) {
				$urltype = 1;
			}

			if ( $urltype == 1 ) {
				$ex = explode( "/", $path );

				return $videoid = $ex[4];
			} elseif ( $urltype == 2 ) {
				if ( isset( $pars['query'] ) ) {
					parse_str( $pars['query'], $e );
					if ( array_key_exists( 'v', $e ) ) {
						return $videoid = $e['v'];
					} else {
						return $videoid = null;
					}
				} else {
					return $videoid = null;
				}
			} elseif ( $urltype == 3 ) {
				$ex = explode( "/", $path );

				return $videoid = $ex[3];
			} else {
				return $videoid = null;
			}
		} else {
			return $videoid = null;
		}
	}

	public function contents() {
		$id       = $this->fbvideoid( $this->url );
		$agent    = [
			'http' => [
				'method' => 'GET',
				'header' => "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.47 Safari/537.36",
			],
		];
		$this->id = $this->fbvideoid( $this->url );
		$id       = $this->fbvideoid( $this->url );
		$context  = stream_context_create( $agent );
		$url = "https://www.facebook.com/video.php?v=$id";
		$content = file_get_contents($url ,false, $context);
		
		$_SESSION['fb'] = $content;

		return $content;
	}

	public function get_url() {
		$content = $this->contents();
		$links = array();
		$hd = '/hd_src_no_ratelimit:"([^"]+)"/';
		if ( preg_match( $hd, $content, $match ) ) {
			$this->fb_hd = $match[1];
			$links[] = array(
				'quality' => 'HD',
				'link' => $match[1],
				'size' => $this->size($match[1]),
			);

		}

		$sd = '/sd_src_no_ratelimit:"([^"]+)"/';
		if ( preg_match( $sd, $content, $sd_match ) ) {
			$this->fb_sd = $sd_match[1];
			$links[] = array(
				'quality' => 'SD',
				'link' => $sd_match[1],
				'size' => $this->size($this->fb_sd),
			);

		}elseif ( preg_match( '/sd_src:"([^"]+)"/', $content, $sd_match ) ) {
			$this->fb_sd = $sd_match[1];
			$links[] = array(
				'quality' => 'SD',
				'link' => $sd_match[1],
				'size' => $this->size($this->fb_sd),
			);

		}

		$reg1 = '/h2 class="uiHeaderTitle"?[^>]+>(.+?)<\/h2>/';
		$reg2 = '/title id="pageTitle">(.+?)<\/title>/';
		if ( preg_match( $reg1, $content, $title_match ) ) {
			$this->fb_title = html_entity_decode( strip_tags( $title_match[1] ),
				ENT_QUOTES, 'UTF-8' );
		} elseif ( preg_match( $reg2, $content, $title_match ) ) {
			$this->fb_title = html_entity_decode( strip_tags( $title_match[1] ),
				ENT_QUOTES, 'UTF-8' );
		} else {
			$this->fb_title = "No title found";
		}
		
		if ( preg_match( '/"thumbnailUrl":"([^"]+)"/', $content, $img_match ) ) {
			$this->image = str_replace('\/', '/', $img_match[1]);
		}

		$tr = '<tr><td>%s</small></td><td>%s</td><td><a class="btn btn-outline-dark" href="%s" download>Download</a></td></tr>';

		$link = '';

		foreach ($links as $key => $value) {
			$this->fb_url .= sprintf($tr, $value['quality'], $value['size'], $value['link']);
		}
	}

    private function size($url, $formatSize = true, $useHead = true) {
        if (false !== $useHead) {
            stream_context_set_default(array('http' => array('method' => 'HEAD')));
        }
        $head = array_change_key_case(get_headers($url, 1));
        // content-length of download (in bytes), read from Content-Length: field
        $clen = isset($head['content-length']) ? $head['content-length'] : 0;

        // cannot retrieve file size, return "-1"
        if (!$clen) {
            return -1;
        }

        if (!$formatSize) {
            return $clen; // return size in bytes
        }

        $size = $clen;
		if(is_array($clen))$clen=end($clen);
        switch ($clen) {
            case $clen < 1024:
                $size = $clen . ' B';
                break;
            case $clen < 1048576:
                $size = round($clen / 1024, 2) . ' KB';
                break;
            case $clen < 1073741824:
                $size = round($clen / 1048576, 2) . ' MB';
                break;
            case $clen < 1099511627776:
                $size = round($clen / 1073741824, 2) . ' GB';
                break;
        }
        return $size; // return formatted size
    }
}
