<?php

function unauthorizedMessage() {
	$text = '<div class="grid-container">';
	$text .= '<div class="grid-x grid-margin-x">';
	$text .= '<div class="cell small-12">';
	$text .= '<br />';
	$text .= '<div class="callout alert">';
	$text .= '<h5>'.lng('unauthorized').'</h5>';
	$text .= '<p>'.lng('access_denied_for_guest_users').'</p>';
	$text .= '</div>';
	$text .= '</div>';
	$text .= '</div>';
	$text .= '</div>';
	return $text;
}

function br2nl($string) {
    return preg_replace('/\<br(\s*)?\/?\>/i', "\n", $string);
}

function inString($needle, $haystack) {
	$pos = strpos($haystack, $needle);
	if($pos !== false) {
		return true;
	} else {
		return false;
	}
}

function deleteAllBetween($beginning, $end, $string) {
	$beginningPos = strpos($string, $beginning);
	$endPos = strpos($string, $end);
	if ($beginningPos === false || $endPos === false) {
		return $string;
	}
	$textToDelete = substr($string, $beginningPos, ($endPos + strlen($end)) - $beginningPos);
	return deleteAllBetween($beginning, $end, str_replace($textToDelete, '', $string)); // recursion to ensure all occurrences are replaced
}

function strBetween($string, $str1, $str2) {
	$string = " ".$string;
	$ini = strpos($string, $str1);
	if($ini == 0) {
		return "";
	} else {
		$ini += strlen($str1);
		$len = strpos($string, $str2, $ini) - $ini;
		return substr($string, $ini, $len);
	}
}

function curlGet($url) {
	// Default browser ID
	$browser_id = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13';
	// create curl resource
    $ch = curl_init();
    // set url
    curl_setopt($ch, CURLOPT_URL, $url);
    //return the transfer as a string
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch,CURLOPT_USERAGENT,$browser_id);
    // $output contains the output string
    $output = curl_exec($ch);
    // close curl resource to free up system resources
    curl_close($ch);

    return $output;
}

function deleteDir($directory) {
    if (! is_dir($directory)) {
        throw new InvalidArgumentException("$directory must be a directory");
    }
    if (substr($directory, strlen($directory) - 1, 1) != '/') {
        $directory .= '/';
    }
    $files = glob($directory . '*', GLOB_MARK);
    foreach ($files as $file) {
        if (is_dir($file)) {
            deleteDir($file);
        } else {
            unlink($file);
        }
    }
    rmdir($directory);
}

function getFileList($directory) {
	$filelist = array();
	$dir_handle = @opendir($directory);
	while($file = @readdir($dir_handle)) {
		if($file != '.' and $file != '..') {
			if(is_dir($directory.'/'.$file)) {
                //echo $file.'<br>';

				$dir_handle2 = opendir($directory.'/'.$file);
				while($file3 = readdir($dir_handle2)) {
					if($file3 != '.' and $file3 != '..') {
						$filelist[] = $directory.'/'.$file.'/'.$file3;
					}
				}
				closedir($dir_handle);

			} else {
				$filelist[] = $directory.'/'.$file;
			}
		}
	}
	@closedir($dir_handle);
	return $filelist;
}

function getFileExtension($filename) {
	$filename_extension = explode(".", $filename);
	return $filename_extension[count($filename_extension)-1];
}

function getVersion() {
	$version = @file_get_contents('version.txt');
	$version = explode("\n", $version);
	$version_local = $version[0];
	$version_local = explode(":", $version_local);
	$version_local = trim($version_local[1]);
	return $version_local;
}

// Returns a file size limit in bytes based on the PHP upload_max_filesize and post_max_size
function file_upload_max_size() {
  static $max_size = -1;

  if ($max_size < 0) {
    // Start with post_max_size.
    $post_max_size = parse_size(ini_get('post_max_size'));
    if ($post_max_size > 0) {
      $max_size = $post_max_size;
    }

    // If upload_max_size is less, then reduce. Except if upload_max_size is
    // zero, which indicates no limit.
    $upload_max = parse_size(ini_get('upload_max_filesize'));
    if ($upload_max > 0 && $upload_max < $max_size) {
      $max_size = $upload_max;
    }
  }
  return $max_size;
}

function parse_size($size) {
  $unit = preg_replace('/[^bkmgtpezy]/i', '', $size); // Remove the non-unit characters from the size.
  $size = preg_replace('/[^0-9\.]/', '', $size); // Remove the non-numeric characters from the size.
  if ($unit) {
    // Find the position of the unit in the ordered string which is the power of magnitude to multiply a kilobyte by.
    return round($size * pow(1024, stripos('bkmgtpezy', $unit[0])));
  }
  else {
    return round($size);
  }
}

