<?php
/**
 * URL Shortener logic
 */

include_once(dirname(__FILE__).'/./config.inc.php');
include_once(dirname(__FILE__).'/./MySQLDbStorage.class.php');

class UrlShortener {

	private $storage;

	function __construct() {
		$this->storage = new MySQLDbStorage();
	}
	
	function shortenUrl($urlToShorten, $shortId = NULL) {
		if (empty($urlToShorten) == true) {
			return NULL;
		}
		if ($this->checkUrlPattern($urlToShorten) == false) {
			return NULL;
		}
		if ($this->checkUserShortId($shortId) == false) {
			$shortId = NULL;
		}
		
		// check if this url has been shortened before
		$existingEntry = $this->storage->getEntryByUrl($urlToShorten);
		if (empty($existingEntry) == false) {
			if (empty($shortId) == true) {
				return $existingEntry['id'];
			}
			if ($shortId == $existingEntry['id']) {
				return $existingEntry['id'];
			}
		}
		
		// assign URL
		$newId = $this->storage->reserveId($shortId, $urlToShorten);
		return $newId;
	}
	
	function expandUrl($urlToExpand, $markVisited = false) {
		$shortUrl = $urlToExpand;
		if (str_startswith($shortUrl, SERVICE_BASE_URL)) {
			$shortUrl = substr($shortUrl, strlen(SERVICE_BASE_URL));
		}
		$foundEntry = $this->storage->getEntryById($shortUrl);
		if (($foundEntry != NULL) && ($markVisited == true)) {
			$this->storage->markVisited($foundEntry['id']);
			// increase counter in object
			$foundEntry['visited']++;
		}
		return $foundEntry;
	}
	
	function checkUrlPattern($urlToCheck) {
		if (empty($urlToCheck) == true) {
			return false;
		}
		$urlToCheck = strtolower($urlToCheck);
		$supportedSchemas = array("http://", "https://", "mailto:");
		foreach ($supportedSchemas as $oneSchema) {
			if (str_startswith($urlToCheck, $oneSchema)) {
				return true;
			}
  		}
  		return false;
	}
	
	function checkUserShortId($shortidToCheck) {
		// check pattern
		if (preg_match("/[a-zA-Z0-9_-]+/", $shortidToCheck) != 1) {
			return false;
		}
		// check against blacklist
		
		// allow all short ids
		return true;
	}
	
	function getStatisticsOverview() {
		return $this->storage->getStatisticsOverview();
	}

	function getRandomLink() {
		return $this->storage->getRandomLink();
	}
	
	function getStatsCountByType() {
		return $this->storage->getStatsCountByType();
	}
	
	function getStatsAllLinksByType($t) {
		return $this->storage->getStatsAllLinksByType($t);
	}

	function getStatsListActiveLinks($cnt = 10) {
		return $this->storage->getStatsListActiveLinks($cnt);
	}
	
	function getStatsLinkData($t = -1) {
		return $this->storage->getStatsLinkData($t);
	}

}
