Create New Item
×
Item Type
File
Folder
Item Name
×
Search file in folder and subfolders...
File Manager
/
wp-content
/
plugins
/
unlimited-elements-for-elementor
/
inc_php
/
framework
Advanced Search
Upload
New Item
Settings
Back
Back Up
Advanced Editor
Save
<?php defined('UNLIMITED_ELEMENTS_INC') or die('Restricted access'); class UniteFunctionsUC { const SANITIZE_ID = "sanitize_id"; const SANITIZE_TEXT_FIELD = "sanitize_text_field"; const SANITIZE_KEY = "sanitize_key"; const SANITIZE_NOTHING = "sanitize_nothing"; private static $serial = 0; private static $arrCache = array(); public static function throwError($message, $code = null) { if (!empty($code)) { throw new Exception($message); } else { throw new Exception($message); } } public static function showTrace($exit = false) { try { throw new Exception("Show me the trace"); } catch (Exception $e) { $trace = $e->getTraceAsString(); dmp($trace); if ($exit == true) { exit; } } } public static function isArrayAssoc($arr) { if (is_array($arr) == false) { return false; } if (array() === $arr) { return false; } return array_keys($arr) !== range(0, count($arr) - 1); } public static function getPostGetVariable($name, $initVar = "", $sanitizeType = "") { $var = $initVar; if (isset($_POST[$name])) { $var = $_POST[$name]; } else { if (isset($_GET[$name])) { $var = $_GET[$name]; } } $var = UniteProviderFunctionsUC::sanitizeVar($var, $sanitizeType); return $var; } public static function getPostVariable($name, $initVar = "", $sanitizeType = "") { $var = $initVar; if (isset($_POST[$name])) { $var = $_POST[$name]; } $var = UniteProviderFunctionsUC::sanitizeVar($var, $sanitizeType); return $var; } public static function getGetVar($name, $initVar = "", $sanitizeType = "") { $var = $initVar; if (isset($_GET[$name])) { $var = $_GET[$name]; } $var = UniteProviderFunctionsUC::sanitizeVar($var, $sanitizeType); return $var; } public static function z_________ARRAYS_______() { } public static function getVal($arr, $key, $altVal = "") { if (isset($arr[$key])) { return $arr[$key]; } return $altVal; } public static function getArrFirstValue($arr) { if (empty($arr)) { return ""; } if (is_array($arr) == false) { return ""; } $firstValue = reset($arr); return $firstValue; } public static function getFirstNotEmptyKey($arr) { foreach ($arr as $key => $item) { if (!empty($key)) { return $key; } } return ""; } public static function filterArrFields($arr, $fields, $isFieldsAssoc = false) { $arrNew = array(); if ($isFieldsAssoc == false) { foreach ($fields as $field) { if (array_key_exists($field, $arr)) { $arrNew[$field] = $arr[$field]; } } } else { foreach ($fields as $field => $value) { if (array_key_exists($field, $arr)) { $arrNew[$field] = $arr[$field]; } } } return $arrNew; } public static function removeArrItemsByKeys($arrItems, $keysToRemove) { foreach ($keysToRemove as $key) { if (array_key_exists($key, $arrItems)) { unset($arrItems[$key]); } } return $arrItems; } public static function convertStdClassToArray($d) { if (is_object($d)) { $d = get_object_vars($d); } if (is_array($d)) { return array_map(array("UniteFunctionsUC", "convertStdClassToArray"), $d); } else { return $d; } } public static function getRandomArrayItem($arr) { $numItems = count($arr); $rand = rand(0, $numItems - 1); $item = $arr[$rand]; return $item; } public static function getDiffArrItems($arr, $arrDefault, $arrMustKeys = array()) { if (gettype($arrDefault) != "array") { return $arr; } if (!empty($arrMustKeys)) { $arrMustKeys = UniteFunctionsUC::arrayToAssoc($arrMustKeys); } $arrValues = array(); foreach ($arr as $key => $value) { if (array_key_exists($key, $arrMustKeys) == true) { $arrValues[$key] = self::getVal($arrDefault, $key); if (array_key_exists($key, $arr) == true) { $arrValues[$key] = $arr[$key]; } continue; } if (array_key_exists($key, $arrDefault) == false) { $arrValues[$key] = $value; continue; } $defaultValue = $arrDefault[$key]; if ($defaultValue !== $value) { $arrValues[$key] = $value; continue; } } return $arrValues; } public static function arrayToAssoc($arr, $field = null, $field2 = null) { if (empty($arr)) { return array(); } $arrAssoc = array(); foreach ($arr as $item) { if (empty($field)) { $arrAssoc[$item] = $item; } else { if (!empty($field2)) { $arrAssoc[$item[$field]] = $item[$field2]; } else { $arrAssoc[$item[$field]] = $item; } } } return $arrAssoc; } public static function assocToArray($assoc) { $arr = array(); foreach ($assoc as $key => $item) { $arr[] = $item; } return $arr; } public static function assocToArrayKeyValue($assoc, $keyName, $valueName, $firstItem = null) { $arr = array(); if (!empty($firstItem)) { $arr = $firstItem; } foreach ($assoc as $item) { if (!array_key_exists($keyName, $item)) { UniteFunctionsUC::throwError("field: {$keyName} not found in array"); } if (!array_key_exists($valueName, $item)) { UniteFunctionsUC::throwError("field: {$valueName} not found in array"); } $key = $item[$keyName]; $value = $item[$valueName]; $arr[$key] = $value; } return $arr; } public static function trimArrayItems($arr) { if (gettype($arr) != "array") { UniteFunctionsUC::throwError("trimArrayItems error: The type must be array"); } foreach ($arr as $key => $item) { $arr[$key] = trim($item); } return $arr; } public static function jsonEncodeForClientSide($arr) { if (empty($arr)) { $arr = array(); } $json = json_encode($arr); $json = addslashes($json); $json = "'" . $json . "'"; return $json; } public static function jsonEncodeForHtmlData($arr, $dataKey = "") { $strJson = ""; if (!empty($arr)) { $strJson = json_encode($arr); $strJson = htmlspecialchars($strJson); } if (!empty($dataKey)) { $strJson = " data-{$dataKey}=\"{$strJson}\""; } return $strJson; } public static function arrStyleToStrStyle($arrStyle, $styleName = "", $addCss = "", $addImportant = false) { if (empty($arrStyle) && empty($addCss)) { return ""; } $br = "\n"; $tab = "\t"; $output = $br; if (!empty($styleName)) { $output .= $styleName . "{" . $br; } foreach ($arrStyle as $key => $value) { if ($key == "inline_css") { $addCss .= $value; continue; } if ($addImportant == true) { $value = $value . " !important"; } $output .= $tab . $key . ":" . $value . ";" . $br; } if (!empty($addCss)) { $arrAddCss = explode($br, $addCss); $output .= $br; foreach ($arrAddCss as $str) { $output .= $tab . $str . $br; } } if (!empty($styleName)) { $output .= "}" . $br; } return $output; } public static function arrStyleToStrInlineCss($arrStyle, $addCss = "", $addStyleTag = true) { $addCss = trim($addCss); if (empty($arrStyle) && empty($addCss)) { return ""; } $output = ""; foreach ($arrStyle as $key => $value) { $output .= $key . ":" . $value . ";"; } if (!empty($addCss)) { $addCss = self::removeLineBreaks($addCss); $output .= $addCss; } if ($addStyleTag && !empty($output)) { $output = "style=\"{$output}\""; } return $output; } public static function isAssocArray($arr) { if (array() === $arr) { return false; } return array_keys($arr) !== range(0, count($arr) - 1); } public static function insertToAssocArray($arrItems, $arrNewItems) { $arrInsert = array(); $arrInsertTop = array(); $counter = 0; $arrOutput = array(); foreach ($arrNewItems as $item) { $insertAfter = UniteFunctionsUC::getVal($item, "insert_after"); if ($insertAfter == "bottom") { $insertAfter = null; } if (empty($insertAfter)) { $counter++; $insertAfter = "bottom_" . $counter; } if ($insertAfter == "top") { $arrInsertTop[] = $item; } else { if (isset($arrInsert[$insertAfter])) { if (self::isAssocArray($arrInsert[$insertAfter]) == false) { $arrInsert[$insertAfter][] = $item; } else { $arrInsert[$insertAfter] = array($arrInsert[$insertAfter], $item); } } else { $arrInsert[$insertAfter] = $item; } } } foreach ($arrInsertTop as $newItem) { $newItemKey = $newItem["key"]; $newItemText = $newItem["text"]; $arrOutput[$newItemKey] = $newItemText; } foreach ($arrItems as $key => $item) { $arrOutput[$key] = $item; if (array_key_exists($key, $arrInsert)) { $arrNewItem = $arrInsert[$key]; if (self::isAssocArray($arrNewItem) == false) { foreach ($arrNewItem as $newItemReal) { $newItemKey = $newItemReal["key"]; $newItemText = $newItemReal["text"]; $arrOutput[$newItemKey] = $newItemText; } } else { $newItemKey = $arrNewItem["key"]; $newItemText = $arrNewItem["text"]; $arrOutput[$newItemKey] = $newItemText; } unset($arrInsert[$key]); } } foreach ($arrInsert as $newItem) { $newItemKey = $newItem["key"]; $newItemText = $newItem["text"]; $arrOutput[$newItemKey] = $newItemText; } return $arrOutput; } public static function addArrFirstValue($arr, $text, $value = "") { $arr = array($value => $text) + $arr; return $arr; } public static function phpArrayToJsArrayText($arr, $tabPrefix = "\t\t\t") { $str = ""; $length = count($arr); $counter = 0; foreach ($arr as $key => $value) { $str .= $tabPrefix . "{$key}:\"{$value}\""; $counter++; if ($counter != $length) { $str .= ",\n"; } } return $str; } public static function getArrayDuplicateValues($arrAssoc) { $arrDuplicate = array_diff_assoc($arrAssoc, array_unique($arrAssoc)); $arrDuplicate = array_flip($arrDuplicate); return $arrDuplicate; } public static function iterateArrayRecursive($arr, $callback) { if (is_array($arr) == false) { return false; } call_user_func($callback, $arr); foreach ($arr as $item) { if (is_array($item)) { self::iterateArrayRecursive($item, $callback); } } } public static function mergeArraysUnique($arr1, $arr2, $arr3 = array()) { if (empty($arr2) && empty($arr3)) { return $arr1; } $arrIDs = array_merge($arr1, $arr2, $arr3); $arrIDs = array_unique($arrIDs); return $arrIDs; } public static function modifyDataArrayForShow($arrData, $convertSingleArray = false) { if (is_array($arrData) == false) { return $arrData; } $arrDataNew = array(); foreach ($arrData as $key => $value) { $key = htmlspecialchars($key); if (is_string($value) == true) { $value = htmlspecialchars($value); } $key = " {$key}"; $arrDataNew[$key] = $value; if ($convertSingleArray == true && is_array($value) && count($value) == 1 && isset($value[0])) { $arrDataNew[$key] = $value[0]; } } return $arrDataNew; } public static function z_____________STRINGS_____________() { } public static function addTabsToText($str, $tab = "\t") { $lines = explode("\n", $str); foreach ($lines as $index => $line) { $lineTrimmed = trim($line); if (!empty($lineTrimmed)) { $line = $tab . $line; } $lines[$index] = $line; } $str = implode("\n", $lines); return $str; } public static function isStringContains($strContent, $strSearch) { $searchString = trim($strSearch); if (empty($strSearch)) { return true; } $strContent = strtolower($strContent); $strSearch = strtolower($strSearch); $pos = strpos($strContent, $strSearch); if ($pos === false) { return false; } return true; } public static function removeLineBreaks($string) { $string = str_replace("\r", "", $string); $string = str_replace("\n", "", $string); return $string; } public static function getRandomString($length = 10, $numbersOnly = false) { $characters = '0123456789abcdefghijklmnopqrstuvwxyz'; if ($numbersOnly === "hex") { $characters = '0123456789abcdef'; } if ($numbersOnly === true) { $characters = '0123456789'; } $randomString = ''; for ($i = 0; $i < $length; $i++) { $randomString .= $characters[rand(0, strlen($characters) - 1)]; } return $randomString; } public static function limitStringSize($str, $numChars, $addDots = true) { if (function_exists("mb_strlen") == false) { return $str; } if (mb_strlen($str) <= $numChars) { return $str; } if ($addDots) { $str = mb_substr($str, 0, $numChars - 3) . "..."; } else { $str = mb_substr($str, 0, $numChars); } return $str; } public static function truncateString($value, $length = 100, $preserve = true, $separator = '...', $charset = "utf-8") { $value = strip_tags($value); if (mb_strlen($value, $charset) > $length) { if ($preserve) { if (false === ($breakpoint = mb_strpos($value, ' ', $length, $charset))) { return $value; } $length = $breakpoint; } return rtrim(mb_substr($value, 0, $length, $charset)) . $separator; } return $value; } public static function arrayToXML($array, $rootName, $xml = null) { if ($xml === null) { $xml = new SimpleXMLElement("<{$rootName}/>"); self::arrayToXML($array, $rootName, $xml); $strXML = $xml->asXML(); if ($strXML === false) { UniteFunctionsUC::throwError("Wrong xml output"); } return $strXML; } foreach ($array as $key => $value) { if (is_numeric($key)) { $key = 'item' . $key; } if (is_array($value)) { $node = $xml->addChild($key); self::arrayToXML($value, $rootName, $node); } else { $xml->addChild($key, htmlspecialchars($value)); } } } public static function formatXmlString($xml) { $xml = preg_replace('/(>)(<)(\\/*)/', "\$1\n\$2\$3", $xml); $token = strtok($xml, "\n"); $result = ''; $pad = 0; $matches = array(); while ($token !== false) { if (preg_match('/.+<\\/\\w[^>]*>$/', $token, $matches)) { $indent = 0; } elseif (preg_match('/^<\\/\\w/', $token, $matches)) { $pad--; $indent = 0; } elseif (preg_match('/^<\\w[^>]*[^\\/]>.*$/', $token, $matches)) { $indent = 1; } else { $indent = 0; } $line = str_pad($token, strlen($token) + $pad, ' ', STR_PAD_LEFT); $result .= $line . "\n"; $token = strtok("\n"); $pad += $indent; } return $result; } public static function maybeUnserialize($str) { if (empty($str)) { return array(); } if (is_array($str)) { return $str; } $arrOutput = @unserialize($str); if (empty($arrOutput)) { return array(); } if (!is_array($arrOutput)) { UniteFunctionsUC::throwError("The unserialized string should be alwayas array type"); } return $arrOutput; } public static function sanitizeAttr($strAttr) { $strAttr = htmlspecialchars($strAttr); return $strAttr; } public static function getArrSanitizeTypes() { $arrSanitize = array(); $arrSanitize[self::SANITIZE_ID] = __("Sanitize ID", "unlimited-elements-for-elementor"); $arrSanitize[self::SANITIZE_KEY] = __("Sanitize KEY", "unlimited-elements-for-elementor"); $arrSanitize[self::SANITIZE_TEXT_FIELD] = __("Sanitize Text Field", "unlimited-elements-for-elementor"); $arrSanitize[self::SANITIZE_NOTHING] = __("No Sanitize (not recomended)", "unlimited-elements-for-elementor"); return $arrSanitize; } public static function normalizeSize($value) { $value = (string) $value; $value = strtolower($value); if (is_numeric($value) == false) { return $value; } $value = (int) $value; $value .= "px"; return $value; } public static function isTextEncoded($content) { if (is_string($content) == false) { return false; } if (empty($content)) { return false; } if (!preg_match('/^[a-zA-Z0-9\\/\\r\\n+]*={0,2}$/', $content)) { return false; } $decoded = @base64_decode($content, true); if (empty($decoded)) { return false; } if (base64_encode($decoded) != $content) { return false; } return true; } public static function maybeDecodeTextContent($value) { if (empty($value)) { return $value; } if (is_string($value) == false) { return $value; } $isEncoded = self::isTextEncoded($value); if ($isEncoded == false) { return $value; } $decoded = self::decodeTextContent($value); return $decoded; } public static function decodeTextContent($content) { $content = rawurldecode(base64_decode($content)); return $content; } public static function encodeContent($content) { if (is_array($content)) { $content = json_encode($content); } $content = rawurlencode($content); $content = base64_encode($content); return $content; } public static function decodeContent($content, $convertToArray = true) { if (empty($content)) { return $content; } $content = rawurldecode(base64_decode($content)); if ($convertToArray == true) { $arr = self::jsonDecode($content); } else { $arr = @json_decode($content); } return $arr; } public static function jsonDecode($content, $outputArray = false) { if ($outputArray == true && empty($content)) { return array(); } $arr = @json_decode($content); $arr = self::convertStdClassToArray($arr); if ($outputArray == true && empty($content)) { return array(); } return $arr; } public static function cleanPath($path) { if (defined("DIRECTORY_SEPARATOR")) { $ds = DIRECTORY_SEPARATOR; } else { $ds = "/"; } if (!is_string($path) && !empty($path)) { self::throwError('JPath::clean: $path is not a string.'); } $path = trim($path); if (empty($path)) { return $path; } elseif ($ds == '\\' && $path[0] == '\\' && $path[1] == '\\') { $path = "\\" . preg_replace('#[/\\\\]+#', $ds, $path); } else { $path = preg_replace('#[/\\\\]+#', $ds, $path); } return $path; } public static function getNumberFromString($str) { $str = preg_replace("/[^0-9]/", '', $str); return $str; } public static function getNumberFromStringEnd($str) { $matches = array(); if (!preg_match('#(\\d+)$#', $str, $matches)) { return ""; } if (!isset($matches[1])) { return ""; } return $matches[1]; } public static function getStringTextPortion($str) { $num = self::getNumberFromStringEnd($str); if ($num === "") { return $str; } $lastPost = strlen($str) - strlen($num); $textPortion = substr($str, 0, $lastPost); return $textPortion; } public static function getSerialID($prefix) { self::$serial++; $rand = self::getRandomString(5, true); $id = $prefix . "_" . $rand . "_" . self::$serial; return $id; } public static function getPrettyHtml($html) { $html = preg_replace('/<\\/?div[^>]*\\>/i', '', $html); $html = preg_replace('/<\\/?span[^>]*\\>/i', '', $html); $html = preg_replace('#<script(.*?)>(.*?)</script>#is', '', $html); $html = preg_replace('#<style(.*?)>(.*?)</style>#is', '', $html); $html = preg_replace('/<i [^>]*><\\/i[^>]*>/', '', $html); $html = preg_replace('/ class=".*?"/', '', $html); $html = preg_replace('/(^[\\r\\n]*|[\\r\\n]+)[\\s\\t]*[\\r\\n]+/', "\n", $html); $html = trim($html); return $html; } public static function getHrefFromHtml($str) { $arrFound = array(); preg_match('/href=(["\'])([^\\1]*)\\1/i', $str, $arrFound); if (empty($arrFound)) { return null; } $href = self::getVal($arrFound, 2); return $href; } public static function convertHandleToTitle($handle) { $title = str_replace("_", " ", $handle); $title = ucwords($title); return $title; } public static function truncateHTML($maxLength, $html) { mb_internal_encoding("UTF-8"); $printedLength = 0; $position = 0; $tags = array(); ob_start(); while ($printedLength < $maxLength && preg_match('{</?([a-z]+)[^>]*>|&#?[a-zA-Z0-9]+;}', $html, $match, PREG_OFFSET_CAPTURE, $position)) { list($tag, $tagPosition) = $match[0]; $str = mb_strcut($html, $position, $tagPosition - $position); if ($printedLength + mb_strlen($str) > $maxLength) { print mb_strcut($str, 0, $maxLength - $printedLength); $printedLength = $maxLength; break; } print $str; $printedLength += mb_strlen($str); if ($tag[0] == '&') { print $tag; $printedLength++; } else { $tagName = $match[1][0]; if ($tag[1] == '/') { $openingTag = array_pop($tags); assert($openingTag == $tagName); print $tag; } else { if ($tag[mb_strlen($tag) - 2] == '/') { print $tag; } else { print $tag; $tags[] = $tagName; } } } $position = $tagPosition + mb_strlen($tag); } if ($printedLength < $maxLength && $position < mb_strlen($html)) { print mb_strcut($html, $position, $maxLength - $printedLength); } while (!empty($tags)) { printf('</%s>', array_pop($tags)); } $bufferOuput = ob_get_contents(); ob_end_clean(); $html = $bufferOuput; return $html; } public static function z__________URLS__________() { } public static function getUrlContents($url, $arrPost = array(), $method = "post", $debug = false) { $ch = curl_init(); $timeout = 0; if (empty($arrPost)) { $arrPost = array(); } $strPost = ''; foreach ($arrPost as $key => $value) { if (!empty($strPost)) { $strPost .= "&"; } if (is_array($value)) { $value = json_encode($value); } $value = urlencode($value); $strPost .= "{$key}={$value}"; } if (strtolower($method) == "post") { curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $strPost); } else { if (!empty($strPost)) { $url = self::addUrlParams($url, $strPost); } } curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); $headers = array(); $headers[] = "User-Agent:Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.8) Gecko/20100722 Firefox/3.6.8"; $headers[] = "Accept-Charset:utf-8;q=0.7,*;q=0.7"; curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); $response = curl_exec($ch); if ($debug == true) { dmp($url); dmp($response); exit; } if ($response == false) { throw new Exception("getUrlContents Request failed"); } curl_close($ch); return $response; } public static function urlToHandle($url = '') { $url = preg_replace('/[^\\w\\-' . '~_\\.' . ']+/u', '-', $url); return mb_strtolower(preg_replace('/--+/u', '-', $url), 'UTF-8'); } public static function addUrlParams($url, $params, $addOnlyNewParam = false) { if (empty($params)) { return $url; } if (strpos($url, "?") !== false) { if ($addOnlyNewParam == true) { return $url; } $url .= "&"; } else { $url .= "?"; } if (is_array($params)) { $strParams = ""; foreach ($params as $key => $value) { if (!empty($strParams)) { $strParams .= "&"; } $strParams .= $key . "=" . urlencode($value); } $params = $strParams; } $url .= $params; return $url; } public static function urlToSsl($url) { $url = str_replace("http://", "https://", $url); $url = str_replace("HTTP://", "HTTPS://", $url); return $url; } public static function cleanUrl($url) { $url = preg_replace('/([^:])(\\/{2,})/', '$1/', $url); return $url; } public static function getBaseUrl($url) { $arrUrl = parse_url($url); $scheme = UniteFunctionsUC::getVal($arrUrl, "scheme", "http"); $host = UniteFunctionsUC::getVal($arrUrl, "host"); $path = UniteFunctionsUC::getVal($arrUrl, "path"); $url = "{$scheme}://{$host}{$path}"; return $url; } public static function z___________VALIDATIONS_________() { } public static function validateObjectMethod($object, $strMethod, $objectName) { if (method_exists($object, "initByID") == false) { UniteFunctionsUC::throwError("Object: {$objectName} don't have method {$strMethod}"); } } public static function validateValueInArray($value, $valueTitle, $arr) { if (is_array($arr) == false) { self::throwError("array of {$valueTitle} should be array"); } if (array_search($value, $arr) === false) { self::throwError("wrong {$value}, should be: " . implode(",", $arr)); } } public static function validateFilepath($filepath, $errorPrefix = null) { if (file_exists($filepath) == true && is_file($filepath) == true) { return false; } if ($errorPrefix == null) { $errorPrefix = "File"; } $message = $errorPrefix . " {$filepath} not exists!"; self::throwError($message); } public static function validateDir($pathDir, $errorPrefix = null) { if (is_dir($pathDir) == true) { return false; } if ($errorPrefix == null) { $errorPrefix = "Directory"; } $message = $errorPrefix . " {$pathDir} not exists!"; self::throwError($message); } private static function validateWritable($name, $path, $strList, $validateExists = true) { if ($validateExists == true) { if (file_exists($path) == false) { throw new Exception("{$name} doesn't exists"); } } else { if (file_exists($path) == false) { return false; } } if (is_writable($path) == false) { chmod($path, 0755); if (is_writable($path) == false) { $strType = "Folder"; if (is_file($path)) { $strType = "File"; } $message = "{$strType} {$name} is doesn't have a write permissions. Those folders/files must have a write permissions in order that this application will work properly: {$strList}"; throw new Exception($message); } } } public static function validateNumeric($val, $fieldName = "") { self::validateNotEmpty($val, $fieldName); if (empty($fieldName)) { $fieldName = "Field"; } if (!is_numeric($val)) { self::throwError("{$fieldName} should be numeric "); } } public static function validateNotEmpty($val, $fieldName = "") { if (empty($fieldName)) { $fieldName = "Field"; } if (empty($val) && is_numeric($val) == false) { self::throwError("Field <b>{$fieldName}</b> should not be empty"); } } public static function validateNoTags($val, $fieldName = "") { if ($val == strip_tags($val)) { return true; } if (empty($fieldName)) { $fieldName = "Field"; } self::throwError("Field <b>{$fieldName}</b> should not contain tags"); } public static function validateCharNotExists($str, $sign, $objectName) { if (strpos($str, $sign) !== false) { self::throwError("{$objectName} doesn't allow & signs"); } } private static function validatePHPVersion() { $strVersion = phpversion(); $version = (float) $strVersion; if ($version < 5) { self::throwError("You must have php5 and higher in order to run the application. Your php version is: {$version}"); } } public static function validateGD() { if (function_exists('gd_info') == false) { throw new Exception("You need PHP GD library to operation. Please turn it on in php.ini"); } } public static function isAlphaNumeric($val) { $match = preg_match('/^[\\w_]+$/', $val); if ($match == 0) { return false; } return true; } public static function validateIDsList($val, $fieldName = "") { if (empty($val)) { return true; } $match = preg_match('/^[0-9,]+$/', $val); if ($match == 0) { self::throwError("Field <b>{$fieldName}</b> allow only numbers and comas."); } } public static function isValidIDsArray($arr) { if (is_array($arr) == false) { return false; } if (empty($arr)) { return true; } foreach ($arr as $key => $value) { if (is_numeric($key) == false || is_numeric($value) == false) { return false; } } return true; } public static function validateAlphaNumeric($val, $fieldName = "") { if (empty($fieldName)) { $fieldName = "Field"; } if (self::isAlphaNumeric($val) == false) { self::throwError("Field <b>{$fieldName}</b> allow only english words, numbers and underscore."); } } public static function validateUrlAlias($alias, $fieldName = "") { if (empty($fieldName)) { $fieldName = "Field"; } self::validateNotEmpty($alias, $fieldName); $url = "http://example.com/" . $alias; $isValid = filter_var($url, FILTER_VALIDATE_URL); if ($isValid == false) { self::throwError("Field <b>{$fieldName}</b> allow only words, numbers hypens and underscores."); } } public static function validateEmail($email, $fieldName = "email") { $isValid = self::isEmailValid($email); if ($isValid == true) { return false; } self::throwError(__("The {$fieldName} is not valid", "unlimited-elements-for-elementor")); } public static function isEmailValid($email) { return preg_match('/^[^@]+@[a-zA-Z0-9._-]+\\.[a-zA-Z]+$/', $email); } public static function validateHTML($string) { $start = strpos($string, '<'); $end = strrpos($string, '>', $start); if ($end !== false) { $string = substr($string, $start); } else { $string = substr($string, $start, strlen($string) - $start); } $string = "<div>{$string}</div>"; libxml_use_internal_errors(true); libxml_clear_errors(); simplexml_load_string($string); $arrErrors = libxml_get_errors(); return $arrErrors; } public static function z________FILE_SYSTEM________() { } public static function checkCreateDir($dir) { if (!is_dir($dir)) { mkdir($dir); } } public static function mkdirValidate($path, $dirName) { if (is_dir($path) == false) { @mkdir($path); if (!is_dir($path)) { UniteFunctionsUC::throwError("{$dirName} path: {$path} could not be created. Please check your permissions"); } } } public static function getPathInfo($filepath) { $info = pathinfo($filepath); if (!isset($info["filename"])) { $filename = $info["basename"]; if (isset($info["extension"])) { $filename = substr($info["basename"], 0, -strlen($info["extension"]) - 1); } $info["filename"] = $filename; } return $info; } public static function getFilenameNoExtension($filepath) { $info = self::getPathInfo($filepath); $filename = self::getVal($info, "filename"); return $filename; } public static function getFilenameExtension($filepath) { $info = self::getPathInfo($filepath); $ext = self::getVal($info, "extension"); return $ext; } public static function writeFile($str, $filepath) { if (is_array($str)) { UniteFunctionsUC::throwError("write file should accept only string in file: " . $filepath); } $fp = fopen($filepath, "w+"); fwrite($fp, $str); fclose($fp); } public static function getFileList($path) { $dir = scandir($path); $arrFiles = array(); foreach ($dir as $file) { if ($file == "." || $file == "..") { continue; } $filepath = $path . "/" . $file; if (is_file($filepath)) { $arrFiles[] = $file; } } return $arrFiles; } public static function getPathSize($path) { if (empty($path)) { return 0; } if (is_dir($path) == false) { return 0; } $arrFiles = self::getFileListTree($path); if (empty($arrFiles)) { return 0; } $totalSize = 0; foreach ($arrFiles as $pathFile) { if (is_file($pathFile) == false) { continue; } $fileSize = filesize($pathFile); $totalSize += $fileSize; } return $totalSize; } public static function getFileListTree($path, $filetype = null, $arrFiles = null) { if (empty($arrFiles)) { $arrFiles = array(); } if (is_dir($path) == false) { return $arrFiles; } $path = self::addPathEndingSlash($path); $arrPaths = scandir($path); foreach ($arrPaths as $file) { if ($file == "." || $file == "..") { continue; } $filepath = $path . $file; if (is_dir($filepath)) { if (is_array($filetype) && array_search("dir", $filetype) !== false || !is_array($filetype) && $filetype == "dir") { $arrFiles[] = $filepath; } $arrFiles = self::getFileListTree($filepath, $filetype, $arrFiles); } $info = pathinfo($filepath); $ext = self::getVal($info, "extension"); $ext = strtolower($ext); if (!empty($filetype) && is_array($filetype) && array_search($ext, $filetype) === false) { continue; } if (!empty($filetype) && is_array($filetype) == false && $filetype != $ext) { continue; } $arrFiles[] = $filepath; } return $arrFiles; } public static function getDirList($path) { $arrDirs = scandir($path); $arrFiles = array(); foreach ($arrDirs as $dir) { if ($dir == "." || $dir == "..") { continue; } $dirpath = $path . "/" . $dir; if (is_dir($dirpath)) { $arrFiles[] = $dir; } } return $arrFiles; } public static function clearDebug($filepath = "debug.txt") { if (file_exists($filepath)) { unlink($filepath); } } public static function writeDebugError(Exception $e, $filepath = "debug.txt") { $message = $e->getMessage(); $trace = $e->getTraceAsString(); $output = $message . "\n"; $output .= $trace . "\n"; $fp = fopen($filepath, "a+"); fwrite($fp, $output); fclose($fp); } public static function addToFile($str, $filepath) { $fp = fopen($filepath, "a+"); fwrite($fp, "---------------------\n"); fwrite($fp, $str . "\n"); fclose($fp); } public static function deleteDir($path, $deleteOriginal = true, $arrNotDeleted = array(), $originalPath = "") { if (empty($originalPath)) { $originalPath = $path; } if (getType($path) == "array") { $arrPaths = $path; foreach ($path as $singlePath) { $arrNotDeleted = self::deleteDir($singlePath, $deleteOriginal, $arrNotDeleted, $originalPath); } return $arrNotDeleted; } if (!file_exists($path)) { return $arrNotDeleted; } if (is_file($path)) { $deleted = unlink($path); if (!$deleted) { $arrNotDeleted[] = $path; } } else { $arrPaths = scandir($path); foreach ($arrPaths as $file) { if ($file == "." || $file == "..") { continue; } $filepath = realpath($path . "/" . $file); $arrNotDeleted = self::deleteDir($filepath, $deleteOriginal, $arrNotDeleted, $originalPath); } if ($deleteOriginal == true || $originalPath != $path) { $deleted = @rmdir($path); if (!$deleted) { $arrNotDeleted[] = $path; } } } return $arrNotDeleted; } public static function copyDir($src, $dst) { $dir = opendir($src); @mkdir($dst); while (false !== ($file = readdir($dir))) { if ($file != '.' && $file != '..') { if (is_dir($src . '/' . $file)) { self::copyDir($src . '/' . $file, $dst . '/' . $file); } else { copy($src . '/' . $file, $dst . '/' . $file); } } } closedir($dir); } public static function addPathEndingSlash($path) { $slashType = strpos($path, '\\') === 0 ? 'win' : 'unix'; $lastChar = substr($path, strlen($path) - 1, 1); if ($lastChar != '/' && $lastChar != '\\') { $path .= $slashType == 'win' ? '\\' : '/'; } return $path; } public static function removePathEndingSlash($path) { $path = rtrim($path, "/"); $path = rtrim($path, "\\"); return $path; } public static function pathToUnix($path) { $path = str_replace('\\', '/', $path); $path = preg_replace('/\\/+/', '/', $path); return $path; } public static function pathToRelative($path, $basePath) { $path = str_replace($basePath, "", $path); $path = ltrim($path, '/'); return $path; } public static function joinPaths($basePath, $path) { $newPath = $basePath . "/" . $path; $newPath = self::pathToUnix($newPath); return $newPath; } public static function realpath($path, $addEndingSlash = true) { $path = realpath($path); if (empty($path)) { return $path; } $path = self::pathToUnix($path); if (is_dir($path) && $addEndingSlash == true) { $path .= "/"; } return $path; } public static function isPathUnderBase($path, $basePath) { $path = self::pathToUnix($path); $basePath = self::pathToUnix($basePath); if (strpos($path, $basePath) === 0) { return true; } return false; } public static function findFreeFilepath($path, $filename, $filepathSource = null) { $filepath = $path . $filename; if (file_exists($filepath) == false) { return $filename; } $checkSizes = false; if (!empty($filepathSource)) { $checkSizes = true; $sizeSource = filesize($filepathSource); $sizeDest = filesize($filepath); if ($sizeSource == $sizeDest) { return $filename; } } $info = pathinfo($filename); $basename = $info["filename"]; $ext = $info["extension"]; $counter = 0; $textPortion = self::getStringTextPortion($basename); if (empty($textPortion)) { $textPortion = $basename . "_"; } do { $counter++; $filename = $textPortion . $counter . "." . $ext; $filepath = $path . $filename; $isFileExists = file_exists($filepath); if ($isFileExists == true && $checkSizes == true) { $sizeDest = filesize($filepath); if ($sizeSource == $sizeDest) { return $filename; } } } while ($isFileExists == true); return $filename; } public static function z__________SESSIONS_______() { } public static function getSessionVar($name, $base) { if (empty($base)) { UniteFunctionsUC::throwError("Can't get session var without the base"); } if (!isset($_SESSION)) { return ""; } $arrBase = UniteFunctionsUC::getVal($_SESSION, $base); if (empty($arrBase)) { return ""; } $value = UniteFunctionsUC::getVal($_SESSION, $name); return $value; } public static function setSessionVar($name, $value, $base) { if (empty($base)) { UniteFunctionsUC::throwError("Can't set session var without the base"); } if (!isset($_SESSION[$base])) { $_SESSION[$base] = array(); } $_SESSION[$base][$name] = $value; } public static function clearSessionVar($name, $base) { if (!isset($_SESSION[$base])) { return false; } $_SESSION[$base][$name] = null; unset($_SESSION[$base][$name]); } public static function z___________OTHERS__________() { } public static function encodeSVGForBGUrl($svgContent) { if (empty($svgContent)) { return ""; } $urlBG = "data:image/svg+xml;base64," . base64_encode($svgContent); return $urlBG; } public static function getPHPMemoryLimit() { if (isset(self::$arrCache["memory_limit"])) { return self::$arrCache["memory_limit"]; } $memory_limit = ini_get("memory_limit"); $found = preg_match('/^(\\d+)(.)$/', $memory_limit, $matches); if (!$found) { return null; } $numLimit = $matches[1]; $letter = $matches[2]; switch ($letter) { case "M": $memory_limit = $numLimit * 1024 * 1024; break; case "G": $memory_limit = $numLimit * 1024 * 1024 * 1024; break; case "K": $memory_limit = $numLimit * 1024; break; } self::$arrCache["memory_limit"] = $memory_limit; return $memory_limit; } public static function isEnoughtPHPMemory($mbReserve = 32) { $limit = self::getPHPMemoryLimit(); if (empty($limit)) { return true; } $reserve = $mbReserve * 1024 * 1024; $maxReserve = $limit * 0.3; if ($reserve > $maxReserve) { } $reserve = $maxReserve; $available = $limit - $reserve; $used = memory_get_usage(); if ($used > $available) { return false; } return true; } public static function timestamp2Time($stamp) { $strTime = date("H:i", $stamp); return $strTime; } public static function timestamp2DateTime($stamp) { $strDateTime = date("d M Y, H:i", $stamp); return $strDateTime; } public static function timestamp2Date($stamp) { $strDate = date("d M Y", $stamp); return $strDate; } public static function normalizeTextareaContent($content) { if (empty($content)) { return $content; } $content = stripslashes($content); $content = trim($content); return $content; } public function downloadImage($filepath, $filename, $mimeType = "") { $contents = file_get_contents($filepath); $filesize = strlen($contents); if ($mimeType == "") { $info = UniteFunctionsUC::getPathInfo($filepath); $ext = $info["extension"]; $mimeType = "image/{$ext}"; } header("Content-Type: {$mimeType}"); header("Content-Disposition: attachment; filename=\"{$filename}\""); header("Content-Length: {$filesize}"); echo UniteProviderFunctionsUC::escCombinedHtml($contents); exit; } public static function downloadTextFile($text, $filename) { $filesize = strlen($text); header("Content-Type: text"); header("Content-Disposition: attachment; filename=\"{$filename}\""); header("Content-Length: {$filesize}"); echo UniteProviderFunctionsUC::escCombinedHtml($text); exit; } public static function downloadFile($filepath, $filename = null) { UniteFunctionsUC::validateFilepath($filepath, "export file"); if (empty($filename)) { $filename = basename($filepath); } header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename="' . $filename . '"'); header('Expires: 0'); header('Cache-Control: must-revalidate'); header('Pragma: public'); header('Content-Length: ' . filesize($filepath)); readfile($filepath); exit; } public static function strToBool($str) { if (is_bool($str)) { return $str; } if (empty($str)) { return false; } if (is_numeric($str)) { return $str != 0; } $str = strtolower($str); if ($str == "true") { return true; } return false; } public static function boolToStr($bool) { $bool = self::strToBool($bool); if ($bool == true) { return "true"; } else { return "false"; } } public static function yiq($r, $g, $b) { return $r * 0.299 + $g * 0.587 + $b * 0.114; } public static function isEmptyColorString($color) { $color = trim($color); if (empty($color)) { return true; } $color = strtolower($color); if (strpos($color, "nan") !== false) { return true; } return false; } public static function sanitizeColorString($color) { if (self::isEmptyColorString($color) == true) { return ""; } return $color; } public static function html2rgb($color) { if (empty($color)) { return false; } if ($color[0] == '#') { $color = substr($color, 1); } if (strlen($color) == 6) { list($r, $g, $b) = array($color[0] . $color[1], $color[2] . $color[3], $color[4] . $color[5]); } elseif (strlen($color) == 3) { list($r, $g, $b) = array($color[0] . $color[0], $color[1] . $color[1], $color[2] . $color[2]); } else { return false; } $r = hexdec($r); $g = hexdec($g); $b = hexdec($b); return array($r, $g, $b); } public static function toString($obj) { return trim((string) $obj); } public static function remove_utf8_bom($content) { $content = str_replace(chr(239), "", $content); $content = str_replace(chr(187), "", $content); $content = str_replace(chr(191), "", $content); $content = trim($content); return $content; } public static function printPath() { try { throw new Exception("We are here"); } catch (Exception $e) { dmp($e->getTraceAsString()); exit; } } public static function isLocal() { if (isset($_SERVER["HTTP_HOST"]) && $_SERVER["HTTP_HOST"] == "localhost") { return true; } return false; } public static function redirectToUrl($url) { header("location: {$url}"); exit; } }