Source of file GlobalFunctions.php

Size: 9,534 Bytes - Last Modified: 2018-03-22T03:07:44+01:00

C:/xampp/htdocs/PodTube/src/classes/GlobalFunctions.php

1234567891011121314151617
Covered by 1 test(s):
  • UtilitiesTest::testSecondsToTime
1819202122232425
Covered by 1 test(s):
  • UtilitiesTest::testSecondsToTime
26272829
Covered by 1 test(s):
  • UtilitiesTest::testSecondsToTime
30
Covered by 1 test(s):
  • UtilitiesTest::testSecondsToTime
31
Covered by 1 test(s):
  • UtilitiesTest::testSecondsToTime
32
Covered by 1 test(s):
  • UtilitiesTest::testSecondsToTime
33
Covered by 1 test(s):
  • UtilitiesTest::testSecondsToTime
3435
Covered by 1 test(s):
  • UtilitiesTest::testSecondsToTime
36
Covered by 1 test(s):
  • UtilitiesTest::testSecondsToTime
37
Covered by 1 test(s):
  • UtilitiesTest::testSecondsToTime
3839404142
Covered by 1 test(s):
  • UtilitiesTest::testSecondsToTime
4344
Covered by 1 test(s):
  • UtilitiesTest::testSecondsToTime
45
Covered by 1 test(s):
  • UtilitiesTest::testSecondsToTime
46
Covered by 1 test(s):
  • UtilitiesTest::testSecondsToTime
47
Covered by 1 test(s):
  • UtilitiesTest::testSecondsToTime
48
Covered by 1 test(s):
  • UtilitiesTest::testSecondsToTime
49
Covered by 1 test(s):
  • UtilitiesTest::testSecondsToTime
5051
Covered by 1 test(s):
  • UtilitiesTest::testSecondsToTime
525354
Covered by 1 test(s):
  • UtilitiesTest::testSecondsToTime
5556575859606162636465666768697071727374757677787980818283848586878889
Covered by 1 test(s):
  • UtilitiesTest::testUserLoginLogout
90
Covered by 1 test(s):
  • UtilitiesTest::testUserLoginLogout
91
Covered by 1 test(s):
  • UtilitiesTest::testUserLoginLogout
9293949596979899100
Covered by 1 test(s):
  • UtilitiesTest::testUserLoginLogout
101
Covered by 1 test(s):
  • UtilitiesTest::testUserLoginLogout
102
Covered by 1 test(s):
  • UtilitiesTest::testUserLoginLogout
103
Covered by 1 test(s):
  • UtilitiesTest::testUserLoginLogout
104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
Covered by 1 test(s):
  • UtilitiesTest::testPluralize
191
Covered by 1 test(s):
  • UtilitiesTest::testPluralize
192
Covered by 1 test(s):
  • UtilitiesTest::testPluralize
193
Covered by 1 test(s):
  • UtilitiesTest::testPluralize
194
Covered by 1 test(s):
  • UtilitiesTest::testPluralize
195196
Covered by 1 test(s):
  • UtilitiesTest::testPluralize
197
Covered by 1 test(s):
  • UtilitiesTest::testPluralize
198
Covered by 1 test(s):
  • UtilitiesTest::testPluralize
199
Covered by 1 test(s):
  • UtilitiesTest::testPluralize
200201
Covered by 1 test(s):
  • UtilitiesTest::testPluralize
202
Covered by 1 test(s):
  • UtilitiesTest::testPluralize
203
Covered by 1 test(s):
  • UtilitiesTest::testPluralize
204205206
Covered by 1 test(s):
  • UtilitiesTest::testPluralize
207208209210211
Covered by 1 test(s):
  • UtilitiesTest::testStringListicle
212
Covered by 1 test(s):
  • UtilitiesTest::testStringListicle
213214
Covered by 1 test(s):
  • UtilitiesTest::testStringListicle
215
Covered by 1 test(s):
  • UtilitiesTest::testStringListicle
216
Covered by 1 test(s):
  • UtilitiesTest::testStringListicle
217
Covered by 1 test(s):
  • UtilitiesTest::testStringListicle
218
Covered by 1 test(s):
  • UtilitiesTest::testStringListicle
219220221222
Covered by 1 test(s):
  • UtilitiesTest::testStringListicle
223224225226
Covered by 1 test(s):
  • UtilitiesTest::test_mb_str_split
