Documentation

Utils
in package
Uses BackwardCompatibility

Holds some widely used stuff, like $context and $smcFunc.

Table of Contents

Constants

ENT_LIST  = '&(?' . '>nbsp|quot|gt|lt|a(?' . '>pos|mp)|#(?' . '>\\d+|x[0-9a-fA-F]+));'
Regular expression to match named entities for HTML special characters and any numeric entities.
ENT_NBSP  = '&(?' . '>nbsp|#(?' . '>x0*A0|0*160));'
Regular expression to match all forms of the non-breaking space entity.

Properties

$context  : array<string|int, mixed>
$smcFunc  : array<string|int, mixed>
$backcompat  : array<string|int, mixed>

Methods

arrayLength()  : int
Gets the total byte length of all leaf nodes in an array.
buildRegex()  : string|array<string|int, mixed>
Creates optimized regular expressions from an array of strings.
call_helper()  : mixed
Backward compatibility method.
casefold()  : string
Convenience alias of Utils::convertCase($string, 'fold')
checkMimeType()  : int
Checks whether a file or data has the expected MIME type.
cleanXml()  : string
Clean up the XML to make sure it doesn't contain invalid characters.
convertCase()  : string
Performs case conversion on UTF-8 strings.
emitFile()  : void
Emits a file for download. Mostly used for attachments.
entity_fix__callback()  : string
Strips out invalid HTML entities and fixes double-encoded entities.
entityDecode()  : string
Decodes and sanitizes HTML entities.
entityFix()  : string
Fixes double-encoded entities in a string.
entityStrlen()  : int
Like standard mb_strlen(), except that it counts HTML entities as single characters. This essentially amounts to getting the length of the string as it would appear to a human reader.
entityStrpos()  : int|false
Like standard mb_strpos(), except that it counts HTML entities as single characters.
entitySubstr()  : string
Like standard mb_substr(), except that it counts HTML entities as single characters.
escapestringRecursive()  : array<string|int, mixed>|string
Recursively applies database string escaping to all elements of an array.
exportStatic()  : void
Provides a way to export a class's public static properties and methods to global namespace.
fixchar__callback()  : string
Converts HTML entities to UTF-8 equivalents.
getCallable()  : string|array<string|int, mixed>|bool
Parses $input to find some sort of callable.
getMimeType()  : string|bool
Attempts to determine the MIME type of some data or a file.
htmlspecialchars()  : string
Wrapper for standard htmlspecialchars() that ensures the output respects the database's support (or lack thereof) for four-byte UTF-8 characters.
htmlspecialcharsDecode()  : string
Replaces special entities in strings with the real characters.
htmlspecialcharsRecursive()  : array<string|int, mixed>|string
Recursively applies self::htmlspecialchars() to all elements of an array.
htmlTrim()  : string
Like standard trim(), except that it also trims &nbsp; entities, control characters, and Unicode whitespace characters beyond the ASCII range.
htmlTrimRecursive()  : array<string|int, mixed>|string
Recursively applies self::htmlTrim to all elements of an array.
JavaScriptEscape()  : string
Escapes (replaces) characters in strings to make them safe for use in JavaScript
jsonDecode()  : mixed
Wrapper function for json_decode() with error handling.
jsonEncode()  : mixed
Wrapper function for json_encode().
load()  : void
(Re)initializes some $context values that need to be set dynamically.
makeWritable()  : bool
Tries different modes to make files or directories writable.
normalize()  : string
Performs Unicode normalization on a UTF-8 string.
normalizeSpaces()  : string
Normalizes space characters and line breaks.
obExit()  : void
Ends execution. Takes care of template loading and remembering the previous URL.
randomBytes()  : string
Wrapper for random_bytes() that sets a default length.
randomInt()  : int
Wrapper for random_int() that sets default values.
redirectexit()  : void
Make sure the browser doesn't come back and repost the form data.
replaceEntities__callback()  : string
Decode HTML entities to their UTF-8 equivalent character, except for HTML special characters, which are always converted to numeric entities.
safeSerialize()  : string
Safe serialize() replacement.
safeUnserialize()  : mixed
Safe unserialize() replacement
sanitizeChars()  : string
Replaces invalid characters with a substitute.
sanitizeEntities()  : string
Replaces HTML entities for invalid characters with a substitute.
sendHttpStatus()  : void
Sends an appropriate HTTP status header based on a given status code.
serverResponse()  : mixed
Outputs a response.
shorten()  : string
Like Utils::entitySubstr(), except that this also appends an ellipsis to the returned string to indicate that it was truncated (unless it wasn't truncated because it was already short enough).
stripslashesRecursive()  : array<string|int, mixed>|string
Recursively applies stripslashes() to all elements of an array.
strtolower()  : string
Convenience alias of Utils::convertCase($string, 'lower')
strtotitle()  : string
Convenience alias of Utils::convertCase($string, 'title')
strtoupper()  : string
Convenience alias of Utils::convertCase($string, 'upper')
text2words()  : array<string|int, mixed>
Chops a string into words and prepares them to be inserted into (or searched from) the database.
truncate()  : string
Truncates a string to fit within the specified byte length, while making sure not to cut in the middle of an HTML entity or multi-byte character.
truncateArray()  : array<string|int, mixed>
Truncates the leaf nodes of an array so that their cumulative byte length fits within a specified maximum.
ucfirst()  : string
Convenience alias of Utils::convertCase($string, 'ucfirst')
ucwords()  : string
Convenience alias of Utils::convertCase($string, 'ucwords')
unescapestringRecursive()  : array<string|int, mixed>|string
Recursively removes database string escaping in all elements of an array.
urldecodeRecursive()  : array<string|int, mixed>|string
Recursively applies urldecode() to all elements of an array.
fixUtf8mb4()  : string
Converts four-byte Unicode characters to entities, but only if the database can't handle four-byte characters natively.
loadFile()  : string|bool
Helper method for Utils::call_helper.

Constants

ENT_LIST

Regular expression to match named entities for HTML special characters and any numeric entities.

public mixed ENT_LIST = '&(?' . '>nbsp|quot|gt|lt|a(?' . '>pos|mp)|#(?' . '>\\d+|x[0-9a-fA-F]+));'

ENT_NBSP

Regular expression to match all forms of the non-breaking space entity.

public mixed ENT_NBSP = '&(?' . '>nbsp|#(?' . '>x0*A0|0*160));'

Properties

$context

public static array<string|int, mixed> $context = [ // Assume UTF-8 until proven otherwise. 'utf8' => true, 'character_set' => 'UTF-8', // Define a list of icons used across multiple places. 'stable_icons' => ['xx', 'thumbup', 'thumbdown', 'exclamation', 'question', 'lamp', 'smiley', 'angry', 'cheesy', 'grin', 'sad', 'wink', 'poll', 'moved', 'recycled', 'clip'], // Define an array for custom profile fields placements. 'cust_profile_fields_placement' => ['standard', 'icons', 'above_signature', 'below_signature', 'below_avatar', 'above_member', 'bottom_poster', 'before_member', 'after_member'], // Define an array for content-related <meta> elements (e.g. description, // keywords, Open Graph) for the HTML head. 'meta_tags' => [], // Define an array of allowed HTML tags. 'allowed_html_tags' => ['<img>', '<div>'], // Define a list of allowed tags for descriptions. 'description_allowed_tags' => ['abbr', 'anchor', 'b', 'br', 'center', 'color', 'font', 'hr', 'i', 'img', 'iurl', 'left', 'li', 'list', 'ltr', 'pre', 'right', 's', 'sub', 'sup', 'table', 'td', 'tr', 'u', 'url'], // Define a list of deprecated BBC tags. // Even when enabled, they'll only work in old posts and not new ones. 'legacy_bbc' => ['acronym', 'bdo', 'black', 'blue', 'flash', 'ftp', 'glow', 'green', 'move', 'red', 'shadow', 'tt', 'white'], // Define a list of BBC tags that require permissions to use. 'restricted_bbc' => ['html'], // Login Cookie times. Format: time => txt 'login_cookie_times' => [3153600 => 'always_logged_in', 60 => 'one_hour', 1440 => 'one_day', 10080 => 'one_week', 43200 => 'one_month'], 'show_spellchecking' => false, ]

SMF's venerable $context variable, now available as Utils::$context.

$smcFunc

public static array<string|int, mixed> $smcFunc = ['entity_decode' => __CLASS__ . '::entityDecode', 'sanitize_entities' => __CLASS__ . '::sanitizeEntities', 'entity_fix' => __CLASS__ . '::entityFix', 'htmlspecialchars' => __CLASS__ . '::htmlspecialchars', 'htmltrim' => __CLASS__ . '::htmlTrim', 'strlen' => __CLASS__ . '::entityStrlen', 'strpos' => __CLASS__ . '::entityStrpos', 'substr' => __CLASS__ . '::entitySubstr', 'strtolower' => __CLASS__ . '::strtolower', 'strtoupper' => __CLASS__ . '::strtoupper', 'ucfirst' => __CLASS__ . '::ucfirst', 'ucwords' => __CLASS__ . '::ucwords', 'convert_case' => __CLASS__ . '::convertCase', 'normalize' => __CLASS__ . '::normalize', 'truncate' => __CLASS__ . '::truncate', 'json_encode' => __CLASS__ . '::jsonEncode', 'json_decode' => __CLASS__ . '::jsonDecode', 'random_int' => __CLASS__ . '::randomInt', 'random_bytes' => __CLASS__ . '::randomBytes']

Backward compatibility aliases of various utility functions.

$backcompat

private static array<string|int, mixed> $backcompat = ['func_names' => ['sanitizeChars' => 'sanitize_chars', 'normalizeSpaces' => 'normalize_spaces', 'htmlspecialcharsRecursive' => 'htmlspecialchars__recursive', 'htmlspecialcharsDecode' => 'un_htmlspecialchars', 'htmlTrimRecursive' => 'htmltrim__recursive', 'shorten' => 'shorten_subject', 'text2words' => 'text2words', 'buildRegex' => 'build_regex', 'cleanXml' => 'cleanXml', 'JavaScriptEscape' => 'JavaScriptEscape', 'stripslashesRecursive' => 'stripslashes__recursive', 'urldecodeRecursive' => 'urldecode__recursive', 'escapestringRecursive' => 'escapestring__recursive', 'unescapestringRecursive' => 'unescapestring__recursive', 'truncateArray' => 'truncate_array', 'arrayLength' => 'array_length', 'jsonDecode' => 'smf_json_decode', 'safeSerialize' => 'safe_serialize', 'safeUnserialize' => 'safe_unserialize', 'getMimeType' => 'get_mime_type', 'checkMimeType' => 'check_mime_type', 'makeWritable' => 'smf_chmod', 'sendHttpStatus' => 'send_http_status', 'serverResponse' => 'smf_serverResponse', 'redirectexit' => 'redirectexit', 'obExit' => 'obExit', 'getCallable' => 'getCallable', 'call_helper' => 'call_helper', 'replaceEntities__callback' => 'replaceEntities__callback', 'fixchar__callback' => 'fixchar__callback', 'entity_fix__callback' => 'entity_fix__callback'], 'prop_names' => ['context' => 'context', 'smcFunc' => 'smcFunc']]

BackwardCompatibility settings for this class.

Methods

arrayLength()

Gets the total byte length of all leaf nodes in an array.

public static arrayLength(array<string|int, mixed> $array) : int
Parameters
$array : array<string|int, mixed>

The array.

Return values
int

Total byte length of all leaf nodes in an array.

buildRegex()

Creates optimized regular expressions from an array of strings.

public static buildRegex(array<string|int, mixed> $strings[, string $delim = null ][, bool $return_array = false ]) : string|array<string|int, mixed>

An optimized regex built using this function will be much faster than a simple regex built using implode('|', $strings) --- anywhere from several times to several orders of magnitude faster.

However, the time required to build and execute the optimized regex is approximately equal to the time it takes to execute the simple regex. Therefore, it is usually only worth calling this method if the resulting regex will be used more than once.

Because PHP places an upper limit on the allowed length of a regex, very large arrays of $strings may not fit in a single regex. Normally, the excess strings will simply be dropped. However, if the $return_array parameter is set to true, this function will build as many regexes as necessary to accommodate everything in $strings and return them in an array. You will need to iterate through all elements of the returned array in order to test all possible matches.

Parameters
$strings : array<string|int, mixed>

An array of strings to make a regex for.

$delim : string = null

Optional delimiter character to pass to preg_quote().

$return_array : bool = false

If true, returns an array of regexes.

Return values
string|array<string|int, mixed>

One or more regular expressions to match any of the input strings.

call_helper()

Backward compatibility method.

public static call_helper(mixed $input[, bool $return = false ]) : mixed

Basically just a wrapper for Utils::getCallable(), except that if this method's $return parameter is false, the callable will be called inside this method..

Parameters
$input : mixed

Input to parse to find a callable.

$return : bool = false

If true, just return the callable instead of calling it. Default: false.

Return values
mixed

If $return is false, nothing. Otherwise, either a callable or false if no callable was found.

casefold()

Convenience alias of Utils::convertCase($string, 'fold')

public static casefold(string $string) : string
Parameters
$string : string

The input string.

Return values
string

The casefolded version of the input string.

checkMimeType()

Checks whether a file or data has the expected MIME type.

public static checkMimeType(string $data, string $type_pattern[, bool $is_path = false ]) : int
Parameters
$data : string

The data to check, or the path or URL of a file to check.

$type_pattern : string

A regex pattern to match the acceptable MIME types.

$is_path : bool = false

If true, $data is a path or URL to a file.

Return values
int

1 if the detected MIME type matches the pattern, 0 if it doesn't, or 2 if we can't check.

cleanXml()

Clean up the XML to make sure it doesn't contain invalid characters.

public static cleanXml(string $string) : string

See https://www.w3.org/TR/xml/#charsets

Parameters
$string : string

The string to clean

Return values
string

The cleaned string

convertCase()

Performs case conversion on UTF-8 strings.

public static convertCase(string $string, string $case[, bool $simple = false ][, string $form = 'c' ]) : string

Similar to, but with more capabilities than, mb_convert_case().

Note that setting $form to 'kc_casefold' will override any value of $case and will always fold the case of the string. Also note that setting $form to 'kc_casefold' is not the same as setting $case to 'fold' and $form to 'kc'; specifically, setting $case to 'fold' and $form to 'kc' does not remove "default ignorable code points" from the string, whereas setting $form to 'kc_casefold' does. See notes on the normalize() method for more information about when 'kc_casefold' should be used.

Parameters
$string : string

The input string.

$case : string

One of 'upper', 'lower', 'fold', 'title', 'ucfirst', or 'ucwords'.

$simple : bool = false

If true, use simple maps instead of full maps. Default: false.

$form : string = 'c'

A Unicode normalization form: 'c', 'd', 'kc', 'kd', or 'kc_casefold'.

Return values
string

The normalized string.

emitFile()

Emits a file for download. Mostly used for attachments.

public static emitFile(array<string|int, mixed>|object $file[, bool $show_thumb = false ]) : void
Parameters
$file : array<string|int, mixed>|object

Information about the file. Must be either an array or an object that implements the \ArrayAccess interface.

$show_thumb : bool = false

Whether to send the image's embedded thumbnail, if it has one.

entity_fix__callback()

Strips out invalid HTML entities and fixes double-encoded entities.

public static entity_fix__callback(array<string|int, mixed> $matches) : string

Callback function for preg_replace_callback.

Unused by SMF. Only retained for backward compatibility purposes.

Parameters
$matches : array<string|int, mixed>

An array of matches (relevant info should be the 3rd item in the array)

Tags
deprecated

since 3.0

Return values
string

The fixed string

entityDecode()

Decodes and sanitizes HTML entities.

public static entityDecode(string $string[, bool $mb4 = false ][, int $flags = ENT_QUOTES | ENT_HTML5 ][, bool $nbsp_to_space = false ]) : string

If database does not support 4-byte UTF-8 characters, entities for 4-byte characters are left in place, unless the $mb4 argument is set to true.

Parameters
$string : string

The string in which to decode entities.

$mb4 : bool = false

If true, always decode 4-byte UTF-8 characters. Default: false.

$flags : int = ENT_QUOTES | ENT_HTML5

Flags to pass to html_entity_decode. Default: ENT_QUOTES | ENT_HTML5.

$nbsp_to_space : bool = false

If true, decode ' ' to space character. Default: false.

Return values
string

The string with the entities decoded.

entityFix()

Fixes double-encoded entities in a string.

public static entityFix(string $string) : string
Parameters
$string : string

The string.

Return values
string

The fixed string.

entityStrlen()

Like standard mb_strlen(), except that it counts HTML entities as single characters. This essentially amounts to getting the length of the string as it would appear to a human reader.

public static entityStrlen(string $string) : int
Parameters
$string : string

The string.

Return values
int

The length of the string.

entityStrpos()

Like standard mb_strpos(), except that it counts HTML entities as single characters.

public static entityStrpos(string $haystack, string $needle[, int $offset = 0 ]) : int|false
Parameters
$haystack : string

The string to search in.

$needle : string

The substring to search for.

$offset : int = 0

Search offset within $haystack.

Return values
int|false

Position of $needle in $haystack, or false on failure.

entitySubstr()

Like standard mb_substr(), except that it counts HTML entities as single characters.

public static entitySubstr(string $string, int $offset[, int $length = null ]) : string
Parameters
$string : string

The input string.

$offset : int

Offset where substring will start.

$length : int = null

Maximum length, in characters, of the substring.

Return values
string

The substring.

escapestringRecursive()

Recursively applies database string escaping to all elements of an array.

public static escapestringRecursive(array<string|int, mixed>|string $var) : array<string|int, mixed>|string

Affects both keys and values of arrays.

Parameters
$var : array<string|int, mixed>|string

A string or array of strings to escape

Return values
array<string|int, mixed>|string

The escaped string or array of escaped strings

exportStatic()

Provides a way to export a class's public static properties and methods to global namespace.

public static exportStatic() : void

To do so:

  1. Use this trait in the class.
  2. At the END of the class's file, call its exportStatic() method.

Although it might not seem that way at first glance, this approach conforms to section 2.3 of PSR 1, since executing this method is simply a dynamic means of declaring functions when the file is included; it has no other side effects.

Regarding the $backcompat items:

A class's static properties are not exported to global variables unless explicitly included in $backcompat['prop_names']. Likewise, a class's static methods are not exported as global functions unless explicitly included in $backcompat['func_names'].

$backcompat['prop_names'] is a simple array where the keys are the names of one or more of a class's static properties, and the values are the names of global variables. In each case, the global variable will be set to a reference to the static property. Static properties that are not named in this array will not be exported.

$backcompat['func_names'] is a simple array where the keys are the names of one or more of a class's static methods, and the values are the names that should be used for global functions that will encapsulate those methods. Methods that are not named in this array will not be exported.

Adding non-static properties or methods to the $backcompat arrays will produce runtime errors. It is the responsibility of the developer to make sure not to do this.

fixchar__callback()

Converts HTML entities to UTF-8 equivalents.

public static fixchar__callback(array<string|int, mixed> $matches) : string

Callback function for preg_replace_callback. Uses capture group 1 in the supplied array. Does basic checks to keep characters inside a viewable range.

Unused by SMF. Only retained for backward compatibility purposes.

Parameters
$matches : array<string|int, mixed>

An array of matches (relevant info should be the 2nd item in the array)

Tags
deprecated

since 3.0

Return values
string

The fixed string

getCallable()

Parses $input to find some sort of callable.

public static getCallable(mixed $input[, bool|null $ignore_errors = null ]) : string|array<string|int, mixed>|bool

If a method is found, it looks for a "#" which indicates SMF should create a new instance of the given class.

ADD MORE HERE.

Parameters
$input : mixed

Input to parse to find a callable.

$ignore_errors : bool|null = null
Return values
string|array<string|int, mixed>|bool

Either a callable, or false on failure.

getMimeType()

Attempts to determine the MIME type of some data or a file.

public static getMimeType(string $data[, string $is_path = false ]) : string|bool
Parameters
$data : string

The data to check, or the path or URL of a file to check.

$is_path : string = false

If true, $data is a path or URL to a file.

Return values
string|bool

A MIME type, or false if we cannot determine it.

htmlspecialchars()

Wrapper for standard htmlspecialchars() that ensures the output respects the database's support (or lack thereof) for four-byte UTF-8 characters.

public static htmlspecialchars(string $string[, int $flags = ENT_COMPAT ][, string $encoding = 'UTF-8' ]) : string
Parameters
$string : string

The string being converted.

$flags : int = ENT_COMPAT

Bitmask of flags to pass to standard htmlspecialchars(). Default is ENT_COMPAT.

$encoding : string = 'UTF-8'

Character encoding. Default is UTF-8.

Return values
string

The converted string.

htmlspecialcharsDecode()

Replaces special entities in strings with the real characters.

public static htmlspecialcharsDecode(string $string[, int $flags = ENT_QUOTES ][, string $encoding = 'UTF-8' ]) : string

Functionally equivalent to htmlspecialchars_decode(), except that this also replaces ' ' with a simple space character.

Parameters
$string : string

A string.

$flags : int = ENT_QUOTES

Bitmask of flags to pass to standard htmlspecialchars(). Default is ENT_QUOTES.

$encoding : string = 'UTF-8'

Character encoding. Default is UTF-8.

Return values
string

The string without entities.

htmlspecialcharsRecursive()

Recursively applies self::htmlspecialchars() to all elements of an array.

public static htmlspecialcharsRecursive(array<string|int, mixed>|string $var[, int $flags = ENT_COMPAT ][, string $encoding = 'UTF-8' ]) : array<string|int, mixed>|string

Only affects values.

Parameters
$var : array<string|int, mixed>|string

The string or array of strings to add entities to

$flags : int = ENT_COMPAT

Bitmask of flags to pass to standard htmlspecialchars(). Default is ENT_COMPAT.

$encoding : string = 'UTF-8'

Character encoding. Default is UTF-8.

Return values
array<string|int, mixed>|string

The string or array of strings with entities added

htmlTrim()

Like standard trim(), except that it also trims &nbsp; entities, control characters, and Unicode whitespace characters beyond the ASCII range.

public static htmlTrim(string $string) : string
Parameters
$string : string

The string.

Return values
string

The trimmed string.

htmlTrimRecursive()

Recursively applies self::htmlTrim to all elements of an array.

public static htmlTrimRecursive(array<string|int, mixed>|string $var) : array<string|int, mixed>|string

Only affects values.

Parameters
$var : array<string|int, mixed>|string

The string or array of strings to trim.

Return values
array<string|int, mixed>|string

The trimmed string or array of trimmed strings.

JavaScriptEscape()

Escapes (replaces) characters in strings to make them safe for use in JavaScript

public static JavaScriptEscape(string $string[, bool $as_json = false ]) : string
Parameters
$string : string

The string to escape

$as_json : bool = false

If true, escape as double-quoted string. Default false.

Return values
string

The escaped string

jsonDecode()

Wrapper function for json_decode() with error handling.

public static jsonDecode(string $json[, bool $associative = false ][, bool $should_log = true ]) : mixed
Parameters
$json : string

The string to decode.

$associative : bool = false

Whether to force JSON objects to be returned as associative arrays. SMF nearly always wants this to be true, but for the sake of consistency with json_decode(), the default is false.

$should_log : bool = true

Whether to log errors. Default: true.

Return values
mixed

The decoded data.

jsonEncode()

Wrapper function for json_encode().

public static jsonEncode(mixed $value[, int $flags = 0 ][, int $depth = 512 ]) : mixed

This method exists merely to complement Utils::jsonDecode() for the sake of completeness. Calling this method is functionally identical to calling json_encode() directly.

Parameters
$value : mixed

The value to encode.

$flags : int = 0

Bitmask of flags for json_encode(). Default: 0.

$depth : int = 512

Maximum depth. Default: 512.

Return values
mixed

The decoded data.

load()

(Re)initializes some $context values that need to be set dynamically.

public static load() : void

makeWritable()

Tries different modes to make files or directories writable.

public static makeWritable(string $path) : bool

Wrapper function for PHP's chmod().

Parameters
$path : string

The full path of the file or directory.

Return values
bool

Whether the file/dir exists and is now writable.

normalize()

Performs Unicode normalization on a UTF-8 string.

public static normalize(string $string[, string $form = 'c' ]) : string

Note that setting $form to 'kc_casefold' will cause the string's case to be folded and will also remove all "default ignorable code points" from the string. It should be used (1) when validating identifier strings that must be unambigously unique, such as domain names, file names, or even SMF user names, or (2) when performing caseless matching of strings, such as when performing a search or checking for censored words in a post.

Parameters
$string : string

The input string.

$form : string = 'c'

A Unicode normalization form: 'c', 'd', 'kc', 'kd', or 'kc_casefold'.

Return values
string

The normalized string.

normalizeSpaces()

Normalizes space characters and line breaks.

public static normalizeSpaces(string $string[, bool $vspace = true ][, bool $hspace = false ][, array<string|int, mixed> $options = [] ]) : string
Parameters
$string : string

The string to sanitize.

$vspace : bool = true

If true, replaces all line breaks and vertical space characters with "\n". Default: true.

$hspace : bool = false

If true, replaces horizontal space characters with a plain " " character. (Note: tabs are not replaced unless the 'replace_tabs' option is supplied.) Default: false.

$options : array<string|int, mixed> = []

An array of boolean options. Possible values are:

  • no_breaks: Vertical spaces are replaced by " " instead of "\n".
  • replace_tabs: If true, tabs are are replaced by " " chars.
  • collapse_hspace: If true, removes extra horizontal spaces.
Return values
string

The sanitized string.

obExit()

Ends execution. Takes care of template loading and remembering the previous URL.

public static obExit([bool $header = null ][, bool $do_footer = null ][, bool $from_index = false ][, bool $from_fatal_error = false ]) : void
Parameters
$header : bool = null

Whether to do the header

$do_footer : bool = null

Whether to do the footer

$from_index : bool = false

Whether we're coming from the board index

$from_fatal_error : bool = false

Whether we're coming from a fatal error

randomBytes()

Wrapper for random_bytes() that sets a default length.

public static randomBytes([int $length = 64 ]) : string

Only exists for backward compatibility purposes.

Parameters
$length : int = 64

Number of bytes to return. Default: 64.

Return values
string

A string of random bytes.

randomInt()

Wrapper for random_int() that sets default values.

public static randomInt([int $min = 0 ][, int $max = PHP_INT_MAX ]) : int

Only exists for backward compatibility purposes.

Parameters
$min : int = 0

Minumum value. Default: 0.

$max : int = PHP_INT_MAX

Maximum value. Default: PHP_INT_MAX.

Return values
int

A random integer.

redirectexit()

Make sure the browser doesn't come back and repost the form data.

public static redirectexit([string $setLocation = '' ][, bool $refresh = false ][, bool $permanent = false ]) : void

Should be used whenever anything is posted.

Parameters
$setLocation : string = ''

The URL to redirect them to

$refresh : bool = false

Whether to use a meta refresh instead

$permanent : bool = false

Whether to send a 301 Moved Permanently instead of a 302 Moved Temporarily

replaceEntities__callback()

Decode HTML entities to their UTF-8 equivalent character, except for HTML special characters, which are always converted to numeric entities.

public static replaceEntities__callback(array<string|int, mixed> $matches) : string

Callback function for preg_replace_callback. Uses capture group 2 in the supplied array. Does basic scan to ensure characters are inside a valid range.

Unused by SMF. Only retained for backward compatibility purposes.

Parameters
$matches : array<string|int, mixed>

An array of matches (relevant info should be the 3rd item)

Tags
deprecated

since 3.0

Return values
string

A fixed string

safeSerialize()

Safe serialize() replacement.

public static safeSerialize(mixed $value) : string
  • Recursive.
  • Outputs a strict subset of PHP's native serialized representation.
  • Does not serialize objects.
Parameters
$value : mixed
Return values
string

safeUnserialize()

Safe unserialize() replacement

public static safeUnserialize(string $str) : mixed
  • Accepts a strict subset of PHP's native serialized representation.
  • Does not unserialize objects.
Parameters
$str : string

sanitizeChars()

Replaces invalid characters with a substitute.

public static sanitizeChars(string $string[, int $level = 0 ][, string|null $substitute = null ]) : string

!!! Warning !!! Setting $substitute to '' in order to delete invalid characters from the string can create unexpected security problems. See https://www.unicode.org/reports/tr36/#Deletion_of_Noncharacters for an explanation.

Parameters
$string : string

The string to sanitize.

$level : int = 0

Controls filtering of invisible formatting characters. 0: Allow valid formatting characters. Use for sanitizing text in posts. 1: Allow necessary formatting characters. Use for sanitizing usernames. 2: Disallow all formatting characters. Use for internal comparisons only, such as in the word censor, search contexts, etc. Default: 0.

$substitute : string|null = null

Replacement string for the invalid characters. If not set, the Unicode replacement character (U+FFFD) will be used (or a fallback like "?" if necessary).

Return values
string

The sanitized string.

sanitizeEntities()

Replaces HTML entities for invalid characters with a substitute.

public static sanitizeEntities(string $string[, string $substitute = '&#65533;' ]) : string

The default substitute is the entity for the replacement character U+FFFD (a.k.a. the question-mark-in-a-box).

!!! Warning !!! Setting $substitute to '' in order to delete invalid entities from the string can create unexpected security problems. See https://www.unicode.org/reports/tr36/#Deletion_of_Noncharacters for an explanation.

Parameters
$string : string

The string to sanitize.

$substitute : string = '&#65533;'

Replacement for the invalid entities. Default: '�'

Return values
string

The sanitized string.

sendHttpStatus()

Sends an appropriate HTTP status header based on a given status code.

public static sendHttpStatus(int $code[, string $status = '' ]) : void
Parameters
$code : int

The status code.

$status : string = ''

The status message. Set automatically if empty.

serverResponse()

Outputs a response.

public static serverResponse([string $data = '' ][, string $type = 'Content-Type: application/json' ]) : mixed

It assumes the data is already a string.

Parameters
$data : string = ''

The data to print

$type : string = 'Content-Type: application/json'

The content type. Defaults to JSON.

shorten()

Like Utils::entitySubstr(), except that this also appends an ellipsis to the returned string to indicate that it was truncated (unless it wasn't truncated because it was already short enough).

public static shorten(string $subject, int $len) : string
Parameters
$subject : string

The string.

$len : int

How many characters to limit it to.

Return values
string

The shortened string.

stripslashesRecursive()

Recursively applies stripslashes() to all elements of an array.

public static stripslashesRecursive(array<string|int, mixed>|string $var[, int $level = 0 ]) : array<string|int, mixed>|string

Affects both keys and values of arrays.

Parameters
$var : array<string|int, mixed>|string

The string or array of strings to strip slashes from

$level : int = 0

= 0 What level we're at within the array (if called recursively)

Return values
array<string|int, mixed>|string

The string or array of strings with slashes stripped

strtolower()

Convenience alias of Utils::convertCase($string, 'lower')

public static strtolower(string $string) : string
Parameters
$string : string

The input string.

Return values
string

The lowercase version of the input string.

strtotitle()

Convenience alias of Utils::convertCase($string, 'title')

public static strtotitle(string $string) : string
Parameters
$string : string

The input string.

Return values
string

The titlecase version of the input string.

strtoupper()

Convenience alias of Utils::convertCase($string, 'upper')

public static strtoupper(string $string) : string
Parameters
$string : string

The input string.

Return values
string

The uppercase version of the input string.

text2words()

Chops a string into words and prepares them to be inserted into (or searched from) the database.

public static text2words(string $string[, int|null $max_length = 20 ][, bool $encrypt = false ]) : array<string|int, mixed>
Parameters
$string : string

The text to split into words.

$max_length : int|null = 20

The maximum byte length for each word.

$encrypt : bool = false

Whether to encrypt the results.

Return values
array<string|int, mixed>

An array of strings or integers, depending on $encrypt.

truncate()

Truncates a string to fit within the specified byte length, while making sure not to cut in the middle of an HTML entity or multi-byte character.

public static truncate(string $string, int $length) : string

The difference between this and the entitySubstr method is that this truncates the string to fit into a certain byte length, whereas entitySubstr truncates to fit into a certain visual character length. This difference is important when dealing with Unicode.

Parameters
$string : string

The input string.

$length : int

The maximum length, in bytes, of the returned string.

Return values
string

The truncated string.

truncateArray()

Truncates the leaf nodes of an array so that their cumulative byte length fits within a specified maximum.

public static truncateArray(array<string|int, mixed> $array[, int $max_length = 1900 ]) : array<string|int, mixed>

The array's keys are not considered when calculating the total length.

Parameters
$array : array<string|int, mixed>

The array to truncate.

$max_length : int = 1900

The upperbound on the length.

Return values
array<string|int, mixed>

The truncated array.

ucfirst()

Convenience alias of Utils::convertCase($string, 'ucfirst')

public static ucfirst(string $string) : string
Parameters
$string : string

The input string.

Return values
string

The string, but with the first character in titlecase.

ucwords()

Convenience alias of Utils::convertCase($string, 'ucwords')

public static ucwords(string $string) : string
Parameters
$string : string

The input string.

Return values
string

The string, but with the first character of each word in titlecase.

unescapestringRecursive()

Recursively removes database string escaping in all elements of an array.

public static unescapestringRecursive(array<string|int, mixed>|string $var) : array<string|int, mixed>|string

Affects both keys and values of arrays.

Parameters
$var : array<string|int, mixed>|string

The string or array of strings to unescape

Return values
array<string|int, mixed>|string

The unescaped string or array of unescaped strings

urldecodeRecursive()

Recursively applies urldecode() to all elements of an array.

public static urldecodeRecursive(array<string|int, mixed>|string $var[, int $level = 0 ]) : array<string|int, mixed>|string

Affects both keys and values of arrays.

Parameters
$var : array<string|int, mixed>|string

The string or array of strings to decode

$level : int = 0

Which level we're at within the array (if called recursively)

Return values
array<string|int, mixed>|string

The decoded string or array of decoded strings

fixUtf8mb4()

Converts four-byte Unicode characters to entities, but only if the database can't handle four-byte characters natively.

protected final static fixUtf8mb4(string $string) : string
Parameters
$string : string

A UTF-8 string.

Return values
string

The string, with four-byte chars encoded as entities.

loadFile()

Helper method for Utils::call_helper.

protected final static loadFile(string $string) : string|bool

Receives a string and tries to figure it out if it contains info to load a file.

Checks for a '|' symbol and tries to load a file with the info given.

The string should be format as follows: 'path/to/file.php|whatever'.

You can use the following wildcards in the path:

  • $boarddir
  • $sourcedir
  • $themedir (only works if SMF\Theme has already been initialized)
Parameters
$string : string

The string containing a valid format.

Return values
string|bool

The given string with the pipe and file info removed or false if the file couldn't be loaded.


        
On this page

Search results