<?php 

if ( ! function_exists('createLockFile'))
{
	function createLockFile ($lockFilePrefix, $maxReach, $timeToUnlock, $colSep = '|', $lockFilePath = '')
	{
		$currentTimeStamp = time();
		$filePath = $lockFilePath.$lockFilePrefix.'_lock';
		$fileExisted = file_exists($filePath);
		$content = '';
		$lastTimeLock = '';
		$lockCount = 0;
		$isLocked = 0;
		$ready = 0;
	
		if ($fileExisted) {
			$content = file_get_contents($filePath);
		}
	
		if ($content != '') {
			list($lockCount, $lastTimeLock, $isLocked) = explode ($colSep, $content);
		}
	
		$timeDiffMin = $lastTimeLock != '' ? dateDifference(date('Y-m-d H:i:s',$currentTimeStamp), date('Y-m-d H:i:s',$lastTimeLock), '%i') : 0;
	
		if ($lockCount < $maxReach && $timeDiffMin < $timeToUnlock) {
			$lockCount ++;
			$isLocked = $lockCount < $maxReach ? 0:1;
			$ready = 1;
		}
		else if ($timeDiffMin > $timeToUnlock) {
			$lockCount = 0;
			$isLocked = 0;
			$ready = 1;
		}
	
		$lockTime = ($isLocked == 1) ? $lastTimeLock : $currentTimeStamp;
		$content = $lockCount . $colSep . $lockTime . $colSep . $isLocked;
		if($ready == 1) {
			$fh = fopen ($filePath,'w');
			fwrite ($fh, $content);
			fclose ($fh);
		}
	
		return $lockCount;
	}
}

if ( ! function_exists('releaseLockFile'))
{
	function releaseLockFile ($lockFilePrefix, $lockFilePath = '')
	{
		$filePath = $lockFilePrefix.'_lock';
		$fileExisted = file_exists($filePath);
		if ($fileExisted) {
			unlink($filePath);
		}
	}
}

/**
 * dateDifference
 * Return difference between two dates
 *
 * @access	public
 * @param	date	date_1
 * @param	date	date_2
 * @param	string	differenceFormat ()
 * @return	string
 *
 * @example '%y Year %m Month %d Day %h Hours %i Minute %s Seconds', %y Year %m Month %d Day','%m Month %d Day'
 * @example '%d Day %h Hours', '%d Day', '%h Hours %i Minute %s Seconds', '%i Minute %s Seconds','%h Hours', '%a Days'
 */

if ( ! function_exists('dateDifference'))
{
	function dateDifference($date_1 , $date_2 , $differenceFormat = '%a' )
	{
		$datetime1 = date_create($date_1);
		$datetime2 = date_create($date_2);

		$interval = date_diff($datetime1, $datetime2);

		return $interval->format($differenceFormat);

	}
}
