
PK 
<?php
//Helper Function for print array
if (!function_exists('p')) {
function p($q = null, $isDie = false)
{
echo "<pre>";
print_r($q);
echo "</pre>";
if ($isDie) {
die('Exit Here What you want');
}
}
}
//Helper Function for print array with additional info
if (!function_exists('vd')) {
function vd($q = null, $isDie = false)
{
echo "<pre>";
var_dump($q);
echo "</pre>";
if ($isDie) {
die('Exit Here What you want');
}
}
}
//Helper Function for print array with additional info
if (!function_exists('dd')) {
function dd($q = null)
{
var_dump($q);
}
}
if (!function_exists('gdf')) {
function gdf()
{
echo "<pre>";
//var_export(get_defined_functions());
print_r(get_defined_functions());
echo "<pre>";
}
}
//Helper Function for activeMenu
if (!function_exists('classActiveMenu')) {
//Route::currentRouteName(); //Request::route()->getName(); //Request::segment(1) //Request::is('admin')
function classActiveMenu($requestName, $start = null, $finish = null)
{
$currentRouteName = Route::currentRouteName();
//if (substr($currentRouteName,$start,$finish)==$requestName) {
if ($currentRouteName == $requestName) {
return ' active';
}
return '';
}
}
if (!function_exists('classActiveSegment')) {
function classActiveSegment($value, $segment = 1)
{
if (!is_array($value)) {
return Request::segment($segment) == $value ? ' active' : '';
}
foreach ($value as $v) {
if (Request::segment($segment) == $v) return ' active';
}
return '';
}
}
if (!function_exists('classActivePath')) {
function classActivePath($path)
{
$path = explode('.', $path);
$segment = 1;
foreach ($path as $p) {
if ((request()->segment($segment) == $p) == false) {
return '';
}
$segment++;
}
return ' active';
}
}
//Helper Function for HierarchicalTree
if (!function_exists('buildTree')) {
function buildTree(array $data, $parent = 0)
{
$tree = array();
foreach ($data as $d) {
/* $parent_id = (!empty($d['parent_id']))?'parent_id':'parentattr_id';
exit;
if ($d[$parent_id] == $parent) { */
if ($d['parent_id'] == $parent) {
$children = buildTree($data, $d['id']);
if (!empty($children)) {
$d['_children'] = $children;
}
$tree[] = $d;
}
}
return $tree;
}
}
//Helper Function for buildPrintTree
if (!function_exists('buildTreeDropdown')) {
function buildTreeDropdown($tree, $r = 0, $p = null, $find_id = null, $current_id = null)
{
foreach ($tree as $i => $t) {
$dash = ($t['parent_id'] == 0) ? '' : str_repeat(' ', $r) . ' ';
if (is_array($find_id)) {
printf("\t<option value='%d' %s style='font-weight: bold;'>%s%s</option>\n", $t['id'], $finder = (in_array($t['id'], $find_id)) ? "selected" : "", $dash, $t['category_name']);
} else {
if ($t['id'] != $current_id) {
printf("\t<option value='%d' %s style='font-weight: bold;'>%s%s</option>\n", $t['id'], $finder = ($t['id'] == $find_id) ? "selected" : "", $dash, $t['category_name']);
}
}
if (isset($t['_children'])) {
buildTreeDropdown($t['_children'], $r + 1, $t['parent_id'], $find_id, $current_id);
}
}
}
}
//Helper Function for HierarchicalTree
if (!function_exists('buildAttrTree')) {
function buildAttrTree(array $data, $parent = 0)
{
$tree = array();
foreach ($data as $d) {
if ($d['parentattr_id'] == $parent) {
$children = buildAttrTree($data, $d['id']);
if (!empty($children)) {
$d['_children'] = $children;
}
$tree[] = $d;
}
}
return $tree;
}
}
//Helper Function for buildPrintTree
if (!function_exists('buildAttrTreeDropdown')) {
function buildAttrTreeDropdown($tree, $r = 0, $p = null, $find_id = null, $current_id = null)
{
foreach ($tree as $i => $t) {
$dash = ($t['parentattr_id'] == 0) ? '' : str_repeat(' ', $r) . ' ';
if (is_array($find_id)) {
printf("\t<option value='%d' %s style='font-weight: bold;'>%s%s</option>\n", $t['id'], $finder = (in_array($t['id'], $find_id)) ? "selected" : "", $dash, $t['attribute_name']);
} else {
if ($t['id'] != $current_id) {
printf("\t<option value='%d' %s style='font-weight: bold;'>%s%s</option>\n", $t['id'], $finder = ($t['id'] == $find_id) ? "selected" : "", $dash, $t['attribute_name']);
}
}
if (isset($t['_children'])) {
buildAttrTreeDropdown($t['_children'], $r + 1, $t['parentattr_id'], $find_id, $current_id);
}
}
}
}
// Menu builder function, parentId 0 is the root
/*if (!function_exists('buildNeighborDealsMenu')) {
function buildNeighborDealsMenu($menuData, $parent = 0)
{
$html = "";
if (isset($menuData['parents'][$parent])) {
$html .= "<ul class='nav navbar-nav navbar-right'>\n";
foreach ($menuData['parents'][$parent] as $itemId) {
if (!isset($menuData['parents'][$itemId])) {
$html .= "<li>\n <a href='#'>" . $menuData['items'][$itemId]['category_name'] . " </a>\n </li>\n";
}
if (isset($menuData['parents'][$itemId])) {
$html .= "<li class='dropdown'>\n <a class='dropdown-toggle tab-hover' data-toggle='dropdown' href='#' >" . $menuData['items'][$itemId]['category_name'] . "</a> \n";
$html .= buildNeighborDealsSubMenu($menuData, $itemId);
$html .= "</li>\n";
}
}
$html .= "</ul>\n";
}
return $html;
}
}*/
if (!function_exists('buildNeighborDealsMenu')) {
function buildNeighborDealsMenu($menuData, $parent = 0)
{
$html = "";
if (isset($menuData['parents'][$parent])) {
//$html .= "<ul class='nav navbar-nav navbar-right'>\n";
foreach ($menuData['parents'][$parent] as $itemId) {
if (!isset($menuData['parents'][$itemId])) {
if(in_array($menuData['items'][$itemId]['category_name'],['sale','Sale'])){
$html .= "<li>\n <a href='" . route('product.details', [$menuData['items'][$itemId]['id'],'here', $menuData['items'][$itemId]['category_slug']]) . "'>" . $menuData['items'][$itemId]['category_name'] . " </a>\n </li>\n";
}else{
$html .= "<li>\n <a href='#'>" . $menuData['items'][$itemId]['category_name'] . " </a>\n </li>\n";
}
}
if (isset($menuData['parents'][$itemId])) {
$html .= "<li class='dropdown'>\n <a class='dropdown-toggle tab-hover' data-toggle='dropdown' href='#' >" . $menuData['items'][$itemId]['category_name'] . "</a> \n";
$html .= buildNeighborDealsSubMenu($menuData, $itemId);
$html .= "</li>\n";
}
}
//$html .= "</ul>\n";
}
return $html;
}
}
// Menu builder function, parentId 0 is the root
if (!function_exists('buildNeighborDealsSubMenu')) {
function buildNeighborDealsSubMenu($menuData, $parent = 0)
{
//echo $parent.'<br>';
$html = "";
if (isset($menuData['parents'][$parent])) {
$html .= "<ul class='dropdown-menu big-dropdown-menu'>\n";
foreach ($menuData['parents'][$parent] as $itemId) {
$html .= "<div class='nav-section'>";
if (!isset($menuData['parents'][$itemId])) {
$html .= "<li>\n <a href='" . route('product.details', [$menuData['items'][$itemId]['parent_id'], $menuData['items'][$itemId]['id'], $menuData['items'][$itemId]['category_slug']]) . "'>" . $menuData['items'][$itemId]['category_name'] . "</a>\n </li>\n";
}
if (isset($menuData['parents'][$itemId])) {
//$html .= "<li>\n <a href='" . url() . "/product-details/" . $menuData['items'][$itemId]['id'] . "/here/" . $menuData['items'][$itemId]['category_slug'] . "'><strong>" . $menuData['items'][$itemId]['category_name'] . "</strong></a>\n </li>\n";
/*$html .= "<li>\n <a href='" . route('product.details', [$menuData['items'][$itemId]['id'], 'here', $menuData['items'][$itemId]['category_slug']]) . "'><strong>" . $menuData['items'][$itemId]['category_name'] . "</strong></a>\n </li>\n";*/
$html .= "<h3>\n
<span id='span_id' class='glyphicon glyphicon-plus'></span>
<a href='" . route('product.details', [$menuData['items'][$itemId]['parent_id'], $menuData['items'][$itemId]['id'], $menuData['items'][$itemId]['category_slug']]) . "'>" . $menuData['items'][$itemId]['category_name'] . "</a>\n</h3>";
$html .= buildNeighborDealsSubChildMenu($menuData, $itemId);
//$html .= "</li>\n";
}
$html .= "</div>";
}
$html .= "</ul>\n";
}
return $html;
}
}
if (!function_exists('buildNeighborDealsSubChildMenu')) {
function buildNeighborDealsSubChildMenu($menuData, $parent = 0)
{
$html = "";
if (isset($menuData['parents'][$parent])) {
foreach ($menuData['parents'][$parent] as $itemId) {
//$html .= "<div>";
if (!isset($menuData['parents'][$itemId])) {
$html .= "<li>\n <a href='" . route('product.details', [$menuData['items'][$itemId]['parent_id'], $menuData['items'][$itemId]['id'], $menuData['items'][$itemId]['category_slug']]) . "'>" . $menuData['items'][$itemId]['category_name'] . " </a>\n </li>\n";
}
if (isset($menuData['parents'][$itemId])) {
//$html.="<li>\n <a href='".url()."/product-details/".$menuData['items'][$itemId]['parent_id']."/".$menuData['items'][$itemId]['id']."/".$menuData['items'][$itemId]['category_slug']."'><strong>".$menuData['items'][$itemId]['category_name']."</strong></a>\n </li>\n";
$html .= "<li style='display: none;'>\n <a href='" . route('product.details', [$menuData['items'][$itemId]['id'], 'here', $menuData['items'][$itemId]['category_slug']]) . "'><strong>" . $menuData['items'][$itemId]['category_name'] . "</strong></a>\n </li>\n";
$html .= buildNeighborDealsSubChildMenu($menuData, $itemId);
//$html .= "</li>\n";
}
//$html .= "</div>\n";
}
//$html .= "</ul>\n";
}
return $html;
}
}
//Helper Function for getBasePath
if (!function_exists('getBasePath')) {
function getBasePath()
{
// This prints file full path and name
#echo "This file full path and file name is '" . __FILE__ . "'.\n";
// This prints file full path, without file name
#echo "This file full path is '" . __DIR__ . "'.\n";
// This prints current line number on file
#echo "This is line number " . __LINE__ . ".\n";
// Really simple basic test function
#echo "This is from '" . __FUNCTION__ . "' function.\n";
/*// output: /myproject/index.php
$currentPath = $_SERVER['PHP_SELF'];
// output: Array ( [dirname] => /myproject [basename] => index.php [extension] => php [filename] => index )
$pathInfo = pathinfo($currentPath);
// output: localhost
$hostName = $_SERVER['HTTP_HOST'];
// output: http://
$protocol = strtolower(substr($_SERVER["SERVER_PROTOCOL"],0,5))=='https://'?'https://':'http://';
// return: http://localhost/myproject/
return $protocol.$hostName.$pathInfo['dirname']."/";*/
$protocol = "";
$protocol = strtolower(substr($_SERVER["SERVER_PROTOCOL"], 0, 5)) == 'https://' ? 'https://' : 'http://';
$hostName = $_SERVER['HTTP_HOST'];
//return $protocol .=$_SERVER['SERVER_NAME'];
$protocol .= $hostName;
if ($protocol === "http://localhost" || $protocol === "http://localhost:8081") {
$protocol .= '/demo.absay.org';
} else {
$protocol;
}
$currentPath = $_SERVER['PHP_SELF'];
$pathInfo = pathinfo($currentPath);
//$baseUrl=$protocol.$pathInfo['dirname']."/";
//$baseUrl = ($pathInfo['dirname'] == "/") ? $protocol . "/" : $protocol . $pathInfo['dirname'] . "/";
$baseUrl = ($pathInfo['dirname'] == "/") ? $protocol . "/" : $protocol . "/";
$relative_path_arr = explode('/', $currentPath);
$page_uri = $relative_path_arr[count($relative_path_arr) - 1];
$currenturl = pathinfo($_SERVER['REQUEST_URI']);
$currenturl = $baseUrl . $page_uri;//$currenturl['filename'].".php";
//$documnet_root = $_SERVER['DOCUMENT_ROOT'];
$url = pathinfo($_SERVER['SCRIPT_NAME'], PATHINFO_DIRNAME);
$url_var = explode('/', $url);
$lastDirPath = end($url_var);
return $baseinfo = array(
"basepath" => $protocol,
"baseurl" => $baseUrl,
"currenturl" => $currenturl,
"pageurl" => $page_uri,
"lastdir" => $lastDirPath,
"adminpath" => $protocol . "/admin",
"userpath" => $protocol . "/useradmin",
//"dirname"=>$pathInfo['dirname'],
//"root"=>$documnet_root,
//"server"=>$_SERVER
);
}
}
//Helper Function for clients IP Address
if (!function_exists('ipAddress')) {
function ipAddress()
{
if (isset($_SERVER)) {
if (isset($_SERVER["HTTP_X_FORWARDED_FOR"]))
return $_SERVER["HTTP_X_FORWARDED_FOR"];
if (isset($_SERVER["HTTP_CLIENT_IP"]))
return $_SERVER["HTTP_CLIENT_IP"];
return $_SERVER["REMOTE_ADDR"];
}
if (getenv('HTTP_X_FORWARDED_FOR'))
return getenv('HTTP_X_FORWARDED_FOR');
if (getenv('HTTP_CLIENT_IP'))
return getenv('HTTP_CLIENT_IP');
return getenv('REMOTE_ADDR');
}
}
//Helper Function for getBrowser
if (!function_exists('getBrowser')) {
function getBrowser()
{
$u_agent = $_SERVER['HTTP_USER_AGENT'];
$bname = 'Unknown';
$platform = 'Unknown';
$version = "";
//First get the platform?
if (preg_match('/linux/i', $u_agent)) {
$platform = 'linux';
} elseif (preg_match('/macintosh|mac os x/i', $u_agent)) {
$platform = 'mac';
} elseif (preg_match('/windows|win32/i', $u_agent)) {
$platform = 'windows';
}
// Next get the name of the useragent yes seperately and for good reason
if (preg_match('/MSIE/i', $u_agent) && !preg_match('/Opera/i', $u_agent)) {
$bname = 'Internet Explorer';
$ub = "MSIE";
} elseif (preg_match('/Firefox/i', $u_agent)) {
$bname = 'Mozilla Firefox';
$ub = "Firefox";
} elseif (preg_match('/Chrome/i', $u_agent)) {
$bname = 'Google Chrome';
$ub = "Chrome";
} elseif (preg_match('/Safari/i', $u_agent)) {
$bname = 'Apple Safari';
$ub = "Safari";
} elseif (preg_match('/Opera/i', $u_agent)) {
$bname = 'Opera';
$ub = "Opera";
} elseif (preg_match('/Netscape/i', $u_agent)) {
$bname = 'Netscape';
$ub = "Netscape";
}
// finally get the correct version number
$known = array('Version', $ub, 'other');
$pattern = '#(?<browser>' . join('|', $known) .
')[/ ]+(?<version>[0-9.|a-zA-Z.]*)#';
if (!preg_match_all($pattern, $u_agent, $matches)) {
// we have no matching number just continue
}
// see how many we have
$i = count($matches['browser']);
if ($i != 1) {
//we will have two since we are not using 'other' argument yet
//see if version is before or after the name
if (strripos($u_agent, "Version") < strripos($u_agent, $ub)) {
$version = $matches['version'][0];
} else {
$version = $matches['version'][1];
}
} else {
$version = $matches['version'][0];
}
// check if we have a number
if ($version == null || $version == "") {
$version = "?";
}
return array(
'userAgent' => $u_agent,
'name' => $bname,
'version' => $version,
'platform' => $platform,
'pattern' => $pattern
);
}
}
//Helper Function for escape
if (!function_exists('escape')) {
function escape($string)
{
return htmlentities($string, ENT_QUOTES, 'UTF-8');
}
}
//Helper Function for stripString
if (!function_exists('stripString')) {
function stripString($string)
{
return str_replace(array("\n\r", "\n", "\r", "<br/>"), '', $string);
}
}
//Helper Function for encryptIt
if (!function_exists('encryptIt')) {
function encryptIt($q)
{
return $q;
/*$cryptKey = 'qJB0rGtIn5UB1xG03efyCp';
$qEncoded = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($cryptKey), trim($q), MCRYPT_MODE_CBC, md5(md5($cryptKey))));
return ($qEncoded);*/
}
}
//Helper Function for decryptIt
if (!function_exists('decryptIt')) {
function decryptIt($q)
{
return $q;
/*$cryptKey = 'qJB0rGtIn5UB1xG03efyCp';
$qDecoded = trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($cryptKey), base64_decode(str_replace(' ','+',$q)), MCRYPT_MODE_CBC, md5(md5($cryptKey))), "\0");
return ($qDecoded);*/
}
}
//Helper Function for serialize
if (!function_exists('_serialize')) {
/**
* Serialize an array
*
* This function first converts any slashes found in the array to a temporary
* marker, so when it gets unserialized the slashes will be preserved
*
* @access private
* @param array
* @return string
*/
function _serialize($data)
{
if (is_array($data)) {
foreach ($data as $key => $val) {
if (is_string($val)) {
$data[$key] = str_replace('\\', '{{slash}}', $val);
}
}
} else {
if (is_string($data)) {
$data = str_replace('\\', '{{slash}}', $data);
}
}
return serialize($data);
}
}
//Helper Function for unserialize
if (!function_exists('_unserialize')) {
/**
* Unserialize
*
* This function unserializes a data string, then converts any
* temporary slash markers back to actual slashes
*
* @access private
* @param array
* @return string
*/
function _unserialize($data)
{
$data = @unserialize(strip_slashes($data));
if (is_array($data)) {
foreach ($data as $key => $val) {
if (is_string($val)) {
$data[$key] = str_replace('{{slash}}', '\\', $val);
}
}
return $data;
}
return (is_string($data)) ? str_replace('{{slash}}', '\\', $data) : $data;
}
}
//Helper Function for makeDir
if (!function_exists('makeDir')) {
function makeDir($directoryName, $mode = 0755)
{
//Check if the directory already exists.
if (!is_dir($directoryName)) {
//Directory does not exist, so lets create it.
mkdir($directoryName, $mode, true);
$file = fopen($directoryName . "index.php", "w+");
fwrite($file, "Access Denied!!");
fclose($file);
//chmod($file,0777);
return true;
}
return false;
}
}
//Helper Function for fileExtension
if (!function_exists('fileExtension')) {
function fileExtension($filename)
{
return pathinfo(basename($filename), PATHINFO_EXTENSION);
//end(explode('.',$file_path));
}
}
//Helper Function for resizeImage
if (!function_exists('resizeImage')) {
function resizeImage($image_path = '', $thumimage_path = '', $width = 150, $height = 150)
{
if ($width && $height) {
$new_width = $width;
$new_height = $height;
$new_ratio = $new_width / $new_height;
// Resize image
$size = getimagesize($image_path); // Get image size
$original_width = $size[0];
$original_height = $size[1];
$original_ratio = $original_width / $original_height; // Get original ratio width/height
if ($original_ratio > $new_ratio) { // If ratio is greater than optimal
$width = $original_width / ($original_height / $new_height);
$height = $new_height;
$shift_x = (($width - $new_width) * ($original_width / $width)) / 2;
$shift_y = 0;
} elseif ($original_ratio < $new_ratio) { // If ratio is lesser than optimal
$width = $new_width;
$height = $original_height / ($original_width / $new_width);
$shift_x = 0;
$shift_y = (($height - $new_height) * ($original_height / $height)) / 2;
} else { // If ratio is already optimal
$width = $new_width;
$height = $new_height;
$shift_x = 0; // No need to crop horizontally
$shift_y = 0; // No need to crop vertically
}
$src = imagecreatefromstring(file_get_contents($image_path));
$dst = imagecreatetruecolor($new_width, $new_height);
imagecopyresampled($dst, $src, 0, 0, $shift_x, $shift_y, $width, $height, $original_width, $original_height);
//imagedestroy($src); // Free up memory
$thumimage_path = $thumimage_path;//$destinationPath . '/thumb/'.$fileName;
imagejpeg($dst, $thumimage_path, 100); // adjust format as needed
//imagedestroy($dst);
}
}
}
//Helper Function for randomString
if (!function_exists('randomString')) {
function randomString()
{
$character_set_array = array();
$character_set_array[] = array('count' => 15, 'characters' => 'abcdefghijklmnopqrstuvwxyz');
$character_set_array[] = array('count' => 10, 'characters' => 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
$character_set_array[] = array('count' => 7, 'characters' => '0123456789');
$character_set_array[] = array('count' => 1, 'characters' => '!@#$+-*&?:'); // Uncomment if need special cherecters
$temp_array = array();
foreach ($character_set_array as $character_set) {
for ($i = 0; $i < $character_set['count']; $i++) {
$temp_array[] = $character_set['characters'][rand(0, strlen($character_set['characters']) - 1)];
}
}
shuffle($temp_array);
return implode('', $temp_array);
}
}
//Helper Function for generateRandom
if (!function_exists('generateRandom')) {
function generateRandom($prefix = '')
{
//$randomno = substr(md5(uniqid(mt_rand(), true)), 0, $length);
return strtoupper(uniqid($prefix, false));
//return $prefix . $randomno;
}
}
//Helper Function for passwordEncrypt
if (!function_exists('passwordEncrypt')) {
function passwordEncrypt($value)
{
$salt = "SA#$8t*";
$password = md5($salt . $value);
return $password;
}
}
//Helper Function for getCurrentDate
if (!function_exists('getCurrentDate')) {
function getCurrentDate($datetime = null, $format = "d-M-Y")
{
//g:i a \n\o\n l jS F Y
$date = ((isset($datetime)) ? date($format, strtotime($datetime)) : ((isset($format) && !isset($datetime)) ? date(($format == "d-M-Y") ? "Y-m-d H:i:s" : $format, strtotime(date("Y-m-d H:i:s"))) : date("Y-m-d H:i:s")));
if ($datetime == null) {
return $date;
}
$checkDate = ['01-Jan-1970', '30-Nov--0001', '0000-00-00', '0000-00-00 00-00-00'];
if (in_array($date, $checkDate)) {
return 'NIL';
} else {
return $date;
}
}
}
//Helper Function for getFormattedDate
if (!function_exists('getFormattedDate')) {
function getFormattedDate($date)
{
$date = strtotime($date);
return date('Y-m-d', $date);
//$date = new DateTime($date);
//return date_format($date, 'l jS \\of F Y H:m:s');
}
}
//Helper Function for formatDate
if (!function_exists('formatDate')) {
function formatDate($date)
{
$created_at = $date;
$today = \Carbon\Carbon::now();
$difference = date_diff($created_at, $today);
if ($difference->days > 1) {
//{{$job->created_at ? $job->created_at->format('l jS \\of F Y') : ''}}
return $date->format('l jS \\of F Y H:m:s');
}
return $date->diffForHumans();
}
}
//Helper Function for covertDateToDay
if (!function_exists('covertDateToDay')) {
function covertDateToDay($date)
{
$day = strtotime($date);
$day = date("l", $day);
return strtoupper($day);
}
}
//Helper Function for getHoursWorked
if (!function_exists('getHoursWorked')) {
function getHoursWorked($inTime, $outTime)
{
$result = strtotime($outTime) - strtotime($inTime);
$totalMinutes = abs($result) / 60;
$minutes = $totalMinutes % '60';
$hours = $totalMinutes - $minutes;
$hours = $hours / 60;
return $hours . ':00' . $minutes . ':00';
}
}
//Helper Function for dateDifrence
if (!function_exists('dateDifrence')) {
function dateDifrence($dt1, $dt2, $dateTime = 'Y-m-d', $format = "%a")
{
$date1 = date_create(date('Y-m-d', strtotime($dt1)));
$date2 = date_create(date('Y-m-d', strtotime($dt2)));
$diff = $date2->diff($date1)->format("%R%a"); //"%R%a" "%a" "%i"
return $diff;
}
}
//Helper Function for ageCalculator
if (!function_exists('ageCalculator')) {
function ageCalculator($dob)
{
if (!empty($dob)) {
$birthdate = new DateTime($dob);
$today = new DateTime('today');
$age = $birthdate->diff($today)->y;
return $age;
} else {
return 0;
}
}
}
//Helper Function for addDays
if (!function_exists('addDays')) {
function addDays($adddays = 0, $date = null)
{
$date = (empty($date)) ? date('d-m-Y') : $date;
return date('d-m-Y', strtotime($date . "+$adddays days"));
}
}
//Helper Function for getDays
if (!function_exists('getDays')) {
function getDays($start = 1, $end = 31)
{
$days = array();
for ($day = $start; $day <= $end; $day++) {
if ($day <= 9) {
$day = "0" . $day;
} else {
$day = $day;
}
$days[] = $day;
}
return $days;
}
}
//Helper Function for getMonths
if (!function_exists('getMonths')) {
function getMonths($start = 1, $end = 12)
{
$months = array();
$monthArray = range($start, $end);
foreach ($monthArray as $month) {
// padding the month with extra zero
$monthPadding = str_pad($month, 2, "0", STR_PAD_LEFT);
// you can use whatever year you want
// you can use 'M' or 'F' as per your month formatting preference
$fdate = date("F", strtotime("2015-$monthPadding-01"));
//echo '<option value="'.$monthPadding.'">'.$fdate.'</option>';
$months[] = $fdate;
}
return $months;
}
}
//Helper Function for getYears
if (!function_exists('getYears')) {
function getYears($age = 18, $startyear = 1930, $endyear = null)
{
$years = array();
$currentyear = (int)date('Y');
$endyear = $currentyear - $age;
//$startyear = 1930;
for ($year = $startyear; $year <= $endyear; $year++) {
$years[] = $year;
}
return $years;
}
}
//Helper Function for getValidMobileNumber
if (!function_exists('getValidMobileNumber')) {
function getValidMobileNumber($mobile_number)
{
$mobile_number = trim(preg_replace("/\s+/", '', $mobile_number));
if (strlen($mobile_number) == 11 && substr($mobile_number, 0, 1) === '0') {
$mobileno = substr($mobile_number, 1);
} elseif (strlen($mobile_number) == 12 && substr($mobile_number, 0, 2) === '91') {
$mobileno = substr($mobile_number, 2);
} elseif (strlen($mobile_number) == 13 && substr($mobile_number, 0, 3) === '+91') {
$mobileno = substr($mobile_number, 3);
} elseif (strlen($mobile_number) == 14 && substr($mobile_number, 0, 4) === '+910') {
$mobileno = substr($mobile_number, 4);
} else {
$mobileno = $mobile_number;
}
return $mobileno;
}
}
//Helper Function for stringShorter
if (!function_exists('stringShorter')) {
function stringShorter($text, $chars_limit)
{
// Check if length is larger than the character limit
if (strlen($text) > $chars_limit) {
// If so, cut the string at the character limit
$new_text = substr($text, 0, $chars_limit);
// Trim off white space
$new_text = trim($new_text);
// Add at end of text ...
return $new_text . '...';
} else { // If not just return the text as is
return $text;
}
}
}
//Helper Function for formatDisplayName
if (!function_exists('formatDisplayName')) {
function formatDisplayName($name, $comment = null)
{
if (preg_match('~[,;:\(\)\[\]\.\\<>@"]~', $name)) {
$name = preg_replace('/"/', '\"', $name);
if (!empty($comment)) {
return '"' . $name . '" (' . $comment . ')';
}
return '"' . $name . '"';
}
if (!empty($comment)) {
return '"' . $name . '" (' . $comment . ')';
}
return $name;
}
}
//Helper Function for formatPhone
if (!function_exists('formatPhone')) {
function formatPhone($input)
{
$digits = trim(ereg_replace('([^[:digit:]])', '', $input));
if (strlen($digits) > 10) {
$digits = substr($digits, -10);
}
return '(' . substr($digits, 0, 3) . ') ' . substr($digits, 3, 3) . '-' . substr($digits, 6, 4);
}
}
//Helper Function for currencyUnit
if (!function_exists('currencyUnit')) {
function currencyUnit($value = '', $currency_type = '')
{
$key = (int)strlen($value);
switch ($currency_type) {
case 'USD':
$curType = '$ ';
break;
default:
$curType = '₹ ';
break;
}
switch ($key) {
case 6:
case 7:
$value = ($value / 100000);
$status = $curType . $value . ' Lakh.';
break;
case 8:
case 9:
$value = ($value / 1000000);
$status = $curType . $value . ' Crore.';
break;
default:
$status = $curType . $value;
break;
}
return $status;
}
}
//Helper Function for currencyFormat
if (!function_exists('currencyFormat')) {
/*echo currencyFormat(1050); # 1,050
echo currencyFormat(1321435.4, true); # 1,321,435.40 */
function currencyFormat($number, $fractional = false)
{
if ($fractional) {
$number = sprintf('%.2f', $number);
}
while (true) {
$replaced = preg_replace('/(-?\d+)(\d\d\d)/', '$1,$2', $number);
if ($replaced != $number) {
$number = $replaced;
} else {
break;
}
}
return $number;
}
}
//Helper Function for currencyInWords
if (!function_exists('currencyInWords')) {
function currencyInWords($number)
{
$no = round($number);
$point = round($number - $no, 2) * 100;
$hundred = null;
$digits_1 = strlen($no);
$i = 0;
$str = array();
$words = array(
'0' => '', '1' => 'one', '2' => 'two',
'3' => 'three', '4' => 'four', '5' => 'five', '6' => 'six',
'7' => 'seven', '8' => 'eight', '9' => 'nine',
'10' => 'ten', '11' => 'eleven', '12' => 'twelve',
'13' => 'thirteen', '14' => 'fourteen',
'15' => 'fifteen', '16' => 'sixteen', '17' => 'seventeen',
'18' => 'eighteen', '19' => 'nineteen', '20' => 'twenty',
'30' => 'thirty', '40' => 'forty', '50' => 'fifty',
'60' => 'sixty', '70' => 'seventy',
'80' => 'eighty', '90' => 'ninety'
);
$digits = array('', 'hundred', 'thousand', 'lakh', 'crore', );
while ($i < $digits_1) {
$divider = ($i == 2) ? 10 : 100;
$number = floor($no % $divider);
$no = floor($no / $divider);
$i += ($divider == 10) ? 1 : 2;
if ($number) {
$plural = (($counter = count($str)) && $number > 9) ? 's' : null;
$hundred = ($counter == 1 && $str[0]) ? ' and ' : null;
$str[] = ($number < 21) ? $words[$number] .
" " . $digits[$counter] . $plural . " " . $hundred
:
$words[floor($number / 10) * 10]
. " " . $words[$number % 10] . " "
. $digits[$counter] . $plural . " " . $hundred;
} else $str[] = null;
}
$str = array_reverse($str);
$result = implode('', $str);
//echo $points%10;
$points = ($point) ?
"." . $words[$point / 10] . " " .
$words[$point = $point % 10] : '';
if ($points != '0' && $points > 0) {
//echo "1st"."<br>";
//echo $result . "Rupees " . $points . " Paise";
return $result . "Rupees ";
} elseif ($points == '0' || $points == null) {
//echo "2nd"."<br>";
//echo $result . "Rupees " . $points . " Paise";
return $result . "Rupees ";
} else {
//echo "3rd"."<br>";
$points = '00';
//echo $result . "Rupees ." . $points . " Paise";
return $result . "Rupees ";
}
}
}
//Helper Function for numberToWords
if (!function_exists('numberToWords')) {
function numberToWords($number)
{
$hyphen = ' ';
$conjunction = ' ';
$separator = ' ';
$negative = 'negative ';
$decimal = ' point ';
$dictionary = array(
0 => 'Zero',
1 => 'One',
2 => 'Two',
3 => 'Three',
4 => 'Four',
5 => 'Five',
6 => 'Six',
7 => 'Seven',
8 => 'Eight',
9 => 'Nine',
10 => 'Ten',
11 => 'Eleven',
12 => 'Twelve',
13 => 'Thirteen',
14 => 'Fourteen',
15 => 'Fifteen',
16 => 'Sixteen',
17 => 'Seventeen',
18 => 'Eighteen',
19 => 'Nineteen',
20 => 'Twenty',
30 => 'Thirty',
40 => 'Fourty',
50 => 'Fifty',
60 => 'Sixty',
70 => 'Seventy',
80 => 'Eighty',
90 => 'Ninety',
100 => 'Hundred',
1000 => 'Thousand',
1000000 => 'Million',
1000000000 => 'Billion',
1000000000000 => 'Trillion',
1000000000000000 => 'Quadrillion',
1000000000000000000 => 'Quintillion'
);
if (!is_numeric($number)) {
return false;
}
if (($number >= 0 && (int)$number < 0) || (int)$number < 0 - PHP_INT_MAX) {
// overflow
trigger_error(
'numberToWords only accepts numbers between -' . PHP_INT_MAX . ' and ' . PHP_INT_MAX,
E_USER_WARNING
);
return false;
}
if ($number < 0) {
return $negative . numberToWords(abs($number));
}
$string = $fraction = null;
if (strpos($number, '.') !== false) {
list($number, $fraction) = explode('.', $number);
}
switch (true) {
case $number < 21:
$string = $dictionary[$number];
break;
case $number < 100:
$tens = ((int)($number / 10)) * 10;
$units = $number % 10;
$string = $dictionary[$tens];
if ($units) {
$string .= $hyphen . $dictionary[$units];
}
break;
case $number < 1000:
$hundreds = $number / 100;
$remainder = $number % 100;
$string = $dictionary[$hundreds] . ' ' . $dictionary[100];
if ($remainder) {
$string .= $conjunction . numberToWords($remainder);
}
break;
default:
$baseUnit = pow(1000, floor(log($number, 1000)));
$numBaseUnits = (int)($number / $baseUnit);
$remainder = $number % $baseUnit;
$string = numberToWords($numBaseUnits) . ' ' . $dictionary[$baseUnit];
if ($remainder) {
$string .= $remainder < 100 ? $conjunction : $separator;
$string .= numberToWords($remainder);
}
break;
}
if (null !== $fraction && is_numeric($fraction)) {
$string .= $decimal;
$words = array();
foreach (str_split((string)$fraction) as $number) {
$words[] = $dictionary[$number];
}
$string .= implode(' ', $words);
}
return $string;
}
}
//Helper Function for sortBy
if (!function_exists('sortBy')) {
function sortBy($field, &$array, $direction = 'desc')
{
usort($array, create_function('$a, $b', '
$a = $a["' . $field . '"];
$b = $b["' . $field . '"];
if ($a == $b) return 0;
$direction = strtolower(trim($direction));
return ($a ' . ($direction == 'desc' ? '>' : '<') . ' $b) ? -1 : 1;
'));
return true;
}
}
//Helper Function for arrayOrderBy
if (!function_exists('arrayOrderBy')) {
function arrayOrderBy(array &$arr, $order = null)
{
//print_r(arrayOrderBy($arr, 'id asc, name desc'));
if (is_null($order)) {
return $arr;
}
$orders = explode(',', $order);
usort($arr, function ($a, $b) use ($orders) {
$result = array();
foreach ($orders as $value) {
list($field, $sort) = array_map('trim', explode(' ', trim($value)));
if (!(isset($a[$field]) && isset($b[$field]))) {
continue;
}
if (strcasecmp($sort, 'desc') === 0) {
$tmp = $a;
$a = $b;
$b = $tmp;
}
if (is_numeric($a[$field]) && is_numeric($b[$field])) {
$result[] = $a[$field] - $b[$field];
} else {
$result[] = strcmp($a[$field], $b[$field]);
}
}
return implode('', $result);
});
return $arr;
}
}
//Helper Function for arrayGroupBy
if (!function_exists('arrayGroupBy')) {
/**
* Groups an array by a given key.
*
* Groups an array into arrays by a given key, or set of keys, shared between all array members.
*
* Based on {@author Jake Zatecky}'s {@link https://github.com/jakezatecky/arrayGroupBy arrayGroupBy()} function.
* This variant allows $key to be closures.
*
* @param array $array The array to have grouping performed on.
* @param mixed $key,... The key to group or split by. Can be a _string_,
* an _integer_, a _float_, or a _callable_.
*
* If the key is a callback, it must return
* a valid key from the array.
*
* If the key is _NULL_, the iterated element is skipped.
*
* ```
* string|int callback ( mixed $item )
* ```
*
* @return array|null Returns a multidimensional array or `null` if `$key` is invalid.
*/
function arrayGroupBy(array $array, $key)
{
$keyName = $key;
if (!is_string($key) && !is_int($key) && !is_float($key) && !is_callable($key)) {
trigger_error('arrayGroupBy(): The key should be a string, an integer, or a callback', E_USER_ERROR);
return null;
}
$func = (!is_string($key) && is_callable($key) ? $key : null);
$_key = $key;
// Load the new array, splitting by the target key
$grouped = [];
foreach ($array as $value) {
$key = null;
if (is_callable($func)) {
$key = call_user_func($func, $value);
} elseif (is_object($value) && isset($value->{$_key})) {
$key = $value->{$_key};
} elseif (isset($value[$_key])) {
$key = $value[$_key];
}
if ($key === null) {
continue;
}
$grouped[$key][] = $value;
}
// Recursively build a nested grouping if more parameters are supplied
// Each grouped array value is grouped according to the next sequential key
if (func_num_args() > 2) {
$args = func_get_args();
foreach ($grouped as $key => $value) {
$params = array_merge([$value], array_slice($args, 2, func_num_args()));
$grouped[$key] = call_user_func_array('arrayGroupBy', $params);
}
}
return $grouped;
}
}
//Helper Function for Multidimension arrayUniqueSort
if (!function_exists('arrayUniqueSort')) {
function arrayUniqueSort($originalArray, $arkey = null)
{
$newArray = array();
$usedArray = array();
if (!empty($arkey)) {
foreach ($originalArray as $key => $line) {
if (!in_array($line[$arkey], $usedArray)) {
$usedArray[] = $line[$arkey];
$newArray[$key] = $line;
}
}
} else {
$newArray = array_map("unserialize", array_unique(array_map("serialize", $originalArray)));
//array_unique($result,SORT_REGULAR);
}
return $newArray;
}
}
//Helper Function for objectToArray
if (!function_exists('objectToArray')) {
function objectToArray($obj)
{
if (!is_object($obj)) {
return $obj;
}
if (is_object($obj)) $obj = (array)$obj;
if (is_array($obj)) {
$new = array();
foreach ($obj as $key => $val) {
$new[$key] = objectToArray($val);
}
} else {
$new = $obj;
}
return $new;
}
}
//Helper Function for arrayToObject
if (!function_exists('arrayToObject')) {
//#$clientProspectList, $arkey='number'
function arrayToObject($array)
{
if (!is_array($array)) {
return $array;
}
$object = new stdClass();
foreach ($array as $key => $value) {
if (is_array($value)) {
$value = arrayToObject($value);
}
$object->$key = $value;
}
return $object;
}
}
//Helper Function for arraySortByColumn
if (!function_exists('arraySortByColumn')) {
function arraySortByColumn(&$arr, $col, $dir = SORT_ASC)
{
$sort_col = array();
foreach ($arr as $key => $row) {
$sort_col[$key] = $row[$col];
}
array_multisort($sort_col, $dir, $arr);
}
}
//Helper Function for subvalSort
if (!function_exists('subvalSort')) {
function subvalSort($a, $subkey)
{
foreach ($a as $k => $v) {
$b[$k] = strtolower($v[$subkey]);
}
asort($b);
foreach ($b as $key => $val) {
$c[] = $a[$key];
}
return $c;
}
}
//Helper Function for createLog
if (!function_exists('createLog')) {
function createLog($str, $logFilename = 'error_log.log', $cacheDir = null)
{
$serverTZoffset = 0;
$str = trim($str);
if (strlen($str) > 50000) {
$str = substr($str, 0, 50000) . ' ... [truncated]';
}
list($sec, $usec) = explode('.', microtime(true));
file_put_contents($cacheDir . $logFilename, '[' . date("Y-m-d H:i:s", $sec + $serverTZoffset) . '.' . substr($usec, 0, 3) . '] ' . $str . PHP_EOL . PHP_EOL, FILE_APPEND | LOCK_EX);
}
}
//Helper Function for validEmail
if (!function_exists('validEmail')) {
function validEmail($email)
{
// First, we check that there's one @ symbol, and that the lengths are right
if (!preg_match("/^[^@]{1,64}@[^@]{1,255}$/", $email)) {
// Email invalid because wrong number of characters in one section, or wrong number of @ symbols.
return false;
}
// Split it into sections to make life easier
$email_array = explode("@", $email);
$local_array = explode(".", $email_array[0]);
for ($i = 0; $i < sizeof($local_array); $i++) {
if (!preg_match("/^(([A-Za-z0-9!#$%&'*+\/=?^_`{|}~-][A-Za-z0-9!#$%&'*+\/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$/", $local_array[$i])) {
return false;
}
}
if (!preg_match("/^\[?[0-9\.]+\]?$/", $email_array[1])) { // Check if domain is IP. If not, it should be valid domain name
$domain_array = explode(".", $email_array[1]);
if (sizeof($domain_array) < 2) {
return false; // Not enough parts to domain
}
for ($i = 0; $i < sizeof($domain_array); $i++) {
if (!preg_match("/^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$/", $domain_array[$i])) {
return false;
}
}
}
return true;
}
}
//Helper Function for getContactType
if (!function_exists('getContactType')) {
function getContactType($type = null)
{
$contactType = [
[
"id" => 1,
"type" => 'Plot Booking Enquiry'
],
[
"id" => 2,
"type" => 'Document Related Enquiry'
],
[
"id" => 3,
"type" => 'Payment Related Enquiry'
],
[
"id" => 4,
"type" => 'Home Loan Enquiry'
],
[
"id" => 5,
"type" => 'User Profile Update/Exit Related Enquiry'
],
[
"id" => 6,
"type" => 'Other Enquiry'
]
];
if (isset($type)) {
$contactName = '';
foreach ($contactType as $key => $value) {
if ($value['id'] == $type) {
$contactName = $value['type'];
}
}
return $contactName;
} else {
return $contactType;
}
}
}
//Helper Function for convertRole
if (!function_exists('convertRole')) {
function convertRole($role)
{
$data = [
'Admin' => '1',
'Director' => '2',
'Research Analyst' => '3',
'Senior Research Analyst' => '4',
'Team Lead' => '5',
'IT Executive' => '6',
'HR Manager' => '7',
'Associate-Enforcement' => '8',
'Enforcement Head' => '9',
'Finance Controller' => '10',
'Consultant' => '11',
'Front desk Executive' => '12',
'Software Developer' => '13',
'Senior Software Developer' => '14',
'Accounts Executive' => '15',
'Manager' => '16'
//bharo baki
];
if ($role) {
return $data[$role];
}
return $data;
}
}
//Helper Function for getStatus
if (!function_exists('getStatus')) {
function getStatus($type = null, $status = null)
{
switch ($type) {
case "isactive":
switch ($status) {
case 0:
return '<span class="label label-danger">Inactive</span>';
break;
case 1:
return '<span class="label label-primary">Active</span>';
break;
case 2:
return '<span class="label label-warning">Due to cancel registration you are not authorized for login</span>';
break;
case 3:
return '';
break;
case 4:
return '';
break;
default:
return '';
break;
}
break;
case "role":
switch ($status) {
case 1:
return 'Super Admin';
break;
case 2:
return 'Master Admin';
break;
case 3:
return 'Admin';
break;
case 4:
return 'Moderator';
break;
case 5:
return 'Editor';
break;
case 6:
return 'Data entry operator';
break;
case 7:
return 'Caller';
break;
default:
return '';
break;
}
break;
case "usertype":
switch ($status) {
case 1:
return 'Website';
break;
case 2:
return 'Facebook';
break;
case 3:
return 'Google';
break;
default:
return '';
break;
}
break;
case "source":
switch ($status) {
case 1:
return 'Web';
break;
case 2:
return 'App';
break;
default:
return '';
break;
}
break;
case "payoption":
switch ($status) {
case 1:
return 'Registration Fee';
break;
case 2:
return 'Plot Payment';
break;
case 3:
return 'Draw Payment';
break;
case 4:
return 'Corporate Plot Payment';
break;
case 5:
return 'Enroll Payment';
break;
case 6:
return 'Flat Payment';
break;
default:
return '';
break;
}
break;
case "paymode":
switch ($status) {
case 1:
return 'COD';
break;
case 2:
return 'Online Txn';
break;
case 3:
return 'Cash Deposit';
break;
case 4:
return 'Cash Received';
break;
case 5:
return 'Waiver';
break;
case 6:
return 'Cheque/Draft';
break;
default:
return '';
break;
}
break;
case "payplan":
switch ($status) {
case 1:
return 'Loan';
break;
case 2:
return 'Installment';
break;
case 3:
return 'Dawn Payment';
break;
default:
return '';
break;
}
break;
case "feestatus":
switch ($status) {
case 1:
return '<span class="label label-danger">Cancel</span>';
break;
case 2:
return '<span class="label label-default">Pending</span>';
break;
case 3:
return '<span class="label label-success">Clearing</span>';
break;
case 4:
return '<span class="label label-primary">Cleared</span>';
break;
case 5:
return '<span class="label label-info">Refund</span>';
break;
default:
return '';
break;
}
break;
case "paystatus":
switch ($status) {
case 1:
return 'unpaid';
break;
case 2:
return 'paid';
break;
default:
return 'unknow';
break;
}
break;
case "promostatus":
switch ($status) {
case 1:
return 'unused';
break;
case 2:
return 'used';
break;
default:
return '';
break;
}
break;
case "discounttype":
switch ($status) {
case 2:
return ' Rs Flat Discount';
break;
case 3:
return ' %';
break;
default:
return '';
break;
}
break;
case "orderstatus":
switch ($status) {
case 0:
case 'canceld':
return 'canceld';
//return '<span class="label label-default">Canceled</span>';
break;
case 1:
case 'placed':
return 'placed';
//return '<span class="label label-success">Order Placed</span>';
break;
case 2:
case 'proccess':
return 'proccess';
//return '<span class="label label-info">Proccess</span>';
break;
case 3:
case 'packed':
return 'packed';
//return '<span class="label label-success">Packed</span>';
break;
case 4:
case 'shiped':
return 'shiped';
//return '<span class="label label-primary">Shiped</span>';
break;
case 5:
case 'onway':
return 'onway';
//return '<span class="label label-info">Onway</span>';
break;
case 6:
case 'delivered':
return 'delivered';
//return '<span class="label label-success">Delivered</span>';
break;
case 7:
case 'pending':
return 'pending';
//return '<span class="label label-info">Pending</span>';
break;
case 8:
case 'return':
return 'return';
//return '<span class="label label-success">Return</span>';
break;
case 9:
case 'returned':
return 'returned';
//return '<span class="label label-success">Returned</span>';
break;
case 10:
case 'exchange':
return 'exchange';
//return '<span class="label label-default">Exchange</span>';
break;
case 11:
case 'exchanged':
return 'exchanged';
//return '<span class="label label-default">Exchanged</span>';
break;
default:
return '';
break;
}
break;
case "plotstatus":
switch ($status) {
case 1:
return '<span class="label label-default">Free</span>';
break;
case 2:
return '<span class="label label-info">Proccess</span>';
break;
case 3:
return '<span class="label label-success">Booked</span>';
break;
case 4:
return '<span class="label label-primary">Admin Corporate</span>';
break;
case 5:
return '<span class="label label-info">User Corporate</span>';
break;
default:
return '';
break;
}
break;
case "slotstatus":
switch ($status) {
case 1:
return '<span class="label label-default">Pending</span>';
break;
case 2:
return '<span class="label label-success">Booked</span>';
break;
default:
return '';
break;
}
break;
case "refundtype":
//1:RegistrationFee;2:CancelRegistration;3:PlotAllotmentPayment;4:DrawSlotRegistraint
switch ($status) {
case 1:
return '<span class="label label-default">Registration Fee</span>';
break;
case 2:
return '<span class="label label-danger">Cancel Registration</span>';
break;
case 3:
return '<span class="label label-primary">Plot Allotment</span>';
break;
case 4:
return '<span class="label label-info">Draw Slot</span>';
break;
default:
return '';
break;
}
break;
default:
return 'select type of status =>isactive,role,source,payoption,paymode,payplan,feestatus,paystatus,promostatus,orderstatus';
break;
}
}
}
//Helper Function for addOrdinalNumberSuffix
if (!function_exists('addOrdinalNumberSuffix')) {
function addOrdinalNumberSuffix($num = 5)
{
// echo addOrdinalNumberSuffix($i) . "\t";
// if ($i % 10 == 0) {echo "\n"; }
if (!in_array(($num % 100), array(11, 12, 13))) {
switch ($num % 10) {
// Handle 1st, 2nd, 3rd
case 1:
return $num . 'st';
case 2:
return $num . 'nd';
case 3:
return $num . 'rd';
}
}
return $num . 'th';
}
}
//Helper Function for verifyUser
if (!function_exists('verifyUser')) {
function verifyUser($condition = null, $search = null)
{
//print_r($condition); echo $search;
if (is_array($search)) {
foreach ($search as $key => $value) {
if (in_array($value, $condition)) {
return true;
}
}
} else {
if (in_array($search, $condition)) {
return true;
}
}
}
}
//Helper Function for cleanData
if (!function_exists('cleanData')) {
function cleanData($data)
{
//echo '<br/><br/>'. urlencode($data);
$data = str_replace('%3Cbr+%2F%3E', ' ', urlencode($data));
$data = urldecode($data);
$data = rtrim($data, "\n");
$data = rtrim($data, ",");
$data = str_replace(',<br/>', '', $data);
$data = trim($data);
if (substr($data, -1, 1) == ',') {
$data = substr($data, 0, -1);
}
$data = rtrim($data, ", \t\n");
$data = rtrim($data, ',');
$data = rtrim($data, ', ');
$data = str_replace('\n', '', $data);
$data = str_replace('. ', '.', $data);
$data = str_replace('.', '. ', $data);
$data = str_replace(' ', ' ', $data);
$data = str_replace(', ', ',', $data);
$data = str_replace(',', ', ', $data);
//$data = str_replace('%2C+%3Cbr+%2F%3E', '', urlencode($data));
//$data = urldecode($data);
//echo '<br/><br/>'. ($data);
return $data;
}
}
//Helper Function for getPlotDiscount
if (!function_exists('getPlotDiscount')) {
function getPlotDiscount($percent = 5, $principalamt = null)
{
$percentDiscount = $principalamt * ($percent / 100);
//$discountedAmount = ceil($principalamt-($principalamt*($percent/100)));
$discountedAmount = ceil($principalamt - $percentDiscount);
$bookingamt = ceil($discountedAmount * (10 / 100)); //first 10% bookingamt payment
$allotmentamt = ceil($discountedAmount * (85 / 100)); //allotmentamt amount payment
$possessionamt = ceil($discountedAmount * (5 / 100)); //possessionamt amount payment
return $value = ['sale_price' => $principalamt, 'percnetamt' => $percent, 'percentdiscount' => $percentDiscount, 'discountamt' => $discountedAmount, 'bookingamt' => $bookingamt, 'allotmentamt' => $allotmentamt, 'possessionamt' => $possessionamt];
exit;
}
}
//Helper Function for getPlotEmi
if (!function_exists('getPlotEmi')) {
function getPlotEmi($year = 22, $principalamt = null, $intpercent = null)
{
$term = $year;
//$intr= $intpercent/100;
//$myintr= $intr/12;
//$myintr= 0;
$bookingamt = ceil($principalamt * (10 / 100)); //first 10% bookingamt payment
$allotmentamt = ceil($principalamt * (15 / 100)); // 15% allotmentamt payment
$new_principalamt = ceil($principalamt - ($bookingamt + $allotmentamt));
$emiamt = ceil(($new_principalamt) / $term);
return $value = ['baseprice' => $principalamt, 'bookingamt' => $bookingamt, 'allotmentamt' => $allotmentamt, 'emiamt' => $emiamt, 'newprincipalamt' => $new_principalamt];
exit;
//installl
/*$x1= $myintr*(1 + $myintr,$term); // This for total EMI
$x2 =ceil(1 + $myintr) - 1;
$interest= ceil(($newprincamt*$x1)/$x2);*/
//return;
// return {'totalbasicamt': princ,'emi': emi,'totalinterest': interest,'myintr': myintr,'bookingamt': bookingamt,'allotmentamt': allotmentamt,'newprincipalamt': newprincamt};
}
}
//Helper Function for getInstallmentDate
if (!function_exists('getInstallmentDate')) {
function getInstallmentDate($bookingdate, $payplan = 1)
{
//echo $startdt
$instduedatedata = [];
$datedata = date_create($bookingdate);
$date = date_format($datedata, 'd-M-Y');
if ($payplan == 1) {
$instduedatedata['bookamtduedate'] = date("d-M-y", strtotime("$date +9 day"));
$instduedatedata['allotamtduedate'] = date("d-M-y", strtotime("$date +59 day"));
for ($m = 1; $m <= 22; $m++) {
$d = 30 * $m;
$instduedatedata['EMI_' . $m . 'duedate'] = date("d-M-y", strtotime("$date +$d day"));
}
}
if ($payplan == 2) {
$instduedatedata['bookamtduedate'] = date("d-M-y", strtotime("$date +9 day"));
$instduedatedata['allotamtduedate'] = date("d-M-y", strtotime("$date +59 day"));
for ($m = 1; $m <= 22; $m++) {
$d = 30 * $m;
$instduedatedata['EMI_' . $m . 'duedate'] = date("d-M-y", strtotime("$date +$d day"));
}
}
if ($payplan == 3) {
$instduedatedata['bookamtduedate'] = date("d-M-y", strtotime("$date +9 day"));
$instduedatedata['allotamtduedate'] = date("d-M-y", strtotime("$date +59 day"));
$instduedatedata['possamtduedate'] = date("d-M-y", strtotime("$date +600 day"));
}
return $instduedatedata;
}
}
//Helper Function for getMinMaxAmountinperc
if (!function_exists('getMinMaxAmountinperc')) {
function getMinMaxAmountinperc($amount = null, $min = null, $max = null, $percent = null, $by = null, $discount = null)
{
$amtdata = array();
if (empty($amount) && !empty($min) && !empty($max) && !empty($percent)) {
$mindata = ($min * $percent / 100);
$maxdata = ($max * $percent / 100);
$amtdata['min'] = ceil($mindata);
$amtdata['max'] = ceil($maxdata);
return $amtdata;
}
if (!empty($min) && !empty($max) && !empty($by)) {
$mindata = ($min / $by);
$maxdata = ($max / $by);
$amtdata['min'] = ceil($mindata);
$amtdata['max'] = ceil($maxdata);
return $amtdata;
}
if (!empty($min) && !empty($max) && !empty($discount)) {
$mindata = ceil($min - ($min * ($discount / 100)));
$maxdata = ceil($max - ($max * ($discount / 100)));
$amtdata['min'] = ceil($mindata);
$amtdata['max'] = ceil($maxdata);
return $amtdata;
}
}
}
//Helper Function for privateJson
if (!function_exists('privateJson')) {
function privateJson($data)
{
header('Content-type: application/json');
return json_encode(array('data' => $data), true);
}
}
//Helper Function for privateXml
if (!function_exists('privateXml')) {
function privateXml($posts)
{
if (is_array($posts)) {
$data = '';
header('Content-type: text/xml');
echo '<posts>';
foreach ($posts as $index => $post) {
if (!is_array($post)) {
echo '<', $index, '>', htmlentities($post), '</', $index, '>';
} else if (is_array($post)) {
foreach ($post as $key => $value) {
echo '<', $key, '>';
if (!is_array($value)) {
//echo '<',$key,'>',htmlentities($value),'</',$key,'>';
echo htmlentities($value);
} else if (is_array($value)) {
foreach ($value as $tag => $val) {
echo '<', $tag, '>', htmlentities($val), '</', $tag, '>';
}
}
echo '</', $key, '>';
}
}
}
echo '</posts>';
}
exit;
}
}
//Helper Function for getApiToken
if (!function_exists('getApiToken')) {
function xmlStatus($posts)
{
if (is_array($posts)) {
$data = '';
header('Content-type: text/xml');
echo '<posts>';
foreach ($posts as $tag => $val) {
echo '<', $tag, '>', htmlentities($val), '</', $tag, '>';
}
echo '</posts>';
}
}
}
//Helper Function for privateXml2 #wrong xml
if (!function_exists('privateXml2')) {
function privateXml2($posts)
{
if (is_array($posts)) {
$data = '';
header('Content-type: text/xml');
echo '<posts>';
foreach ($posts as $index => $post) {
echo '<post>';
if (!is_array($post)) {
echo '<', $index, '>', htmlentities($post), '</', $index, '>';
} else if (is_array($post)) {
foreach ($post as $key => $value) {
echo '<', $key, '>';
if (!is_array($value)) {
//echo '<',$key,'>',htmlentities($value),'</',$key,'>';
echo htmlentities($value);
} else if (is_array($value)) {
foreach ($value as $tag => $val) {
echo '<', $tag, '>', htmlentities($val), '</', $tag, '>';
}
}
echo '</', $key, '>';
}
}
echo '</post>';
}
echo '</posts>';
}
}
}
//Helper Function for getApiToken
if (!function_exists('getApiToken')) {
function getApiToken()
{
$key_arr = array('De#L&^n;&%6h5H1@w`sD_sJ(1@A#&G', 'testapitoken');
return $key_arr;
exit;
}
}
//Helper Function for curlHttpGet
if (!function_exists('curlHttpGet')) {
function curlHttpGet($url = null)
{
// init the resource
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_CUSTOMREQUEST => "GET",
//CURLOPT_POST => 1,
//CURLOPT_POSTFIELDS => $param,
CURLOPT_RETURNTRANSFER => true,
));
//Ignore SSL certificate verification
// curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
// curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
// curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // allow redirects
// curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
// curl_setopt($ch, CURLOPT_MAXREDIRS,5); // return into a variable
// curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(array()));
//get response
$output = curl_exec($ch);
//Print error if any
if (curl_errno($ch)) {
return curl_error($ch);
}
curl_close($ch);
return $output;
}
}
//Helper Function for curlAbsayHttpPost
if (!function_exists('curlAbsayHttpPost')) {
function curlAbsayHttpPost($apiUrl, $dataArr = [])
{
$params = ["token" => "testapitoken", "format" => "json"];
$params = array_merge($params, $dataArr);
$apiUrl = "http://absay.org/rest/api/$apiUrl";
$ch = curl_init($apiUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
$response = curl_exec($ch);
curl_close($ch);
return $jsonData = json_decode($response, true);
}
}
//Helper Function for curlSupportNotify
if (!function_exists('curlSupportNotify')) {
function curlSupportNotify($apiUrl, $dataArr = [])
{
$params = ["token" => "testapitoken", "format" => "json"];
$params = array_merge($params, $dataArr);
$apiUrl = "http://support.absay.org/services/$apiUrl";
$ch = curl_init($apiUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
$response = curl_exec($ch);
curl_close($ch);
return $jsonData = json_decode($response, true);
}
}
//Helper Function for session with a specific timeout
if (!function_exists('sessionStartTimeout')) {
/***
* Starts a session with a specific timeout and a specific GC probability.
* @param int $timeout The number of seconds until it should time out.
* @param int $probability The probablity, in int percentage, that the garbage
* collection routine will be triggered right now.
* @param strint $cookie_domain The domain path for the cookie.
*/
function sessionStartTimeout($timeout = 5, $probability = 100, $cookie_domain = '/')
{
// Set the max lifetime
ini_set("session.gc_maxlifetime", $timeout);
// Set the session cookie to timout
ini_set("session.cookie_lifetime", $timeout);
// Change the save path. Sessions stored in teh same path
// all share the same lifetime; the lowest lifetime will be
// used for all. Therefore, for this to work, the session
// must be stored in a directory where only sessions sharing
// it's lifetime are. Best to just dynamically create on.
$seperator = strstr(strtoupper(substr(PHP_OS, 0, 3)), "WIN") ? "\\" : "/";
$path = ini_get("session.save_path") . $seperator . "session_" . $timeout . "sec";
if (!file_exists($path)) {
if (!mkdir($path, 600)) {
trigger_error("Failed to create session save path directory '$path'. Check permissions.", E_USER_ERROR);
}
}
ini_set("session.save_path", $path);
// Set the chance to trigger the garbage collection.
ini_set("session.gc_probability", $probability);
ini_set("session.gc_divisor", 100); // Should always be 100
// Start the session!
session_start();
// Renew the time left until this session times out.
// If you skip this, the session will time out based
// on the time when it was created, rather than when
// it was last used.
if (isset($_COOKIE[session_name()])) {
setcookie(session_name(), $_COOKIE[session_name()], time() + $timeout, $cookie_domain);
}
}
}
//Helper Function for getCartContant
if (!function_exists('getCartContant')) {
function getCartContant($cart_contant)
{
if ($cart_contant) {
$cartTotal = $activeCartTotal = $cartCount = $activeCartCount = 0;
$carts = ($cart_contant) ? json_decode($cart_contant, true) : [];
if (count($carts) > 0) {
foreach ($carts as $key => $cartval) {
if ($cartval['isdelete'] == 1) {
$activeCartCount++;
$activeCartTotal += round($cartval['product_sale_price'] * $cartval['quantity']);
} else {
$cartCount++;
$cartTotal += round($cartval['product_sale_price'] * $cartval['quantity']);
}
}
return (object)['status' => true, 'active_cart_count' => $activeCartCount, 'active_cart_total' => $activeCartTotal, 'cart_total' => $cartTotal, 'cart_count' => $cartCount];
}
}
return (object)['status' => false, 'active_cart_count' => 0, 'active_cart_total' => 0, 'cart_total' => 0, 'cart_count' => 0, 'cart_contant' => ''];
}
}
//Helper Function for setRecentProduct
if (!function_exists('setRecentProduct')) {
function setRecentProduct($product_id)
{
$cookie_name = md5('cookieRecentViewProduct');
if (@$_COOKIE[$cookie_name]) {
//decode cookie string from JSON
$cookieArr = (array)json_decode(@$_COOKIE[$cookie_name]);
//push additional data
//remove empty values
if (!in_array($product_id, $cookieArr, true)) {
array_push($cookieArr, $product_id);
//encode data again for cookie
$cookie_data = json_encode($cookieArr);
//need to limit cookie size. Default is set to 4Kb. If it is greater than limit. it then gets reset.
//$cookie_data = mb_strlen($cookie_data) >= $limit ? '' : $cookie_data;
//destroy cookie
setcookie($cookie_name, '', time() - 3600, '/');
//set cookie with new data and expires after a week
setcookie($cookie_name, $cookie_data, time() + (3600 * 24 * 7), '/');
}
/* foreach ($cookieArr as $k => $v) {
if ($v == '' || is_null($v) || $v == 0) {
unset($cookieArr[$k]);
}
echo $product_id . "=>" . $v . "<br>";
} */
} else {
//create cookie with json string etc.
$cookie_data = json_encode($product_id);
//set cookie expires after a week
setcookie($cookie_name, $cookie_data, time() + (3600 * 24 * 7), '/');
}
return $recentProViewId = array_values((array)json_decode(@$_COOKIE[$cookie_name]));
}
}
//Helper Function for getCartContant
if (!function_exists('bgColor')) {
function bgColor($key = 1)
{ //echo $var;
$bgcolor = ['placed' => 'bg-purple', 'process' => 'bg-blue', 'packed' => 'bg-olive', 'shiped' => 'bg-fuchsia', 'onway' => 'bg-maroon', 'delivered' => 'bg-green', 'pending' => 'bg-gray', 'return' => 'bg-navy', 'returned' => 'bg-lime', 'exchange' => 'bg-orange', 'exchanged' => 'bg-teal', 'pending' => 'bg-light-blue', 'a' => 'bg-black', 'b' => 'bg-yellow', 'canceld' => 'bg-red', 'c' => 'bg-aqua'];
if (@$bgcolor[$key]) {
return $bgcolor[$key];
} else {
return 'bg-purple';
}
}
//#0:canceld;1:placed;2:process:3:packed;4:shiped;5:onway;6:delivered;7:pending;8:return;9:returned;10:exchange;11:exchanged
}
//CC AVENUE PAYMENT GATE WAY FUNCTIONS
if (!function_exists('encryptCcAvenue')) {
/*
* @param1 : Plain String
* @param2 : Working key provided by CCAvenue
* @return : Decrypted String
*/
function encryptCcAvenue($plainText,$key)
{
$key = hextobinCcAvenue(md5($key));
$initVector = pack("C*", 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f);
$openMode = openssl_encrypt($plainText, 'AES-128-CBC', $key, OPENSSL_RAW_DATA, $initVector);
$encryptedText = bin2hex($openMode);
return $encryptedText;
}
}
//Helper Function for getCartContant
if (!function_exists('decryptCcAvenue')) {
/*
* @param1 : Encrypted String
* @param2 : Working key provided by CCAvenue
* @return : Plain String
*/
function decryptCcAvenue($encryptedText,$key)
{
$key = hextobinCcAvenue(md5($key));
$initVector = pack("C*", 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f);
$encryptedText = hextobinCcAvenue($encryptedText);
$decryptedText = openssl_decrypt($encryptedText, 'AES-128-CBC', $key, OPENSSL_RAW_DATA, $initVector);
return $decryptedText;
}
}
//*********** Padding Function *********************
if (!function_exists('pkcs5_pad')) {
function pkcs5_pad($plainText, $blockSize)
{
$pad = $blockSize - (strlen($plainText) % $blockSize);
return $plainText . str_repeat(chr($pad), $pad);
}
}
//********** Hexadecimal to Binary function for php 4.0 version ********
if (!function_exists('hextobinCcAvenue')) {
function hextobinCcAvenue($hexString)
{
$length = strlen($hexString);
$binString="";
$count=0;
while($count<$length)
{
$subString =substr($hexString,$count,2);
$packedString = pack("H*",$subString);
if ($count==0)
{
$binString=$packedString;
} else
{
$binString.=$packedString;
}
$count+=2;
}
return $binString;
}
}
//CC AVENUE PAYMENT GATE WAY FUNCTIONS
//CC AVENUE PAYMENT GATE WAY FUNCTIONS
/*if (!function_exists('encrypt')) {
function encrypt($plainText, $key)
{
$secretKey = hextobin(md5($key));
$initVector = pack("C*", 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f);
$openMode = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', 'cbc', '');
$blockSize = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, 'cbc');
$plainPad = pkcs5_pad($plainText, $blockSize);
if (mcrypt_generic_init($openMode, $secretKey, $initVector) != -1) {
$encryptedText = mcrypt_generic($openMode, $plainPad);
mcrypt_generic_deinit($openMode);
}
return bin2hex($encryptedText);
}
}
//Helper Function for getCartContant
if (!function_exists('decrypt')) {
function decrypt($encryptedText, $key)
{
$secretKey = hextobin(md5($key));
$initVector = pack("C*", 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f);
$encryptedText = hextobin($encryptedText);
$openMode = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', 'cbc', '');
mcrypt_generic_init($openMode, $secretKey, $initVector);
$decryptedText = mdecrypt_generic($openMode, $encryptedText);
$decryptedText = rtrim($decryptedText, "\0");
mcrypt_generic_deinit($openMode);
return $decryptedText;
}
}
//*********** Padding Function *********************
if (!function_exists('pkcs5_pad')) {
function pkcs5_pad($plainText, $blockSize)
{
$pad = $blockSize - (strlen($plainText) % $blockSize);
return $plainText . str_repeat(chr($pad), $pad);
}
}
//********** Hexadecimal to Binary function for php 4.0 version ********
if (!function_exists('hextobin')) {
function hextobin($hexString)
{
$length = strlen($hexString);
$binString = "";
$count = 0;
while ($count < $length) {
$subString = substr($hexString, $count, 2);
$packedString = pack("H*", $subString);
if ($count == 0) {
$binString = $packedString;
} else {
$binString .= $packedString;
}
$count += 2;
}
return $binString;
}
}*/
//CC AVENUE PAYMENT GATE WAY FUNCTIONS


PK 99