function humanReadableSize($size) {
	if(strlen($size) <= 9 && strlen($size) >= 7) {
		$size = number_format($size / 1048576,1);
		$size .= " MB";
	} elseif(strlen($size) >= 10) {
		$size = number_format($size / 1073741824,1);
		$size .= " GB";
	} else {
		$size = number_format($size / 1024,1);
		$size .= " KB";
	}
	return $size;
}

function humanReadableDateAndTime($date, $format) {
	if($format == 1) {
		$text = substr($date, 4, 2);
		$text .= '/';
		$text .= substr($date, 6, 2);
		$text .= '/';
		$text .= substr($date, 0, 4);
		$text .= ' ';
		$text .= substr($date, 8, 2);
		$text .= ':';
		$text .= substr($date, 10, 2);
		$text .= ':';
		$text .= substr($date, 12, 2);
	}
	if($format == 2) {
		$text = substr($date, 0, 4);
		$text .= '/';
		$text .= substr($date, 4, 2);
		$text .= '/';
		$text .= substr($date, 6, 2);
		$text .= ' ';
		$text .= substr($date, 8, 2);
		$text .= ':';
		$text .= substr($date, 10, 2);
		$text .= ':';
		$text .= substr($date, 12, 2);
	}
	return $text;
}

function lng($id) {
	global $lng;
	return $lng[$id];
}

function countMysqlItems($table, $where) {
	global $link;
	$result = mysqli_query($link, "SELECT ".$table."_id FROM ".$table." ".$where);
    $counter = mysqli_num_rows($result);
	return $counter;
}

function getFilename($directory, $prefix) {
	$dir_handle = opendir($directory);
	while($file = readdir($dir_handle)) {
		if($file != '.' and $file != '..') {
			$pos = strpos($file, $prefix);
			if($pos === false) {
			} elseif($pos == 0) {
				$filename = $directory.'/'.$file;
				closedir($dir_handle);
				return $filename;
			}
		}
	}
	closedir($dir_handle);
}

function getFilenames($directory, $prefix) {
	$files = array();
	$dir_handle = opendir($directory);
	while($file = readdir($dir_handle)) {
		if($file != '.' and $file != '..') {
			if($prefix != '') {
				$pos = strpos($file, $prefix);
				if($pos === false) {
				} elseif($pos == 0)	{
					$files[] = $directory.'/'.$file;
				}
			} else {
				$files[] = $directory.'/'.$file;
			}
		}
	}
	closedir($dir_handle);
	return $files;
}

function purgeTmp() {
	$time = time();
	$time -= 10800;
	unset($files);
	$files = getFilenames('data/tmp', '');
	if(!empty($files)) {
		foreach($files as $value) {
			if($value != 'data/tmp/.gitignore') {
				if(filemtime($value) < $time) {
					unlink($value);
				}
			}
		}
	}
}

function purgeExtracted() {
	$time = time();
	$time -= 10800;
	// Delete all files from /data/extracted
	$files = glob('data/extracted/*'); // get all file names
	foreach($files as $file){ // iterate files
		if(filemtime($file) < $time) {
			if(is_dir($file)) {
				deleteDir($file); // delete file
			}
			if(is_file($file)) {
				unlink($file); // delete file
			}
		}
	}
}

function isImage($image) {
	$size = getimagesize($image);
	if(is_numeric($size[0]) and is_numeric($size[1])) {
		return true;
	} else {
		return false;
	}
}

