Rev 4911 | Rev 6749 | Ir a la última revisión | Autoría | Comparar con el anterior | Ultima modificación | Ver Log |
<?phpdeclare(strict_types=1);namespace LeadersLinked\Library;abstract class Functions{public static function getUserIP(){$client = isset($_SERVER['HTTP_CLIENT_IP']) ? $_SERVER['HTTP_CLIENT_IP'] : '';$forward = isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : '';$remote = $_SERVER['REMOTE_ADDR'];if(filter_var($client, FILTER_VALIDATE_IP)) {$ip = $client;} elseif(filter_var($forward, FILTER_VALIDATE_IP)) {$ip = $forward;} else {$ip = $remote;}return $ip;}/**** @param string $what* @param string $date* @return string*/public static function convertDate($what, $date) {if ($what == 'wherecond') {return date('Y-m-d', strtotime($date));}else if ($what == 'display') {return date('d M, Y h:i A', strtotime($date));}else if ($what == 'displayWeb') {return date('d M Y', strtotime($date));}else if ($what == 'onlyDate') {return date(PHP_DATE_FORMAT, strtotime($date));}else if ($what == 'monthYear') {return date(PHP_DATE_FORMAT_MONTH_YEAR, strtotime($date));}else if ($what == 'onlyMonth') {return date(PHP_DATE_FORMAT_MONTH, strtotime($date));}else if ($what == 'gmail') {return date('D, M d, Y - h:i A', strtotime($date));}else if ($what == 'onlyDateForCSV') {return date('M d,Y', strtotime($date));}else {return date('Y-m-d', strtotime($date));}}/**** @param string $timestamp* @param string $now* @return string*/public static function timeAgo($timestamp, $now = ''){if($now) {$datetime1 = \DateTime::createFromFormat('Y-m-d H:i:s', $now);} else {$now = date('Y-m-d H:i:s');$datetime1 = date_create($now);}$datetime2 = date_create($timestamp);$diff = date_diff($datetime1, $datetime2);$timemsg = '';if ($diff->y > 0) {$timemsg = $diff->y . ' año' . ($diff->y > 1 ? "s" : '');} else if ($diff->m > 0) {$timemsg = $diff->m . ' mes' . ($diff->m > 1 ? "es" : '');} else if ($diff->d > 0) {$timemsg = $diff->d . ' dia' . ($diff->d > 1 ? "s" : '');} else if ($diff->h > 0) {$timemsg = $diff->h . ' hora' . ($diff->h > 1 ? "s" : '');} else if ($diff->i > 0) {$timemsg = $diff->i . ' minuto' . ($diff->i > 1 ? "s" : '');} else if ($diff->s > 0) {$timemsg = $diff->s . ' segundo' . ($diff->s > 1 ? "s" : '');}if (!$timemsg) {$timemsg = "Ahora";} else {$timemsg = $timemsg . '';}return $timemsg;}public static function geoCodeService($key, $address, $address1, $city, $state, $zip){$data = [];array_push($data, $address);array_push($data, $address1);array_push($data, $city);array_push($data, $state);array_push($data, $zip);$data = array_filter($data, function($value) { return !empty($value); } );$url = 'https://maps.googleapis.com/maps/api/geocode/json?' . http_build_query(['address' => implode(',', $data), 'key' => $key]);echo 'URL : ' . $url . '<br>';$ch = curl_init();curl_setopt($ch, CURLOPT_URL,$url);curl_setopt($ch, CURLOPT_POST, false);curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);$response = curl_exec ($ch);curl_close ($ch);$response = json_decode($response, true);print_r($response); exit;$latitude = isset($response['results'][0]['geometry']['location']['lat']) ? $response['results'][0]['geometry']['location']['lat'] : 0;$longitude = isset($response['results'][0]['geometry']['location']['lng']) ? $response['results'][0]['geometry']['location']['lng'] : 0;return ['latitude' => $latitude, 'longitude' => $longitude];}/**** @return string[]*/public static function getAllTimeZones(){$timezones = [];$zones = \DateTimeZone::listIdentifiers();foreach($zones as $zone){array_push($timezones, $zone);}return $timezones;}/**** @param string $from_date* @param string $from_timezone* @param string $to_timezone* @return string*/public static function convertDateBetweenTimeZones($from_date, $from_timezone, $to_timezone){$date = new \DateTime($from_date, new \DateTimeZone($from_timezone));$date->setTimezone(new \DateTimeZone($to_timezone));return $date->format('Y-m-d H:i:s');}/**** @param string $from_datetime* @param string $from_timezone* @param string $to_timezone* @return string*/public static function convertDateTimeBetweenTimeZones($from_datetime, $from_timezone, $to_timezone){$date = new \DateTime($from_datetime, new \DateTimeZone($from_timezone));$date->setTimezone(new \DateTimeZone($to_timezone));return $date->format('Y-m-d H:i:s');}/*public static function timeElapsedString(int $ptime){$etime = time() - $ptime;if ($etime < 1) {return 'LABEL_ZERO_SECOND';}$a = array(365 * 24 * 60 * 60 => 'LABEL_YEAR_SMALL',30 * 24 * 60 * 60 => 'LABEL_MONTH_SMALL',24 * 60 * 60 => 'LABEL_DAY_SMALL',60 * 60 => 'LABEL_HOUR_SMALL',60 => 'LABEL_MINUTE_SMALL',1 => 'LABEL_SECOND_SMALL');$a_plural = array('LABEL_YEAR_SMALL' => 'LABEL_YEARS_SMALL','LABEL_MONTH_SMALL' => 'LABEL_MONTHS_SMALL','LABEL_DAY_SMALL' => 'LABEL_DAYS_SMALL','LABEL_HOUR_SMALL' => 'LABEL_HOURS_SMALL','LABEL_MINUTE_SMALL' => 'LABEL_MINUTES_SMALL','LABEL_SECOND_SMALL' => 'LABEL_SECONDS_SMALL');foreach ($a as $secs => $str) {$d = $etime / $secs;if ($d >= 1) {$r = round($d);return $r . ' ' . ($r > 1 ? $a_plural[$str] : $str);}}}*//**** @param string $date1* @param string $date2* @param string $format*/public static function getYears(string $date1, string $date2, string $format = 'YearMonth'){$date1 = new \DateTime($date1);$date2 = new \DateTime($date2);$interval = date_diff($date1, $date2);$months = $interval->m + ($interval->y * 12);return(int) ($months / 12);}/**** @param number $length* @param string $seeds* @return string*/public static function genrateRandom($length = 8, $seeds = 'alphanum'){$seedings = ['alpha' => 'abcdefghijklmnopqrstuvwqyzABCDEFGHIJKLMNOPQRSTUVWXYZ','numeric' => '0123456789','alphanum' => 'abcdefghijklmnopqrstuvwqyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789','hexidec' => '0123456789abcdef',];if (isset($seedings[$seeds])) {$seeds = $seedings[$seeds];}list($usec, $sec) = explode(' ', microtime());$seed = (float) $sec + ((float) $usec * 100000);mt_srand(intval($seed));$str = '';$seeds_count = strlen($seeds);for ($i = 0; $length > $i; $i++) {$pos = mt_rand(0, $seeds_count - 1);$str .= substr($seeds, $pos, $pos + 1);}return $str;}/**** @param string $date1* @param string $date2* @param string $timeFormat* @param bool $positive* @return number*/public static function getDateDiff(string $date1, string $date2, string $timeFormat = 'sec', bool $positive = false){$dtTime1 = strtotime($date1);$dtTime2 = strtotime($date2);if ($positive === true) {if ($dtTime2 < $dtTime1) {$tmp = $dtTime1;$dtTime1 = $dtTime2;$dtTime2 = $tmp;}}$diff = $dtTime2 - $dtTime1;if ($timeFormat == 'sec') {return $diff;} else if ($timeFormat == 'day') {return $diff / 86400;}}/**** @param string $date1* @param string $date2* @param string $format* @return string*/public static function getDifference(string $date1, string $date2, string $format = 'YearMonth'){$difference = '';$datetime1 = date_create($date1);$datetime2 = date_create($date2);$interval = date_diff($datetime1, $datetime2);$years = $interval->format('%y');$months = $interval->format('%m');$days = $interval->format('%d');$years_text = $months_text = $days_text = '';if ($years == 1) {$years_text = '1 LABEL_YEAR';} else if ($years > 1) {$years_text = $years . ' LABEL_YEARS';}if ($months == 1) {$months_text = '1 LABEL_MONTH';} else if ($months > 1) {$months_text = $months . ' LABEL_MONTHS';}if ($days == 1) {$days_text = '1 LABEL_DAY';} else if ($days > 1) {$days_text = $days . ' LABEL_DAYS';}if ($format == 'Year') {return trim($years_text);} else if ($format == 'YearMonth') {$difference = trim($years_text) . ' ' . trim($months_text);return trim($difference);} else if ($format == 'YearMonthDay') {$difference = trim($years_text) . ' ' . trim($months_text) . ' ' . trim($days_text);return trim($difference);}}/**** @param string $source* @param string $destination* @param int $quality* @return string*/public static function compress(string $source, string $destination, int $quality = null){$info = getimagesize($source);if ($info['mime'] == 'image/jpeg') {$image = imagecreatefromjpeg($source);}elseif ($info['mime'] == 'image/gif') {$image = imagecreatefromgif($source);}elseif ($info['mime'] == 'image/png') {$image = imagecreatefrompng($source);}imagejpeg($image, $destination, $quality);return $destination;}/**** @param string $filename* @param string $newfilename* @param int $max_width* @param int $max_height* @param bool $withSampling* @param array $crop_coords* @return boolean*/public static function resizeImage(string $filename, string $newfilename = "", int $max_width = 0, int $max_height = 0, bool $withSampling = true, $crop_coords = array()){if (empty($newfilename)) {$newfilename = $filename;}$fileExtension = strtolower(self::getExt($filename));if ($fileExtension == 'jpg' || $fileExtension == 'jpeg') {$img = imagecreatefromjpeg($filename);} else if ($fileExtension == 'png') {$img = imagecreatefrompng($filename);} else if ($fileExtension == 'gif') {$img = imagecreatefromgif($filename);} else {$img = imagecreatefromjpeg($filename);}$width = imageSX($img);$height = imageSY($img);$target_width = $max_width;$target_height = $max_height;$target_ratio = $target_width / $target_height;$img_ratio = $width / $height;if (empty($crop_coords)) {if ($target_ratio > $img_ratio) {$new_height = $target_height;$new_width = $img_ratio * $target_height;} else {$new_height = $target_width / $img_ratio;$new_width = $target_width;}if ($new_height > $target_height) {$new_height = $target_height;}if ($new_width > $target_width) {$new_height = $target_width;}$new_img = imagecreatetruecolor($target_width, $target_height);$white = imagecolorallocate($new_img, 255, 255, 255);imagecolortransparent($new_img);imagefilledrectangle($new_img, 0, 0, $target_width - 1, $target_height - 1, $white);imagecopyresampled($new_img, $img, ($target_width - $new_width) / 2, ($target_height - $new_height) / 2, 0, 0, $new_width, $new_height, $width, $height);} else {$new_img = imagecreatetruecolor($target_width, $target_height);$white = imagecolorallocate($new_img, 255, 255, 255);imagefilledrectangle($new_img, 0, 0, $target_width - 1, $target_height - 1, $white);imagecopyresampled($new_img, $img, 0, 0, $crop_coords['x1'], $crop_coords['y1'], $target_width, $target_height, $crop_coords['x2'], $crop_coords['y2']);}if ($fileExtension == 'jpg' || $fileExtension == 'jpeg') {$createImageSave = imagejpeg($new_img, $newfilename);} else if ($fileExtension == 'png') {$createImageSave = imagepng($new_img, $newfilename);} else if ($fileExtension == 'gif') {$createImageSave = imagegif($new_img, $newfilename);} else {$createImageSave = imagejpeg($new_img, $newfilename);}return $createImageSave;}/**** @param string $start* @param string $end* @return array*/public static function getTimeDifference(string $start, string $end) {$uts = ['start' => strtotime($start),'end' => strtotime($end)];if ($uts['start'] !== -1 && $uts['end'] !== -1) {if ($uts['end'] >= $uts['start']) {$diff = $uts['end'] - $uts['start'];if ($days = intval((floor($diff / 86400)))) {$diff = $diff % 86400;}if ($hours = intval((floor($diff / 3600)))) {$diff = $diff % 3600;}if ($minutes = intval((floor($diff / 60)))) {$diff = $diff % 60;}$diff = intval($diff);return ['days' => $days,'hours' => $hours,'minutes' => $minutes,'seconds' => $diff];} else {trigger_error("Ending date/time is earlier than the start date/time", E_USER_WARNING);}} else {trigger_error("Invalid date/time data detected", E_USER_WARNING);}return;}/**** @param number $length* @return string*/public static function generatePassword($length = 8){$password = '';$possible = '2346789bcdfghjkmnpqrtvwxyzBCDFGHJKLMNPQRTVWXYZ';$maxlength = strlen($possible);if ($length > $maxlength) {$length = $maxlength;}$i = 0;while ($i < $length) {$char = substr($possible, mt_rand(0, $maxlength - 1), 1);if (!strstr($password, $char)) {$password .= $char;$i++;}}return $password;}/**** @param string $date* @param boolean $time_required* @return string*/public static function countRemainingDays(string $date, $time_required = true){$datestr = $date;$date = strtotime($datestr);$diff = $date - time();if ($time_required) {$days = floor($diff / (60 * 60 * 24));$hours = round(($diff - $days * 60 * 60 * 24) / (60 * 60));return "$days days $hours hours remaining";} else {$days = ceil($diff / (60 * 60 * 24));return "$days days remaining";}}/**** @param string $varPhoto* @param string $uploadDir* @param string $tmp_name* @param array $th_arr* @param string $file_nm* @param boolean $addExt* @param array $crop_coords* @return string|boolean*/public static function generateThumbnail(string $varPhoto, string $uploadDir, string $tmp_name, $th_arr = array(), $file_nm = '', $addExt = true, $crop_coords = array()){$ext = '.' . strtolower(self::getExt($varPhoto));$tot_th = count($th_arr);if (($ext == ".jpg" || $ext == ".gif" || $ext == ".png" || $ext == ".bmp" || $ext == ".jpeg" || $ext == ".ico")) {if (!file_exists($uploadDir)) {mkdir($uploadDir, 0777);}if ($file_nm == '')$imagename = rand() . time();else$imagename = $file_nm;if ($addExt || $file_nm == '')$imagename = $imagename . $ext;$pathToImages = $uploadDir . $imagename;$Photo_Source = copy($tmp_name, $pathToImages);if ($Photo_Source) {for ($i = 0; $i < $tot_th; $i++) {Functions::resizeImage($uploadDir . $imagename, $uploadDir . 'th' . ($i + 1) . '_' . $imagename, $th_arr[$i]['width'], $th_arr[$i]['height'], false, $crop_coords);}return $imagename;} else {return false;}} else {return false;}}/**** @param string $file* @return mixed*/public static function getExt(string $file){$path_parts = pathinfo($file);$ext = $path_parts['extension'];return $ext;}/**** @param string $source* @param string $target_path* @param string $target_filename* @param number $target_width* @param number $target_height* @return boolean*/public static function uploadImage($source, $target_path, $target_filename, $target_width, $target_height ){try {$data = file_get_contents($source);$img = imagecreatefromstring($data);if(!file_exists($target_path)) {mkdir($target_path, 0755);}if($img) {list($source_width, $source_height) = getimagesize($source);$width_ratio = $target_width / $source_width;$height_ratio = $target_height / $source_height;if($width_ratio > $height_ratio) {$resized_width = $target_width;$resized_height = $source_height * $width_ratio;} else {$resized_height = $target_height;$resized_width = $source_width * $height_ratio;}$resized_width = round($resized_width);$resized_height = round($resized_height);$offset_width = round(($target_width - $resized_width) / 2);$offset_height = round(($target_height - $resized_height) / 2);$new_image = imageCreateTrueColor($target_width, $target_height);imageAlphaBlending($new_image, False);imageSaveAlpha($new_image, True);$transparent = imageColorAllocateAlpha($new_image, 0, 0, 0, 127);imagefill($new_image, 0, 0, $transparent);imageCopyResampled($new_image, $img , $offset_width, $offset_height, 0, 0, $resized_width, $resized_height, $source_width, $source_height);$target = $target_path . DIRECTORY_SEPARATOR . $target_filename;if(file_exists($target)) {@unlink($target);}imagepng($new_image, $target);}unlink($source);return true;}catch (\Throwable $e){error_log($e->getTraceAsString());return false;}}/**** @param string $source* @param string $target_path* @param string $target_filename* @return boolean*/public static function uploadFile($source, $target_path, $target_filename){try {$target_filename = self::normalizeString(basename($target_filename));$parts = explode('.', $target_filename);$basename = trim($parts[0]);if(strlen($basename) > 220) {$basename = substr($basename, 0, 220);}$basename = $basename . '-' . uniqid() . '.' . $parts[1];$full_filename = $target_path . DIRECTORY_SEPARATOR . $basename;return move_uploaded_file($source, $full_filename);}catch (\Throwable $e){error_log($e->getTraceAsString());return false;}}/**** @param string $path* @param string $prefix* @return boolean*/public static function delete($path, $prefix){try {if (is_dir($path)){if ($dh = opendir($path)) {while (($file = readdir($dh)) !== false){if($file == '.' || $file == '..') {continue;}if(strpos($file, $prefix) !== false) {unlink($path . DIRECTORY_SEPARATOR . $file);}}closedir($dh);}}return true;}catch (\Throwable $e){error_log($e->getTraceAsString());return false;}}/**** @param string $str* @return string*/public static function normalizeString ($str = ''){$str = strtolower($str);$str = trim($str);$str = strip_tags($str);$str = preg_replace('/[\r\n\t ]+/', ' ', $str);$str = preg_replace('/[\"\*\/\:\<\>\?\'\|\,]+/', ' ', $str);$str = strtolower($str);$str = html_entity_decode( $str, ENT_QUOTES, "utf-8" );$str = htmlentities($str, ENT_QUOTES, "utf-8");$str = preg_replace("/(&)([a-z])([a-z]+;)/i", '$2', $str);$str = str_replace(' ', '-', $str);$str = rawurlencode($str);$str = str_replace('%', '-', $str);$str = str_replace(['-----','----','---', '--'], '-', $str);return trim(strtolower($str));}/**** @return string*/public static function genUUID(){$data = random_bytes(16);$data[6] = chr(ord($data[6]) & 0x0f | 0x40);$data[8] = chr(ord($data[8]) & 0x3f | 0x80);return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));}/**** @param string $dir*/public static function rmDirRecursive(string $dir){if (is_dir($dir)) {$objects = scandir($dir);foreach ($objects as $object){if ($object != '.' && $object != '..') {if (is_dir($dir . DIRECTORY_SEPARATOR . $object)) {self::rmDirRecursive($dir . DIRECTORY_SEPARATOR . $object);rrmdir($dir . DIRECTORY_SEPARATOR . $object);} else {unlink($dir . DIRECTORY_SEPARATOR . $object);}}}rmdir($dir);}}/**** @param string $dir*/public static function deleteFiles(string $dir){if (is_dir($dir)) {$objects = scandir($dir);foreach ($objects as $object){if ($object != '.' && $object != '..') {if (is_dir($dir . DIRECTORY_SEPARATOR . $object)) {self::rmDirRecursive($dir . DIRECTORY_SEPARATOR . $object);rrmdir($dir . DIRECTORY_SEPARATOR . $object);} else {unlink($dir . DIRECTORY_SEPARATOR . $object);}}}}}/**** @param string $address* @return array*/public static function reverseGeocode(string $address){$array = [];$address = str_replace(" ", "+", $address);$url = "http://maps.google.com/maps/api/geocode/json?address=$address&sensor=false";$ch = curl_init();curl_setopt($ch, CURLOPT_URL, $url);curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);curl_setopt($ch, CURLOPT_PROXYPORT, 3128);curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);$response = curl_exec($ch);curl_close($ch);$json = json_decode($response);//print_r($json);foreach ($json->results as $result) {$address1='';foreach($result->address_components as $addressPart){if((in_array('locality', $addressPart->types)) && (in_array('political', $addressPart->types))) {$city = $addressPart->long_name;}else if((in_array('administrative_area_level_1', $addressPart->types) && (in_array('political', $addressPart->types))) || (in_array('administrative_area_level_2', $addressPart->types) && (in_array('political', $addressPart->types)))){$state = $addressPart->long_name;} else if((in_array('postal_code', $addressPart->types))){$postal_code = $addressPart->long_name;} else if((in_array('country', $addressPart->types)) && (in_array('political', $addressPart->types))) {$country = $addressPart->long_name;} else {$address1 .= $addressPart->long_name.', ';}}if(($city != '') && ($state != '') && ($country != '')) {$address = $city.', '.$state.', '.$country;} else if(($city != '') && ($state != '')) {$address = $city.', '.$state;} else if(($state != '') && ($country != '')) {$address = $state.', '.$country;} else if($country != '') {$address = $country;}$address1=trim($address1, ',');$array['country']=$country;$array['state']=$state;$array['city']=$city;$array['address']=$address1;$array['postal_code']=$postal_code;}$array['status']=$json->status;$array['lat'] = $json->results[0]->geometry->location->lat;$array['long'] = $json->results[0]->geometry->location->lng;return $array;}/**** @param number $number* @param number $significance* @return number|boolean*/public static function ceiling($number, $significance = 1){return ( is_numeric($number) && is_numeric($significance) ) ? (ceil($number / $significance) * $significance) : 0;}}