227228229230231232233234235
Covered by 1 test(s):
  • UtilitiesTest::testGetDAL
236237
Covered by 1 test(s):
  • UtilitiesTest::testGetDAL
238239240241242243244245246247248249250
Covered by 1 test(s):
  • UtilitiesTest::testDeepSetDictionaryValues
251
Covered by 1 test(s):
  • UtilitiesTest::testDeepSetDictionaryValues
252
Covered by 1 test(s):
  • UtilitiesTest::testDeepSetDictionaryValues
253
Covered by 1 test(s):
  • UtilitiesTest::testDeepSetDictionaryValues
254
Covered by 1 test(s):
  • UtilitiesTest::testDeepSetDictionaryValues
255256257
Covered by 1 test(s):
  • UtilitiesTest::testDeepSetDictionaryValues
258
Covered by 1 test(s):
  • UtilitiesTest::testDeepSetDictionaryValues
259260261262
Covered by 1 test(s):
  • UtilitiesTest::testDeepSetDictionaryValues
263264
Covered by 1 test(s):
  • UtilitiesTest::testDeepSetDictionaryValues
265266267268269
Covered by 1 test(s):
  • UtilitiesTest::testVerifySameOriginHeader
270
Covered by 1 test(s):
  • UtilitiesTest::testVerifySameOriginHeader
271272273
Covered by 1 test(s):
  • UtilitiesTest::testVerifySameOriginHeader
274
Covered by 1 test(s):
  • UtilitiesTest::testVerifySameOriginHeader
275
Covered by 1 test(s):
  • UtilitiesTest::testVerifySameOriginHeader
276277278
Covered by 1 test(s):
  • UtilitiesTest::testVerifySameOriginHeader
279280281
Covered by 1 test(s):
  • UtilitiesTest::testVerifySameOriginHeader
282
Covered by 1 test(s):
  • UtilitiesTest::testVerifySameOriginHeader
283284
Covered by 1 test(s):
  • UtilitiesTest::testVerifySameOriginHeader
285286287288
Covered by 1 test(s):
  • UtilitiesTest::testRandomToken
289290291292
Covered by 1 test(s):
  • UtilitiesTest::testRandomToken
293
Covered by 1 test(s):
  • UtilitiesTest::testRandomToken
294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
<?php

namespace AudioDidact;

require_once __DIR__ . '/../header.php';

class GlobalFunctions {

	/**
	 * Convert number of seconds into hours, minutes and seconds
	 * and return an array containing those values
	 *
	 * @param integer $inputSeconds Number of seconds to parse
	 * @return array
	 */
	public static function secondsToTime($inputSeconds){
		$conversion = ["second" => ["second" => 1],
			"minute" => ["second" => 60],
			"hour" => ["minute" => 60],
			"day" => ["hour" => 24],
			"week" => ["day" => 7],
			"month" => ["week" => 4],
			"year" => ["day" => 365]];

		return static::modularUnitExpansion($inputSeconds, $conversion);
	}

	public static function modularUnitExpansion($value, $conversionTable){
		$baseUnit = "";
		$newConversion = [];
		foreach($conversionTable as $unit => $convertArr){
			if(array_key_exists($unit, $convertArr) && $convertArr[$unit] == 1){
				$baseUnit = $unit;
			}
			foreach($convertArr as $conversionUnit => $conversionFactor){
				$conversionTable[$unit][$baseUnit] = $conversionTable[$conversionUnit][$baseUnit] * $conversionFactor;
				$newConversion[$unit] = $conversionTable[$conversionUnit][$baseUnit] * $conversionFactor;
			}
		}

		// Reverse sort so that the largest units are iterated through first
		arsort($newConversion);

		$remainingUnits = $value;
		$outputArray = [];
		foreach($newConversion as $unit => $conversionFactor){
			$val = intval(floor($remainingUnits / $conversionFactor));
			if($val > 0){
				$outputArray[$unit] = $val;
			}
			$remainingUnits = $remainingUnits % $conversionFactor;
		}

		return $outputArray;
	}

	/**
	 * Deletes all session variables and the session cookies
	 */
	public static function clearSession(){
		$params = session_get_cookie_params();
		setcookie(session_name(), '', time() - 42000,
			$params["path"], $params["domain"],
			$params["secure"], $params["httponly"]
		);
		session_destroy();
		session_write_close();
	}