function createImage($image, $maxwidth, $maxheight, $cut = false) {
	if($maxwidth == NULL or $maxheight == NULL) {
		$size = getimagesize($image);
		$width = $size[0];
		$height = $size[1];
	} else {
		$dimensions = imageSizeCalculator($image, $maxwidth, $maxheight, $cut);
		$width = $dimensions['width'];
		$height = $dimensions['height'];
	}

	$filename = explode('/', $image);
	if($filename[count($filename)-2] != '') {
		$prefix = $filename[count($filename)-2].'-';
	}
	$filename = $filename[count($filename)-1];
	$extension = explode('.', $filename);
	$extension = $extension[count($extension)-1];
	$filename = substr($filename, 0, (strlen($filename) - strlen($extension) - 1));
	$filename = 'data/tmp/image-'.$prefix.$width.'-'.$height.'-'.base64_encode($filename).'.'.$extension;
	if(!is_file($filename)) {
		if($cut == true) {
			$src_x = 0;
			$src_y = 0;
			if($width > $maxwidth) {
				$src_x = ($width - $maxwidth) / 2;
			}
			if($height > $maxheight) {
				$src_y = ($height - $maxheight) / 2;
			}
		}
		$mime_type = getMimetype($image);
		if($mime_type == 'image/gif') {
			$src_img = imagecreatefromgif($image);
			$dst_img = imagecreate($width, $height);
			imagecolortransparent($dst_img, imagecolorallocate($dst_img, 0, 0, 0));
			imagealphablending($dst_img, false);
			imagesavealpha($dst_img, true);
			imagecopyresampled($dst_img,$src_img,0,0,0,0,$width,$height,imagesx($src_img),imagesy($src_img));
			if($cut == true) {
				$cut_img = imagecreate($maxwidth, $maxheight);
				imagecolortransparent($cut_img, imagecolorallocate($cut_img, 0, 0, 0));
				imagealphablending($cut_img, false);
				imagesavealpha($cut_img, true);
				imagecopyresampled($cut_img,$dst_img,0,0,$src_x,$src_y,$maxwidth,$maxheight,$maxwidth,$maxheight);
				$dst_img = $cut_img;
			}
			imagegif($dst_img, $filename);
			imagedestroy($dst_img);
		}
		if($mime_type == 'image/jpeg' or $mime_type == 'image/pjpeg') {
			$src_img = imagecreatefromjpeg($image);
			$dst_img = imagecreatetruecolor($width, $height);
			imagecopyresampled($dst_img,$src_img,0,0,0,0,$width,$height,imagesx($src_img),imagesy($src_img));
			if($cut == true) {
				$cut_img = imagecreatetruecolor($maxwidth, $maxheight);
				imagecopyresampled($cut_img,$dst_img,0,0,$src_x,$src_y,$maxwidth,$maxheight,$maxwidth,$maxheight);
				$dst_img = $cut_img;
			}
			imagejpeg($dst_img, $filename, 95);
			imagedestroy($dst_img);
		}
		if($mime_type == 'image/png') {
			$src_img = imagecreatefrompng($image);
			$dst_img = imagecreatetruecolor($width, $height);
			imagecolortransparent($dst_img, imagecolorallocate($dst_img, 0, 0, 0));
			imagealphablending($dst_img, false);
			imagesavealpha($dst_img, true);
			imagecopyresampled($dst_img,$src_img,0,0,0,0,$width,$height,imagesx($src_img),imagesy($src_img));
			if($cut == true) {
				$cut_img = imagecreatetruecolor($maxwidth, $maxheight);
				imagecolortransparent($cut_img, imagecolorallocate($cut_img, 0, 0, 0));
				imagealphablending($cut_img, false);
				imagesavealpha($cut_img, true);
				imagecopyresampled($cut_img,$dst_img,0,0,$src_x,$src_y,$maxwidth,$maxheight,$maxwidth,$maxheight);
				$dst_img = $cut_img;
			}
			imagepng($dst_img, $filename);
			imagedestroy($dst_img);
		}
	}
	return $filename;
}

function imageSizeCalculator($image, $maxwidth, $maxheight, $cut = false) {
	if($image == '') {
		echo '<p>imageSizeCalculator() > Parameter missing: $image</p>';
		return;
	}
	if(!file_exists($image)) {
		echo '<p>imageSizeCalculator() > File missing: '.$image.'</p>';
		return;
	}
	$size = getimagesize($image);
	if($size[0] > $maxwidth or $size[1] > $maxheight) {
		if($size[0] > $size[1]) {
			// width is larger
			$width = $maxwidth;
			$percent = ($width / $size[0]);
			$height = ($size[1] * $percent);
			// if height is still too large
			if($height > $maxheight) {
				$height2 = $maxheight;
				$percent = ($height2 / $height);
				$width2 = ($width * $percent);
				$width = $width2;
				$height = $height2;
			}
		} else {
			// height is larger
			$height = $maxheight;
			$percent = ($height / $size[1]);
			$width = ($size[0] * $percent);
			// width is still too large
			if($width > $maxwidth) {
				$width2 = $maxwidth;
				$percent = ($width2 / $width);
				$height2 = ($height * $percent);
				$width = $width2;
				$height = $height2;
			}
		}
		if($cut == true) {
			if($width < $maxwidth) {
				// only width is smaller
				$percent = $maxwidth / $width;
				$width += ($maxwidth - $width);
				$height = $height * $percent;
			}
			if($height < $maxheight) {
				// only height is smaller
				$percent = $maxheight / $height;
				$height += ($maxheight - $height);
				$width = $width * $percent;
			}
		}
		$dimensions['width'] = round($width);
		$dimensions['height'] = round($height);
	} else {
		if($cut == true) {
			if($size[0] < $maxwidth and $size[1] < $maxheight) {
				if($maxwidth > $maxheight) {
					$size[0] = $maxwidth;
					$size[1] = $maxwidth;
				} elseif($maxheight > $maxwidth) {
					$size[0] = $maxheight;
					$size[1] = $maxheight;
				} else {
					$size[0] = $maxwidth;
					$size[1] = $maxheight;
				}
			}
		}
		$dimensions['width'] = $size[0];
		$dimensions['height'] = $size[1];
	}
	return $dimensions;
}

