# final class \Smart
{ } ::

Class: Smart (Base Functions) - provides the base methods for an easy and secure development with Smart.Framework and PHP.

- Language: PHP
- Located at: lib/framework/lib_smart.php
- Package: @Core
- Namespace: \
- Class Name: Smart
- Version: v.20241123
- Depends: extensions: PHP JSON ; classes: SmartUnicode, SmartFrameworkSecurity, SmartEnvironment ; constants: SMART_FRAMEWORK_CHARSET ; optional-constants: SMART_FRAMEWORK_SECURITY_KEY, SMART_SOFTWARE_NAMESPACE, SMART_FRAMEWORK_NETSERVER_ID, SMART_FRAMEWORK_INFO_LOG
- Hints: It is recommended to use the methods in this class instead of PHP native methods whenever is possible because this class will offer Long Term Support and the methods will be supported even if the behind PHP methods can change over time, so the code would be easier to maintain.
- Usage: static object: Class::method() - This class provides only STATIC methods

## class Methods

public static function is_nscalar ( MIXED $val ) {} :: BOOL
@return: {BOOL} FALSE if array, object or resource ; TRUE for the rest
@param: {MIXED} $val: The value to be tested
Test if a variable value is Scalar or Null
public static function is_arr_or_nscalar ( MIXED $val ) {} :: BOOL
@return: {BOOL} FALSE if object or resource ; TRUE for the rest
@param: {MIXED} $val: The value to be tested
Test if a variable value is Array or Scalar or Null
public static function get_from_config ( string $param, string $type = "" ) {} :: MIXED
@return: {MIXED} The value for the selected parameter. If the Config parameter does not exists, will return an empty string.
@param: {STRING} $param: The selected configuration parameter. Example: 'app.info-url' will get value (STRING) from $configs['app']['info-url'] ; 'app' will get the value (ARRAY) from $configs['app']
@param: {ENUM} $type: The type to pre-format the value: 'array', 'string', 'boolean', 'integer', 'numeric' OR '' to leave the value as is (raw)
Get the value for a Config parameter from the app $configs array.
public static function fix_path_separator ( string $y_path, bool $y_force = false ) {} :: STRING
@return: {STRING} The fixed path name
@param: {STRING} $y_path: The path name to fix
Fix for Directory Separator if on Windows
public static function real_path ( string $y_path ) {} :: STRING
@return: {STRING} The real path
@param: {STRING} $y_path: The path name from to extract realpath()
Return the FIXED realpath() as absolute path, also with fix on Windows
This should be mostly used for existing paths. If path does not exists will return the same path as passed argument.
It does not support passing empty paths to avoid security issues like rtrim(Smart::real_path(''),'/').'/' which will point to the root folder of the filesystem.
public static function dir_name ( string $y_path ) {} :: STRING
@return: {STRING} The dirname or . or empty string
@param: {STRING} $y_path: The path name from to extract dirname()
Return the FIXED dirname(), safe on Linux and Unix and with safety fix on Windows
public static function base_name ( string $y_path, string $y_suffix = "" ) {} :: STRING
@return: {STRING} The basename
@param: {STRING} $y_path: The path name from to extract basename()
@param: {STRING} $y_suffix: If the name component ends in suffix this will also be cut off
Return the FIXED basename(), in a safe way
The directory separator character is the forward slash (/), except Windows where both slash (/) and backslash (\) are considered
public static function path_info ( string $y_path ) {} :: ARRAY
@return: {ARRAY} The pathinfo array
@param: {STRING} $y_path: The path to process as pathinfo()
Return the FIXED pathinfo(), also with fix on Windows
public static function str_replace_first ( string $search, string $replace, string $str ) {} :: STRING
@return: {STRING} This function returns a string with the replaced value only on first occurence if search value is found
@param: {STRING} $search: The value being searched for, otherwise known as the needle
@param: {STRING} $replace: The replacement value that replaces found search value
@param: {STRING} $str: The string being searched and replaced on, otherwise known as the haystack
Str Replace, Only First Occurence
public static function str_replace_last ( string $search, string $replace, string $str ) {} :: STRING
@return: {STRING} This function returns a string with the replaced value only on last occurence if search value is found
@param: {STRING} $search: The value being searched for, otherwise known as the needle
@param: {STRING} $replace: The replacement value that replaces found search value
@param: {STRING} $str: The string being searched and replaced on, otherwise known as the haystack
Str Replace, Only Last Occurence
public static function url_parse ( string $y_url, bool $y_skiport = false ) {} :: ARRAY
@return: {ARRAY} The separed URL (associative array) as: protocol, server, port, path, scriptname
@param: {STRING} $y_url: The URL to be parsed
@param: {BOOL} $y_skiport: If set to TRUE will skip the port if standard (empty: 80 or 443) ; Default is FALSE
Safe Parse URL :: a better replacement for parse_url()
public static function url_parse_query ( string $y_query_url ) {} :: ARRAY
@return: {ARRAY} The array with all parsed values
@param: {STRING} $y_query_url: The URL Query to be parsed ; Ex: first=value&arr[]=foo+bar&arr[]=baz
Safe Parse URL Query :: a better replacement for parse_str()
public static function url_build_query ( array $y_params, bool $y_allow_late_binding_params ) {} :: STRING
@return: {STRING} The prepared URL in the standard RFC3986 format (all values are escaped using rawurlencode() to be Unicode full compliant
@param: {ARRAY} $y_params: Associative array as [param1 => value1, Param2 => Value2]
@param: {BOOLEAN} $y_allow_late_binding_params: Allow late binding params ex: a={{{param}}}&b=true
Build an URL Query (Build a standard RFC3986 URL from an array of parameters) as: a=b&param1=value1&param2=value2&c[0]=a&c[1]=x&d[a]=15&d[b]=z
public static function url_remove_params ( string $y_url, array $y_params, bool $y_allow_late_binding_params = true ) {} :: STRING
@return: {STRING} The prepared URL in the standard RFC3986 format (all values are escaped using rawurlencode() to be Unicode full compliant
@param: {STRING} $y_url: The base URL like: script.php or script.php?a=b or empty
@param: {ARRAY} $y_params: Non-Associative array as [param1, Param2]
@param: {BOOLEAN} $y_allow_late_binding_params: Allow late binding params in URL query (when re-parsing) ex: a={{{param}}}&b=true
Remove URL Params (Build a standard RFC3986 URL from script and parameters) as: script.xyz?a=b&param1=value1&param2=value2&param3={{{late-binding}}}
It may allow or not late binding params in url (when re-parsing url query) such as 'param3={{{late-binding}}}'
public static function url_add_params ( string $y_url, array $y_params, bool $y_allow_late_binding_params = true ) {} :: STRING
@return: {STRING} The prepared URL in the standard RFC3986 format (all values are escaped using rawurlencode() to be Unicode full compliant
@param: {STRING} $y_url: The base URL like: script.php or script.php?a=b or empty
@param: {ARRAY} $y_params: Associative array as [param1 => value1, Param2 => Value2, param3 => {{{late-binding}}}]
@param: {BOOLEAN} $y_allow_late_binding_params: Allow late binding params ex: a={{{param}}}&b=true
Add URL Params (Build a standard RFC3986 URL from script and parameters) as: script.xyz?a=b&param1=value1&param2=value2&param3={{{late-binding}}}
It may allow or not late binding params such as 'param3' => '{{{late-binding}}}'
public static function url_add_suffix ( string $y_url, string $y_suffix ) {} :: STRING
@return: {STRING} The prepared URL in the standard RFC3986 format (all values are escaped using rawurlencode() to be Unicode full compliant
@param: {STRING} $y_url: The base URL to use as prefix like: script.php or script.php?a=b&c=d or empty
@param: {STRING} $y_suffix: A RFC3986 URL segment like: a=b or E=%20d (without ? or not starting with & as they will be detected if need append ? or &; variable values must be encoded using rawurlencode() RFC3986)
Add URL Suffix (to a standard RFC3986 URL) as: script.php?a=b&C=D&e=%20d
public static function url_add_anchor ( string $y_url, string $y_anchor ) {} :: STRING
@return: {STRING} The prepared URL as script.php?a=b&c=d&e=%20d#myAnchor
@param: {STRING} $y_url: The base URL to use as prefix like: script.php or script.php?a=b&c=d or empty
@param: {STRING} $y_anchor: A RFC3986 URL anchor like: myAnchor
Add URL Anchor (to a standard RFC3986 URL) as: script.php?a=b&C=D&e=%20d
public static function escape_url ( string $y_string ) {} :: STRING
@return: {STRING} The escaped URL variable using the RFC3986 standard format (this variable can be appended to URL, by example: ?variable={escaped-value-returned-by-this-method}
@param: {STRING} $y_string: The variable value to be escaped
Safe escape URL Variable (using RFC3986 standards to be full Unicode compliant)
This is a shortcut to the rawurlencode() to provide a standard into Smart.Framework
public static function escape_html ( string $y_string ) {} :: STRING
@return: {STRING} The escaped string using htmlspecialchars() HTML standards with Unicode-Safe control
@param: {STRING} $y_string: The string to be escaped
Safe escape strings to be injected in HTML code
This is a shortcut to the htmlspecialchars() for HTML mode, to avoid use long options each time and provide a standard into Smart.Framework
public static function escape_xml ( string $y_string ) {} :: STRING
@return: {STRING} The escaped string using htmlspecialchars() XML standards with Unicode-Safe control
@param: {STRING} $y_string: The string to be escaped
Safe escape strings to be injected in XML code
This is a shortcut to the htmlspecialchars() for XML mode, to avoid use long options each time and provide a standard into Smart.Framework
public static function escape_css ( string $y_string ) {} :: STRING
@return: {STRING} The escaped string using the WD-CSS21-20060411 standard
@param: {STRING} $y_string: The string to be escaped
Safe escape strings to be injected in CSS code
public static function escape_js ( string $str ) {} :: STRING
@return: {STRING} The escaped string using a json_encode() standard to be injected between single quotes '' or double quotes ""
@param: {STRING} $str: The string to be escaped
Safe escape strings to be injected in Javascript code as strings
public static function json_encode ( MIXED $data, bool $prettyprint = false, bool $unescaped_unicode = true, bool $htmlsafe = true, int $depth = 512 ) {} :: STRING
@return: {STRING} The JSON encoded string
@param: {MIXED} $data: The variable to be encoded (mixed): numeric, string, array
@param: {BOOLEAN} $prettyprint: *Optional* Default to FALSE ; If TRUE will format the json as pretty-print (takes much more space, but sometimes make sense ...)
@param: {BOOLEAN} $unescaped_unicode: *Optional* Default to TRUE ; If FALSE will escape unicode characters
@param: {BOOLEAN} $htmlsafe: *Optional* Default to TRUE ; If FALSE the JSON will not be HTML-Safe as it will not escape: < > ' " &
@param: {INTEGER+} $depth: *Optional* Default to 512 ; the maximum depth ; must be greater than zero and no more than 1024 (to keep memory footprint low) !
JSON Encode PHP variables to a JSON string
public static function json_decode ( string $json, bool $return_array = true, int $depth = 512 ) {} :: MIXED
@return: {MIXED} The PHP native Variable: NULL ; INT ; NUMERIC ; STRING ; ARRAY
@param: {STRING} $json: The JSON string
@param: {BOOLEAN} $return_array: *Optional* Default to FALSE ; When TRUE, returned objects will be converted into associative arrays (default to TRUE)
@param: {INTEGER+} $depth: *Optional* Default to 512 ; the maximum depth ; must be greater than zero and no more than 1024 (to keep memory footprint low) !
Decode JSON strings to PHP native variable(s)
public static function seryalize ( MIXED $data ) {} :: STRING
@return: {STRING} The JSON encoded string
@param: {MIXED} $data: The variable to be encoded: numeric, string, array
Serialize PHP variables to a JSON string
This is a safe replacement for PHP serialize() which can break the security if contain unsafe Objects
public static function unseryalize ( string $y_json ) {} :: MIXED
@return: {MIXED} The PHP native Variable
@param: {STRING} $y_json: The JSON string
Unserialize JSON data to PHP native variable(s)
This is a safe replacement for PHP unserialize() which can break the security if contain unsafe Objects
public static function check_int_number_overflow ( $y_number ) {} :: BOOL
@return: {BOOLEAN} TRUE if overflows the max safe integer ; FALSE if is OK (not overflow maximum)
Check if an integer number overflows the minimum or maximum safe int
All numbers over this must use special operators from BCMath to avoid floating point precision issues
On 32-bit platforms the INTEGER is between -2147483648 to 2147483647
On 64-bit platforms the INTEGER is between -9223372036854775808 to 9223372036854775807
public static function check_dec_number_overflow ( $y_number ) {} :: BOOL
@return: {BOOLEAN} TRUE if overflows the max safe decimal ; FALSE if is OK (not overflow maximum)
Check if a decimal number overflows the minimum or maximum safe decimal as precision = 14 (PHP default)
Thus decimal numbers must be between -999999999999.9900 and 999999999999.9900
All numbers over this must use special operators from BCMath to avoid floating point precision issues
This is more intended for decimal numbers like financial operations where the significant decimal digits are important
public static function format_number_float ( NUMERIC $y_number, string $y_signed = null ) {} :: FLOAT
@return: {FLOAT} An float number
@param: {NUMERIC} $y_number: A numeric value
@param: {ENUM} $y_signed: Default to '' ; If set to '+' will return (enforce) an UNSIGNED/POSITIVE Number ; If set to '-' will return (enforce) an NEGATIVE Number ; Otherwise if set to NULL or '' will return just a regular SIGNED Number wich can be negative or positive
Format a number as FLOAT
public static function format_number_int ( NUMERIC $y_number, string $y_signed = null ) {} :: INT
@return: {INTEGER} An integer number
@param: {NUMERIC} $y_number: A numeric value
@param: {ENUM} $y_signed: Default to '' ; If set to '+' will return (enforce) an UNSIGNED/POSITIVE Number ; If set to '-' will return (enforce) an NEGATIVE Number ; Otherwise if set to NULL or '' will return just a regular SIGNED Number wich can be negative or positive
Format a number as INTEGER
On 64-bit platforms the INTEGER is between -9223372036854775808 to 9223372036854775807
public static function format_number_dec ( NUMERIC $y_number, INTEGER+ $y_decimals = 2, string $y_sep_decimals = ".", string $y_sep_thousands = "" ) {} :: STRING
@return: {DECIMAL} A decimal number as string
@param: {NUMERIC} $y_number: A numeric value
@param: {INTEGER+} $y_decimals: The number of decimal to use (safe value is between 1..13, keeping in mind the 14 max precision) ; Default is 2
@param: {STRING} $y_sep_decimals: The decimal separator symbol as: . or , (default is .)
@param: {STRING} $y_sep_thousands: The thousand separator symbol as: , or . (default is [none])
Format a number as DECIMAL (NOTICE: The maximum PHP.INI precision is 14, includding decimals).
Because of the precision, it supports values between -999999999999.9900 and 999999999999.9900 ; If a value overflows limits will return -limit / +limit depends if value is negative or positive
This is a better replacement for the PHP's number_format() which throws a warning if first argument passed is a string since PHP 5.3
public static function array_size ( ARRAY/MIXED $y_arr ) {} :: INT
@return: {INTEGER} The array COUNT of elements, or zero if array is empty or non-array is provided
@param: {ARRAY/MIXED} $y_arr: The array to count elements on ; can be a mixed variable ; if non-array will return zero
Safe array count(), for safety, with array type check ; this should be used instead of count() because count(string) returns a non-zero value and can confuse if a string is passed to count instead of an array
public static function array_sort ( array $y_arr, string $y_mode ) {} :: ARRAY
@return: {ARRAY} The sorted array
@param: {ARRAY} $y_arr: The array to be sorted by a criteria (type, see below)
@param: {ENUM} $y_mode: The sort type: natsort, sort, rsort, asort, arsort, ksort, krsort
Easy sort for NON-Associative arrays ...
public static function array_shuffle ( array $y_arr ) {} :: ARRAY
@return: {ARRAY} The sorted array
@param: {ARRAY} $y_arr: The array to be sorted by a criteria (type, see below)
Shuffle for NON-Associative arrays ...
public static function array_get_by_key_path ( array $y_arr, string $y_key_path, string $y_path_separator ) {} :: MIXED
@return: {MIXED} The value from the specified array by the specific key path or NULL if the value does not exists
@param: {ARRAY} $y_arr: The input array
@param: {STRING} $y_key_path: The composed key path by levels (Ex: key1.key2) :: case-sensitive
@param: {STRING} $y_path_separator: The key path separator (Example: .)
Array Get (value) By Key Path (case sensitive)
public static function array_test_key_by_path_exists ( array $y_arr, string $y_key_path, string $y_path_separator ) {} :: BOOL
@return: {BOOL} TRUE if Key Exist / FALSE if NOT
@param: {ARRAY} $y_arr: The input array
@param: {STRING} $y_key_path: The composed key path by levels (Ex: key1.key2) :: case-sensitive
@param: {STRING} $y_path_separator: The key path separator (Example: .)
Array Test if Key Exist By (Key) Path (case sensitive)
public static function array_change_key_case_recursive ( array $y_arr, string $y_mode ) {} :: ARRAY
@return: {ARRAY} The modified array
@param: {ARRAY} $y_arr: The input array
@param: {ENUM} $y_mode: Change Mode: LOWER | UPPER
Array Recursive Change Key Case
public static function array_init_keys ( ARRAY/MIXED $y_arr, LIST/ARRAY $y_keys ) {} :: ARRAY
@return: {ARRAY} The modified array
@param: {ARRAY/MIXED} $y_arr: The input array
@param: {LIST/ARRAY} $y_keys: The array keys to initialize: will add these keys to the array assigned with a NULL value only if the key does not exists ; the existing keys will be preserved with their existing values ; must be a non-associative array, as: [ 'key1', 'key2', '', ...] ; a key can be also an empty string
Array Initialize Keys
public static function array_type_test ( ARRAY $y_arr ) {} :: INT
@return: {INT/ENUM} The array type as: 0 = not an array ; 1 = non-associative (sequential) array or empty array ; 2 = associative array or non-sequential, must be non-empty
@param: {ARRAY} $y_arr: The array to test
Test if the Array Type for being associative or non-associative sequential (0..n)
public static function array_diff_assoc_recursive ( array $array1, array $array2 ) {} :: ARRAY
@return: {ARRAY}
@param: {ARRAY} $array1
@param: {ARRAY} $array2
Array recursive Diff (Dual-Way, from Left to Right and from Right to Left)
public static function array_diff_assoc_oneway_recursive ( array $array1, array $array2 ) {} :: ARRAY
@return: {ARRAY}
@param: {ARRAY} $array1
@param: {ARRAY} $array2
Array recursive Diff (One Way Only, from Left to Right)
public static function text_cut_by_limit ( string $ytxt, int $ylen, bool $y_cut_words = true, string $y_suffix = "..." ) {} :: STRING
@return: {STRING} The processed string (text)
@param: {STRING} $ytxt: The text string to be processed
@param: {STRING} $ylen: The fixed length of the string
@param: {BOOLEAN} $y_cut_words: *Optional* Default TRUE ; if TRUE, will CUT last word to provide a fixed length ; if FALSE will eliminate unterminate last word ; default is TRUE
@param: {ENUM} $y_suffix: *Optional* Default '...' ; Can be '' or '[...a cutoff-message...]'
Cut a text by a fixed length, if longer than allowed length.
If cut words option is FALSE it may make the string shorted by rolling back until the last space and cutting off the last partial word.
The default cut suffix is (...) but can be disabled using the last parameter.
public static function nl_2_br ( string $y_code, bool $y_trim = true ) {} :: STRING
@return: {STRING} The formatted string
@param: {STRING} $y_code: The string to apply nl2br()
Easy HTML5 compliant nl2br() ; Will replace new lines (\n) with HTML5 <br> instead of XHTML <br />
public static function decode_xml_entities ( string $str ) {} :: STRING
@return: {STRING} The processed Code
@param: {STRING} $str: The code to be processed
Decode XML Entities
public static function decode_html_entities ( string $str ) {} :: STRING
@return: {STRING} The processed Code
@param: {STRING} $str: The code to be processed
Decode HTML Entities
public static function stripTags ( string $yhtmlcode, bool $ynewline = true, bool $ynormalize = true ) {} :: STRING
@return: {STRING} The processed HTML Code
@param: {ARRAY} $yhtmlcode: HTML Code to be stripped of tags
@param: {BOOL} $y_mode: Default is TRUE to convert <br> to new lines \n, otherwise (if FALSE) will convert <br> to spaces
@param: {BOOL} $ynormalize: Default is TRUE to normalize the code as text, otherwise (if FALSE) will do not use extra normalize feature so the code may be re-used for re-encoding as html (ex: extract markdown) ...
Enhanced strip_tags() :: will revert also special entities like nbsp; and more
public static function safe_pathname ( string $y_path, string $ysupresschar = "" ) {} :: STRING
@return: {STRING} The safe path ; if invalid will return empty value
@param: {STRING} $y_path: Path to be processed
@param: {STRING} $ysupresschar: The suppression character to replace weird characters ; optional ; default is ''
Create a Safe Path Name to be used to process dynamic build paths to avoid weird path character injections
This should be used for relative or absolute path to files or dirs
It should allow also both: absolute and relative paths, thus if absolute path should be tested later
NOTICE: It may return an empty string if all characters in the path are invalid or invalid path sequences detected, so if empty path name must be tested later
ALLOWED CHARS: [a-zA-Z0-9] _ - . @ # /
public static function safe_filename ( string $y_fname, string $ysupresschar = "" ) {} :: STRING
@return: {STRING} The safe file or dir name ; if invalid will return empty value
@param: {STRING} $y_fname: File Name or Dir Name to be processed
@param: {STRING} $ysupresschar: The suppression character to replace weird characters ; optional ; default is ''
Create a Safe File Name to be used to process dynamic build file names or dir names to avoid weird path character injections
To should be used only for file or dir names (not paths)
NOTICE: DO NOT USE for full paths or full dir paths because will break them, as the / character is supressed
NOTICE: It may return an empty string if all characters in the file/dir name are invalid or invalid path sequences detected, so if empty file/dir name must be tested later
ALLOWED CHARS: [a-zA-Z0-9] _ - . @ #
public static function safe_validname ( string $y_name, string $ysupresschar = "", bool $y_allow_upper = false ) {} :: STRING
@return: {STRING} The safe name ; if invalid should return empty value
@param: {STRING} $y_name: Name to be processed
@param: {STRING} $ysupresschar: The suppression character to replace weird characters ; optional ; default is ''
@param: {BOOL} $y_allow_upper: Allow UpperCase ; *Optional* ; Default is FALSE
Create a (RFC, ISO) Safe compliant User Name, Domain Name or Email Address
NOTICE: It may return an empty string if all characters in the given name are invalid or invalid path sequences detected, so if empty name must be tested later
ALLOWED CHARS: [a-z0-9] _ - . @
public static function safe_username ( string $y_name ) {} :: STRING
@return: {STRING} The safe name ; if invalid should return empty value
@param: {STRING} $y_name: Name to be processed
Create a Safe Valid Strict User Name
NOTICE: It may return an empty string if all characters in the given name are invalid or invalid path sequences detected, so if empty name must be tested later
ALLOWED CHARS: [a-z0-9] .
public static function safe_varname ( string $y_name, bool $y_allow_upper = true ) {} :: STRING
@return: {STRING} The safe variable name ; if invalid instead of returning an empty value, will return an undef var name
@param: {STRING} $y_name: Variable Name to be processed
@param: {BOOL} $y_allow_upper: Allow UpperCase ; *Optional* ; Default is TRUE
Creates a Safe Valid Variable Name
NOTICE: this have a special usage and must allow also 0..9 as prefix because is can be used for other purposes not just for real safe variable names, thus if real safe valid variable name must be tested later (real safe variable names cannot start with numbers ...)
NOTICE: In case of empty string will return Undef____V_a_r
ALLOWED CHARS: [a-zA-Z0-9] _
public static function create_slug ( string $y_str, bool $y_lowercase = false, int $y_maxlen = 0 ) {} :: STRING
@return: {STRING} The slug which will contain only: a-z 0-9 _ - (A-Z will be converted to a-z if lowercase is enforced)
@param: {STRING} $y_str: The string to be processed
@param: {BOOLEAN} $y_lowercase: *OPTIONAL* If TRUE will return the slug with enforced lowercase characters ; DEFAULT is FALSE
@param: {INTEGER+} $y_maxlen: *OPTIONAL* If a positive value greater than zero is supplied here the slug max length will be constrained to this value
Creates a Slug (URL safe slug) from a string
public static function create_htmid ( string $y_str ) {} :: STRING
@return: {STRING} The HTML-ID which will contain only: a-z A-Z 0-9 _ -
@param: {STRING} $y_str: The string to be processed
Creates a compliant HTML-ID (HTML ID used for HTML elements) from a string
public static function create_jsvar ( string $y_str ) {} :: STRING
@return: {STRING} The Js-Var which will contain only: a-z A-Z 0-9 _ $
@param: {STRING} $y_str: The string to be processed
Creates a compliant Js-Var (JavaScript Variable Name) from a string
public static function normalize_spaces ( string $y_txt ) {} :: STRING
@return: {STRING} The normalized text
@param: {STRING} $y_txt: Text to be normalized
Normalize Spaces
This will replace: "\r", "\n", "\t", "\v" = "\x0B", "\0" = "\x00", "\f" = \x0C, "\b", "\a" with normal space ' '
public static function random_number ( int $y_min = 0, int $y_max = -1, bool $y_seed = false ) {} :: INT
@return: {INTEGER} An integer random number
Generates an integer random number between min and max using mt_rand() which is4x times faster than rand().
It may use a random seed based on microtime or custom using mt_srand() which uses MT_RAND_MT19937 for PHP >= 7.1
NOTICE: using a time based seed may result in most of the calls to a random number may return the same number which perhaps is not what is expected !!
The min is zero. The max is limited to 2147483647 on most of the platforms.
public static function safe_hex_2_bin ( string $hexstr, bool $ignore_case = true, bool $log_if_invalid = true ) {} :: STRING
@return: {STRING} The decoded string or empty string on failure
@param: {STRING} $hexstr: The Bin2Hex (HEX) encoded string
@param: {BOOL} $ignore_case: Default is TRUE (hex2bin default behaviour, accept both lower/upper case letters and numbers) ; if set to FALSE will accept just lowercase letters and numbers
@param: {BOOL} $log_if_invalid: Default is TRUE (hex2bin default behaviour, except that will log notice not warning) ; if set to FALSE will not log at all (useful for input that comes from untrusted sources, ex: URL)
Returns the Safe Decoded string from a HEX String
It will validate the string to have an EVEN length not ODD, as required by hex2bin ; if string length is ODD or invalid HEX, a notice will be logged
Hint: to avoid warnings from hex2bin use this method instead, on invalid input will log just notices
public static function base_to_hex_convert ( string $encoded, int $currentBase, string $charset = "" ) {} :: STRING
@return: {STRING} The decoded string (as hex) from the selected base or empty string on error
@param: {STRING} $encoded: A string (baseXX encoded) that was previous encoded using Smart::base_from_hex_convert()
@param: {INTEGER} $currentBase: The base to convert ; Available source base: 32, 36, 58, 62, 85, 92
@param: {STRING} $charset: *OPTIONAL* an alternate charset if non-empty ; if empty (default) the built-in charset will be used
Safe convert to hex from any of the following bases: 32, 36, 58, 62, 85, 92
In case of error will return an empty string.
public static function base_from_hex_convert ( string $hexstr, int $targetBase, string $charset = "" ) {} :: STRING
@return: {STRING} The encoded string in the selected base or empty string on error
@param: {STRING} $hexstr: A hexadecimal string (base16) ; can be from bin2hex($string) or from dechex($integer) but in the case of using dechex must use also left padding with zeros to have an even length of the hex data
@param: {INTEGER} $targetBase: The base to convert ; Available target base: 32, 36, 58, 62, 85, 92
@param: {STRING} $charset: *OPTIONAL* an alternate charset if non-empty ; if empty (default) the built-in charset will be used
Safe convert from hex to any of the following bases: 32, 36, 58, 62, 85, 92
In case of error will return an empty string.
public static function hex_to_int10 ( string $hex ) {} :: INT
public static function int10_to_hex ( int $num ) {} :: STRING
public static function int10_to_base62_str ( int $num ) {} :: STRING
public static function net_server_id ( bool $base36 = false ) {} :: STRING
Returns the valid Net Server ID (to be used in a cluster)
Valid values are 0..1295 (or 00..ZZ if BASE36)
public static function unique_entropy ( string $y_suffix = "", bool $y_use_net_server_id = true ) {} :: STRING
@return: {STRING} variable length Unique Entropy string
Generates a time based entropy as replacement for uniqid() to ensure is unique in time and space.
It is based on a full unique signature in space and time: server name, server unique id, a unique time sequence that repeats once in 1000 years and 2 extremely large (fixed length) random values .
If a suffix is provided will append it.
public static function uuid_10_num ( ) {} :: STRING
@return: {STRING} the UUID
Intended usage: Small scale.
Generates a random, almost unique numeric UUID of 10 characters [0..9] ; Example: 5457229400 .
For the same time moment, duplicate values can happen with a chance of 1 in a 9 million.
Min is: 0000000001 ; Max id: 9999999999 .
Values: 9999999998 .
public static function uuid_10_str ( ) {} :: STRING
@return: {STRING} the UUID
Intended usage: Medium scale.
Generates a random, almost unique string (base36) UUID of 10 characters [0..9A..Z] ; Example: Z4C9S6F1H1 .
For the same time moment, duplicate values can occur with a chance of ~ 1 in a 3000 trillion.
Min is: 0A0A0A0A0A (28232883707050) ; Max id: Z9Z9Z9Z9Z9 (3582752942424645) .
Values YZYZYZYZYZ (3554520058717595) .
public static function uuid_10_seq ( ) {} :: STRING
@return: {STRING} the UUID
Intended usage: Large scale.
Generates a random string (base36) UUID of 10 characters [0..9A..Z] ; Example: 0G1G74W362 .
Intended usage: Medium scale / Sequential / Non-Repeating (never repeats in a period cycle of 1000 years).
This is sequential, date and time based with miliseconds and a randomizer factor to ensure an ~ unique ID.
Duplicate values can occur just in the same milisecond (1000 miliseconds = 1 second) with a chance of ~ 3%
Values: 34 k / sec ; 200 k / min ; 120 mil / hour .
Advantages: This is one of the most powerful UUID system for medium scale as the ID will never repeat in a large period of time.
Compared with the classic autoincremental IDs this UUID is much better as on the next cycle can fill up unallocated
values and more, because the next cycle occur after so many time there is no risk to re-use some IDs if they were
previous deleted or deactivated in terms of generating confusions with previous records.
The classic autoincremental systems can NOT do this and also, once the max ID is reached the DB table is blocked
as autoincremental records reach the max ID !!!
Disadvantages: The database connectors require more complexity and must be able to retry within a cycle with
double check before alocating, such UUIDs and must use a pre-alocation table since the UUIDs are time based and if
in the same milisecond more than 1 inserts is allocated they can conflict each other without such pre-alocation !
Smart.Framework implements the retry + cycle + pre-alocating table as a standard feature
in the bundled PostgreSQL library (connector/plugin) as PostgreSQL can do DDLs in transactions.
Using such functionality with MySQL would be tricky as DDLs will break the transactions, but still usable ;-).
And for SQLite it does not make sense since SQLite is designed for small DBs thus no need for such high scalability ...
public static function uuid_12_seq ( ) {} :: STRING
@return: {STRING} the UUID
Intended usage: Large scale, in a cluster.
Generates a random string (base62) UUID of 12 characters [0..9a..zA..Z] ; Example: 0K4M6V04JM01 .
It is based on Smart::uuid_10_seq() but will append the last two characters in base36 00..ZZ using Smart::net_server_id(true) that represent the Net Server ID in a cluster.
To set the Net Server ID as unique per each running instance of Smart.Framework under the same domain,
set the constant SMART_FRAMEWORK_NETSERVER_ID in etc/init.php with a number between 0..1295 to have a unique number for each instance of Smart.Framework
where supposed all this instances will run in a cluster.
If there is only one instance running and no plans at all to implement a multi-server cluster, makes non-sense to use this function, use instead the Smart::uuid_10_seq()
For how is implemented, read the documentation for the functions: Smart::uuid_10_seq() and Smart::net_server_id(true)
public static function uuid_13_seq ( ) {} :: STRING
@return: {STRING} the UUID
Intended usage: Very Large scale. Case sensitive.
Generates a random string (base62) UUID of 13 characters [0..9a..zA..Z] ; Example: 00wA0whhw2e9L .
Intended usage: Very Large scale / Sequential / Non-Repeating (never repeats in a period cycle of 9999999 years).
This is sequential, date and time based with miliseconds and a randomizer factor to ensure an ~ unique ID.
Duplicate values can occur just in the same milisecond (1000 miliseconds = 1 second) with a chance of ~ 0.3%
Values: 340000 k / sec ; 2000000 k / min ; 1200000 mil / hour .
Advantages: This is one of the most powerful UUID system for large scale as the ID will never repeat in a huge period of time.
Compared with the classic autoincremental IDs this UUID is much better as on the next cycle can fill up unallocated
values and more, because the next cycle occur after so many time there is no risk to re-use some IDs if they were
previous deleted or deactivated in terms of generating confusions with previous records.
The classic autoincremental systems can NOT do this and also, once the max ID is reached the DB table is blocked
as autoincremental records reach the max ID !!!
Disadvantages: The database connectors require more complexity and must be able to retry within a cycle with
double check before alocating, such UUIDs and must use a pre-alocation table since the UUIDs are time based and if
in the same milisecond more than 1 inserts is allocated they can conflict each other without such pre-alocation !
Smart.Framework implements the retry + cycle + pre-alocating table as a standard feature
in the bundled PostgreSQL library (connector/plugin) as PostgreSQL can do DDLs in transactions.
Using such functionality with MySQL would be tricky as DDLs will break the transactions, but still usable ;-).
And for SQLite it does not make sense since SQLite is designed for small DBs thus no need for such high scalability ...
public static function uuid_15_seq ( ) {} :: STRING
@return: {STRING} the UUID
Intended usage: Very Large scale, in a cluster. Case sensitive.
Generates a random string (base62) UUID of 15 characters [0..9a..zA..Z] ; Example: 00wA0whhw2e9L01 .
It is based on Smart::uuid_13_seq() but will append the last two characters in base36 00..ZZ using Smart::net_server_id(true) that represent the Net Server ID in a cluster.
To set the Net Server ID as unique per each running instance of Smart.Framework under the same domain,
set the constant SMART_FRAMEWORK_NETSERVER_ID in etc/init.php with a number between 0..1295 to have a unique number for each instance of Smart.Framework
where supposed all this instances will run in a cluster.
If there is only one instance running and no plans at all to implement a multi-server cluster, makes non-sense to use this function, use instead the Smart::uuid_13_seq()
For how is implemented, read the documentation for the functions: Smart::uuid_13_seq() and Smart::net_server_id(true)
public static function uuid_32 ( ) {} :: STRING
@return: {STRING} the UUID
Generates an almost unique BASE36 based UUID of 32 characters [0..9A..Z] ; Example: Y123AY7WK5-9187139702-Z98W7T091K .
This compose as: Smart::uuid_10_seq().'-'.Smart::uuid_10_num().'-'.Smart::uuid_10_str()
Intended usage: Very Large scale.
public static function uuid_34 ( ) {} :: STRING
@return: {STRING} the UUID
Generates an almost unique BASE36 based UUID of 34 characters [0..9A..Z] ; Example: Y123AY7WK501-9187139702-Z98W7T091K .
This compose as: Smart::uuid_12_seq().'-'.Smart::uuid_10_num().'-'.Smart::uuid_10_str()
Intended usage: Very Large scale, in a cluster.
public static function uuid_35 ( ) {} :: STRING
@return: {STRING} the UUID
Generates an almost unique BASE62 + BASE36 based UUID of 35 characters [0..9a..zA..Z] ; Example: 00wA0whhw2e9L-9187139702-Z98W7T091K .
This compose as: Smart::uuid_13_seq().'-'.Smart::uuid_10_num().'-'.Smart::uuid_10_str()
Intended usage: Extremely Large scale. Case sensitive.
public static function uuid_37 ( ) {} :: STRING
@return: {STRING} the UUID
Generates an almost unique BASE62 + BASE36 based UUID of 37 characters [0..9a..zA..Z] ; Example: 00wA0whhw2e9L01-9187139702-Z98W7T091K .
This compose as: Smart::uuid_15_seq().'-'.Smart::uuid_10_num().'-'.Smart::uuid_10_str()
Intended usage: Extremely Large scale, in a cluster. Case sensitive.
public static function uuid_36 ( string $prefix = "" ) {} :: STRING
@return: {STRING} the UUID
@param: {STRING} $prefix: A prefix to use for more uniqueness entropy ; Ex: can use the Smart::net_server_id()
Generates an almost unique MD5 based UUID of 36 characters [0..9a..f] ; Example: cfcb6c2a-a6e0-f539-141d-083abee19a4e .
The uniqueness of this is based on a full unique signature in space and time: 2 random UUIDS, server name, year/day/month hour:minute:seconds, time, microseconds, a random value 0...9999 .
For the same time moment, duplicates values can occur with a chance of 1 in ~ a 340282366920938586008062602462446642046 .
The Net Server ID can be passed via the $prefix parameter
Intended usage: Large scale. Standard.
public static function uuid_45 ( string $prefix = "" ) {} :: STRING
@return: {STRING} the UUID
@param: {STRING} $prefix: A prefix to use for more uniqueness entropy ; Ex: can use the Smart::net_server_id()
Generates an almost unique SHA1 based UUID of 45 characters [0..9a..f] ; Example: c02acc84-97f4-0807-b12c-ed6f28dd2078-400c1baf .
The uniqueness of this is based on a full unique signature in space and time: 2 random UUIDS, server name, year/day/month hour:minute:seconds, time, microseconds, a random value 0...9999 .
For the same time moment, duplicates values can occur with a chance of 1 in ~ a 1461501637330903466848266086008062602462446642046 .
The Net Server ID can be passed via the $prefix parameter
Intended usage: Large scale. Standard.
public static function array_to_list ( ARRAY $y_arr ) {} :: STRING
@return: {STRING} The List String: '<elem1>, <elem2>, ..., <elemN>'
@param: {ARRAY} $y_arr: The Array to be converted: Array(elem1, elem2, ..., elemN)
Convert an Array to a List String
public static function list_to_array ( string $y_list, bool $y_trim = true ) {} :: ARRAY
@return: {ARRAY} The Array: Array(elem1, elem2, ..., elemN)
@param: {STRING} $y_list: The List String to be converted: '<elem1>, <elem2>, ..., <elemN>'
@param: {BOOLEAN} $y_trim: *Optional* default is TRUE ; If set to FALSE will not trim the values in the list
Convert a List String to Array
public static function b64_to_b64s ( string $str, bool $pad = true ) {} :: STRING
@return: {STRING} The Base64s or Base64u (if no padding) encoded string
@param: {STRING} $str: The Base64 string to be converted
@param: {BOOL} $pad: Use padding ; Default is TRUE ; if set to FALSE will not use padding (`=`:`` instead of `=`:`.`)
Converts from Base64 to Base64s / Base64u (Base64 Safe URL / Base64 URL) by replacing characters as follows:
'+' with '-',
'/' with '_',
'=' with '.' (if padding) or '' (if no padding)
public static function b64s_to_b64 ( string $str ) {} :: STRING
@return: {STRING} The Base64 string
@param: {STRING} $str: The Base64s or Base64u (if no padding) string to be converted
Converts from Base64s / Base64u (Base64 Safe URL / Base64 URL) to Base64 by replacing characters as follows:
'-' with '+',
'_' with '/',
'.' with '=' (optional, if padded, otherwise ignore)
public static function b64s_enc ( string $str, bool $pad = true ) {} :: STRING
@return: {STRING} The Base64s or Base64u (if no padding) encoded string
@param: {STRING} $str: The string to be encoded
@param: {BOOL} $pad: Use padding ; Default is TRUE ; if set to FALSE will not use padding (`=`:`` instead of `=`:`.`)
Returns the Base64s / Base64u (Base64 Safe URL / Base64 URL) Modified Encoding from a string by replacing the standard base64 encoding as follows:
'+' with '-',
'/' with '_',
'=' with '.' (if padding) or '' (if no padding)
public static function b64s_dec ( string $str ) {} :: STRING
@return: {STRING} The decoded string
@param: {STRING} $str: The Base64s or Base64u (if no padding) encoded string
Returns the Decoded string from Base64s / Base64u (Base64 Safe URL / Base64 URL) Encoding by replacing back as follows before applying the standard base64 decoding:
'-' with '+',
'_' with '/',
'.' with '=' (optional, if padded, otherwise ignore)
public static function ip_addr_compress ( string $ipv4orv6 ) {} :: STRING
@return: {STRING} The validated (IPV6 also compressed) IP address ; will return an empty string if invalid IP
@param: {STRING} $ipv4orv6: The IP address ; IPv4 (ex: 127.0.0.1) or IPv6 (ex: ::ffff:127.0.0.1)
Compress an IPv6 address to shortest form, lowercase ; they are also validated
The IPv4 will be returned as they are, they are only validated
public static function ip_addr_compare ( string $ip1, string $ip2 ) {} :: BOOL
@return: {BOOL} Will return TRUE if they are identical, valid, non-empty ; FALSE if not identical OR not valid OR empty
@param: {STRING} $ip1: The first IP address to compare
@param: {STRING} $ip2: The second IP address to compare
Compare 2 IP addresses if they are identical
Works for IPv4 / IPv6 (any form, will standardize it using compression)
Will compare them using numeric translation format IP to INTEGER
public static function ip_addr_in_range ( string $lower_range_ip_address, string $upper_range_ip_address, string $needle_ip_address ) {} :: BOOL
@return: {BOOL} Will return TRUE if the IP is in range ; FALSE if not
@param: {STRING} $lower_range_ip_address: The lower range IP
@param: {STRING} $upper_range_ip_address: The upper range IP
Check if an IPv4 or IPv6 is in range ; doesn't matter what form IPv6 is, will do numeric validation
Works for IPv4 / IPv6 (any form, will standardize it using compression)
Will compare the range and IP using numeric translation format IP to INTEGER
public static function log_info ( string $title, string $message ) {} :: VOID
@return: {-} This function does not return anything
@param: {STRING} $title: The title of the message to be logged
@param: {STRING} $message: The message to be logged
The Info logger.
This will add messages to the App Info Log. (depending if on admin or index, will output into 'tmp/logs/adm/' or 'tmp/logs/idx/')
public static function log_notice ( string $message ) {} :: VOID
@return: {-} This function does not return anything
@param: {STRING} $message: The message to be triggered
A quick replacement for trigger_error() / E_USER_NOTICE.
This is intended to log APP Level Notices.
This will log the message as NOTICE into the App Error Log.
Notices are logged ONLY for Development Environment (and NOT for Production Environment)
public static function log_warning ( string $message ) {} :: VOID
@return: {-} This function does not return anything
@param: {STRING} $message: The message to be triggered
A quick replacement for trigger_error() / E_USER_WARNING.
This is intended to log APP Level Warnings.
This will log the message as WARNING into the App Error Log.
public static function raise_error ( string $message_to_log, string $message_to_display = "", bool $is_html_message_to_display = false ) {} :: VOID
@return: {-} This function does not return anything
@param: {STRING} $message_to_log: The message to be triggered
@param: {STRING} $message_to_display: *Optional* the message to be displayed (must be html special chars safe)
A quick replacement for trigger_error() / E_USER_ERROR.
Since PHP 8.4 E_USER_ERROR has dissapeared
Fix: E_USER_ERROR was replaced by E_USER_WARNING + a message that must start with: '#SMART-FRAMEWORK.ERROR#' in order to preserve the past behaviour ...
This is intended to log APP Level Errors.
This will log the message as ERROR into the App Error Log and stop the execution (also in the Smart Error Handler will raise a HTTP 500 Code).
public static function InstantFlush ( ) {} :: VOID

## class Properties

## class Constants

public const REGEX_SAFE_PATH_NAME = "/^[_a-zA-Z0-9\\-\\.@\\#\\/]+$/" ; ::
public const REGEX_SAFE_FILE_NAME = "/^[_a-zA-Z0-9\\-\\.@\\#]+$/" ; ::
public const REGEX_SAFE_VAR_NAME = "/^[_a-zA-Z0-9]+$/" ; ::
public const REGEX_SAFE_VALID_NAME = "/^[_a-z0-9\\-\\.@]+$/" ; ::
public const REGEX_SAFE_USERNAME = "/^[a-z0-9\\.]+$/" ; ::
public const REGEX_SAFE_HEX_STR = "/^[0-9a-f]+$/" ; ::
public const REGEX_SAFE_B64_STR = "/^[a-zA-Z0-9\\+\\/\\=]+$/" ; ::
public const REGEX_SAFE_B64S_STR = "/^[a-zA-Z0-9\\-_\\.]+$/" ; ::
public const DECIMAL_NUM_PRECISION = "9999999999999.9" ; ::
public const CHARSET_BASE_16 = "0123456789abcdef" ; ::
public const CHARSET_BASE_32 = "0123456789ABCDEFGHIJKLMNOPQRSTUV" ; ::
public const CHARSET_BASE_36 = "0123456789abcdefghijklmnopqrstuvwxyz" ; ::
public const CHARSET_BASE_58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" ; ::
public const CHARSET_BASE_62 = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" ; ::
public const CHDIFF_BASE_64s = ["+" => "-", "/" => "_", "=" => "."] ; ::
public const CHDIFF_BASE_64u = ["+" => "-", "/" => "_", "=" => ""] ; ::
public const CHARSET_BASE_85 = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.-:+=^!/*?&<>()[]{}@%$#" ; ::
public const CHARSET_BASE_92 = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.-:+=^!/*?&<>()[]{}@%$#|;,_~`\"" ; ::
public const UNDEF_VAR_NAME = "Undef____V_a_r" ; ::

## Sample code: PHP

`

    <?php

    // Usage example:
     Smart::some_method_of_this_class(...);

    // #end php code

`

documentation generated on: 2024-12-16 16:53:44 +0000

Smart.Framework © 2009-2024 unix-world.org