<?php
class functions
{

	function getTotalRecordsShown()
	{
		return -1;
	}

	function youtube_id_from_url($url)
	{

		$pattern = '%^# Match any youtube URL
				(?:https?://)?  # Optional scheme. Either http or https
				(?:www\.)?      # Optional www subdomain
				(?:             # Group host alternatives
				youtu\.be/    # Either youtu.be,
				| youtube\.com  # or youtube.com
				(?:           # Group path alternatives
					/embed/     # Either /embed/
				| /v/         # or /v/
				| /watch\?v=  # or /watch\?v=
				)             # End path alternatives.
				)               # End host alternatives.
				([\w-]{10,12})  # Allow 10-12 for 11 char youtube id.
				$%x';

		$result = preg_match($pattern, $url, $matches);

		if (false !== $result) {
			return $matches[1];
		}
		return false;
	}


	/*
		"https://youtu.be/yVpbFMhOAwE",
		"https://www.youtube.com/embed/yVpbFMhOAwE",
		"youtu.be/yVpbFMhOAwE",
		"youtube.com/watch?v=yVpbFMhOAwE",
		"http://youtu.be/yVpbFMhOAwE&t=2m",
		"http://www.youtube.com/embed/yVpbFMhOAwE&t=2m5s",
		"http://www.youtube.com/watch?v=yVpbFMhOAwE",
		"http://www.youtube.com/watch?v=yVpbFMhOAwE&feature=g-vrec&t=30s",
		"http://www.youtube.com/watch?v=yVpbFMhOAwE&feature=player_embedded",
		"http://www.youtube.com/v/yVpbFMhOAwE?fs=1&hl=en_US",
		"http://www.youtube.com/ytscreeningroom?v=yVpbFMhOAwE",
		"http://www.youtube.com/watch?NR=1&feature=endscreen&v=yVpbFMhOAwE",
		"http://www.youtube.com/user/Scobleizer#p/u/1/1p3vcRhsYGo",
		"http://www.youtube.com/watch?v=6zUVS4kJtrA&feature=c4-overview-vl&list=PLbzoR-pLrL6qucl8-lOnzvhFc2UM1tcZA",
		"https://www.youtube.com/watch?v=FZu097wb8wU&list=RDFZu097wb8wU"
		*/

	// Automatically parse youtube video/playlist links and generate the respective embed code
	function ParseYoutubeLink($data)
	{
		$isYouTubeURL = $this->isYouTubeURL($data);
		// Check if youtube link is a playlist
		if (strpos($data, 'list=') !== false) {
			// Generate the code	
			$data = preg_replace('~(?:http|https|)(?::\/\/|)(?:www.|)(?:youtu\.be\/|youtube\.com(?:\/embed\/|\/v\/|\/watch\?v=|\/ytscreeningroom\?v=|\/feeds\/api\/videos\/|\/user\S*[^\w\-\s]|\S*[^\w\-\s]))([\w\-]{12,})[a-z0-9;:@#?&%=+\/\$_.-]*~i', '$1', $data);
			return array('type' => 'list', 'value' => $data, 'isYT' => $isYouTubeURL);
		}

		// If the above conditions were false then the youtube link is probably just a plain video link. So generate the code already.
		$data = preg_replace('~(?:http|https|)(?::\/\/|)(?:www.|)(?:youtu\.be\/|youtube\.com(?:\/embed\/|\/v\/|\/watch\?v=|\/ytscreeningroom\?v=|\/feeds\/api\/videos\/|\/user\S*[^\w\-\s]|\S*[^\w\-\s]))([\w\-]{11})[a-z0-9;:@#?&%=+\/\$_.-]*~i', '$1', $data);
		return array('type' => 'channel', 'value' => $data, 'isYT' => $isYouTubeURL);
	}

	function isYouTubeURL($url)
	{
		$yt_rx = '/^((?:https?:)?\/\/)?((?:www|m)\.)?((?:youtube\.com|youtu.be))(\/(?:[\w\-]+\?v=|embed\/|v\/)?)([\w\-]+)(\S+)?$/';
		$has_match_youtube = preg_match($yt_rx, $url, $yt_matches);

		//Then we want the video id which is:
		if ($has_match_youtube) {
			//$video_id = $yt_matches[5];
			//$type = 'youtube';
			return 'true';
		} else {
			//$video_id = 0;
			//$type = 'none';
			return 'false';
		}

		//$data['video_id'] = $video_id;
		//$data['video_type'] = $type;

		//return $data;

	}
	function getInfo($video_url)
	{

		$oembed = 'https://www.youtube.com/oembed';

		if (preg_match('|^http(s)?://(.*?)vimeo.com|', $video_url)) {
			$oembed = 'https://vimeo.com/api/oembed.json';
		}

		$oembed .= '?format=json&url=' . urlencode($video_url);

		$json_string = @file_get_contents($oembed);

		/**
		 * @var null|\stdClass
		 */
		$obj = json_decode($json_string);

		if ($obj == null || !$obj) {
			return null;
		}
		return $obj;
	}

	function get_random_string($valid_chars, $length)
	{

		// start with an empty random string
		$random_string = "";

		// count the number of chars in the valid chars string so we know how many choices we have
		$num_valid_chars = strlen($valid_chars);

		// repeat the steps until we've created a string of the right length
		for ($i = 0; $i < $length; $i++) {
			// pick a random number from 1 up to the number of valid chars
			$random_pick = mt_rand(1, $num_valid_chars);

			// take the random character out of the string of valid chars
			// subtract 1 from $random_pick because strings are indexed starting at 0, and we started picking at 1
			$random_char = $valid_chars[$random_pick - 1];

			// add the randomly-chosen char onto the end of our string so far
			$random_string .= $random_char;
		}

		// return our finished random string
		return $random_string;
	} // end of get_random_string()

	// Get base url
	function getBaseUrl($array = false)
	{
		$protocol = "http";
		$host = "";
		$port = "";
		$dir = "";

		// Get protocol
		if (array_key_exists("HTTPS", $_SERVER) && $_SERVER["HTTPS"] != "") {
			if ($_SERVER["HTTPS"] == "on") {
				$protocol = "https";
			} else {
				$protocol = "http";
			}
		} elseif (array_key_exists("REQUEST_SCHEME", $_SERVER) && $_SERVER["REQUEST_SCHEME"] != "") {
			$protocol = $_SERVER["REQUEST_SCHEME"];
		}

		// Get host
		if (array_key_exists("HTTP_X_FORWARDED_HOST", $_SERVER) && $_SERVER["HTTP_X_FORWARDED_HOST"] != "") {
			$host = trim(end(explode(',', $_SERVER["HTTP_X_FORWARDED_HOST"])));
		} elseif (array_key_exists("SERVER_NAME", $_SERVER) && $_SERVER["SERVER_NAME"] != "") {
			$host = $_SERVER["SERVER_NAME"];
		} elseif (array_key_exists("HTTP_HOST", $_SERVER) && $_SERVER["HTTP_HOST"] != "") {
			$host = $_SERVER["HTTP_HOST"];
		} elseif (array_key_exists("SERVER_ADDR", $_SERVER) && $_SERVER["SERVER_ADDR"] != "") {
			$host = $_SERVER["SERVER_ADDR"];
		}
		//elseif(array_key_exists("SSL_TLS_SNI", $_SERVER) && $_SERVER["SSL_TLS_SNI"] != "") { $host = $_SERVER["SSL_TLS_SNI"]; }

		// Get port
		if (array_key_exists("SERVER_PORT", $_SERVER) && $_SERVER["SERVER_PORT"] != "") {
			$port = $_SERVER["SERVER_PORT"];
		} elseif (stripos($host, ":") !== false) {
			$port = substr($host, (stripos($host, ":") + 1));
		}
		// Remove port from host
		$host = preg_replace("/:\d+$/", "", $host);

		// Get dir
		if (array_key_exists("SCRIPT_NAME", $_SERVER) && $_SERVER["SCRIPT_NAME"] != "") {
			$dir = $_SERVER["SCRIPT_NAME"];
		} elseif (array_key_exists("PHP_SELF", $_SERVER) && $_SERVER["PHP_SELF"] != "") {
			$dir = $_SERVER["PHP_SELF"];
		} elseif (array_key_exists("REQUEST_URI", $_SERVER) && $_SERVER["REQUEST_URI"] != "") {
			$dir = $_SERVER["REQUEST_URI"];
		}
		// Shorten to main dir
		if (stripos($dir, "/") !== false) {
			$dir = substr($dir, 0, (strripos($dir, "/") + 1));
		}

		// Create return value
		if (!$array) {
			if ($port == "80" || $port == "443" || $port == "") {
				$port = "";
			} else {
				$port = ":" . $port;
			}
			return htmlspecialchars($protocol . "://" . $host . $port . $dir, ENT_QUOTES);
		} else {
			return ["protocol" => $protocol, "host" => $host, "port" => $port, "dir" => $dir];
		}
	}
}
