ElixirVault/www/system-brs-core/functions/com.funct.php

1945 lines
56 KiB
PHP

<?php
use BRSystems\Core\Library\cCore\cCore;
use BRSystems\Core\Library\cDb\cDb;
use BRSystems\Core\Library\cDefuseCrypto\cDefuseCrypto;
/**
* Function to get variable from $_post
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @category Functions
* @param string $key - key for the variable
* @param mixed $default - (optional) default value
* @return mixed variable, false or default value if passed
*/
function getP($key, $default = false) {
if (isset($_POST[$key])) {
if (empty($_POST[$key]) && $default) {
return $default;
} else {
return $_POST[$key];
}
} else {
return $default;
}
}
/**
* Function to get variable from $_get
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @category Functions
* @param string $key - key for the variable
* @param mixed $default - (optional) default value
* @return mixed variable, false or default value if passed
*/
function getG($key, $default = false) {
if (isset($_GET[$key])) {
if (empty($_GET[$key]) && $default) {
return $default;
} else {
return $_GET[$key];
}
} else {
return $default;
}
}
/**
* Function to get variable from $_get or $_post
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @category Functions
* @param string $key - key for the variable
* @param string|boolean $default - (optional) default value
* @return mixed variable, false or default value if passed
*/
function getV($key, $default = false) {
if (isset($_POST[$key])) {
if (empty($_POST[$key]) && $default) {
return getG($key, $default);
} else {
return $_POST[$key];
}
} else {
return getG($key, $default);
}
}
/**
* Function to start secure session
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @category Functions
* @param int $maxLifeTime - session cookie lifetime
* @param boolean $bDestroySession - destroy last session
* @param string|boolean $sHost - domain host
*/
function startSessionSameSite($maxLifeTime = 3600, $bDestroySession = false, $sHost = false)
{
// If you only want to receive the cookie over HTTPS
$httpOnly = true; // prevent JavaScript access to session cookie
$sameSite = 'lax'; // none, lax, strict
// Check recent session to destroy - when login time expired
if ($bDestroySession) session_destroy();
// Default values
$sHost = ($sHost ? $sHost : $_SERVER['HTTP_HOST']); // Update as well setSameSiteCookie
//$sHost = '.' . extractDomain($sHost);
if ($_SERVER['SERVER_PORT'] != 80) $sHost = str_replace(":{$_SERVER['SERVER_PORT']}", "", $sHost);
$secure = !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443;
if (PHP_VERSION_ID < 70300) {
session_set_cookie_params($maxLifeTime, '/; samesite=' . $sameSite, $sHost, $secure, $httpOnly);
} else {
session_set_cookie_params([
'lifetime' => $maxLifeTime,
'path' => '/',
'domain' => $sHost,
'secure' => $secure,
'httponly' => $httpOnly,
'samesite' => $sameSite
]);
}
//session_name($sessionName);
session_start();
//session_regenerate_id(true);
}
/**
* Function to start secure session
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @category Functions
* @param string $sCookieName - cookie name
* @param string $sValue - cookie value
* @param int $iLifeTime - session cookie lifetime in seconds
* @param string|boolean $sHost - domain host
*/
function setSameSiteCookie($sCookieName = '', $sValue = '', $iLifeTime = 3600, $sHost = false){
// If you only want to receive the cookie over HTTPS
$httpOnly = true; // prevent JavaScript access to session cookie
$sameSite = 'lax'; // none, lax, strict
// Default values
$iLifeTime += time();
$sHost = ($sHost ? $sHost : $_SERVER['HTTP_HOST']); // Update as well startSessionSameSite
//$sHost = '.' . extractDomain($sHost);
if($_SERVER['SERVER_PORT'] != 80) $sHost = str_replace(":{$_SERVER['SERVER_PORT']}","", $sHost);
$secure = !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443;
if($sCookieName){
if(PHP_VERSION_ID < 70300){
setcookie($sCookieName, $sValue, $iLifeTime, '/; samesite='.$sameSite, $sHost, $secure, $httpOnly);
}else{
setcookie($sCookieName, $sValue, [
'expires' => $iLifeTime,
'path' => '/',
'domain' => $sHost,
'samesite' => $sameSite,
'secure' => $secure,
'httponly' => $httpOnly,
]);
}
}
}
/**
* Function to get domain part without sub domain part
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @category Functions
* @param string $sDomain - domain host string
* @return string - domain part
*/
function extractDomain($sDomain){
if(preg_match("/(?P<domain>[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i", $sDomain, $matches)){
return $matches['domain'];
}else{
return $sDomain;
}
}
/**
* Function to get sub-domain part without domain
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @category Functions
* @param string $sDomain - domain host string
* @return string - domain part
*/
function extractSubDomains($sDomain){
$sSubDomains = $sDomain;
$sDomain = extractDomain($sSubDomains);
$sSubDomains = rtrim(strstr($sSubDomains, $sDomain, true), '.');
return $sSubDomains;
}
function pR(){
if(defined('DEBUG_MODE') && DEBUG_MODE){
if($numargs = func_num_args()){
$output = "";
// Get all arguments
$arg_list = func_get_args();
for($i=0;$i<$numargs;$i++){
// first match - inaccurate in case multiple same values defined
if(0 && $arg_list[$i]){
// $vname = false;
foreach ($GLOBALS as $key => $val) {
if ($val === $arg_list[$i]){
// $vname = $key;
break;
}
}
}
if($_SERVER['REQUEST_METHOD'] === 'POST')
$output .= print_r($arg_list[$i], true) . "\n";
else
$output .= "<pre class='logger' style='text-align:left;padding-left:25px;display:none;'><span class='content'>" . print_r($arg_list[$i], true) . "</span></pre>";
}
echo $output;
}
}
}
function pRr(){
if($numargs = func_num_args()){
$output = "";
// Get all arguments
$arg_list = func_get_args();
for($i=0;$i<$numargs;$i++){
if($_SERVER['REQUEST_METHOD'] === 'POST')
$output .= print_r($arg_list[$i], true);
else
$output .= "<pre class='logger' style='text-align:left;padding-left:25px;display:none;'><span class='content'>" . print_r($arg_list[$i], true) . "</span></pre>";
}
return $output;
}
return false;
}
function mprint(){
return call_user_func_array("pR", func_get_args());
}
/**
* Function to get file extension.
*
* @param string $filename
* @return string - extension
*/
function getFileExtension($filename) {
return pathinfo($filename, PATHINFO_EXTENSION);
}
function getExtension($filename) {
return pathinfo($filename, PATHINFO_EXTENSION);
}
/**
* Function to get current folder name
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @param string $dir - directory path
* @param string $upTill - search upwards till folder
* @return string $dir - folder name till chosen dir from right side
*/
function getCurrentFolder($dir, $upTill = 'system-brs-core') {
$ret_val = '';
$path = str_replace('\\', '/', $dir);
$vars = explode('/', $path);
foreach($vars as $v){
if($v && ($v == $upTill || $ret_val)){
$ret_val .= '/' . $v;
}
}
return $ret_val;
}
/**
* Function to get current folder name removing last parts marked till
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @param string $path - directory path
* @param string $till - search upwards till folder
* @return string $path - folder name till file dir from left side on first occurance
*/
function getSubPath($path, $till = 'system-brs-core') {
$ret_val = '';
$path = str_replace('\\', '/', $path);
$vars = explode('/', $path);
foreach($vars as $v){
if($v){
$ret_val .= '/' . $v;
if($v == $till){
break;
}
}
}
if(substr($path, 0, 1) == '/'){
return $ret_val;
}else{
return substr($ret_val, 1);
}
}
/**
* Function to get folder file name content.
*
* @param string $dir - directory name (optional)
* @param array $vExclude - exclude extensions (optional)
* @return array $aa - array with folder file names
*/
function getFolderFileNames($dir = '.', $vExclude = array('.', '..', '.svn')) {
$aa = array();
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
if (!in_array($file, $vExclude)) {
$aa[] = $file;
}
}
closedir($handle);
}
return $aa;
}
/**
* Function to handle all occurring errors
*
* @param string $errNr - library name
* @param string $errStr - load type
* @param string $errFile - initiate new library
* @param string $errLine - data to set to object
* @param string|boolean $errContext - data to set to object (optional)
* @returns void
*/
function errorHandler($errNr, $errStr, $errFile, $errLine, $errContext = false){
if(defined('__LOGS__')){
$errorDescription = date("d-m-Y H:i:s") . ' | Err: ' . $errNr . ' Line: '. $errLine . " Error: ". $errStr;
writeToFile($errorDescription, __LOGS__ . basename($errFile) . '.txt');
/*pr($a = 'Into '.__FUNCTION__.'()');
pr($a = 'at line '.__LINE__);
pr($a = "\n\n---ERR_NR---\n". print_r( $errNr, true));
pr($a = "\n\n---ERR_STR---\n". print_r( $errStr, true));
pr($a = "\n\n---ERR_FILE---\n". print_r( $errFile, true));
pr($a = "\n\n---ERR_LINE---\n". print_r( $errLine, true));
pr($a = "\n\n---ERR_CONTEXT---\n".print_r( $errContext, true));
pr($a = "\n\nBacktrace of errorHandler()\n");*/
//print_r( debug_backtrace(), true);
}
}
/**
* Function to write content to file
*
* @param string $content - data to append to file
* @param string $file - file path in which to store data
* @returns void
*/
function writeToFile($content, $file){
if($content && $file){
$fh = fopen($file, 'a');
fwrite($fh, "\n" . $content);
fclose($fh);
}
}
/**
* Function to custom log data to project log folder based on class title
*
* @param mixed $content - data to append to file
* @param cCore $module - file path in which to store data
* @returns void
*/
function brsLog($content, cCore $module)
{
$a = new \ReflectionClass(get_class($module));
$fileTitle = $a->getFileName();
$errorDescription = date("d-m-Y H:i:s") . " | Log: \n";
$errorDescription .= print_r($content, true) . "\n";
writeToFile($errorDescription, __LOGS__ . basename($fileTitle) . '.txt');
}
/**
* Function to calculate exec time
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @return string - Time in miliseconds.
*/
function getExecutionTime()
{
static $microtime_start = null;
if($microtime_start === null)
{
$microtime_start = microtime(true);
return 0.0;
}
$return = round(microtime(true) - $microtime_start, 5);
$microtime_start = null;
return $return . 's';
}
/**
* Convenient method for htmlspecialchars().
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @param mixed $value - to escape
* @return mixed - cleared object value
*/
function clearTxt($value) {
if (is_array($value)) {
return array_map('clearTxt', $value);
} else {
return htmlspecialchars(trim($value), ENT_QUOTES, 'UTF-8');
}
}
/**
* Decode specialchars when retrievinig from database
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @param string|array $value - to escape
* @return mixed - cleared object value
*/
function prepForDisplay($value) {
if (is_array($value)) {
return $value = array_map('prepForDisplay', $value);
} else {
return stripslashes($value);
}
}
function prepForDisplayHtml($value) {
if (is_array($value)) {
return $value = array_map('prepForDisplayHtml', $value);
} else {
return htmlspecialchars_decode(stripslashes($value), ENT_QUOTES);
}
}
function prepForOriginalHtml($value) {
if (is_array($value)) {
return $value = array_map('prepForOriginalHtml', $value);
} else {
return html_entity_decode(htmlspecialchars_decode(stripslashes($value), ENT_QUOTES), ENT_QUOTES, 'UTF-8');
}
}
/**
* Convenient method for redirect.
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @param string $uri - uri to where redirect
* @throws null
*/
function redirectToUri($uri = false)
{
if (!$uri) {
$uri = $_SERVER['REQUEST_URI'];
}
if (isset($GLOBALS['coverage_tests_running'])) {
throw new Exception("Redirected to Location: $uri");
}
header("Location: $uri");
die();
}
/**
* Convenient method for getting full current url.
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @param string $uri - uri to where redirect
* @return string - redirect site
*/
function getURL() {
return "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
}
/**
* Convenient method for triming fields
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @param mixed $value - value / array of data
* @return string - redirect site
*/
function mtrim($data) {
$data = is_array($data) ? array_map('mtrim', $data) : trim($data);
return $data;
}
/**
* Convenient method for adding slashes deep by stepping into array
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @param mixed $value - value / array of data
* @return string - redirect site
*/
function addSlashesDeep($data) {
$data = is_array($data) ? array_map('addSlashesDeep', $data) : addslashes($data);
return $data;
}
function stripSlashesDeep($data) {
$data = is_array($data) ? array_map('stripSlashesDeep', $data) : stripslashes($data);
return $data;
}
/**
* Convenient method for striping special characters
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @param string $string - value to strip specials
* @param bool|array $skip - redirect site
* @param string $regexAllowedChars - match allowed characters
* @param string $replaceIllegalCharacters - replace illegal characters
* @return string - string replaced illegal characters
*/
function stripSpecialChars($string, $skip = false, $regexAllowedChars = '/[^\w\d_ -]/si', $replaceIllegalCharacters = ''){
// Replace other special chars
$specialCharacters = array(
'#' => '',
'$' => '',
'%' => '',
'&' => '',
'@' => '',
'.' => '',
'€' => '',
'+' => '',
'=' => '',
'§' => '',
'\\' => '',
'/' => '',
'-' => '_',
'\'' => '',
'"' => '',
);
$specialCharactersL = array(
'Š'=>'S', 'š'=>'s', 'Ð'=>'Dj', 'Ģ'=>'G','Ž'=>'Z', 'ž'=>'z', 'À'=>'A', 'Á'=>'A', 'Â'=>'A', 'Ã'=>'A', 'Ä'=>'A', 'Ā'=>'A',
'Å'=>'A', 'Æ'=>'A', 'Ç'=>'C', 'Č'=>'C', 'È'=>'E', 'É'=>'E', 'Ê'=>'E', 'Ë'=>'E', 'Ē'=>'E', 'Ì'=>'I', 'Í'=>'I', 'Î'=>'I',
'Ï'=>'I', 'Ñ'=>'N', 'Ò'=>'O', 'Ó'=>'O', 'Ô'=>'O', 'Õ'=>'O', 'Ö'=>'O', 'Ø'=>'O', 'Ù'=>'U', 'Ú'=>'U', 'Ī'=>'I', 'ī'=>'i',
'Û'=>'U', 'Ü'=>'U', 'Ý'=>'Y', 'Þ'=>'B', 'ß'=>'Ss','à'=>'a', 'á'=>'a', 'â'=>'a', 'ã'=>'a', 'ä'=>'a', 'ģ'=>'g',
'å'=>'a', 'æ'=>'a', 'ā'=>'a', 'ç'=>'c', 'č'=>'c', 'ē'=>'e', 'è'=>'e', 'é'=>'e', 'ê'=>'e', 'ë'=>'e', 'ì'=>'i', 'í'=>'i', 'î'=>'i',
'ï'=>'i', 'ð'=>'o', 'ñ'=>'n', 'ò'=>'o', 'ó'=>'o', 'ô'=>'o', 'õ'=>'o', 'ö'=>'o', 'ø'=>'o', 'ù'=>'u', 'Ņ'=>'N', 'ņ'=>'n',
'ú'=>'u', 'û'=>'u', 'ý'=>'y', 'þ'=>'b', 'ÿ'=>'y', 'ƒ'=>'f', 'Ķ'=>'K', 'ķ'=>'k', 'Ū'=>'U', 'ū'=>'u', 'Ļ'=>'L', 'ļ'=>'l'
);
// Ignore chars
if(is_array($skip)){
foreach($skip as $k=>$v){
unset($specialCharacters[$v]);
unset($specialCharactersL[$v]);
}
}
$string = strtr($string, $specialCharacters);
$string = strtr($string, $specialCharactersL);
if($regexAllowedChars)
$string = trim(preg_replace($regexAllowedChars, $replaceIllegalCharacters, $string));//remove all illegal chars
return $string;
}
/**
* Convenient method for striping special characters
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @param string $string - value to remove specials
* @param bool|array skip - characters to skip
* @param bool|string $regexAllowedChars - regex allowed chars
* @param bool|string $replaceIllegalCharacters - regex replace with chars
* @return string - redirect site
*/
function removeSpecialChars($string, $skip = false, $regexAllowedChars = '/[^\w\d_ -]/si', $replaceIllegalCharacters = ''){
// Replace other special chars
$specialCharacters = array(
'#' => '',
'$' => '',
'%' => '',
'&' => '',
'@' => '',
'.' => '',
'€' => '',
'+' => '',
'=' => '',
'§' => '',
'\\' => '',
'/' => '',
'-' => '',
'_' => '',
'`' => '',
'[' => '',
']' => '',
',' => '',
';' => '',
);
$specialCharacters = array_keys($specialCharacters);
$specialCharactersl = array(
'Š'=>'S', 'š'=>'s', 'Ð'=>'Dj', 'Ģ'=>'G','Ž'=>'Z', 'ž'=>'z', 'À'=>'A', 'Á'=>'A', 'Â'=>'A', 'Ã'=>'A', 'Ä'=>'A', 'Ā'=>'A',
'Å'=>'A', 'Æ'=>'A', 'Ç'=>'C', 'Č'=>'C', 'È'=>'E', 'É'=>'E', 'Ê'=>'E', 'Ë'=>'E', 'Ē'=>'E', 'Ì'=>'I', 'Í'=>'I', 'Î'=>'I',
'Ï'=>'I', 'Ñ'=>'N', 'Ò'=>'O', 'Ó'=>'O', 'Ô'=>'O', 'Õ'=>'O', 'Ö'=>'O', 'Ø'=>'O', 'Ù'=>'U', 'Ú'=>'U', 'Ī'=>'I', 'ī'=>'i',
'Û'=>'U', 'Ü'=>'U', 'Ý'=>'Y', 'Þ'=>'B', 'ß'=>'Ss','à'=>'a', 'á'=>'a', 'â'=>'a', 'ã'=>'a', 'ä'=>'a', 'ģ'=>'g',
'å'=>'a', 'æ'=>'a', 'ā'=>'a', 'ç'=>'c', 'č'=>'c', 'ē'=>'e', 'è'=>'e', 'é'=>'e', 'ê'=>'e', 'ë'=>'e', 'ì'=>'i', 'í'=>'i', 'î'=>'i',
'ï'=>'i', 'ð'=>'o', 'ñ'=>'n', 'ò'=>'o', 'ó'=>'o', 'ô'=>'o', 'õ'=>'o', 'ö'=>'o', 'ø'=>'o', 'ù'=>'u', 'Ņ'=>'N', 'ņ'=>'n',
'ú'=>'u', 'û'=>'u', 'ý'=>'y', 'þ'=>'b', 'ÿ'=>'y', 'ƒ'=>'f', 'Ķ'=>'K', 'ķ'=>'k', 'Ū'=>'U', 'ū'=>'u', 'Ļ'=>'L', 'ļ'=>'l'
);
$specialCharactersl = array_keys($specialCharactersl);
// Ignore chars
if(is_array($skip)){
foreach($skip as $k=>$v){
unset($specialCharacters[$v]);
unset($specialCharactersl[$v]);
}
}
$string = str_replace($specialCharacters, '', $string);
$string = str_replace($specialCharactersl, '', $string);
if($regexAllowedChars)
$string = trim(str_replace($regexAllowedChars, $replaceIllegalCharacters, $string));//remove all illegal chars
return $string;
}
/*
function cleanForShortURL($toClean) {
$toClean = str_replace('&', '-and-', $toClean);
$toClean = trim(preg_replace('/[^\w\d_ -]/si', '', $toClean));//remove all illegal chars
$toClean = str_replace(' ', '-', $toClean);
$toClean = str_replace('--', '-', $toClean);
return strtr($toClean, $GLOBALS['normalizeChars']);
}*/
/**
* Function to make a nested path , creating directories down the path
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @category CMS
* @return string query
* @version 1.1
*/
function makePath($sPath){
$dir = pathinfo($sPath , PATHINFO_DIRNAME);
if(is_dir($dir))
return true;
else{
if(makePath($dir)){
if(mkdir($dir)){
chmod($dir , 0777);
return true;
}
}
}
return false;
}
/**
* Function to copy dir content recursively
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @category CMS
* @return string query
* @version 1.1
*/
function RecursiveCopy($source, $dest, $diffDir = '') {
$sourceHandle = opendir($source);
if (!$diffDir)
$diffDir = $source;
if(file_exists($dest . '/' . $diffDir)){
return true;
}
mkdir($dest . '/' . $diffDir);
while ($res = readdir($sourceHandle)) {
if ($res == '.' || $res == '..')
continue;
if (is_dir($source . '/' . $res)) {
RecursiveCopy($source . '/' . $res, $dest, $diffDir . '/' . $res);
} else {
if(file_exists($dest . '/' . $diffDir . '/' . $res)){
return true;
}
copy($source . '/' . $res, $dest . '/' . $diffDir . '/' . $res);
}
}
return false;
}
/**
* Function to delete dir & subDirs recursively
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @category CMS
* @return string query
* @param string $directory - path to dir
* @param bool $empty - clear only dir contents
* @version 1.1
*/
function deleteDir($directory, $empty = false) {
if (substr($directory, -1) == "/") {
$directory = substr($directory, 0, -1);
}
if (!file_exists($directory) || !is_dir($directory)) {
return false;
} elseif (!is_readable($directory)) {
return false;
} else {
$directoryHandle = opendir($directory);
while ($contents = readdir($directoryHandle)) {
if ($contents != '.' && $contents != '..') {
$path = $directory . "/" . $contents;
if (is_dir($path)) {
deleteDir($path);
} else {
unlink($path);
}
}
}
closedir($directoryHandle);
if ($empty == false) {
if (!rmdir($directory)) {
return false;
}
}
return true;
}
}
/**
* Function to check if email is valide
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @category Validation
* @return bool - true / false
*/
function isValidEmail($email){
return preg_match('/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/', $email);
}
/**
* Function to check if email is valide
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @category Validation
* @return bool - true / false
*/
function isAlpha($item) {
return preg_match('/^[a-zA-Z|\s]+$/', $item);
}
/**
* Function to get all subfolder files
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @category CMS
* @param string $folderDir - base path
* @param array $hidden_files - files to exclude
* @param array $extensions - files types to collect
* @return bool - true / false
*/
function getFolderContent($folderDir, $hidden_files = array('.', '..', '.svn', '.DS_Store'), $extensions = false) {
$foundFiles = array();
if(file_exists($folderDir)){
foreach(scandir($folderDir) as $v){
if(!in_array(strtolower($v), $hidden_files)){
if(is_dir($folderDir . $v)){
$foundFiles = array_merge($foundFiles, getFolderContent($folderDir . $v . '/', $hidden_files));
}else{
if(!$extensions){
$foundFiles[] = $folderDir . $v;
}else if(in_array(getFileExtension(strtolower($v)), $extensions)){
$foundFiles[] = $folderDir . $v;
}
}
}
}
}
return $foundFiles;
}
/**
* Function to get folder tree
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @category CMS
* @param string $folderDir - base path
* @param array $hidden_files - files to exclude
* @param array $extensions - files types to collect
* @return bool - true / false
*/
function getFolderTree(&$data, $folderDir, $hidden_files = array('.', '..', '.svn', '.ds_store'), $extensions = false, $first_level = false, $addin = '', $full_path = true) {
$foundFiles = array();
if(file_exists($folderDir)){
foreach(scandir($folderDir) as $v){
if(!in_array(strtolower($v), $hidden_files)){
if(is_dir($folderDir . $v)){
$data[$addin . $v] = array();
if(is_bool($first_level)){
if(!$first_level){
$hf = (isset($hidden_files[$addin . $v])?$hidden_files[$addin . $v]:$hidden_files);
getFolderTree($data[$addin . $v], $folderDir . $v . '/', $hf, $extensions, false, $addin, $full_path);
}
}else{
if($first_level>1){
$hf = (isset($hidden_files[$addin . $v])?$hidden_files[$addin . $v]:$hidden_files);
getFolderTree($data[$addin . $v], $folderDir . $v . '/', $hf, $extensions, $first_level - 1, $addin, $full_path);
}
}
}else{
if($full_path){
if(!$extensions){
$data[$addin . $v] = $folderDir . $v;
}else if($ex = getFileExtension($v)){
if(in_array($ex, $extensions))
$data[$addin . $v] = $folderDir . $v;
}
}else{
if(!$extensions){
$data[$addin . $v] = $v;
}else if($ex = getFileExtension($v)){
if(in_array($ex, $extensions))
$data[$addin . $v] = $v;
}
}
}
}
}
}
return $foundFiles;
}
/**
* Function to get array first element
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @category cms
* @param array $foo
* @return array|bool - true / false
*/
function firstE($foo) {
if(is_array($foo) && !!$foo){
foreach ($foo as $k=>$v){
return $v;
}
}
return false;
}
/**
* Function to get array last element
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @category cms
* @param array $foo
* @return array|bool - true / false
*/
function lastE($foo) {
if(is_array($foo) && !!$foo){
return $foo[array_key_last($foo)];
}
return false;
}
/**
* Function to check language exists by code
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @category cms
* @return array - language data
*/
function chkLang($code) {
// Load db class
$db = cDb::getInstance(DB_HOST, DB_USR, DB_PWD, DB_PORT, DB_NAME);
if($lang = $db->_querySelect('site_languages', false, array(
//'type' => 0,
'lang_code' => $code,
'lang_blocked' => 0
))){
return $lang[0];
}
return false;
}
/**
* Function to check language exists by code
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @category cms
* @return array - language data
*/
function chkAppLang($code) {
// Load db class
$db = cDb::getInstance(DB_HOST, DB_USR, DB_PWD, DB_PORT, DB_NAME);
if($lang = $db->_querySelect('site_languages', false, array(
'type' => 0,
'lang_code' => $code,
'lang_blocked' => 0
))){
return $lang[0];
}
return false;
}
/**
* Function to get site default language
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @category cms
* @param bool $cms - indicates cms side or public side
* @return array - public side language code
*/
function getDefaultAppLang($cms = false) {
// Load db class
$db = cDb::getInstance(DB_HOST, DB_USR, DB_PWD, DB_PORT, DB_NAME);
if($lang = $db->_querySelectRow('site_languages', false, array(
'type' => ($cms?1:0),
'default' => 1,
'lang_blocked' => 0
))){
return $lang;
}
die('No default language marked!');
}
/**
* Function to sort array
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @category cms
* @return string - public side language code
*/
function sortArray($data, $field) {
// Fixed for php 5.2
if (!is_array($field))
$field = array($field);
$GLOBALS['field'] = $field;
usort($data, 'sortArraySubF');
unset($GLOBALS['field']);
/*usort($data, function($a, $b) use($field) {
$retval = 0;
foreach ($field as $fieldname) {
if ($retval == 0)
$retval = strnatcmp($a[$fieldname], $b[$fieldname]);
}
return $retval;
});*/
return $data;
}
function sortArraySubF($a, $b){
$retval = 0;
foreach ($GLOBALS['field'] as $fieldname) {
if ($retval == 0)
$retval = strnatcmp($a[$fieldname], $b[$fieldname]);
}
return $retval;
}
/**
* Function to get number from IP
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @category cms
* @return string - public side language code
*/
function ipToNumber($IPaddress) {
if (!$IPaddress) {
return false;
} else {
return sprintf('%u', ip2long($IPaddress));
}
}
/**
* Function to create new file
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @category cms
* @return bool true / false if file created
*/
function mkFile($fileName) {
if ($fileName && !file_exists($fileName)) {
$ourFileHandle = fopen($fileName, 'w') or die("can't open file");
fclose($ourFileHandle);
return true;
}else{
return false;
}
}
/**
* Function to check table exists in db
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @category cms
* @return bool true / false if file created
*/
function chkDbtableExists($tableName, $dbName = false) {
if(!$dbName && defined('DB_NAME')){
$dbName = DB_NAME;
}
if($dbName && $tableName){
$db = cDb::getInstance(DB_HOST, DB_USR, DB_PWD, DB_PORT, DB_NAME);
if($db->_querySelectOne(
'information_schema.tables',
array('TABLE_NAME'),
array('table_schema' => $dbName, 'table_name' => $tableName)
)){
return true;
}
}
return false;
}
/**
* Function to add table in db
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @category cms
* @return bool true / false if file created
*/
function createDbtable($tableName, $schema, $dbName = false) {
if(!$dbName && defined('DB_NAME')){
$dbName = DB_NAME;
}
if(!chkDbtableExists($tableName, $dbName)){
$db = cDb::getInstance(DB_HOST, DB_USR, DB_PWD, DB_PORT, DB_NAME);
$db->query("CREATE TABLE `{$tableName}`" . $schema . " ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=0");
}
return false;
}
/**
* Function to get age from date
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @category cms
* @param string $date - age in format DD-MM-YYYY
* @return bool true / false if file created
*/
function getAge($date){
list($day,$month,$year) = explode("-",$date);
$year_diff = date("Y") - $year;
$month_diff = date("m") - $month;
$day_diff = date("d") - $day;
if ($day_diff < 0 || $month_diff < 0){
$year_diff--;
}
return $year_diff;
}
/**
* Function to split long words for wrapping
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @category cms
* @return bool true / false if file created
*/
function splitLongWordsForWrap($data, $maxLen = 20) {
if (is_array($data)) {
return array_map("splitLongWordsForWrap", $data);
} else {
$strArray = explode(' ', $data);
if(count($strArray)){
foreach ($strArray as &$v) {
if(strlen($v) > $maxLen){
$v = chunk_split($v, $maxLen, ' ');
}
}
return implode(' ', $strArray);
}
}
return false;
}
/**
* Function to check array has at least one value set
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @category cms
* @param array $arr - array containing data
* @return array - empty of input full
*/
function chkArrVal($arr) {
$empty = true;
if(is_array($arr) && count($arr)){
foreach($arr as $v){
if($v){
$empty = false;
break;
}
}
}
if($empty){
return array();
}else{
return $arr;
}
}
/**
* Function to get first matching site map url data config
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @category cms
* @param int $mapId - containing search map id
* @param bool $cms - cms side request
* @return array
*/
function getFirstMatchByMapId(int $mapId, bool $cms = false): array
{
if ($mapId < 0) {
return [];
}
$db = cDb::getInstance(DB_HOST, DB_USR, DB_PWD, DB_PORT, DB_NAME);
// Get default cms lang
$appLang = getDefaultAppLang($cms);
$lang = array_shift($appLang);
// Get url data
$sSql = "
SELECT
sm.*,
smm.mod_code,
smm.mod_primary,
smm.mod_call_method,
smm.mod_use_tmpl,
1 as uri_lang_default
FROM
site_map sm
LEFT JOIN site_map_modules smm ON
sm.id = smm.mod_map_id
AND smm.mod_primary = '1'
WHERE
sm.p_lang_ref_id IN (
SELECT sm.p_lang_ref_id FROM site_map sm WHERE sm.id = {$mapId}
)
AND sm.p_lang_id = {$lang}";
// Get url data
$db->query($sSql);
return $db->getRow();
}
/**
* Function to get first matching site map url data config
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @category cms
* @param $str
* @param $len
* @return array
*/
function right($str, $len) {
if($str && $len){
if($strlen = strlen($str) < $len){
return $str;
}else{
return substr($str, $strlen - $len, $len);
}
}
return false;
}
/**
* Function to reorder php array based on confing array
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @category cms
* @param $array - base array to reorder
* @param bool|array $cfg - config array according to which to reorder
* @param bool $bExclude - exclude if not in cfg
* @return array
*/
function reOrderTableFields($array, $cfg, $bExclude = true)
{
if (
is_array($array)
&& is_array($cfg)
&& count($cfg)
) {
$nArray = [];
foreach ($cfg as $k => $v) {
if ($v || !$bExclude) {
if (!is_string($k)) {
$k = $v;
}
$k = substr($k, 2);
if (isset($array[$k])) {
$nArray[$k] = $array[$k];
$nArray[$k]['sel'] = ($v ? 1 : 0);
unset($array[$k]);
}
}
}
$vArray = &$array;
if (!$bExclude) {
$vArray = &$nArray;
$nArray = $nArray + $array;
}
// Set specific fields at beginning & end
if (isset($vArray['checkbox'])) {
$vTmp = $vArray['checkbox'];
$vTmp['sel'] = true;
unset($nArray['checkbox']);
$nArray = array('checkbox' => $vTmp) + $nArray;
}
if (isset($vArray['buttons'])) {
$vTmp = $vArray['buttons'];
$vTmp['sel'] = true;
unset($nArray['buttons']);
$nArray['buttons'] = $vTmp;
}
return $nArray;
}
// Select * if no cfg found
if ($array && count($array)) {
foreach ($array as &$v) {
$v['sel'] = true;
}
unset($v);
}
return $array;
}
/**
* Function to extract string keywords
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @category cms
* @param string $str - string to search keywords
* @param array $keys - key name array
* @return array
*/
function extractKeywords(&$str, $keys){
$tKeys = explode(' ', $str);
$keys = array_intersect_key($keys, array_flip($tKeys));
$str = implode(' ', array_diff($tKeys, array_keys($keys)));
return $keys;
}
/**
* Function to check if date is between one of following date pair
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @category cms
* @param array $dates - dates to match
* @param bool|int $time - time to match
* @return array
*/
function betweenTime($dates = array(), $time = false){
if(!$time)
$time = time();
if(count($dates)){
foreach($dates as $k=>$v){
$k = strtotime($k);
$v = strtotime($v);
if($k > $v){
$k = $k + $v;
$v = $k - $v;
}
if($k <= $time && $time <= $v){
return true;
}
}
}
return false;
}
/**
* Function to create old style table menu dropdown
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @category cms
* @param array $dropDownData - drop down data
* @param bool $bDropLastSep - drop last seperator line
* @return array
*/
function reformatDropDown(&$dropDownData = array(), $bDropLastSep = true){
$oLastItem = 0;
foreach($dropDownData as $k=>&$v){
if(!is_array($v) && $v == 'sepline'){
if($oLastItem)
$oLastItem['sepline'] = true;
unset($dropDownData[$k]);
}else{
$oLastItem = &$v;
}
}
if($bDropLastSep)
unset($oLastItem['sepline']);
unset($v);
return true;
}
/**
* Helper function for encoding base64 url safe
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @param string $input - input string to encode
* @return string - folder name till file dir from left side on first occurance
*/
function base64_url_encode($input)
{
return strtr(base64_encode($input), '+/=', '-_,');
}
/**
* Function to decode row id's and merge duplicates
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @category cms
* @param array $chkRows - all checked rows
* @param array $tableRows - shown table rows
* @param bool $encoded - id are encoded
* @param bool|string $idKey - id key string to search for
* @return array
*/
function mergeAndDecodeChkRows(&$chkRows, &$tableRows, $encoded = true, $idKey = false){
if($encoded){
$clean = array();
$cry = new cDefuseCrypto();
if(!!$chkRows && !!$tableRows){
if($idKey){
// Get decoded keys
foreach($chkRows as $k=>$v)
$clean[$cry->decrypt($k)] = $k;
// Set selected rows
foreach($tableRows as &$v)
if(!empty($clean[$v[$idKey]])){
$v['sel'] = true;
$clean[$v[$idKey]] = $v['id'];
}
unset($v);
}else{
// Get decoded keys
foreach($chkRows as $k=>$v){
$clean[$id = $cry->decrypt($k)] = $k;
if(!empty($tableRows[$id])){
$clean[$id] = $tableRows[$id]['id'];
$tableRows[$id]['sel'] = true;
}
}
}
// Reset key values
if(!!$clean)
$chkRows = array_flip(array_values($clean));
}
}else{
}
return true;
}
/**
* Function to convert pre 1970 years to time
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @category cms
* @param string $strInput - date to convert
* @return array
*/
function safeStrToTime($strInput) {
for ($i=1900; $i<=1969; $i++){
// Check for this year string in date
$strYear = (string)$i;
if (!(strpos($strInput, $strYear)===false)){
$replYear = $strYear;
$yearSkew = 1970 - $i;
$strInput = str_replace($strYear, '1970', $strInput);
}
}
$iVal = strtotime($strInput);
if ($yearSkew > 0){
$numSecs = (60 * 60 * 24 * 365 * $yearSkew);
$iVal = $iVal - $numSecs;
$numLeapYears = 0; // determine number of leap years in period
for ($j=$replYear; $j<=1969; $j++){
$thisYear = $j;
$isLeapYear = false;
// Is div by 4?
if (($thisYear % 4) == 0){
$isLeapYear = true;
}
// Is div by 100?
if (($thisYear % 100) == 0){
$isLeapYear = false;
}
// Is div by 1000?
if (($thisYear % 1000) == 0){
$isLeapYear = true;
}
if ($isLeapYear == true){
$numLeapYears++;
}
}
$iVal = $iVal - (60 * 60 * 24 * $numLeapYears);
}
return $iVal;
};
function zip($source, $destination){
if(!extension_loaded('zip') || !file_exists($source)){
return false;
}
$zip = new ZipArchive();
if(!$zip->open($destination, ZIPARCHIVE::CREATE)){
return false;
}
$source = str_replace('\\', '/', realpath($source));
if(is_dir($source) === true){
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);
foreach($files as $file){
$file = str_replace('\\', '/', $file);
// Ignore "." and ".." folders
if(in_array(substr($file, strrpos($file, '/')+1), array('.', '..')) )
continue;
$file = realpath($file);
if(is_dir($file) === true){
$zip->addEmptyDir(str_replace($source . '/', '', $file . '/'));
}
else if(is_file($file) === true){
$zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file));
}
}
}
else if(is_file($source) === true){
$zip->addFromString(basename($source), file_get_contents($source));
}
return $zip->close();
}
/**
* Function to get width class from w10 w8 ect class
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @category Functions
* @param string $class - string containing wXXX class
* @return array
*/
function findWidth($class){
$classes = explode(" ", $class);
foreach($classes as $v)
if(strlen($v) <= 3 && substr($v, 0, 1) == "w")
return substr($v, 1);
return false;
}
/**
* Function to create old style table menu dropdown
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @category Functions
* @param string $key - current array key
* @param array $fields - table field array
* @return array
*/
function getSearchAreaMergeCellWidth($key, $fields){
while(key($fields) !== $key)
next($fields);
$item = current($fields);
if(!empty($item['colspan']) && $item['colspan'] > 0){
$skip = $item['colspan'];
$w = findWidth($item['class']);
for($i = 1; $i < $skip; $i++){
$x = next($fields);
$w += findWidth($x['class']);
}
return "w{$w}";
}
return true;
}
/**
* Function to get user permission based data
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @category Functions
* @param object $modObj - module object by reference
* @param string $table - table where to search
* @param array $condition - array with where condition
* @param array $cp_id - company table field and value
* @param array/int $ids - which ids to check
* @param array $p - user permissions
* @param bool $bForEdit - if we need it for edit ( for view only )
* @return array
*/
function chkUserPermissionForEdit($modObj, $table, $condition, $cp_id, $ids = array(), $p = array(), $bForEdit = false){
if(!!$ids && !!$table && !!$cp_id && is_array($cp_id)){
if(!is_array($ids))
$ids = array($ids);
$leftJoin = "";
$where = "oo.id IN (" . implode(',', $ids) . ")";
// Add company check in where else return false.
foreach($cp_id as $k => $v)
$where .= " AND og.{$k} = {$v}";
if(!$modObj->user->suser->link_all){
// Where condition with left join;
if(!empty($condition['where']) && is_array($condition['where']) && !empty($condition['leftJoin']) && is_array($condition['leftJoin'])){
$leftJoin = " LEFT JOIN mod_users_to_object_groups og ON ";
foreach($condition['where'] as $field => $val)
$where .= " AND oo.{$field} = {$val}";
foreach($condition['leftJoin'] as $field1 => $field2)
$leftJoin .= " oo.{$field1} = og.{$field2}";
}
}
$sSelect = "";
if($p['see_current']){
if(!!$condition['between'] && is_array($condition['between'])){
foreach($condition['between'] as $field => $val){
if($bForEdit){
$sSelect .= ", oo.{$field} BETWEEN {$val[0]} AND {$val[1]} as a_b3m";
}else{
$where .= " AND oo.{$field} BETWEEN {$val[0]} AND {$val[1]}";
}
}
}
}
// Create sql string
$sSql = "
SELECT
oo.id
{$sSelect}
FROM
{$table} oo
{$leftJoin}
WHERE {$where}
";
// return ids which user can modify
$modObj->module->db->query($sSql);
if($bForEdit)
return $modObj->module->db->getFieldBasedArrayFieldsAdv('id', 'a_b3m');
else
return $modObj->module->db->getKeyValBasedArray('id', 'id');
}
return false;
}
/**
* array_merge_recursive does indeed merge arrays, but it converts values with duplicate
* keys to arrays rather than overwriting the value in the first array with the duplicate
* value in the second array, as array_merge does. I.e., with array_merge_recursive,
* this happens (documented behavior):
*
* array_merge_recursive(array('key' => 'org value'), array('key' => 'new value'));
* => array('key' => array('org value', 'new value'));
*
* array_merge_recursive_distinct does not change the datatypes of the values in the arrays.
* Matching keys' values in the second array overwrite those in the first array, as is the
* case with array_merge, i.e.:
*
* array_merge_recursive_distinct(array('key' => 'org value'), array('key' => 'new value'));
* => array('key' => array('new value'));
*
* Parameters are passed by reference, though only for performance reasons. They're not
* altered by this function.
*
* @param array $array1
* @param array $array2
* @return array
* @author Daniel <daniel (at) danielsmedegaardbuus (dot) dk>
* @author Gabriel Sobrinho <gabriel (dot) sobrinho (at) gmail (dot) com>
*/
function array_merge_recursive_distinct(array &$array1, array &$array2)
{
$merged = $array1;
foreach($array2 as $key => &$value){
if(is_array($value) && isset ($merged [$key]) && is_array($merged [$key])){
$merged [$key] = array_merge_recursive_distinct($merged [$key], $value);
}else{
$merged [$key] = $value;
}
}
return $merged;
}
/**
* Function to get datepicker translations
*
* @author Aivars Žukovskis <info@brsystems.lv>
* @category Functions
* @param cCore|object $modObj - module object by reference
* @param bool $bWhen - if we need months/days for when time ( example: martā...)
* @return array
*/
function getDatepickerTranslations($modObj, $bWhen = false){
if($bWhen){
$sApcKey = "DATEPICKER_TRANSLATIONS_FOR_WHEN_{$modObj->langId}";
$vMonthNames = array(
$modObj->gM('January_when'), $modObj->gM('February_when'), $modObj->gM('March_when'), $modObj->gM('April_when'),
$modObj->gM('May_when'), $modObj->gM('June_when'), $modObj->gM('July_when'), $modObj->gM('August_when'), $modObj->gM('September_when'),
$modObj->gM('October_when'), $modObj->gM('November_when'), $modObj->gM('December_when')
);
/*$vDayNames = array(
$modObj->gM('Sunday_when'), $modObj->gM('Monday_when'), $modObj->gM('Tuesday_when'), $modObj->gM('Wednesday_when'),
$modObj->gM('Thursday_when'), $modObj->gM('Friday_when'), $modObj->gM('Saturday_when')
);*/
}else{
$sApcKey = "DATEPICKER_TRANSLATIONS_{$modObj->langId}";
$vMonthNames = array(
$modObj->gM('January'), $modObj->gM('February'), $modObj->gM('March'), $modObj->gM('April'), $modObj->gM('May'), $modObj->gM('June'),
$modObj->gM('July'), $modObj->gM('August'), $modObj->gM('September'), $modObj->gM('October'), $modObj->gM('November'), $modObj->gM('December')
);
}
$vDayNames = array(
$modObj->gM('Sunday'), $modObj->gM('Monday'), $modObj->gM('Tuesday'), $modObj->gM('Wednesday'), $modObj->gM('Thursday'), $modObj->gM('Friday'), $modObj->gM('Saturday')
);
if(!($vTranslations = $modObj->oApc->check($sApcKey))){
$vTranslations = array(
'closeText' => $modObj->gM('Done'),
'prevText' => $modObj->gM('Prev'),
'nextText' => $modObj->gM('Next'),
'currentText' => $modObj->gM('Today'),
'monthNames' => $vMonthNames,
'monthNamesShort' => array(
$modObj->gM('Jan'), $modObj->gM('Feb'), $modObj->gM('Mar'), $modObj->gM('Apr'), $modObj->gM('May'), $modObj->gM('Jun'),
$modObj->gM('Jul'), $modObj->gM('Aug'), $modObj->gM('Sep'), $modObj->gM('Oct'), $modObj->gM('Nov'), $modObj->gM('Dec')
),
'dayNames' => $vDayNames,
'dayNamesShort' => array(
$modObj->gM('Sun'), $modObj->gM('Mon'), $modObj->gM('Tue'), $modObj->gM('Wed'), $modObj->gM('Thu'), $modObj->gM('Fri'), $modObj->gM('Sat')
),
'dayNamesMin' => array(
$modObj->gM('Su'), $modObj->gM('Mo'), $modObj->gM('Tu'), $modObj->gM('We'), $modObj->gM('Th'), $modObj->gM('Fr'), $modObj->gM('Sa')
),
'weekHeader' => $modObj->gM('Wk'),
);
$modObj->oApc->store($sApcKey, $vTranslations);
}
return $vTranslations;
}
/**
* Function to split key - val based array by specific keys
*
* @author Aivars Žukovskis <info@brsystems.lv>
* @category Functions
* @param string $sStrTSplit - string to split
* @param array $vDelimiters - array of delimiters
* @return array - data array
*/
function splitStrToArrayByDelimiters($sStrTSplit, $vDelimiters = array()){
$vData = array();
if(!!$vDelimiters){
$vEscapedDelimiters = array();
foreach($vDelimiters as $v){
$vEscapedDelimiters[] = preg_quote($v);
}
$sPattern = '/(' . implode(')|(', $vEscapedDelimiters) . ')/';
$x = preg_split($sPattern, $sStrTSplit, false, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
if(!!$x){
for($i=0;$i<=count($x);$i++){
if(!empty($x[$i]) && in_array($x[$i], $vDelimiters)){
$vData[$x[$i]] = $x[++$i];
continue;
}
}
}
unset($vEscapedDelimiters);
}
return $vData;
}
/**
* Function to split key - val based array by specific keys
*
* @author Aivars Žukovskis <info@brsystems.lv>
* @category Functions
* @param string|array $vData - text or array to check for link fields like [%gL(NUMBER)%]
* @param cCore|object $oCore - core object for link structure requests
* @return array - data array
*/
function findAndReplaceLinksInText(&$vData, &$oCore){
if(is_callable(array($oCore, 'gL'))){
$vData = (is_array($vData) ? $vData : array($vData));
foreach($vData as &$v){
if(is_array($v) && !!$v) findAndReplaceLinksInText($v, $oCore);
else{
$matches = array();
preg_match_all('/\[% *gL\([0-9]* *\)%\]/i', $v, $matches);
if(!!$matches){
foreach($matches as $sGLID){
if(!!$sGLID){
$vReplace = array();
foreach($sGLID as $sID){
if($mapId = preg_replace('/(\[% *gL\()([0-9]+)( *\)%\])/i', '$2', $sID)){
$vReplace[] = $oCore->gL($mapId);
}
}
$v = str_replace($sGLID, $vReplace, $v);
}
}
}
}
unset($v);
}
}
return $vData;
}
/**
* Function to insert element into array before index preserving key
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @category Functions
* @param array $vInput - input array
* @param int $index - index to set element
* @param string $newKey - new element key
* @param mixed $element - element to set on key
* @return array - data array
* @throws string if index not found
*/
function array_insertBefore($vInput, $index, $newKey, $element) {
if (!array_key_exists($index, $vInput)) {
throw new Exception("Index not found");
}
$tmpArray = array();
foreach ($vInput as $key => $value) {
if ($key === $index) {
$tmpArray[$newKey] = $element;
}
$tmpArray[$key] = $value;
}
return $vInput;
}
/**
* Function to insert element into array after index preserving key
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @category Functions
* @param array $vInput - input array
* @param int $index - index to set element
* @param string $newKey - new element key
* @param mixed $element - element to set on key
* @return array - data array
* @throws string if index not found
*/
function array_insertAfter($vInput, $index, $newKey, $element) {
if (!array_key_exists($index, $vInput)) {
throw new Exception("Index not found");
}
$tmpArray = array();
foreach ($vInput as $key => $value) {
$tmpArray[$key] = $value;
if ($key === $index) {
$tmpArray[$newKey] = $element;
}
}
return $tmpArray;
}
/**
* Function to Gets the last key of an array
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @category Functions
* @param array $array
* @return mixed - array last key
*/
if (! function_exists("array_key_last")) {
function array_key_last($array) {
if (!is_array($array) || empty($array)) {
return NULL;
}
return array_keys($array)[count($array)-1];
}
}
/**
* Function to get array key first
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @category Functions
* @param array $array
* @return mixed - array first key
*/
if (!function_exists('array_key_first')) {
function array_key_first(array $arr) {
foreach($arr as $key => $unused) {
return $key;
}
return NULL;
}
}
/**
* Function to load remote page data
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @category Functions
* @param string $url - request url from url
* @return mixed - array last key
*/
function curl_get_contents($url)
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
/**
* Function to return value or default value if value is empty
*
* @param mixed $value
* @param mixed $default
* @return mixed - $value or $default value
* @throws string if index not found
* @author Aivars Žukovskis <info@brsystems.lv>
* @category Functions
*/
function defaultVal($value, $default)
{
return !empty($value) ? $value : $default;
}
// To avoid collisions where function already defined (starting php8.0)
if (!function_exists("str_starts_with")) {
function str_starts_with(string $haystack = '', string $needle = ''): string
{
return substr($haystack, 0, 1) === $needle;
}
}
/**
* Convenience function for getting appropriate Fully-qualified name (FQN) namespace
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @category Module
* @param string $className - class to search for
* @return string
*/
function getModuleNamespacePath(string $className): string
{
if (!class_exists($className)) {
foreach (['App', 'Cms', 'Sys'] as $type) {
$nameSpace = "\\BRSystems\\Core\\$type\\$className\\$className";
if (class_exists($nameSpace)) {
$className = $nameSpace;
break;
}
}
}
return $className;
}