/** * funtions for app */ use Support\Str; function getSignedVODPath($filePath = '', $cdnResourceUrl = '', $secureToken = '', $expiryTimestamp = '', $userIP = '') { $filePath = str_replace('https://stream.thaibinhtv.vn', '', $filePath); $expiryTimestamp = empty($expiryTimestamp) ? time() + 12 * 60 * 60 : $expiryTimestamp; $secureToken = empty($secureToken) ? 'D7pEHzB173XsFp0l' : $secureToken; $cdnResourceUrl = empty($cdnResourceUrl) ? 'https://1253668792.e.cdneverest.net' : $cdnResourceUrl; // because of hls/dash, anything included after the last slash (e.g. playlist/{chunk}) shouldn't be part of the path string, // for which we generate the secure token. Because of that, everything included after the last slash is stripped. $strippedPath = substr($filePath, 0, strrpos($filePath, '/')); // replace invalid URL query string characters +, =, / with valid characters -, _, ~ $invalidChars = ['+', '/']; $validChars = ['-', '_']; $hashStr = md5("$secureToken$strippedPath$expiryTimestamp$userIP", TRUE); $valid_str = str_replace($invalidChars, $validChars, base64_encode($hashStr)); $hotkey_params = str_replace('=', '', $valid_str); $final_str = $cdnResourceUrl . '/' . $hotkey_params . '/' . $expiryTimestamp . $filePath; // the URL is however, intensionaly returned with the previously stripped parts (eg. playlist/{chunk}..) return $final_str; } function clean_xss_input() { $allinput = request()->all(); if ($allinput) { foreach ($allinput as $key => $value) { request()->merge($key, xss_clean($value)); } } } function validParams($allow_params = []) { $all_inputs = request()->all(); $not_allow_param = 0; if ($all_inputs) { foreach ($all_inputs as $k => $v) { if (!in_array($k, $allow_params)) { $not_allow_param = $k; break; } } } return $not_allow_param; } if (!function_exists('csrf_validate')) { function csrf_validate() { $ajaxRequest = request()->ajax(); $token = $ajaxRequest ? request()->header('X-Csrf-Token') : request()->input('token'); // if (request()->isGet()) { // return true; // } // logger()->log(session()->getToken() .' --- '. $token); if (session()->getToken() != $token) { return false; } return true; } } if (!function_exists('validUrlXss')) { function validUrlXss() { $filename_bad_chars = array( '../', '', '<', '>', '$', '{', '}', '[', ']', ';', '%22', '%3c', // < '%253c', // < '%3e', // > '%0e', // > '%28', // ( '%29', // ) '%2528', // ( '%26', // & '%24', // $ '%3f', // ? '%3b', // ; '%3d', // = ); $url = request()->fullUrl(); $parsed = parse_url($url); $path = $parsed ? $parsed['path'] : ''; $query = $parsed ? $parsed['query'] : ''; $query_arr = explode('=', $query); $query_keys = array_keys($query_arr); $query_vals = array_values($query_arr); if (!valid_domain($url)) { return redirect('error/404'); } if ($path) { if (preg_match('/[^a-zA-Z0-9\/\_\-\.]/', $path)) { return abort('Page not found', 404); } } if ($query) { foreach ($filename_bad_chars as $k => $char) { $query_keys_str = $query_keys ? join("", $query_keys) : $query; $query_vals_str = $query_vals ? join("", $query_vals) : $query; if (substr_count($query_keys_str, stu($char)) || substr_count($query_vals_str, stu($char))) { return abort('Page not found', 404); } } } } } function valid_domain($path = null) { if (!preg_match('/(mediatech\.vn)|(thaibinhtv\.vn)/', $path)) { if (request()->ajax()) { return response()->json(['errCode' => 1, 'errMsg' => 'Access denied']); } else { return abort('Access denied', 403); } } return true; } function valid_referer() { $host = request()->header('host'); $referer = request()->referer(); if ($host != $referer) { if (request()->ajax()) { return response()->json(['errCode' => 1, 'errMsg' => 'Access denied']); } else { return abort('Access denied', 403); } } return true; } /** * chặn truy cập với thông báo */ if (!function_exists('abort')) { function abort($message = '', $code = 200, $response_type = 'text') { $message = is_null($message) ? response()->getContent() : $message; if (request()->ajax()) { response()->json(['errCode' => 0, 'errMsg' => $message]); exit; } else { if (is_null($message)) { response()->send(); exit; } else { $code = (int) $code; if ($response_type == 'text') { if ($code == 200) { response()->setContent($message); } else { response()->error($code, $message); } } else { response()->json(['errCode' => $code, 'errMsg' => $message]); } response()->send(); exit; } } } } function xss_clean($dirty_html = '') { return strip_tags((new \Helpers\Security)->xss_clean($dirty_html)); } function xss_clean_url($path = '') { preg_match('/[\'\"\:\;\<\>]/', $path, $matches); if (!empty($path) && $matches) { return substr($path, stripos($path, $matches[0])); } $path = strip_tags($path); $path = preg_replace('#[^0-9a-zA-Z-_./:?]#', '', $path); return $path; } /** * get value from db or form * @param [type] $default_val [description] * @param [type] $form_field [description] * @return [type] [description] */ function inputVal($data = null, $field = null, $default_value = null) { $value = session()->hasOldInput($field) ? old($field) : ($data && isset($data->$field) ? $data->$field : (is_null($default_value) ? '' : $default_value)); return $value; } function env($key) { if (function_exists('getenv')) { return getenv($key); } else { return $_ENV[$key]; } } function fillquerydata($sql, $data) { $sql = db()->preparePrefix($sql); if ($data) { foreach ($data as $key => $value) { $sql = str_replace(':' . $key, $value, $sql); } } return $sql; } function trunc($str = '', $limit = 100, $last = '...') { $n = mb_strlen($str); if ($n <= $limit) { return $str; } else { return mb_substr($str, 0, mb_strrpos(mb_substr($str, 0, $limit + 10), ' ')) . $last; } } function stats() { if (config()->site->stats_enable) { new \App\Libs\Stats\StatsHit(); } } function encode_unicode_hex($char) { if (empty($char)) { return ''; } else { $char = is_array($char) ? $char[0] : $char; $char = addslashes(trim(json_encode($char), '"')); // $char = addslashes(trim(json_encode($char),'"')); return $char; } } function gen_order_code($number, $prefix = 'ORD') { $str_order = strlen($number) < 6 ? $prefix . '000000' : $prefix . str_repeat('0', strlen($number)); return substr_replace($str_order, $number, strlen($str_order) - strlen($number)); } function csrf_token() { return session()->getToken(); } function session($key = NULL, $value = NULL) { if (empty($key) && empty($value)) { return Session\Session::getInstance(); } else { if (!isset($value)) { $session = Session\Session::getInstance(); return $session->get($key); } else { $session = Session\Session::getInstance(); return $session->put($key, $value); } } } function config() { return Core\Config::getInstance(); } function cookie() { return Helpers\Cookie::getInstance(); } function form() { return Helpers\Form::getInstance(); } function cache() { return Cache\Cache::getInstance(); } function fastcache() { return Helpers\FastCache::getInstance(); } function db() { return Helpers\Database::getInstance(); } function auth() { return Core\Auth::getInstance(); } function security() { return Helpers\Hash::getInstance(); } function validator($data = false, $rules = false, $message = [], $customAttribute = []) { $validator = new Validation\Factory(); return $validator->make($data, $rules, $message, $customAttribute); } function url() { return Helpers\Url::getInstance(); } function app($class = NULL) { if ($class) { $app = Core\Application::getInstance(); return $app->{$class}; } else { return Core\Application::getInstance(); } } function controller() { return Core\Controller::getInstance(); } function model($class = NULL) { if ($class) { return Core\Model::getInstance()->getClass($class); } else { return Core\Model::getInstance(); } } function view() { return Core\View::getInstance(); } function template() { return Core\Template::getInstance(); } function request() { return Http\Request::getInstance(); } function response() { return Http\Response::getInstance(); } // make url wrapper function route($url, $full = false) { $url = app()->route($url); if ($full) { return !substr_count($url, request()->base()) ? request()->base() . $url : $url; } else { return $url; } } //find routers function router() { return Core\Router::getInstance(); } //find application path function assets_path($url = '') { return SITE_PATH . 'assets/' . $url; } //find application path function app_path($url = '') { return APP_PATH . $url; } //find application path function resource_path($url = '') { return RESOURCE_PATH . $url; } //find base path function base_path() { return BASE_PATH; } //find site path function site_path($url = '', $isfull = false) { if (!$isfull) { return base_path() . $url; } else { return SITE_PATH . ltrim($url, '/'); } } function full_site_path($url = '') { return request()->root() . '/' . $url; } function short_site_path($url = '') { return site_path($url, false); } //find template path function template_path($isfull = false) { return site_path(app()->template_path, $isfull); } function site_template_path($isfull = false) { return site_path(app()->site_template_path, $isfull); } function admin_template_path($isfull = false) { return site_path(app()->admin_template_path, $isfull); } //http redirect function redirect($url = NULL, $headers = NULL, $code = NULL) { if (!empty($url)) { $url = (!preg_match('/^https?\:\/\//i', $url)) ? route($url, true) : $url; $redirector = Http\Redirector::getInstance(); return $redirector->to($url); } else { return Http\Redirector::getInstance(); } } function language() { return Core\Language::getInstance(); } function old($name) { if (session()->hasOldInput($name)) { return session()->getOldInput($name); } else { return request()->input($name); } } function html() { return Helpers\Html::getInstance(); } function detect_live_type($live_src = '') { if (preg_match('/(.m3u8)$/i', $live_src)) { $type = 'application/x-mpegURL'; } elseif (preg_match('/^(rtmp)/i', $live_src)) { $type = 'rtmp/mp4'; } elseif (preg_match('/(.wav)$/i', $live_src)) { $type = 'audio/wav'; } elseif (preg_match('/(.ogg)$/i', $live_src)) { $type = 'audio/ogg'; } else { $type = 'audio/mp3'; } if (preg_match('/(.m3u8)$/i', $live_src)) { $type = 'application/x-mpegURL'; } elseif (preg_match('/(.webm)$/i', $live_src)) { $type = 'video/webm'; } elseif (preg_match('/(.ogg)$/i', $live_src)) { $type = 'video/ogg'; } elseif (preg_match('/(.mp4)$/i', $live_src)) { $type = 'video/mp4'; } elseif (preg_match('/^(rtmp)/i', $live_src)) { $type = 'rtmp/mp4'; } elseif (preg_match('/(youtube|youtu.be)/i', $live_src)) { $type = 'video/youtube'; } return $type; } function img_placeholder($size = '') { return !empty($size) ? site_path() . 'thumb/' . $size . '/assets/images/imgstd.jpg' : site_path() . 'assets/images/imgstd.jpg'; } function load_img($src = '', $size = '', $lazyload = false, $lazysrc = NULL, $show_default_path = false) { $site_path = site_path(); $upload_type = config()->site->upload_type; if ($upload_type == 'ftp') { $ftp_config = config()->ftp->{config()->ftp->driver}; $site_path = $show_default_path ? $ftp_config->ftp_path_default : $ftp_config->ftp_path; } else { $path = $src; } if (empty($src) || !preg_match('/\.(jpg|jpeg|png|gif|webp)$/i', $src)) { return !empty($size) ? site_path() . 'thumb/' . $size . '/assets/images/imgstd.jpg' : site_path() . 'assets/images/imgstd.jpg'; } if (preg_match('/^(http)/', $src)) { return $src; } $lazysrc = empty($lazysrc) ? (empty($size) ? site_path() . 'assets/images/imgstd.jpg' : site_path() . 'thumb/' . $size . '/assets/images/imgstd.jpg') : $lazysrc; // check if file not exist then return imgstd image if ($upload_type == 'local') { // decode url string to real chars $src = rawurldecode(parse_url($src, PHP_URL_PATH)); // check exist src if (!empty($src) && preg_match('/\.(jpg|jpeg|png|gif|webp)$/i', $src)) { if (!file_exists($src)) { return !empty($size) ? site_path() . 'thumb/' . $size . '/assets/images/imgstd.jpg' : site_path() . 'assets/images/imgstd.jpg'; } // if empty src or not image } else { return !empty($size) ? site_path() . 'thumb/' . $size . '/assets/images/imgstd.jpg' : site_path() . 'assets/images/imgstd.jpg'; } } if (!empty($size)) { $path = $site_path . 'thumb/' . $size . '/' . $src; } else { $path = $site_path . $src; } if ($lazyload) { $path = $lazysrc . '" data-src="' . $path . '" class="lazy" '; } return $path; } function load_file($src, $fullUrl = false, $show_default_path = false) { $site_path = site_path(); if (config()->site->upload_type == 'ftp') { $ftp_config = config()->ftp->{config()->ftp->driver}; $site_path = $show_default_path ? $ftp_config->ftp_path_default : $ftp_config->ftp_path; return $site_path . $src; } else { if ($src != '' && file_exists(ROOT_DIR . $src)) { return site_path($src, $fullUrl); } else { return site_path('', $fullUrl); } } } function load_img_full_path($src = '', $size = '', $lazyload = false, $lazysrc = NULL, $show_default_path = true) { $img_src = load_img($src, $size, $lazyload, $lazysrc, $show_default_path); if (config()->site->upload_type == 'local') { return full_site_path() . substr($img_src, strlen(site_path())); } else { return $img_src; } } function load_img_resize_lazy($type = 'news', $size = '200x115', $src, $lazyload = false, $show_default_path = NULL) { return load_img('upload/' . $type . '/' . $src, $size, $lazyload, NULL, $show_default_path); } function img_thumb($src, $size = '150x150', $lazyload = false, $lazysrc = null, $show_default_path = false) { return load_img($src, $size, $lazyload, $lazysrc, $show_default_path); } function timeago($ptime, $locale = 'vi') { $etime = time() - $ptime; if ($etime < 1) { return 'vừa xong'; } $a = array( 365 * 24 * 60 * 60 => 'year', 30 * 24 * 60 * 60 => 'month', 24 * 60 * 60 => 'day', 60 * 60 => 'hour', 60 => 'minute', 1 => 'second', ); $a_plural['en'] = [ 'year' => 'years', 'month' => 'months', 'day' => 'days', 'hour' => 'hours', 'minute' => 'minutes', 'second' => 'seconds', ]; $a_plural['vi'] = [ 'year' => 'năm', 'month' => 'tháng', 'day' => 'ngày', 'hour' => 'giờ', 'minute' => 'phút', 'second' => 'giây', ]; $ago = ['en' => 'ago', 'vi' => 'trước']; foreach ($a as $secs => $str) { $d = $etime / $secs; if ($d >= 1) { $r = round($d); return $r . ' ' . ($r >= 1 ? $a_plural[$locale][$str] : $str) . ' ' . $ago[$locale]; } } } function build_filter_query($key, $val) { parse_str($_SERVER['QUERY_STRING'], $params); $params[$key] = $val; return http_build_query($params); } function resize_markup($markup, $dimensions) /* dismentsion as array of attribute*/ { $patterns = array(); $replacements = array(); if (count($dimensions)) { foreach ($dimensions as $k => $v) { $patterns[] = '/' . $k . '="([0-9a-zA-Z]+)"/'; $replacements[] = $k . '="' . $v . '"'; } } return preg_replace($patterns, $replacements, $markup); } /** * Is HTTPS? * * Determines if the application is accessed via an encrypted * (HTTPS) connection. * * @return bool */ function is_https() { if (!empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off') { return TRUE; } elseif (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && strtolower($_SERVER['HTTP_X_FORWARDED_PROTO']) === 'https') { return TRUE; } elseif (!empty($_SERVER['HTTP_FRONT_END_HTTPS']) && strtolower($_SERVER['HTTP_FRONT_END_HTTPS']) !== 'off') { return TRUE; } return FALSE; } /** * Is CLI? * * Test to see if a request was made from the command line. * * @return bool */ function is_cli() { return (PHP_SAPI === 'cli' or defined('STDIN')); } // I18N functions /** * translate and format text * @param string $text * @param string $code * @param array $params * @return string */ function trans($text, $code = NULL, $params = [], $extcode = NULL) { return language()->get($text, $code, $params, $extcode); } /** * Get the formatted and translated message back. * * @param string $message English default message * @param mixed $args * @return string|void */ function __($message, $args = null) { if (!$message) { return ''; } $params = (func_num_args() === 2) ? (array) $args : array_slice(func_get_args(), 1); return language()->translate($message, $params); } /** * Get the formatted and translated message back with Domain. * * @param string $domain * @param string $message * @param mixed $args * @return string|void */ function __d($domain, $message, $args = null) { if (!$message) { return ''; } $params = (func_num_args() === 3) ? (array) $args : array_slice(func_get_args(), 2); return language()->translate($message, $params); } /** * store an message with name to session then show it in view * @param string $name * @param string $message * @return string */ function flash($name = '', $message = '') { return session()->flash($name, $message); } /** * log all error message * @param [type] $error [description] * @return write to log file */ function logger($error = NULL) { if (is_object($error)) { return Helpers\Logger::exceptionHandler($error); } else if (is_string($error)) { return Helpers\Logger::errorMessage($error); } else { return new Helpers\Logger(); } } /** * show trace log php */ function trace($str = NULL, $exit = false) { if ($str) { pr($str); } echo '
'; debug_print_backtrace(); echo ''; ($exit) ? exit : ''; } /** * show pagination in view * @param integer $total Number items * @param integer $perpage Show number item per page * @param string $path Navigate link * @param string $page_query Name of current page * @param string $ext_query Some query extras * @param boolean $showTotal Show total label and dropbox list * @return html */ function pagination($total = 0, $limit = 10, $path = '?', $page_query = 'page', $limit_query = 'limit', $showTotal = false) { return (new Helpers\Paginator($total, $limit, $path, $page_query, $limit_query, $showTotal))->pageLinks(); } /** * Check value to find if it was serialized. * * @param string $data * @param bool $strict * @return bool */ function is_serialized($data, $strict = true) { if (!is_string($data)) { return false; } $data = trim($data); if ('N;' == $data) { return true; } if (strlen($data) < 4) { return false; } if (':' !== $data[1]) { return false; } if ($strict) { $lastc = substr($data, -1); if ((';' !== $lastc) && ('}' !== $lastc)) { return false; } } else { $semicolon = strpos($data, ';'); $brace = strpos($data, '}'); if ((false === $semicolon) && (false === $brace)) { return false; } if ((false !== $semicolon) && ($semicolon < 3)) { return false; } if ((false !== $brace) && ($brace < 4)) { return false; } } $token = $data[0]; switch ($token) { case 's': if ($strict) { if ('"' !== substr($data, -2, 1)) { return false; } } else if (false === strpos($data, '"')) { return false; } case 'a': case 'O': return (bool) preg_match("/^{$token}:[0-9]+:/s", $data); case 'b': case 'i': case 'd': $end = $strict ? '$' : ''; return (bool) preg_match("/^{$token}:[0-9.E-]+;$end/", $data); } return false; } /** * Serialize data, if needed. * * @param mixed $data * @return mixed */ function maybe_serialize($data) { if (is_array($data) || is_object($data)) { return serialize($data); } return $data; } /** * Unserialize value only if it was serialized. * * @param string $original * @return mixed */ function maybe_unserialize($original) { if (\is_serialized($original)) { return @unserialize($original); } return $original; } /** Array helpers. */ /** * Convert object to array recusive */ function obj2array($object) { return json_decode(json_encode($object), true); } /** * Add an element to an array if it doesn't exist. * * @param array $array * @param string $key * @param mixed $value * @return array */ function array_add($array, $key, $value) { if (!isset($array[$key])) { $array[$key] = $value; } return $array; } /** * Add an element to an array if it doesn't exist. * * @param array $array * @param string $key * @param mixed $value * @return array */ function array_remove($array, $key) { if (!isset($array[$key])) { return $array; } foreach ($array as $k => $v) { if ($k == $key) { unset($array); } } return $array; } /** * Build a new array using a callback. * * @param array $array * @param \Closure $callback * @return array */ function array_build($array, Closure $callback) { $results = array(); foreach ($array as $key => $value) { list($innerKey, $innerValue) = call_user_func($callback, $key, $value); $results[$innerKey] = $innerValue; } return $results; } /** * Divide an array into two arrays. One with keys and the other with values. * * @param array $array * @return array */ function array_divide($array) { return array(array_keys($array), array_values($array)); } /** * Flatten a multi-dimensional associative array with dots. * * @param array $array * @param string $prepend * @return array */ function array_dot($array, $prepend = '') { $results = array(); foreach ($array as $key => $value) { if (is_array($value)) { $results = array_merge($results, array_dot($value, $prepend . $key . '.')); } else { $results[$prepend . $key] = $value; } } return $results; } /** * Get all of the given array except for a specified array of items. * * @param array $array * @param array $keys * @return array */ function array_except($array, $keys) { return array_diff_key($array, array_flip((array) $keys)); } /** * Fetch a flattened array of a nested array element. * * @param array $array * @param string $key * @return array */ function array_fetch($array, $key) { foreach (explode('.', $key) as $segment) { $results = array(); foreach ($array as $value) { $value = (array) $value; $results[] = $value[$segment]; } $array = array_values($results); } return array_values($results); } /** * Return the first element in an array passing a given truth test. * * @param array $array * @param Closure $callback * @param mixed $default * @return mixed */ function array_first($array, $callback, $default = null) { foreach ($array as $key => $value) { if (call_user_func($callback, $key, $value)) { return $value; } } return value($default); } /** * Return the last element in an array passing a given truth test. * * @param array $array * @param Closure $callback * @param mixed $default * @return mixed */ function array_last($array, $callback, $default = null) { return array_first(array_reverse($array), $callback, $default); } /** * Flatten a multi-dimensional array into a single level. * * @param array $array * @return array */ function array_flatten($array) { $return = array(); array_walk_recursive($array, function ($x) use (&$return) { $return[] = $x; }); return $return; } /** * Get an item from an array using "dot" notation. * * @param array $array * @param string $key * @param mixed $default * @return mixed */ function array_get($array, $key, $default = null) { if (is_null($key)) { return $array; } if (isset($array[$key])) { return $array[$key]; } foreach (explode('.', $key) as $segment) { if (!is_array($array) || !array_key_exists($segment, $array)) { return $default; } $array = $array[$segment]; } return $array; } /** * Set an array item to a given value using "dot" notation. * * If no key is given to the method, the entire array will be replaced. * * @param array $array * @param string $key * @param mixed $value * @return array */ function array_set(&$array, $key, $value) { if (is_null($key)) { return $array = $value; } $keys = explode('.', $key); while (count($keys) > 1) { $key = array_shift($keys); if (!isset($array[$key]) || !is_array($array[$key])) { $array[$key] = array(); } $array = &$array[$key]; } $array[array_shift($keys)] = $value; return $array; } /** * Get a subset of the items from the given array. * * @param array $array * @param array $keys * @return array */ function array_only($array, $keys) { return array_intersect_key($array, array_flip((array) $keys)); } /** * Remove an array item from a given array using "dot" notation. * * @param array $array * @param string $key * @return void */ function array_forget(&$array, $key) { $keys = explode('.', $key); while (count($keys) > 1) { $key = array_shift($keys); if (!isset($array[$key]) || !is_array($array[$key])) { return; } $array = &$array[$key]; } unset($array[array_shift($keys)]); } /** * Pluck an array of values from an array. * * @param array $array * @param string $value * @param string $key * @return array */ function array_pluck($array, $value, $key = null) { $results = array(); foreach ($array as $item) { $itemValue = is_object($item) ? $item->{$value} : $item[$value]; // If the key is "null", we will just append the value to the array and keep // looping. Otherwise we will key the array using the value of the key we // received from the developer. Then we'll return the final array form. if (is_null($key)) { $results[] = $itemValue; } else { $itemKey = is_object($item) ? $item->{$key} : $item[$key]; $results[$itemKey] = $itemValue; } } return $results; } /** * Get a value from the array, and remove it. * * @param array $array * @param string $key * @param mixed $default * @return mixed */ function array_pull(&$array, $key, $default = null) { $value = array_get($array, $key, $default); array_forget($array, $key); return $value; } /** * Sort the array using the given Closure. * * @param array $array * @param \Closure $callback * @return array */ function array_sort($array, Closure $callback) { return \Support\Collection::make($array)->sortBy($callback)->all(); } /** * Filter the array using the given Closure. * * @param array $array * @param \Closure $callback * @return array */ function array_where($array, Closure $callback) { $filtered = array(); foreach ($array as $key => $value) { if (call_user_func($callback, $key, $value)) { $filtered[$key] = $value; } } return $filtered; } function array_search_value($array, $key, $value = NULL) { if (count($array)) { foreach ($array as $k => $v) { if (is_array($v)) { if (array_key_exists($key, $v) && array_search($value, $v)) { return $array[$k]; } } else { if (array_key_exists($key, $array) && array_search($value, $array)) { return $array[$k]; } } } } return false; } /** * Get the first element of an array. * * @param array $array * @return mixed */ function head($array) { return reset($array); } /** * Get the last element from an array. * * @param array $array * @return mixed */ function last($array) { return end($array); } /** String helpers. */ // /** // * Determine if a given string matches a given pattern. // * // * @param string $pattern // * @param string $value // * @return bool // */ // function str_is($pattern, $value) // { // return Str::is($pattern, $value); // } // /** // * Determine if a given string contains a given substring. // * // * @param string $haystack // * @param string|array $needles // * @return bool // */ // function str_contains($haystack, $needles) // { // return Str::contains($haystack, $needles); // } // /** // * Test for string starts with // * @param $haystack // * @param $needle // * @return bool // */ // function str_starts_with($haystack, $needle) // { // return Str::startsWith($haystack, $needle); // } // /** // * Test for string ends with // * @param $haystack // * @param $needle // * @return bool // */ // function str_ends_with($haystack, $needle) // { // return Str::endsWith($haystack, $needle); // } /** * Generate a random alpha-numeric string. * * @param int $length * @return string * * @throws \RuntimeException */ function str_random($length = 16) { return Str::random($length); } /** * Replace a given value in the string sequentially with an array. * * @param string $search * @param array $replace * @param string $subject * @return string */ function str_replace_array($search, array $replace, $subject) { foreach ($replace as $value) { $subject = preg_replace('/' . $search . '/', $value, $subject, 1); } return $subject; } /** * Escape HTML entities in a string. * * @param string $value * @return string */ function e($value) { return htmlentities($value, ENT_QUOTES); } /** * Class name helper * @param string $className * @return string */ function class_basename($class) { $className = is_object($class) ? get_class($class) : $class; return basename(str_replace('\\', '/', $className)); } /** * Determine if the given object has a toString method. * * @param object $object * @return bool */ function str_object($object) { return (is_object($object) && method_exists($object, '__toString')); } /** * Return the default value of the given value. * * @param mixed $value * @return mixed */ function value($value) { return $value instanceof Closure ? $value() : $value; } /** * Return the given object. * * @param mixed $object * @return mixed */ function with($object) { return $object; } /** Common data lookup methods. */ /** * Get an item from an array or object using "dot" notation. * * @param mixed $target * @param string $key * @param mixed $default * @return mixed */ function data_get($target, $key, $default = null) { if (is_null($key)) { return $target; } foreach (explode('.', $key) as $segment) { if (is_array($target)) { if (!array_key_exists($segment, $target)) { return value($default); } $target = $target[$segment]; } elseif (is_object($target)) { if (!isset($target->{$segment})) { return value($default); } $target = $target->{$segment}; } else { return value($default); } } return $target; } /** * Get an item from an object using "dot" notation. * * @param object $object * @param string $key * @param mixed $default * @return mixed */ function object_get($object, $key, $default = null) { if (is_null($key) || trim($key) == '') { return $object; } foreach (explode('.', $key) as $segment) { if (!is_object($object) || !isset($object->{$segment})) { return value($default); } $object = $object->{$segment}; } return $object; } /** * Convert BR tags to nl * * @param string The string to convert * @return string The converted string */ function br2nl($string) { return preg_replace('/\
"; print_r($x); echo ""; }, func_get_args()); die; } /** * print for all user * @return [type] [description] */ function pra() { array_map(function ($x) { echo "
"; print_r($x); echo ""; }, func_get_args()); } /** * print_r call wrapped in pre tags * * @param string or array $data * @param boolean $exit */ function pr($data) { if (session('username') == 'anhtuan' || $_SERVER["SERVER_NAME"] == "localhost") { array_map(function ($x) { echo "
"; print_r($x); echo ""; }, func_get_args()); } } /** * print_r and die * */ function pd($data) { if (session('username') == 'anhtuan' || $_SERVER["SERVER_NAME"] == "localhost") { array_map(function ($x) { echo "
"; print_r($x); echo ""; }, func_get_args()); die; } } /** * print_r and die * */ function adminLog($data) { if (session('username') == 'anhtuan' || $_SERVER["SERVER_NAME"] == "localhost") { array_map(function ($x) { print_r($x); }, func_get_args()); die; } } /** * var_dump call * * @param string or array $data * @param boolean $exit * */ function vd($data, $exit = false) { if (session('username') == 'anhtuan' || $_SERVER["SERVER_NAME"] == "localhost") { array_map(function ($x) { var_dump($x); }, func_get_args()); if ($exit == true) { exit; } } } /** * strlen call - count the length of the string. * * @param string $data * @return string return the count */ function sl($data) { return strlen($data); } /** * strtoupper - convert string to uppercase. * * @param string $data * @return string */ function stu($data) { return mb_strtoupper($data); } /** * strtolower - convert string to lowercase. * * @param string $data * @return string */ function stl($data) { return mb_strtolower($data); } /** * ucwords - the first letter of each word to be a capital. * * @param string $data * @return string */ function ucw($data) { return ucwords($data); } /** * mb_ucfrist make the first letter to upper * @param string $str * @param string $encoding default utf-8 * */ if (!function_exists('mb_ucfirst')) { function mb_ucfirst($str = '', $encoding = "UTF-8", $lower_str_end = false) { $first_letter = mb_strtoupper(mb_substr($str, 0, 1, $encoding), $encoding); $str_end = ""; if ($lower_str_end) { $str_end = mb_strtolower(mb_substr($str, 1, mb_strlen($str, $encoding), $encoding), $encoding); } else { $str_end = mb_substr($str, 1, mb_strlen($str, $encoding), $encoding); } $str = $first_letter . $str_end; return $str; } } /** * key - this will generate a 32 character key * @return string */ function createKey($length = 32) { return str_random($length); } /** * addhttp - this will ensire $url starts with http * * @param $url string * @param $scheme string * @return string */ function add_http($url, $scheme = 'http://') { return parse_url($url, PHP_URL_SCHEME) === null ? $scheme . $url : $url; } /* * get youtube video ID from URL * * @param string $url * @return string Youtube video id or FALSE if none found. */ function youtube_id_from_url($url) { $pattern = '%^# Match any youtube URL (?:https?://)? # Optional scheme. Either http or https (?:www\.)? # Optional www subdomain (?: # Group host alternatives youtu\.be/ # Either youtu.be, | youtube\.com # or youtube.com (?: # Group path alternatives /embed/ # Either /embed/ | /v/ # or /v/ | /watch\?v= # or /watch\?v= ) # End path alternatives. ) # End host alternatives. ([\w-]{10,12}) # Allow 10-12 for 11 char youtube id. $%x'; $result = preg_match($pattern, $url, $matches); if ($result) { return $matches[1]; } return false; } /* * get youtube video ID from URL * * @param string $url * @return string Youtube video id or FALSE if none found. */ function youtube_image($youtube_link, $type = NULL) { $yt_id = substr_count($youtube_link, 'http') ? youtube_id_from_url($youtube_link) : $youtube_link; if (!$yt_id) { return ''; } switch ($type) { case 'bg_thumb': // Player Background Thumbnail (480x360 pixels) $url = 'https://i1.ytimg.com/vi/' . $yt_id . '/0.jpg'; break; case 'start_thumb': // Start Thumbnail (120x90 pixels) $url = 'https://i1.ytimg.com/vi/' . $yt_id . '/1.jpg'; break; case 'middle_thumb': // Middle Thumbnail (120x90 pixels) $url = 'https://i1.ytimg.com/vi/' . $yt_id . '/2.jpg'; break; case 'end_thumb': // End Thumbnail (120x90 pixels) $url = 'https://i1.ytimg.com/vi/' . $yt_id . '/3.jpg'; break; case 'hight_quality': // High Quality Thumbnail (480x360 pixels) $url = 'https://i1.ytimg.com/vi/' . $yt_id . '/hqdefault.jpg'; break; case 'medium_quality': // Medium Quality Thumbnail (320x180 pixels) $url = 'https://i1.ytimg.com/vi/' . $yt_id . '/mqdefault.jpg'; break; case 'normal_quality': // Normal Quality Thumbnail (120x90 pixels) $url = 'https://i1.ytimg.com/vi/' . $yt_id . '/default.jpg'; break; case 'sd_quality': // Standard Definition Thumbnail (640x480 pixels) $url = 'https://i1.ytimg.com/vi/' . $yt_id . '/sddefault.jpg'; break; case 'hd_quality': // Maximum Resolution Thumbnail (1920x1080 pixels) $url = 'https://i1.ytimg.com/vi/' . $yt_id . '/maxresdefault.jpg'; break; default: // Normal Quality Thumbnail (120x90 pixels) $url = 'https://i1.ytimg.com/vi/' . $yt_id . '/default.jpg'; break; } return $url; } // remove all utf8mb4 chars function clean_non_utf8($text) { $clean_text = ""; // Match Emoticons $regexEmoticons = '/[\x{1F600}-\x{1F64F}]/u'; $clean_text = preg_replace($regexEmoticons, '', $text); // Match Miscellaneous Symbols and Pictographs $regexSymbols = '/[\x{1F300}-\x{1F5FF}]/u'; $clean_text = preg_replace($regexSymbols, '', $clean_text); // Match Transport And Map Symbols $regexTransport = '/[\x{1F680}-\x{1F6FF}]/u'; $clean_text = preg_replace($regexTransport, '', $clean_text); // Match flags (iOS) $regexTransport = '/[\x{1F1E0}-\x{1F1FF}]/u'; $clean_text = preg_replace($regexTransport, '', $clean_text); return $clean_text; } if (!function_exists('blank')) { /** * Determine if the given value is "blank". * * @param mixed $value * @return bool */ function blank($value) { if (is_null($value)) { return true; } if (is_string($value)) { return trim($value) === ''; } if (is_numeric($value) || is_bool($value)) { return false; } if ($value instanceof Countable) { return count($value) === 0; } return empty($value); } } if (!function_exists('class_basename')) { /** * Get the class "basename" of the given object / class. * * @param string|object $class * @return string */ function class_basename($class) { $class = is_object($class) ? get_class($class) : $class; return basename(str_replace('\\', '/', $class)); } } if (!function_exists('class_uses_recursive')) { /** * Returns all traits used by a class, its parent classes and trait of their traits. * * @param object|string $class * @return array */ function class_uses_recursive($class) { if (is_object($class)) { $class = get_class($class); } $results = []; foreach (array_reverse(class_parents($class)) + [$class => $class] as $class) { $results += trait_uses_recursive($class); } return array_unique($results); } } if (!function_exists('collect')) { /** * Create a collection from the given value. * * @param mixed $value * @return \Illuminate\Support\Collection */ function collect($value = null) { return new \Support\Collection($value); } } if (!function_exists('filled')) { /** * Determine if a value is "filled". * * @param mixed $value * @return bool */ function filled($value) { return !blank($value); } } if (!function_exists('head')) { /** * Get the first element of an array. Useful for method chaining. * * @param array $array * @return mixed */ function head($array) { return reset($array); } } if (!function_exists('last')) { /** * Get the last element from an array. * * @param array $array * @return mixed */ function last($array) { return end($array); } } if (!function_exists('object_get')) { /** * Get an item from an object using "dot" notation. * * @param object $object * @param string|null $key * @param mixed $default * @return mixed */ function object_get($object, $key, $default = null) { if (is_null($key) || trim($key) == '') { return $object; } foreach (explode('.', $key) as $segment) { if (!is_object($object) || !isset($object->{$segment})) { return value($default); } $object = $object->{$segment}; } return $object; } } if (!function_exists('optional')) { /** * Provide access to optional objects. * * @param mixed $value * @param callable|null $callback * @return mixed */ function optional($value = null, callable $callback = null) { if (is_null($callback)) { return new Optional($value); } elseif (!is_null($value)) { return $callback($value); } } } if (!function_exists('preg_replace_array')) { /** * Replace a given pattern with each value in the array in sequentially. * * @param string $pattern * @param array $replacements * @param string $subject * @return string */ function preg_replace_array($pattern, array $replacements, $subject) { return preg_replace_callback($pattern, function () use (&$replacements) { foreach ($replacements as $key => $value) { return array_shift($replacements); } }, $subject); } } if (!function_exists('retry')) { /** * Retry an operation a given number of times. * * @param int $times * @param callable $callback * @param int $sleep * @param callable|null $when * @return mixed * * @throws \Exception */ function retry($times, callable $callback, $sleep = 0, $when = null) { $attempts = 0; beginning: $attempts++; $times--; try { return $callback($attempts); } catch (\Exception $e) { if ($times < 1 || ($when && !$when($e))) { throw $e; } if ($sleep) { usleep($sleep * 1000); } goto beginning; } } } if (!function_exists('throw_if')) { /** * Throw the given exception if the given condition is true. * * @param mixed $condition * @param \Throwable|string $exception * @param array ...$parameters * @return mixed * * @throws \Throwable */ function throw_if($condition, $exception, ...$parameters) { if ($condition) { throw (is_string($exception) ? new $exception(...$parameters) : $exception); } return $condition; } } if (!function_exists('throw_unless')) { /** * Throw the given exception unless the given condition is true. * * @param mixed $condition * @param \Throwable|string $exception * @param array ...$parameters * @return mixed * * @throws \Throwable */ function throw_unless($condition, $exception, ...$parameters) { if (!$condition) { throw (is_string($exception) ? new $exception(...$parameters) : $exception); } return $condition; } } if (!function_exists('trait_uses_recursive')) { /** * Returns all traits used by a trait and its traits. * * @param string $trait * @return array */ function trait_uses_recursive($trait) { $traits = class_uses($trait); foreach ($traits as $trait) { $traits += trait_uses_recursive($trait); } return $traits; } } if (!function_exists('transform')) { /** * Transform the given value if it is present. * * @param mixed $value * @param callable $callback * @param mixed $default * @return mixed|null */ function transform($value, callable $callback, $default = null) { if (filled($value)) { return $callback($value); } if (is_callable($default)) { return $default($value); } return $default; } } if (!function_exists('value')) { /** * Return the default value of the given value. * * @param mixed $value * @return mixed */ function value($value) { return $value instanceof \Closure ? $value() : $value; } } if (!function_exists('windows_os')) { /** * Determine whether the current environment is Windows based. * * @return bool */ function windows_os() { return PHP_OS_FAMILY === 'Windows'; } } if (!function_exists('with')) { /** * Return the given value, optionally passed through the given callback. * * @param mixed $value * @param callable|null $callback * @return mixed */ function with($value, callable $callback = null) { return is_null($callback) ? $value : $callback($value); } } function unique_multidim_array($array, $key) { $temp_array = array(); $i = 0; $key_array = array(); foreach ($array as $val) { if (!in_array($val[$key], $key_array)) { $key_array[$i] = $val[$key]; $temp_array[$i] = $val; } $i++; } return $temp_array; }