changed deprecated import() function so the script works with >=PHP8.0

This commit is contained in:
Darko Luketic 2021-11-29 00:16:05 +01:00
parent 08f4d4f856
commit 692f324074
2 changed files with 150 additions and 76 deletions

View File

@ -15,6 +15,10 @@ Open for PRs. Please see the original repository for credits.
== Changelog == == Changelog ==
= 2.8.6 =
* changed deprecated import() function so the script works with >=PHP8.0
= 2.8.5 = = 2.8.5 =
* FIXED: * FIXED:
* Added a bunch of PRs and made it work with latest Wordpress * Added a bunch of PRs and made it work with latest Wordpress

View File

@ -1,7 +1,9 @@
<?php <?php
/* Common utility functions mainly for formatting, parsing etc. */ /* Common utility functions mainly for formatting, parsing etc. */
class CrayonUtil {
class CrayonUtil
{
// Used to detect touchscreen devices // Used to detect touchscreen devices
private static $touchscreen = NULL; private static $touchscreen = NULL;
@ -12,7 +14,8 @@ class CrayonUtil {
r - escape regex chars r - escape regex chars
c - remove comments c - remove comments
s - return as string */ s - return as string */
public static function lines($path, $opts = NULL) { public static function lines($path, $opts = NULL)
{
$path = self::pathf($path); $path = self::pathf($path);
if (($str = self::file($path)) === FALSE) { if (($str = self::file($path)) === FALSE) {
// Log failure, n = no log // Log failure, n = no log
@ -70,14 +73,15 @@ class CrayonUtil {
if ($whitespace) { if ($whitespace) {
$delimiter = CRAYON_NL; $delimiter = CRAYON_NL;
} }
$lines = implode($lines, $delimiter); $lines = implode($delimiter, $lines);
} }
return $lines; return $lines;
} }
// Returns the contents of a file // Returns the contents of a file
public static function file($path) { public static function file($path)
{
if (($str = @file_get_contents($path)) === FALSE) { if (($str = @file_get_contents($path)) === FALSE) {
return FALSE; return FALSE;
} else { } else {
@ -91,7 +95,8 @@ class CrayonUtil {
* @param $src A directory or file * @param $src A directory or file
* @param $dest A directory or zip file. If a zip file is provided it must exist beforehand. * @param $dest A directory or zip file. If a zip file is provided it must exist beforehand.
*/ */
public static function createZip($src, $dest, $removeExistingZip = FALSE) { public static function createZip($src, $dest, $removeExistingZip = FALSE)
{
if ($src == $dest) { if ($src == $dest) {
throw new InvalidArgumentException("Source '$src' and '$dest' cannot be the same"); throw new InvalidArgumentException("Source '$src' and '$dest' cannot be the same");
} }
@ -148,7 +153,8 @@ class CrayonUtil {
* 'file' (optional file path of the attachment) * 'file' (optional file path of the attachment)
* @see http://webcheatsheet.com/php/send_email_text_html_attachment.php * @see http://webcheatsheet.com/php/send_email_text_html_attachment.php
*/ */
public static function emailFile($args) { public static function emailFile($args)
{
$to = self::set_default($args['to']); $to = self::set_default($args['to']);
$from = self::set_default($args['from']); $from = self::set_default($args['from']);
$subject = self::set_default($args['subject'], ''); $subject = self::set_default($args['subject'], '');
@ -226,7 +232,8 @@ EOT;
* ignore: An array of paths to ignore * ignore: An array of paths to ignore
* @return array Files in the directory * @return array Files in the directory
*/ */
public static function getFiles($path, $args = array()) { public static function getFiles($path, $args = array())
{
$hidden = self::set_default($args['hidden'], TRUE); $hidden = self::set_default($args['hidden'], TRUE);
$ignoreRef = self::set_default($args['ignoreRef'], TRUE); $ignoreRef = self::set_default($args['ignoreRef'], TRUE);
$recursive = self::set_default($args['recursive'], FALSE); $recursive = self::set_default($args['recursive'], FALSE);
@ -263,7 +270,8 @@ EOT;
return $result; return $result;
} }
public static function deleteDir($path) { public static function deleteDir($path)
{
if (!is_dir($path)) { if (!is_dir($path)) {
throw new InvalidArgumentException("deleteDir: $path is not a directory"); throw new InvalidArgumentException("deleteDir: $path is not a directory");
} }
@ -281,7 +289,8 @@ EOT;
rmdir($path); rmdir($path);
} }
public static function copyDir($src, $dst, $mkdir = NULL) { public static function copyDir($src, $dst, $mkdir = NULL)
{
// http://stackoverflow.com/questions/2050859 // http://stackoverflow.com/questions/2050859
if (!is_dir($src)) { if (!is_dir($src)) {
throw new InvalidArgumentException("copyDir: $src is not a directory"); throw new InvalidArgumentException("copyDir: $src is not a directory");
@ -305,7 +314,8 @@ EOT;
} }
// Supports arrays in the values // Supports arrays in the values
public static function array_flip($array) { public static function array_flip($array)
{
$result = array(); $result = array();
foreach ($array as $k => $v) { foreach ($array as $k => $v) {
if (is_array($v)) { if (is_array($v)) {
@ -319,7 +329,8 @@ EOT;
return $result; return $result;
} }
private static function _array_flip(&$array, $k, $v) { private static function _array_flip(&$array, $k, $v)
{
if (is_string($v) || is_int($v)) { if (is_string($v) || is_int($v)) {
$array[$v] = $k; $array[$v] = $k;
} else { } else {
@ -328,7 +339,8 @@ EOT;
} }
// Detects if device is touchscreen or mobile // Detects if device is touchscreen or mobile
public static function is_touch() { public static function is_touch()
{
// Only detect once // Only detect once
if (self::$touchscreen !== NULL) { if (self::$touchscreen !== NULL) {
return self::$touchscreen; return self::$touchscreen;
@ -347,7 +359,8 @@ EOT;
} }
// Removes duplicates in array, ensures they are all strings // Removes duplicates in array, ensures they are all strings
public static function array_unique_str($array) { public static function array_unique_str($array)
{
if (!is_array($array) || empty($array)) { if (!is_array($array) || empty($array)) {
return array(); return array();
} }
@ -358,7 +371,8 @@ EOT;
} }
// Same as array_key_exists, but returns the key when exists, else FALSE; // Same as array_key_exists, but returns the key when exists, else FALSE;
public static function array_key_exists($key, $array) { public static function array_key_exists($key, $array)
{
if (!is_array($array) || empty($array) || !is_string($key) || empty($key)) { if (!is_array($array) || empty($array) || !is_string($key) || empty($key)) {
FALSE; FALSE;
} }
@ -368,7 +382,8 @@ EOT;
} }
// Performs explode() on a string with the given delimiter and trims all whitespace // Performs explode() on a string with the given delimiter and trims all whitespace
public static function trim_e($str, $delimiter = ',') { public static function trim_e($str, $delimiter = ',')
{
if (is_string($delimiter)) { if (is_string($delimiter)) {
$str = trim(preg_replace('|\s*(?:' . preg_quote($delimiter) . ')\s*|', $delimiter, $str)); $str = trim(preg_replace('|\s*(?:' . preg_quote($delimiter) . ')\s*|', $delimiter, $str));
return explode($delimiter, $str); return explode($delimiter, $str);
@ -378,7 +393,8 @@ EOT;
/* Creates an array of integers based on a given range string of format "int - int" /* Creates an array of integers based on a given range string of format "int - int"
Eg. range_str('2 - 5'); */ Eg. range_str('2 - 5'); */
public static function range_str($str) { public static function range_str($str)
{
preg_match('#(\d+)\s*-\s*(\d+)#', $str, $matches); preg_match('#(\d+)\s*-\s*(\d+)#', $str, $matches);
if (count($matches) == 3) { if (count($matches) == 3) {
return range($matches[1], $matches[2]); return range($matches[1], $matches[2]);
@ -387,7 +403,8 @@ EOT;
} }
// Creates an array out of a single range string (e.i "x-y") // Creates an array out of a single range string (e.i "x-y")
public static function range_str_single($str) { public static function range_str_single($str)
{
$match = preg_match('#(\d+)(?:\s*-\s*(\d+))?#', $str, $matches); $match = preg_match('#(\d+)(?:\s*-\s*(\d+))?#', $str, $matches);
if ($match > 0) { if ($match > 0) {
if (empty($matches[2])) { if (empty($matches[2])) {
@ -401,7 +418,8 @@ EOT;
} }
// Sets a variable to a string if valid // Sets a variable to a string if valid
public static function str(&$var, $str, $escape = TRUE) { public static function str(&$var, $str, $escape = TRUE)
{
if (is_string($str)) { if (is_string($str)) {
$var = ($escape == TRUE ? self::htmlentities($str) : $str); $var = ($escape == TRUE ? self::htmlentities($str) : $str);
return TRUE; return TRUE;
@ -410,21 +428,25 @@ EOT;
} }
// Converts all special characters to entities // Converts all special characters to entities
public static function htmlentities($str) { public static function htmlentities($str)
{
return htmlentities($str, ENT_COMPAT, 'UTF-8'); return htmlentities($str, ENT_COMPAT, 'UTF-8');
} }
public static function html_entity_decode($str) { public static function html_entity_decode($str)
{
return html_entity_decode($str, ENT_QUOTES, 'UTF-8'); return html_entity_decode($str, ENT_QUOTES, 'UTF-8');
} }
// Converts <, >, & into entities // Converts <, >, & into entities
public static function htmlspecialchars($str) { public static function htmlspecialchars($str)
{
return htmlspecialchars($str, ENT_NOQUOTES, 'UTF-8'); return htmlspecialchars($str, ENT_NOQUOTES, 'UTF-8');
} }
// Sets a variable to an int if valid // Sets a variable to an int if valid
public static function num(&$var, $num) { public static function num(&$var, $num)
{
if (is_numeric($num)) { if (is_numeric($num)) {
$var = intval($num); $var = intval($num);
return TRUE; return TRUE;
@ -433,7 +455,8 @@ EOT;
} }
// Sets a variable to an array if valid // Sets a variable to an array if valid
public static function arr(&$var, $array) { public static function arr(&$var, $array)
{
if (is_array($array)) { if (is_array($array)) {
$var = $array; $var = $array;
return TRUE; return TRUE;
@ -442,26 +465,31 @@ EOT;
} }
// Sets a variable to an array if valid // Sets a variable to an array if valid
public static function set_array($var, $array, $false = FALSE) { public static function set_array($var, $array, $false = FALSE)
{
return isset($array[$var]) ? $array[$var] : $false; return isset($array[$var]) ? $array[$var] : $false;
} }
// Sets a variable to null if not set // Sets a variable to null if not set
public static function set_var(&$var, $false = NULL) { public static function set_var(&$var, $false = NULL)
{
$var = isset($var) ? $var : $false; $var = isset($var) ? $var : $false;
} }
// Sets a variable to null if not set // Sets a variable to null if not set
public static function set_default(&$var, $default = NULL) { public static function set_default(&$var, $default = NULL)
{
return isset($var) ? $var : $default; return isset($var) ? $var : $default;
} }
public static function set_default_null($var, $default = NULL) { public static function set_default_null($var, $default = NULL)
{
return $var !== NULL ? $var : $default; return $var !== NULL ? $var : $default;
} }
// Thanks, http://www.php.net/manual/en/function.str-replace.php#102186 // Thanks, http://www.php.net/manual/en/function.str-replace.php#102186
function str_replace_once($str_pattern, $str_replacement, $string) { function str_replace_once($str_pattern, $str_replacement, $string)
{
if (strpos($string, $str_pattern) !== FALSE) { if (strpos($string, $str_pattern) !== FALSE) {
$occurrence = strpos($string, $str_pattern); $occurrence = strpos($string, $str_pattern);
return substr_replace($string, $str_replacement, strpos($string, $str_pattern), strlen($str_pattern)); return substr_replace($string, $str_replacement, strpos($string, $str_pattern), strlen($str_pattern));
@ -470,7 +498,8 @@ EOT;
} }
// Removes non-numeric chars in string // Removes non-numeric chars in string
public static function clean_int($str, $return_zero = TRUE) { public static function clean_int($str, $return_zero = TRUE)
{
$str = preg_replace('#[^\d]#', '', $str); $str = preg_replace('#[^\d]#', '', $str);
if ($return_zero) { if ($return_zero) {
// If '', then returns 0 // If '', then returns 0
@ -482,38 +511,44 @@ EOT;
} }
// Replaces whitespace with hypthens // Replaces whitespace with hypthens
public static function space_to_hyphen($str) { public static function space_to_hyphen($str)
{
return preg_replace('#\s+#', '-', $str); return preg_replace('#\s+#', '-', $str);
} }
// Replaces hypthens with spaces // Replaces hypthens with spaces
public static function hyphen_to_space($str) { public static function hyphen_to_space($str)
{
return preg_replace('#-#', ' ', $str); return preg_replace('#-#', ' ', $str);
} }
// Remove comments with /* */, // or #, if they occur before any other char on a line // Remove comments with /* */, // or #, if they occur before any other char on a line
public static function clean_comments($str) { public static function clean_comments($str)
{
$comment_pattern = '#(?:^\s*/\*.*?^\s*\*/)|(?:^(?!\s*$)[\s]*(?://|\#)[^\r\n]*)#ms'; $comment_pattern = '#(?:^\s*/\*.*?^\s*\*/)|(?:^(?!\s*$)[\s]*(?://|\#)[^\r\n]*)#ms';
$str = preg_replace($comment_pattern, '', $str); $str = preg_replace($comment_pattern, '', $str);
return $str; return $str;
} }
// Convert to title case and replace underscores with spaces // Convert to title case and replace underscores with spaces
public static function ucwords($str) { public static function ucwords($str)
{
$str = strval($str); $str = strval($str);
$str = str_replace('_', ' ', $str); $str = str_replace('_', ' ', $str);
return ucwords($str); return ucwords($str);
} }
// Escapes regex characters as literals // Escapes regex characters as literals
public static function esc_regex($regex) { public static function esc_regex($regex)
{
return /*htmlspecialchars(*/ return /*htmlspecialchars(*/
preg_quote($regex) /* , ENT_NOQUOTES)*/ preg_quote($regex) /* , ENT_NOQUOTES)*/
; ;
} }
// Escapes hash character as literals // Escapes hash character as literals
public static function esc_hash($regex) { public static function esc_hash($regex)
{
if (is_string($regex)) { if (is_string($regex)) {
return preg_replace('|(?<!\\\\)#|', '\#', $regex); return preg_replace('|(?<!\\\\)#|', '\#', $regex);
} else { } else {
@ -522,18 +557,21 @@ EOT;
} }
// Ensure all parenthesis are atomic to avoid conflicting with element matches // Ensure all parenthesis are atomic to avoid conflicting with element matches
public static function esc_atomic($regex) { public static function esc_atomic($regex)
{
return preg_replace('#(?<!\\\\)\((?!\?)#', '(?:', $regex); return preg_replace('#(?<!\\\\)\((?!\?)#', '(?:', $regex);
} }
// Returns the current HTTP URL // Returns the current HTTP URL
public static function current_url() { public static function current_url()
{
$p = self::isSecure() ? "https://" : "http://"; $p = self::isSecure() ? "https://" : "http://";
return $p . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; return $p . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
} }
// Removes crayon plugin path from absolute path // Removes crayon plugin path from absolute path
public static function path_rel($url) { public static function path_rel($url)
{
if (is_string($url)) { if (is_string($url)) {
return str_replace(CRAYON_ROOT_PATH, '/', $url); return str_replace(CRAYON_ROOT_PATH, '/', $url);
} }
@ -542,13 +580,15 @@ EOT;
// Returns path according to detected use of forwardslash/backslash // Returns path according to detected use of forwardslash/backslash
// Deprecated from regular use after v.1.1.1 // Deprecated from regular use after v.1.1.1
public static function path($path, $detect) { public static function path($path, $detect)
{
$slash = self::detect_slash($detect); $slash = self::detect_slash($detect);
return str_replace(array('\\', '/'), $slash, $path); return str_replace(array('\\', '/'), $slash, $path);
} }
// Detect which kind of slash is being used in a path // Detect which kind of slash is being used in a path
public static function detect_slash($path) { public static function detect_slash($path)
{
if (strpos($path, '\\')) { if (strpos($path, '\\')) {
// Windows // Windows
return $slash = '\\'; return $slash = '\\';
@ -559,35 +599,40 @@ EOT;
} }
// Returns path using forward slashes // Returns path using forward slashes
public static function pathf($url) { public static function pathf($url)
{
return str_replace('\\', '/', trim(strval($url))); return str_replace('\\', '/', trim(strval($url)));
} }
// Returns path using back slashes // Returns path using back slashes
public static function pathb($url) { public static function pathb($url)
{
return str_replace('/', '\\', trim(strval($url))); return str_replace('/', '\\', trim(strval($url)));
} }
// returns 'true' or 'false' depending on whether this PHP file was served over HTTPS // returns 'true' or 'false' depending on whether this PHP file was served over HTTPS
public static function isSecure() { public static function isSecure()
{
// From https://core.trac.wordpress.org/browser/tags/4.0.1/src/wp-includes/functions.php // From https://core.trac.wordpress.org/browser/tags/4.0.1/src/wp-includes/functions.php
if ( isset($_SERVER['HTTPS']) ) { if (isset($_SERVER['HTTPS'])) {
if ( 'on' == strtolower($_SERVER['HTTPS']) ) if ('on' == strtolower($_SERVER['HTTPS']))
return true; return true;
if ( '1' == $_SERVER['HTTPS'] ) if ('1' == $_SERVER['HTTPS'])
return true; return true;
} elseif ( isset($_SERVER['SERVER_PORT']) && ( '443' == $_SERVER['SERVER_PORT'] ) ) { } elseif (isset($_SERVER['SERVER_PORT']) && ('443' == $_SERVER['SERVER_PORT'])) {
return true; return true;
} }
return false; return false;
} }
public static function startsWith($haystack, $needle) { public static function startsWith($haystack, $needle)
{
return substr($haystack, 0, strlen($needle)) === $needle; return substr($haystack, 0, strlen($needle)) === $needle;
} }
// Append either forward slash or backslash based on environment to paths // Append either forward slash or backslash based on environment to paths
public static function path_slash($path) { public static function path_slash($path)
{
$path = self::pathf($path); $path = self::pathf($path);
if (!empty($path) && !preg_match('#\/$#', $path)) { if (!empty($path) && !preg_match('#\/$#', $path)) {
$path .= '/'; $path .= '/';
@ -598,12 +643,14 @@ EOT;
return $path; return $path;
} }
public static function path_slash_remove($path) { public static function path_slash_remove($path)
{
return preg_replace('#\/+$#', '', $path); return preg_replace('#\/+$#', '', $path);
} }
// Append a forward slash to a path if needed // Append a forward slash to a path if needed
public static function url_slash($url) { public static function url_slash($url)
{
$url = self::pathf($url); $url = self::pathf($url);
if (!empty($url) && !preg_match('#\/$#', $url)) { if (!empty($url) && !preg_match('#\/$#', $url)) {
$url .= '/'; $url .= '/';
@ -615,13 +662,15 @@ EOT;
} }
// Removes extension from file path // Removes extension from file path
public static function path_rem_ext($path) { public static function path_rem_ext($path)
{
$path = self::pathf($path); $path = self::pathf($path);
return preg_replace('#\.\w+$#m', '', $path); return preg_replace('#\.\w+$#m', '', $path);
} }
// Shorten a URL into a string of given length, used to identify a URL uniquely // Shorten a URL into a string of given length, used to identify a URL uniquely
public static function shorten_url_to_length($url, $length) { public static function shorten_url_to_length($url, $length)
{
if ($length < 1) { if ($length < 1) {
return ''; return '';
} }
@ -640,16 +689,18 @@ EOT;
} }
// Creates a unique ID from a string // Creates a unique ID from a string
public static function get_var_str() { public static function get_var_str()
{
$get_vars = array(); $get_vars = array();
foreach ($_GET as $get => $val) { foreach ($_GET as $get => $val) {
$get_vars[] = $get . '=' . $val; $get_vars[] = $get . '=' . $val;
} }
return implode($get_vars, '&'); return implode('&', $get_vars);
} }
// Creates a unique ID from a string // Creates a unique ID from a string
public static function str_uid($str) { public static function str_uid($str)
{
$uid = 0; $uid = 0;
for ($i = 1; $i < strlen($str); $i++) { for ($i = 1; $i < strlen($str); $i++) {
$uid += round(ord($str[$i]) * ($i / strlen($str)), 2) * 100; $uid += round(ord($str[$i]) * ($i / strlen($str)), 2) * 100;
@ -658,7 +709,8 @@ EOT;
} }
// Breaks up a version string into parts // Breaks up a version string into parts
public static function version_parts($version) { public static function version_parts($version)
{
preg_match('#[\d+\.]+#msi', $version, $match); preg_match('#[\d+\.]+#msi', $version, $match);
if (count($match[0])) { if (count($match[0])) {
return explode('.', $match[0]); return explode('.', $match[0]);
@ -668,7 +720,8 @@ EOT;
} }
// Compares two version strings lexicographically // Compares two version strings lexicographically
public static function version_compare($a, $b) { public static function version_compare($a, $b)
{
$a_parts = self::version_parts($a); $a_parts = self::version_parts($a);
$b_parts = self::version_parts($b); $b_parts = self::version_parts($b);
return self::array_compare_lexi($a_parts, $b_parts); return self::array_compare_lexi($a_parts, $b_parts);
@ -676,7 +729,8 @@ EOT;
// Compares two arrays lexicographically // Compares two arrays lexicographically
// This could be extended with a compare function argument // This could be extended with a compare function argument
public static function array_compare_lexi($a, $b) { public static function array_compare_lexi($a, $b)
{
$short = count($a) < count($b) ? $a : $b; $short = count($a) < count($b) ? $a : $b;
for ($i = 0; $i < count($short); $i++) { for ($i = 0; $i < count($short); $i++) {
if ($a[$i] > $b[$i]) { if ($a[$i] > $b[$i]) {
@ -689,7 +743,8 @@ EOT;
} }
// strpos with an array of $needles // strpos with an array of $needles
public static function strposa($haystack, $needles, $insensitive = FALSE) { public static function strposa($haystack, $needles, $insensitive = FALSE)
{
if (is_array($needles)) { if (is_array($needles)) {
foreach ($needles as $str) { foreach ($needles as $str) {
if (is_array($str)) { if (is_array($str)) {
@ -708,7 +763,8 @@ EOT;
} }
// tests if $needle is equal to any strings in $haystack // tests if $needle is equal to any strings in $haystack
public static function str_equal_array($needle, $haystack, $case_insensitive = TRUE) { public static function str_equal_array($needle, $haystack, $case_insensitive = TRUE)
{
if (!is_string($needle) || !is_array($haystack)) { if (!is_string($needle) || !is_array($haystack)) {
return FALSE; return FALSE;
} }
@ -730,7 +786,8 @@ EOT;
} }
// Support for singular and plural string variations // Support for singular and plural string variations
public static function spnum($int, $singular, $plural = NULL) { public static function spnum($int, $singular, $plural = NULL)
{
if (!is_int($int) || !is_string($singular)) { if (!is_int($int) || !is_string($singular)) {
$int = intval($int); $int = intval($int);
$singular = strval($singular); $singular = strval($singular);
@ -742,12 +799,14 @@ EOT;
} }
// Turn boolean into Yes/No // Turn boolean into Yes/No
public static function bool_yn($bool) { public static function bool_yn($bool)
{
return $bool ? 'Yes' : 'No'; return $bool ? 'Yes' : 'No';
} }
// String to boolean, default decides what boolean value to return when not found // String to boolean, default decides what boolean value to return when not found
public static function str_to_bool($str, $default = TRUE) { public static function str_to_bool($str, $default = TRUE)
{
$str = self::tlower($str); $str = self::tlower($str);
if ($default === FALSE) { if ($default === FALSE) {
if ($str == 'true' || $str == 'yes' || $str == '1') { if ($str == 'true' || $str == 'yes' || $str == '1') {
@ -764,7 +823,8 @@ EOT;
} }
} }
public static function bool_to_str($bool, $strict = FALSE) { public static function bool_to_str($bool, $strict = FALSE)
{
if ($strict) { if ($strict) {
return $bool === TRUE ? 'true' : 'false'; return $bool === TRUE ? 'true' : 'false';
} else { } else {
@ -772,24 +832,28 @@ EOT;
} }
} }
public static function tlower($str) { public static function tlower($str)
{
return trim(strtolower($str)); return trim(strtolower($str));
} }
// Escapes $ and \ from the replacement to avoid becoming a backreference // Escapes $ and \ from the replacement to avoid becoming a backreference
public static function preg_replace_escape_back($pattern, $replacement, $subject, $limit = -1, &$count = 0) { public static function preg_replace_escape_back($pattern, $replacement, $subject, $limit = -1, &$count = 0)
{
return preg_replace($pattern, self::preg_escape_back($replacement), $subject, $limit, $count); return preg_replace($pattern, self::preg_escape_back($replacement), $subject, $limit, $count);
} }
// Escape backreferences from string for use with regex // Escape backreferences from string for use with regex
public static function preg_escape_back($string) { public static function preg_escape_back($string)
{
// Replace $ with \$ and \ with \\ // Replace $ with \$ and \ with \\
$string = preg_replace('#(\\$|\\\\)#', '\\\\$1', $string); $string = preg_replace('#(\\$|\\\\)#', '\\\\$1', $string);
return $string; return $string;
} }
// Detect if on a Mac or PC // Detect if on a Mac or PC
public static function is_mac($default = FALSE) { public static function is_mac($default = FALSE)
{
$user = $_SERVER['HTTP_USER_AGENT']; $user = $_SERVER['HTTP_USER_AGENT'];
if (stripos($user, 'macintosh') !== FALSE) { if (stripos($user, 'macintosh') !== FALSE) {
return TRUE; return TRUE;
@ -801,7 +865,8 @@ EOT;
} }
// Decodes WP html entities // Decodes WP html entities
public static function html_entity_decode_wp($str) { public static function html_entity_decode_wp($str)
{
if (!is_string($str) || empty($str)) { if (!is_string($str) || empty($str)) {
return $str; return $str;
} }
@ -814,14 +879,16 @@ EOT;
// Constructs an html element // Constructs an html element
// If $content = FALSE, then element is closed // If $content = FALSE, then element is closed
public static function html_element($name, $content = NULL, $attributes = array()) { public static function html_element($name, $content = NULL, $attributes = array())
{
$atts = self::html_attributes($attributes); $atts = self::html_attributes($attributes);
$tag = "<$name $atts"; $tag = "<$name $atts";
$tag .= $content === FALSE ? '/>' : ">$content</$name>"; $tag .= $content === FALSE ? '/>' : ">$content</$name>";
return $tag; return $tag;
} }
public static function html_attributes($attributes, $assign = '=', $quote = '"', $glue = ' ') { public static function html_attributes($attributes, $assign = '=', $quote = '"', $glue = ' ')
{
$atts = ''; $atts = '';
foreach ($attributes as $k => $v) { foreach ($attributes as $k => $v) {
$atts .= $k . $assign . $quote . $v . $quote . $glue; $atts .= $k . $assign . $quote . $v . $quote . $glue;
@ -830,16 +897,18 @@ EOT;
} }
// Strips only the given tags in the given HTML string. // Strips only the given tags in the given HTML string.
public static function strip_tags_blacklist($html, $tags) { public static function strip_tags_blacklist($html, $tags)
{
foreach ($tags as $tag) { foreach ($tags as $tag) {
$regex = '#<\s*\b' . $tag . '\b[^>]*>.*?<\s*/\s*'. $tag . '\b[^>]*>?#msi'; $regex = '#<\s*\b' . $tag . '\b[^>]*>.*?<\s*/\s*' . $tag . '\b[^>]*>?#msi';
$html = preg_replace($regex, '', $html); $html = preg_replace($regex, '', $html);
} }
return $html; return $html;
} }
// Strips the given attributes found in the given HTML string. // Strips the given attributes found in the given HTML string.
public static function strip_attributes($html, $atts) { public static function strip_attributes($html, $atts)
{
foreach ($atts as $att) { foreach ($atts as $att) {
$regex = '#\b' . $att . '\b(\s*=\s*[\'"][^\'"]*[\'"])?(?=[^<]*>)#msi'; $regex = '#\b' . $att . '\b(\s*=\s*[\'"][^\'"]*[\'"])?(?=[^<]*>)#msi';
$html = preg_replace($regex, '', $html); $html = preg_replace($regex, '', $html);
@ -848,7 +917,8 @@ EOT;
} }
// Strips all event attributes on DOM elements (prefixe with "on"). // Strips all event attributes on DOM elements (prefixe with "on").
public static function strip_event_attributes($html) { public static function strip_event_attributes($html)
{
$regex = '#\bon\w+\b(\s*=\s*[\'"][^\'"]*[\'"])?(?=[^<]*>)#msi'; $regex = '#\bon\w+\b(\s*=\s*[\'"][^\'"]*[\'"])?(?=[^<]*>)#msi';
return preg_replace($regex, '', $html); return preg_replace($regex, '', $html);
} }