	/**
	 * Sets the CHECK_REQUIRED flag in the config file
	 *
	 * @param bool $checkRequired
	 */
	public static function setCheckRequired($checkRequired){
		$currentConfig = file_get_contents(__DIR__ . '/../config.php');
		$newConfig = preg_replace("/define\(\"CHECK_REQUIRED\",\s+(true|false)\)/", "define(\"CHECK_REQUIRED\", $checkRequired)", $currentConfig);
		file_put_contents(__DIR__ . '/../config.php', $newConfig);
	}

	public static function SRIChecksum($input){
		$hash = hash('sha256', $input, true);
		$hashBase64 = base64_encode($hash);

		return "sha256-$hashBase64";
	}

	public static function userLogIn(User $user){
		$_SESSION["loggedIn"] = true;
		$_SESSION["user"] = $user;
	}

	public static function userLogOut(){
		$_SESSION["loggedIn"] = false;
		unset($_SESSION["user"]);
		static::clearSession();
	}

	public static function userIsLoggedIn(){
		return (isset($_SESSION["loggedIn"])
			&& $_SESSION["loggedIn"]
			&& isset($_SESSION["user"])
			&& $_SESSION["user"] != null);
	}

	public static function is_ssl(){
		return !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off';
	}

	public static function file_get_contents_no_verify($url){
		$options = ["ssl" => [
				"verify_peer" => false,
				"verify_peer_name" => false,
			]];
		return file_get_contents($url, false, stream_context_create($options));
	}

	/**
	 * Returns Pug (Jade) rendered HTML for a given view and options
	 *
	 * @param $view string Name of Pug view to be rendered
	 * @param $title string Title of the webpage
	 * @param array $options Additional options needed to render the view
	 * @param bool $prettyPrint If prettyPrint is false, all HTML is on a single line
	 * @return string Pug generated HTML
	 */
	public static function generatePug($view, $title, $options = [], $prettyPrint = false){
		$verified = true;

		$csrfToken = isset($_COOKIE["AD_CSRF"]) ? $_COOKIE["AD_CSRF"] : "";
		$initialOptions = [
			'title' => $title,
			'subdir' => SUBDIR,
			'loggedIn' => "false",
			'localurl' => LOCAL_URL,
			'emailEnabled' => EMAIL_ENABLED,
			'csrf' => $csrfToken
		];

		if(static::userIsLoggedIn()){
			$initialOptions["loggedIn"] = "true";
			/** @var User $user */
			$user = $_SESSION["user"];
			$userData = ["privateFeed" => $user->isPrivateFeed(), "fName" => $user->getFname(), "lName" => $user->getLname(),
				"gender" => $user->getGender(), "webID" => $user->getWebID(), "username" => $user->getUsername(),
				"email" => $user->getEmail(), "feedLength" => $user->getFeedLength(), "feedDetails" => $user->getFeedDetails()
			];
			if(!$user->isEmailVerified()){
				$verified = false;
			}

			$initialOptions["user"] = $userData;
		}

		$initialOptions["verified"] = $verified;

		// Allow overwriting keys, but log the problem
		$overWrittenKeys = array_intersect_key($initialOptions, $options);
		if(count($overWrittenKeys) > 0){
			error_log("You are overwriting " . count($overWrittenKeys) . " keys in the Pug options! "
				. implode(", ", array_keys($overWrittenKeys)));
		}

		$options = array_merge($initialOptions, $options);

		$pug = new \Pug\Pug(['pretty' => $prettyPrint, 'strict' => true, "expressionLanguage" => "js",
			"cache" => getcwd() . "/pug-cache", "upToDateCheck" => true,
		]);

		/*
		 * Pug-php 3 is significantly slower than previous versions for the first render.
		 * Using native pug is faster for the first render, but when caching is enabled,
		 * the php version becomes faster for subsequent renders.
		 *
		 * To use native pug add the following to the Pug constructor options array
		 * "pugjs" => true, 'localsJsonFile' => true,
		 */

		return $pug->renderFile($view, $options);
	}