function getMimetype($file) {
	if($file == '') {
		echo '<p>getMimetype() > Parameter missing: $file</p>';
		return;
	}
	if(!file_exists($file)) {
		echo '<p>getMimetype() > File missing: '.$file.'</p>';
		return;
	}
	if(function_exists('finfo_open')) {
		$handle = finfo_open(FILEINFO_MIME);
		$mime_type = finfo_file($handle, $file);
		if(inIString('jpg', $mime_type) or inIString('jpeg', $mime_type)) {
			$mime_type = 'image/jpeg';
		}
		if(inIString('gif', $mime_type)) {
			$mime_type = 'image/gif';
		}
		if(inIString('png', $mime_type)) {
			$mime_type = 'image/png';
		}
	} else {
		$size = getimagesize($file);
		$mime_type = $size['mime'];
	}
	return $mime_type;
}

function inIString($needle, $haystack) {
	$pos = stripos($haystack, $needle);
	if($pos !== false) {
		return true;
	} else {
		return false;
	}
}

function remove_accents($string) {
    if ( !preg_match('/[\x80-\xff]/', $string) )
        return $string;

    $chars = array(
    // Decompositions for Latin-1 Supplement
    chr(195).chr(128) => 'A', chr(195).chr(129) => 'A',
    chr(195).chr(130) => 'A', chr(195).chr(131) => 'A',
    chr(195).chr(132) => 'A', chr(195).chr(133) => 'A',
    chr(195).chr(135) => 'C', chr(195).chr(136) => 'E',
    chr(195).chr(137) => 'E', chr(195).chr(138) => 'E',
    chr(195).chr(139) => 'E', chr(195).chr(140) => 'I',
    chr(195).chr(141) => 'I', chr(195).chr(142) => 'I',
    chr(195).chr(143) => 'I', chr(195).chr(145) => 'N',
    chr(195).chr(146) => 'O', chr(195).chr(147) => 'O',
    chr(195).chr(148) => 'O', chr(195).chr(149) => 'O',
    chr(195).chr(150) => 'O', chr(195).chr(153) => 'U',
    chr(195).chr(154) => 'U', chr(195).chr(155) => 'U',
    chr(195).chr(156) => 'U', chr(195).chr(157) => 'Y',
    chr(195).chr(159) => 's', chr(195).chr(160) => 'a',
    chr(195).chr(161) => 'a', chr(195).chr(162) => 'a',
    chr(195).chr(163) => 'a', chr(195).chr(164) => 'a',
    chr(195).chr(165) => 'a', chr(195).chr(167) => 'c',
    chr(195).chr(168) => 'e', chr(195).chr(169) => 'e',
    chr(195).chr(170) => 'e', chr(195).chr(171) => 'e',
    chr(195).chr(172) => 'i', chr(195).chr(173) => 'i',
    chr(195).chr(174) => 'i', chr(195).chr(175) => 'i',
    chr(195).chr(177) => 'n', chr(195).chr(178) => 'o',
    chr(195).chr(179) => 'o', chr(195).chr(180) => 'o',
    chr(195).chr(181) => 'o', chr(195).chr(182) => 'o',
    chr(195).chr(182) => 'o', chr(195).chr(185) => 'u',
    chr(195).chr(186) => 'u', chr(195).chr(187) => 'u',
    chr(195).chr(188) => 'u', chr(195).chr(189) => 'y',
    chr(195).chr(191) => 'y',
    // Decompositions for Latin Extended-A
    chr(196).chr(128) => 'A', chr(196).chr(129) => 'a',
    chr(196).chr(130) => 'A', chr(196).chr(131) => 'a',
    chr(196).chr(132) => 'A', chr(196).chr(133) => 'a',
    chr(196).chr(134) => 'C', chr(196).chr(135) => 'c',
    chr(196).chr(136) => 'C', chr(196).chr(137) => 'c',
    chr(196).chr(138) => 'C', chr(196).chr(139) => 'c',
    chr(196).chr(140) => 'C', chr(196).chr(141) => 'c',
    chr(196).chr(142) => 'D', chr(196).chr(143) => 'd',
    chr(196).chr(144) => 'D', chr(196).chr(145) => 'd',
    chr(196).chr(146) => 'E', chr(196).chr(147) => 'e',
    chr(196).chr(148) => 'E', chr(196).chr(149) => 'e',
    chr(196).chr(150) => 'E', chr(196).chr(151) => 'e',
    chr(196).chr(152) => 'E', chr(196).chr(153) => 'e',
    chr(196).chr(154) => 'E', chr(196).chr(155) => 'e',
    chr(196).chr(156) => 'G', chr(196).chr(157) => 'g',
    chr(196).chr(158) => 'G', chr(196).chr(159) => 'g',
    chr(196).chr(160) => 'G', chr(196).chr(161) => 'g',
    chr(196).chr(162) => 'G', chr(196).chr(163) => 'g',
    chr(196).chr(164) => 'H', chr(196).chr(165) => 'h',
    chr(196).chr(166) => 'H', chr(196).chr(167) => 'h',
    chr(196).chr(168) => 'I', chr(196).chr(169) => 'i',
    chr(196).chr(170) => 'I', chr(196).chr(171) => 'i',
    chr(196).chr(172) => 'I', chr(196).chr(173) => 'i',
    chr(196).chr(174) => 'I', chr(196).chr(175) => 'i',
    chr(196).chr(176) => 'I', chr(196).chr(177) => 'i',
    chr(196).chr(178) => 'IJ',chr(196).chr(179) => 'ij',
    chr(196).chr(180) => 'J', chr(196).chr(181) => 'j',
    chr(196).chr(182) => 'K', chr(196).chr(183) => 'k',
    chr(196).chr(184) => 'k', chr(196).chr(185) => 'L',
    chr(196).chr(186) => 'l', chr(196).chr(187) => 'L',
    chr(196).chr(188) => 'l', chr(196).chr(189) => 'L',
    chr(196).chr(190) => 'l', chr(196).chr(191) => 'L',
    chr(197).chr(128) => 'l', chr(197).chr(129) => 'L',
    chr(197).chr(130) => 'l', chr(197).chr(131) => 'N',
    chr(197).chr(132) => 'n', chr(197).chr(133) => 'N',
    chr(197).chr(134) => 'n', chr(197).chr(135) => 'N',
    chr(197).chr(136) => 'n', chr(197).chr(137) => 'N',
    chr(197).chr(138) => 'n', chr(197).chr(139) => 'N',
    chr(197).chr(140) => 'O', chr(197).chr(141) => 'o',
    chr(197).chr(142) => 'O', chr(197).chr(143) => 'o',
    chr(197).chr(144) => 'O', chr(197).chr(145) => 'o',
    chr(197).chr(146) => 'OE',chr(197).chr(147) => 'oe',
    chr(197).chr(148) => 'R',chr(197).chr(149) => 'r',
    chr(197).chr(150) => 'R',chr(197).chr(151) => 'r',
    chr(197).chr(152) => 'R',chr(197).chr(153) => 'r',
    chr(197).chr(154) => 'S',chr(197).chr(155) => 's',
    chr(197).chr(156) => 'S',chr(197).chr(157) => 's',
    chr(197).chr(158) => 'S',chr(197).chr(159) => 's',
    chr(197).chr(160) => 'S', chr(197).chr(161) => 's',
    chr(197).chr(162) => 'T', chr(197).chr(163) => 't',
    chr(197).chr(164) => 'T', chr(197).chr(165) => 't',
    chr(197).chr(166) => 'T', chr(197).chr(167) => 't',
    chr(197).chr(168) => 'U', chr(197).chr(169) => 'u',
    chr(197).chr(170) => 'U', chr(197).chr(171) => 'u',
    chr(197).chr(172) => 'U', chr(197).chr(173) => 'u',
    chr(197).chr(174) => 'U', chr(197).chr(175) => 'u',
    chr(197).chr(176) => 'U', chr(197).chr(177) => 'u',
    chr(197).chr(178) => 'U', chr(197).chr(179) => 'u',
    chr(197).chr(180) => 'W', chr(197).chr(181) => 'w',
    chr(197).chr(182) => 'Y', chr(197).chr(183) => 'y',
    chr(197).chr(184) => 'Y', chr(197).chr(185) => 'Z',
    chr(197).chr(186) => 'z', chr(197).chr(187) => 'Z',
    chr(197).chr(188) => 'z', chr(197).chr(189) => 'Z',
    chr(197).chr(190) => 'z', chr(197).chr(191) => 's'
    );

    $string = strtr($string, $chars);

    return $string;
}
