user_logged_in()) { foreach ($capabilities as $capability) { if (current_user_can($capability)) return $capability; } } return ($default_value !== null ? $default_value : array_shift($capabilities)); } /** * Convert number of seconds to 'X {units}' * * E.g. 123 => '2 minutes' * then you can use this string how you want, for e.g. append ' ago' => '2 minutes ago' * * @param int $seconds * @return string */ function fw_human_time($seconds) { static $translations = null; if ($translations === null) { $translations = array( 'year' => __('year', 'fw'), 'years' => __('years', 'fw'), 'month' => __('month', 'fw'), 'months' => __('months', 'fw'), 'week' => __('week', 'fw'), 'weeks' => __('weeks', 'fw'), 'day' => __('day', 'fw'), 'days' => __('days', 'fw'), 'hour' => __('hour', 'fw'), 'hours' => __('hours', 'fw'), 'minute' => __('minute', 'fw'), 'minutes' => __('minutes', 'fw'), 'second' => __('second', 'fw'), 'seconds' => __('seconds', 'fw'), ); } $tokens = array ( 31536000 => 'year', 2592000 => 'month', 604800 => 'week', 86400 => 'day', 3600 => 'hour', 60 => 'minute', 1 => 'second' ); foreach ($tokens as $unit => $translation_key) { if ($seconds < $unit) continue; $number_of_units = floor($seconds / $unit); return $number_of_units .' '. $translations[ $translation_key . ($number_of_units != 1 ? 's' : '') ]; } } /** * Convert bytes to human readable format * * @param integer $bytes Size in bytes to convert * @param integer $precision * @return string * @since 2.4.17 */ function fw_human_bytes($bytes, $precision = 2) { $kilobyte = 1024; $megabyte = $kilobyte * 1024; $gigabyte = $megabyte * 1024; $terabyte = $gigabyte * 1024; if (($bytes >= 0) && ($bytes < $kilobyte)) { return $bytes . ' B'; } elseif (($bytes >= $kilobyte) && ($bytes < $megabyte)) { return round($bytes / $kilobyte, $precision) . ' KB'; } elseif (($bytes >= $megabyte) && ($bytes < $gigabyte)) { return round($bytes / $megabyte, $precision) . ' MB'; } elseif (($bytes >= $gigabyte) && ($bytes < $terabyte)) { return round($bytes / $gigabyte, $precision) . ' GB'; } elseif ($bytes >= $terabyte) { return round($bytes / $terabyte, $precision) . ' TB'; } else { return $bytes . ' B'; } } function fw_strlen($string) { if (function_exists('mb_strlen')) { return mb_strlen($string, 'UTF-8'); } else { return strlen($string); } } /** * If currently is a Post Edit page display/submit * @return bool */ function fw_is_post_edit() { static $result = null; if ($result === null) { $result = false; if (is_admin()) { if ( empty($_POST) && isset($_GET['action']) && $_GET['action'] === 'edit' && isset($_GET['post']) ) { // Display Edit Post page $result = true; } elseif ( isset($_POST['action']) && $_POST['action'] === 'editpost' && isset($_POST['post_type']) && isset($_POST['post_ID']) && strpos(wp_get_referer(), 'action=edit') !== false ) { // Submit Edit Post page $result = true; } } } return $result; } /** * @param string $dirname 'foo-bar' * @return string 'Foo_Bar' */ function fw_dirname_to_classname($dirname) { $class_name = explode('-', $dirname); $class_name = array_map('ucfirst', $class_name); $class_name = implode('_', $class_name); return $class_name; } /** * This function is a wrapper function that set correct width and height for iframes from wp_oembed_get() function * * @param $url * @param array $args * @return bool|string */ function fw_oembed_get($url, $args = array()) { $html = wp_oembed_get($url, $args); if (!empty($args['width']) and !empty($args['height']) and class_exists('DOMDocument') and !empty($html)) { $dom_element = new DOMDocument(); @$dom_element->loadHTML($html); if ($obj = $dom_element->getElementsByTagName('iframe')->item(0)) { $obj->setAttribute('width', $args['width']); $obj->setAttribute('height', $args['height']); //saveXml instead of SaveHTML for php version compatibility $html = $dom_element->saveXML($obj, LIBXML_NOEMPTYTAG); } } return $html; } /** * @var $length * @return string * * Reference * * Strong cryptography in PHP * http://www.zimuel.it/en/strong-cryptography-in-php/ * > Don't use rand() or mt_rand() */ function fw_secure_rand($length) { if (function_exists('openssl_random_pseudo_bytes')) { $rnd = openssl_random_pseudo_bytes($length, $strong); if ($strong) { return $rnd; } } $sha =''; $rnd =''; if (file_exists('/dev/urandom')) { $fp = fopen('/dev/urandom', 'rb'); if ($fp) { if (function_exists('stream_set_read_buffer')) { stream_set_read_buffer($fp, 0); } $sha = fread($fp, $length); fclose($fp); } } for ($i = 0; $i < $length; $i++) { $sha = hash('sha256', $sha.mt_rand()); $char = mt_rand(0, 62); $rnd .= chr(hexdec($sha[$char].$sha[$char+1])); } return $rnd; } /** * Try to make user friendly title from an id * @param string $id 'hello-world' * @return string 'Hello world' */ function fw_id_to_title($id) { // mb_ucfirst() if (function_exists('mb_strtoupper') && function_exists('mb_substr') && function_exists('mb_strlen')) { $id = mb_strtoupper(mb_substr($id, 0, 1, 'UTF-8'), 'UTF-8') . mb_substr($id, 1, mb_strlen($id, 'UTF-8'), 'UTF-8'); } else { $id = strtoupper(substr($id, 0, 1)) . substr($id, 1, strlen($id)); } return str_replace(array('_', '-'), ' ', $id); } /** * Alias * @param string $extension_name * @return FW_Extension|null */ function fw_ext($extension_name) { return fw()->extensions->get($extension_name); } /* * Return URI without scheme */ function fw_get_url_without_scheme( $url ) { return preg_replace( '/^[^:]+:\/\//', '//', $url ); } /** * Try to find file path by its uri and read the file contents * @param string $file_uri * @return bool|string false or string - the file contents */ function fw_read_file_by_uri($file_uri) { static $base = null; if ($base === null) { $base = array(); $base['dir'] = WP_CONTENT_DIR; $base['uri'] = ltrim(content_url(), '/'); $base['uri_prefix_regex'] = '/^'. preg_quote($base['uri'], '/') .'/'; } $file_rel_path = preg_replace($base['uri_prefix_regex'], '', $file_uri); if ($base['uri'] === $file_rel_path) { // the file is not inside base dir return false; } $file_path = $base['dir'] .'/'. $file_rel_path; if (!file_exists($file_path)) { return false; } return file_get_contents($file_path); } /** * Make stylesheet contents (portable) independent of directory location * For e.g. replace relative paths 'url(img/bg.png)' with full paths 'url(http://site.com/assets/img/bg.png)' * * @param string $href 'http://.../style.css' * @param null|string $contents If not specified, will try to read from $href * @return bool|string false - on failure; string - stylesheet contents */ function fw_make_stylesheet_portable($href, $contents = null) { if (is_null($contents)) { $contents = fw_read_file_by_uri($href); if ($contents === false) { return false; } } $dir_uri = dirname($href); /** * Replace relative 'url(img/bg.png)' * with full 'url(http://site.com/assets/img/bg.png)' * * Do not touch if url starts with: * - 'https://' * - 'http://' * - '/' (also matches '//') * - '#' (for css property: "behavior: url(#behaveBinObject)") * - 'data:' */ $contents = preg_replace( '/url\s*\((?!\s*[\'"]?(?:\/|data\:|\#|(?:https?:)?\/\/))\s*([\'"])?/', 'url($1'. $dir_uri .'/', $contents ); return $contents; } /** * Return all images sizes register by add_image_size() merged with * WordPress default image sizes. * @link https://codex.wordpress.org/Function_Reference/get_intermediate_image_sizes * @param string $size * * @return array|bool */ function fw_get_image_sizes( $size = '' ) { global $_wp_additional_image_sizes; $sizes = array(); $get_intermediate_image_sizes = get_intermediate_image_sizes(); // Create the full array with sizes and crop info foreach( $get_intermediate_image_sizes as $_size ) { if ( in_array( $_size, array( 'thumbnail', 'medium', 'large' ) ) ) { $sizes[ $_size ]['width'] = get_option( $_size . '_size_w' ); $sizes[ $_size ]['height'] = get_option( $_size . '_size_h' ); $sizes[ $_size ]['crop'] = (bool) get_option( $_size . '_crop' ); } elseif ( isset( $_wp_additional_image_sizes[ $_size ] ) ) { $sizes[ $_size ] = array( 'width' => $_wp_additional_image_sizes[ $_size ]['width'], 'height' => $_wp_additional_image_sizes[ $_size ]['height'], 'crop' => $_wp_additional_image_sizes[ $_size ]['crop'] ); } } // Get only 1 size if found if ( $size ) { if( isset( $sizes[ $size ] ) ) { return $sizes[ $size ]; } else { return false; } } return $sizes; } /** * @param string $icon A string that is meant to be an icon (an image, a font icon class, or something else) * @param array Additional attributes * @return string */ function fw_string_to_icon_html($icon, array $attributes = array()) { if ( preg_match('/\.(png|jpg|jpeg|gif|svg|webp)$/', $icon) || preg_match('/^data:image\//', $icon) ) { // http://.../image.png $tag = 'img'; $attr = array( 'src' => $icon, 'alt' => 'icon', ); } elseif (preg_match('/^[a-zA-Z0-9\-_ ]+$/', $icon)) { // 'font-icon font-icon-class' $tag = 'span'; $attr = array( 'class' => trim($icon), ); } else { // can't detect. maybe it's raw html ' $attr_val) { if (isset($attr[$attr_name])) { if ($attr_name === 'class') { $attr[$attr_name] .= ' '. $attr_val; } else { // ignore. do not overwrite already set attributes } } else { $attr[$attr_name] = (string)$attr_val; } } return fw_html_tag($tag, $attr); } /** * @return string|null * @since 2.4.10 */ function fw_get_json_last_error_message() { switch (function_exists('json_last_error') ? json_last_error() : -1) { case JSON_ERROR_NONE: return null; // __('No errors', 'fw'); break; case JSON_ERROR_DEPTH: return __('Maximum stack depth exceeded', 'fw'); break; case JSON_ERROR_STATE_MISMATCH: return __('Underflow or the modes mismatch', 'fw'); break; case JSON_ERROR_CTRL_CHAR: return __('Unexpected control character found', 'fw'); break; case JSON_ERROR_SYNTAX: return __('Syntax error, malformed JSON', 'fw'); break; case JSON_ERROR_UTF8: return __('Malformed UTF-8 characters, possibly incorrectly encoded', 'fw'); break; default: return __('Unknown error', 'fw'); break; } } /** * Return mime_types by file extension ex : input : array( 'png', 'jpg', 'jpeg' ) => output : array( 'image/jpeg' ). * * @param array $type * * @return array */ function fw_get_mime_type_by_ext( $type = array() ) { $result = array(); foreach ( wp_get_mime_types() as $key => $mime_type ) { $types = explode( '|', $key ); foreach ( $type as $item ) { if ( in_array( $item, $types ) && ! in_array( $mime_type, $result ) ) { $result[] = $mime_type; } } } return $result; } /** * Return types from file extensions ex : input array( 'png', 'jpg', 'zip' ) => output : array( 'image', 'archive' ). * * @see wp_ext2type() function. * * @param array $ext_array * * @return array */ function fw_multi_ext2type( $ext_array = array() ) { $result = array(); foreach ( $ext_array as $ext ) { if ( ! in_array( $type = wp_ext2type( $ext ), $result ) ) { $result[] = $type; } } return $result; } if ( ! function_exists( 'fw_resize' ) ) { function fw_resize( $url, $width = false, $height = false, $crop = false ) { $fw_resize = FW_Resize::getInstance(); $response = $fw_resize->process( $url, $width, $height, $crop ); return ( ! is_wp_error( $response ) && ! empty( $response['src'] ) ) ? $response['src'] : $url; } } /** * fw_get_path_url( dirname(__FILE__) .'/test.css' ) --> http://site.url/path/to/test.css * @param string $path * @return string|null * @since 2.6.11 */ function fw_get_path_url($path) { try { $paths_to_urls = FW_Cache::get($cache_key = 'fw:paths_to_urls'); } catch (FW_Cache_Not_Found_Exception $e) { $wp_upload_dir = wp_upload_dir(); $paths_to_urls = array( fw_fix_path(WP_PLUGIN_DIR) => plugins_url(), fw_fix_path(get_theme_root()) => get_theme_root_uri(), fw_fix_path($wp_upload_dir['basedir']) => $wp_upload_dir['baseurl'], ); if (is_multisite() && WPMU_PLUGIN_DIR) { $paths_to_urls[ fw_fix_path(WPMU_PLUGIN_DIR) ] = WPMU_PLUGIN_URL; } FW_Cache::set($cache_key, $paths_to_urls); } $path = fw_fix_path($path); foreach ($paths_to_urls as $_path => $_url) { if (preg_match($regex = '/^'. preg_quote($_path, '/') .'($|\/)/', $path)) { return $_url .'/'. preg_replace($regex, '', $path); } } return null; }