	/**
	 * Returns the correct plural or singular form of the given word
	 *
	 * @param $word String singular form of the word
	 * @param $num int number of things the word is referring to
	 * @return string correct form of the given word for the input number
	 */
	public static function pluralize($word, $num){
		$vowels = ["a", "e", "i", "o", "u"];
		$lastCharExceptions = ["s", "o", "x"];
		$lastTwoCharExceptions = ["sh", "ch"];
		if($num == 1){
			return $word;
		}
		$lastChar = mb_substr($word, -1, 1);
		$lastTwoChars = mb_substr($word, -2, 2);
		if($lastChar == "y" && !in_array(mb_substr($word, -2, 1), $vowels, true)){
			return mb_substr($word, 0, mb_strlen($word) - 1) . "ies";
		}
		else if(in_array($lastChar, $lastCharExceptions, true)
			|| in_array($lastTwoChars, $lastTwoCharExceptions, true)){
			return $word . "es";
		}
		else{
			return $word . "s";
		}
	}

	public static function arrayToCommaSeparatedString($list){
		$frontOfList = array_slice($list, 0, -1);
		$lastElement = array_slice($list, -1, 1);

		$prependConjunction = "";
		if(count($frontOfList) > 0){
			$prependConjunction = " and ";
			if(count($frontOfList) > 1){
				$prependConjunction = "," . $prependConjunction;
			}
		}

		return implode(", ", $frontOfList) . $prependConjunction . (count($lastElement) == 0 ? "" : $lastElement[0]);
	}

	public static function mb_str_split($string){
		return preg_split('/(?<!^)(?!$)/u', $string);
	}

	/**
	 * Makes a new DAL class based on values in config.php
	 *
	 * @return \AudioDidact\DB\DAL
	 */
	public static function getDAL(){
		$myDalClass = CHOSEN_DAL;

		return new $myDalClass(PDO_STR);
	}

	/**
	 * Sets the value of a dictionary subkey to $value.
	 *
	 * @param $dict array the dictionary that will have it's subkey set to $value.
	 * @param $keyHierarchy array the array of keys to set. To set something in the form of $array["a"]["b"]["c"],
	 * set $keyHierarchy to ["a","b","c"]
	 * @param $value mixed the value that will be added to the dictionary
	 * @return mixed the dictionary with the new value set
	 */
	public static function deepSetDictionaryValues($dict, $keyHierarchy, $value){
		$o = &$dict;
		for($i = 0; $i < count($keyHierarchy) - 1; $i++){
			$subKeyAtI = $keyHierarchy[$i];
			if(array_key_exists($subKeyAtI, $o)){
				$o = &$o[$subKeyAtI];
			}
			else{
				$o[$subKeyAtI] = [];
				$o = &$o[$subKeyAtI];
			}
		}

		$o[$keyHierarchy[count($keyHierarchy) - 1]] = $value;

		return $dict;
	}

	public static function verifySameOriginHeader(){
		// One of HTTP_ORIGIN or HTTP_REFERER must exist to be a proper request
		if(!isset($_SERVER["HTTP_ORIGIN"]) && !isset($_SERVER["HTTP_REFERER"])){
			return false;
		}

		$url = null;
		if(isset($_SERVER["HTTP_ORIGIN"])){
			$url = parse_url($_SERVER["HTTP_ORIGIN"]);
		}
		else{
			$url = parse_url($_SERVER["HTTP_REFERER"]);
		}

		$port = isset($url["port"]) ? $url["port"] : "";
		$url = $url["host"] . $port;

		return mb_strpos(mb_strtolower($url), LOCAL_URL) >= 0;
	}

	public static function randomToken($length = 32){
		if(!isset($length) || intval($length) <= 8){
			$length = 64;
		}

		if(function_exists('random_bytes')){
			return bin2hex(random_bytes($length));
		}
		if(function_exists('openssl_random_pseudo_bytes')){
			return bin2hex(openssl_random_pseudo_bytes($length));
		}
		else{
			die("No Random function exists!");
		}
	}

	public static function verifyCSRFToken(){
		if(!isset($_COOKIE["AD_CSRF"])){
			return false;
		}

		$token = "";
		if(isset($_SERVER["REQUEST_METHOD"]) && $_SERVER["REQUEST_METHOD"] === "POST"){
			$token = isset($_POST["CSRF_TOKEN"]) ? $_POST["CSRF_TOKEN"] : "";
		}
		else if(isset($_SERVER["REQUEST_METHOD"]) && $_SERVER["REQUEST_METHOD"] === "GET"){
			$token = isset($_GET["CSRF_TOKEN"]) ? $_GET["CSRF_TOKEN"] : "";
		}

		return $token === $_COOKIE["AD_CSRF"];
	}

	public static function fullVerifyCSRF(){
		return static::verifySameOriginHeader() && static::verifyCSRFToken();
	}
}