public class General

class.general.php #10

General is a utility class that offers a number miscellaneous of functions that are used throughout Symphony.

Methods

static integer array_find_available_index(array $array, mixed $seed)

Find the next available index in an array. Works best with numeric keys. The next available index is the minimum integer such that the array does not have a mapping for that index. Uses the increment operator on the index type of the input array, whatever that may do.

Parameters
  • $array arraythe array to find the next index for.

  • $seed mixed(optional) the object with which the search for an empty index is initialized. this defaults to null.

Returns

the minimum empty index into the input array.

static array array_iunique(array $array)

Filter the input array for duplicates, treating each element in the array as a string and comparing them using a case insensitive comparison function.

Parameters
  • $array arraythe array to filter.

Returns

a new array containing only the unique elements of the input array.

static array array_map_recursive(string $function, array $array)

Function recursively apply a function to an array's values. This will not touch the keys, just the values.

Returns

a new array with all the values passed through the given $function

static array array_remove_duplicates(array $array, boolean $ignore_case)

Filter the duplicate values from an array into a new array, optionally ignoring the case of the values (assuming they are strings?). A new array is returned, the input array is left unchanged.

Parameters
  • $array arraythe array to filter.

  • $ignore_case booleantrue if the case of the values in the array should be ignored, false otherwise.

Returns

a new array containing only the unique elements of the input array.

static void array_to_xml(XMLElement $parent, array $data, boolean $validate)

Convert an array into an XML fragment and append it to an existing XML element. Any arrays contained as elements in the input array will also be recursively formatted and appended to the input XML fragment. The input XML element will be modified as a result of calling this.

Parameters
  • $parent XMLElementthe XML element to append the formatted array data to.

  • $data arraythe array to format and append to the XML fragment.

  • $validate booleantrue if the formatted array data should be validated as it is constructed, false otherwise.

static XMLElement buildPaginationElement(integer $total_entries, integer $total_pages, integer $entries_per_page, integer $current_page)

Construct an XML fragment that describes a pagination structure.

Parameters
  • $total_entries integer(optional) the total number of entries that this structure is paginating. this defaults to 0.

  • $total_pages integer(optional) the total number of pages within the pagination structure. this defaults to 0.

  • $entries_per_page integer(optional) the number of entries per page. this defaults to 1.

  • $current_page integer(optional) the current page within the total number of pages within this pagination structure. this defaults to 1.

Returns

the constructed XML fragment.

static boolean checkFile(mixed $file)

Checks that the file and its folder are readable and writable.

Deprecated

@since Symphony 2.7.0

static boolean checkFileDeletable(string $file)

Checks that the file is deletable. It first checks to see if the $file path exists and if it does, checks that is it writable.

Uses
  • clearstatcache()
Parameters
  • $file stringThe path of the file

static boolean checkFileReadable(string $file)

Checks that the file is readable. It first checks to see if the $file path exists and if it does, checks that it is readable.

Uses
  • clearstatcache()
Parameters
  • $file stringThe path of the file

static boolean checkFileWritable(string $file)

Checks that the file is writable. It first checks to see if the $file path exists and if it does, checks that is it writable. If the file does not exits, it checks that the directory exists and if it does, checks that it is writable.

Uses
  • clearstatcache()
Parameters
  • $file stringThe path of the file

static void cleanArray(mixed $arr, array $&$arr)

Strip any slashes from all array values.

Parameters
  • $&$arr arrayPointer to an array to operate on. Can be multi-dimensional.

static integer convertHumanFileSizeToBytes(string $file_size)

Gets the number of bytes from 'human readable' size value. Supports the output of General::formatFilesize as well as reading values from the PHP configuration. eg. 1 MB or 1M

static integer countWords(string $string)

Count the number of words in a string. Words are delimited by "spaces". The characters included in the set of "spaces" are: ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '​', '𠀯', ' ' Any html/xml tags are first removed by strip_tags() and any included html entities are decoded. The resulting string is then split by the above set of spaces and the resulting size of the resulting array returned.

Parameters
  • $string stringthe string from which to count the contained words.

Returns

the number of words contained in the input string.

static string createFilename(string $string, string $delim)

Given a string, this will clean it for use as a filename. Preserves multi-byte characters.

Parameters
  • $string stringString to be cleaned up

  • $delim stringAll non-valid characters will be replaced with this

Returns

Returns created filename

static string createHandle(string $string, integer $max_length, string $delim, boolean $uriencode, array $additional_rule_set)

Given a string, this will clean it for use as a Symphony handle. Preserves multi-byte characters.

Parameters
  • $string stringString to be cleaned up

  • $max_length integerThe maximum number of characters in the handle

  • $delim stringAll non-valid characters will be replaced with this

  • $uriencode booleanForce the resultant string to be uri encoded making it safe for URLs

  • $additional_rule_set arrayAn array of REGEX patterns that should be applied to the $string. This occurs after the string has been trimmed and joined with the $delim

Returns

Returns resultant handle

static boolean|XMLElement createXMLDateObject(integer $timestamp, string $element, string $date_format, string $time_format, string $namespace)

Construct an XML fragment that reflects the structure of the input timestamp.

Parameters
  • $timestamp integerthe timestamp to construct the XML element from.

  • $element string(optional) the name of the element to append to the namespace of the constructed XML. this defaults to "date".

  • $date_format string(optional) the format to apply to the date, defaults to Y-m-d. if empty, uses DateTimeObj settings.

  • $time_format string(optional) the format to apply to the date, defaults to H:i. if empty, uses DateTimeObj settings.

  • $namespace string(optional) the namespace in which the resulting XML entity will reside. this defaults to null.

Returns

false if there is no XMLElement class on the system, the constructed XML element otherwise.

static boolean deleteDirectory(string $dir, boolean $silent)

Recursively deletes all files and directories given a directory. This function has two path. This function optionally takes a $silent parameter, which when false will throw an Exception if there is an error deleting a file or folder.

Parameters
  • $dir stringthe path of the directory to delete

  • $silent boolean(optional) true if an exception should be raised if an error occurs, false otherwise. this defaults to true.

static boolean deleteFile(string $file, boolean $silent)

Delete a file at a given path, silently ignoring errors depending on the value of the input variable $silent.

Uses
  • General::checkFileDeletable()
Parameters
  • $file stringthe path of the file to delete

  • $silent boolean(optional) true if an exception should be raised if an error occurs, false otherwise. this defaults to true.

Returns

true if the file is successfully unlinked, if the unlink fails and silent is set to true then an exception is thrown. if the unlink fails and silent is set to false then this returns false.

static void ensureType(array $params)

Helper to cut down on variables' type check. Currently known types are the PHP defaults. Uses is_XXX() functions internally.

Parameters
    • $params array
    • an array of arrays containing variables info Array[ $key1 => $value1 $key2 => $value2 ... ] $key = the name of the variable $value = Array[ 'var' => the variable to check 'type' => enforced type. Must match the XXX part from an is_XXX() function 'optional' => boolean. If this is set, the default value of the variable must be null ]
static void flattenArray(mixed $source, mixed $output, string $path, array $&$source, array $&$output)

Flatten the input array. Any elements of the input array that are themselves arrays will be removed and the contents of the removed array inserted in its place. The keys for the inserted values will be the concatenation of the keys in the original arrays in which it was embedded. The elements of the path are separated by periods (.). For example, given the following nested array structure: array(1 => array('key' => 'value'), 2 => array('key2' => 'value2', 'key3' => 'value3') ) will flatten to: array('1.key' => 'value', '2.key2' => 'value2', '2.key3' => 'value3')

Parameters
  • $&$source arrayThe array to flatten, passed by reference

  • $&$output array(optional) The array in which to store the flattened input, passed by reference. if this is not provided then a new array will be created.

  • $path string(optional) the current prefix of the keys to insert into the output array. this defaults to null.

static string formatFilesize(integer $file_size)

Format a number of bytes in human readable format. This will append MB as appropriate for values greater than 1,0241,024, KB for values between 1,024 and 1,0241,024-1 and bytes for values between 0 and 1,024.

Parameters
  • $file_size integerthe number to format.

Returns

the formatted number.

static array getExtension(string $file)

Extract the file extension from the input file path.

Parameters
  • $file stringthe path of the file to extract the extension of.

Returns

an array with a single key 'extension' and a value of the extension of the input path.

string|boolean getMimeType(string $file)

Gets mime type of a file.

For email attachments, the mime type is very important. Uses the PHP 5.3 function finfo_open when available, otherwise falls back to using a mapping of known of common mimetypes. If no matches are found application/octet-stream will be returned.

Returns

the mime type of the file, or false is none found

static array getPostData()

Merge $_POST with $_FILES to produce a flat array of the contents of both. If there is no mergefilepost_data function defined then such a function is created. This is necessary to overcome PHP's ability to handle forms. This overcomes PHP's convoluted $_FILES structure to make it simpler to access multi-part/formdata.

Returns

a flat array containing the flattened contents of both $_POST and $_FILES.

static string hash(string $input, string $algorithm)

Uses SHA1 or MD5 to create a hash based on some input This function is currently very basic, but would allow future expansion. Salting the hash comes to mind.

Parameters
  • $input stringthe string to be hashed

  • $algorithm stringThis function supports 'md5', 'sha1' and 'pbkdf2'. Any other algorithm will default to 'pbkdf2'.

Returns

the hashed string

static boolean in_array_all(array $needles, array $haystack)

Search an array for multiple values.

Parameters
  • $needles arraythe values to search the $haystack for.

  • $haystack arraythe in which to search for the $needles

Returns

true if any of the $needles are in $haystack, false otherwise.

static boolean in_array_multi(mixed $needle, array $haystack)

Search a multi-dimensional array for a value.

Parameters
  • $needle mixedthe value to search for.

  • $haystack arraythe multi-dimensional array to search.

Returns

true if $needle is found in $haystack. true if $needle == $haystack. true if $needle is found in any of the arrays contained within $haystack. false otherwise.

static boolean in_iarray(mixed $needle, array $haystack)

Test whether a value is in an array based on string comparison, ignoring the case of the values.

Parameters
  • $needle mixedthe object to search the array for.

  • $haystack arraythe array to search for the $needle.

Returns

true if the $needle is in the $haystack, false otherwise.

static int intval(mixed $value)

Converts a value to a positive integer. This method makes sure that the value is a valid positive integer representation before doing the cast.

Parameters
  • $value mixedThe value to cast to an integer

Returns

The casted integer value if the input is valid, -1 otherwise.

static string|boolean left(string $str, integer $num)

Extract the first $num characters from a string.

Parameters
  • $str stringthe string to extract the characters from.

  • $num integerthe number of characters to extract.

Returns

a string containing the last $num characters of the input string, or false on failure.

static null|string limitWords(string $string, integer $maxChars, boolean $appendHellip)

Truncate a string to a given length, respecting word boundaries. The returned string will always be less than $maxChars. Newlines, HTML elements and leading or trailing spaces are removed from the string.

Parameters
  • $string stringthe string to truncate.

  • $maxChars integer(optional) the maximum length of the string to truncate the input string to. this defaults to 200 characters.

  • $appendHellip boolean(optional) true if the ellipses should be appended to the result in circumstances where the result is shorter than the input string. false otherwise. this defaults to false.

Returns

if the resulting string contains only spaces then null is returned. otherwise a string that satisfies the input constraints.

static null|array listDirStructure(string $dir, string $filter, boolean $recurse, mixed $strip_root, array $exclude, boolean $ignore_hidden)

Construct a multi-dimensional array that reflects the directory structure of a given path.

Parameters
  • $dir string(optional) the path of the directory to construct the multi-dimensional array for. this defaults to '.'.

  • $filter string(optional) A regular expression to filter the directories. This is positive filter, ie. if the filter matches, the directory is included. Defaults to null.

  • $recurse boolean(optional) true if sub-directories should be traversed and reflected in the resulting array, false otherwise.

  • $strip_root mixed(optional) If null, the full path to the file will be returned, otherwise the value of strip_root will be removed from the file path.

  • $exclude array(optional) ignore directories listed in this array. this defaults to an empty array.

  • $ignore_hidden boolean(optional) ignore hidden directory (i.e.directories that begin with a period). this defaults to true.

Returns

return the array structure reflecting the input directory or null if the input directory is not actually a directory.

static null|array listStructure(string $dir, array|string $filters, string $sort, mixed $strip_root, array $exclude, boolean $recurse, boolean $ignore_hidden)

Construct a multi-dimensional array that reflects the directory structure of a given path grouped into directory and file keys matching any input constraints.

Parameters
  • $dir string(optional) the path of the directory to construct the multi-dimensional array for. this defaults to '.'.

  • $filters array|string(optional) either a regular expression to filter the files by or an array of files to include.

  • $recurse boolean(optional) true if sub-directories should be traversed and reflected in the resulting array, false otherwise.

  • $sort string(optional) 'asc' if the resulting filelist array should be sorted, anything else otherwise. this defaults to 'asc'.

  • $strip_root mixed(optional) If null, the full path to the file will be returned, otherwise the value of strip_root will be removed from the file path.

  • $exclude array(optional) ignore files listed in this array. this defaults to an empty array.

  • $ignore_hidden boolean(optional) ignore hidden files (i.e. files that begin with a period). this defaults to true.

Returns

return the array structure reflecting the input directory or null if the input directory is not actually a directory.

static array processFilePostData(array $filedata)

Transform a multi-dimensional array to a flat array. The input array is expected to conform to the structure of the $_FILES variable.

Parameters
  • $filedata arraythe raw $_FILES data structured array

Returns

the flattened array.

static boolean realiseDirectory(string $path, string|integer $mode, boolean $silent)

Create all the directories as specified by the input path. If the current directory already exists, this function will return true.

Parameters
  • $path stringthe path containing the directories to create.

  • $mode string|integer(optional) the permissions (in octal) of the directories to create. Defaults to 0755

  • $silent boolean(optional) true if an exception should be raised if an error occurs, false otherwise. this defaults to true.

static string reverse_sanitize(string $str)

Revert any html entities to their character equivalents.

Parameters
  • $str stringa string to operate on

Returns

the decoded version of the string

static string sanitize(string $source)

Convert any special characters into their entity equivalents. Since Symphony 2.3, this function assumes UTF-8 and will not double encode strings.

Uses
  • htmlspecialchars()
Parameters
  • $source stringa string to operate on.

Returns

the encoded version of the string.

static string sanitizeDouble(string $source)

Convert any special characters into their entity equivalents. Contrary to sanitize(), this version does double encode existing entities.

Uses
  • htmlspecialchars()
Parameters
  • $source stringa string to operate on.

Returns

the fully encoded version of the string.

static int strlen(string $str)

Computes the length of the string. This function will attempt to use PHP's mbstring functions if they are available. This function also forces utf-8 encoding.

Parameters
  • $str stringthe string to operate on

Returns

the string's length

static int strpos(string $haystack, string $needle, int $offset)

Finds position of the first occurrence of a string in a string. This function will attempt to use PHP's mbstring functions if they are available. This function also forces utf-8 encoding for mbstring.

Parameters
  • $haystack stringthe string to look into

  • $needle stringthe string to look for

  • $offset intthe search offset. If it is not specified, 0 is used. A negative offset counts from the end of the string.

Returns

the numeric position of the first occurrence of needle in the haystack

static string substr(string $str, int $start, int $length)

Creates a sub string. This function will attempt to use PHP's mbstring functions if they are available. This function also forces utf-8 encoding.

Parameters
  • $str stringthe string to operate on

  • $start intthe starting offset

  • $length intthe length of the substring

Returns

the resulting substring

static string|boolean substrmax(string $str, integer $val)

Extract the first $val characters of the input string. If $val is larger than the length of the input string then the original input string is returned

Parameters
  • $str stringthe string to operate on

  • $val integerthe number to compare lengths with

Returns

the resulting string or false on failure.

static string|boolean substrmin(string $str, integer $val)

Extract the first $val characters of the input string. If $val is larger than the length of the input string then the original input string is returned.

Parameters
  • $str stringthe string to operate on

  • $val integerthe number to compare lengths with

Returns

the resulting string or false on failure.

static string tabsToSpaces(string $string, integer $spaces)

Replace the tabs with spaces in the input string.

Parameters
  • $string stringthe string in which to replace the tabs with spaces.

  • $spaces integer(optional) the number of spaces to replace each tab with. This argument is optional with a default of 4.

Returns

the resulting string.

static string unwrapCDATA(string $value)

Unwrap a value from CDATA tags to return the raw string

Parameters
  • $value stringThe string to unwrap from CDATA

Returns

The unwrapped string

static boolean uploadFile(string $dest_path, string $dest_name, string $tmp_name, integer|string $perm)

Move a file from the source path to the destination path and name and set its permissions to the input permissions. This will ignore errors in the is_uploaded_file(), move_uploaded_file() and chmod() functions.

Uses
  • General::checkFileWritable()
Parameters
  • $dest_path stringthe file path to which the source file is to be moved.

  • $dest_name stringthe file name within the file path to which the source file is to be moved.

  • $tmp_name stringthe full path name of the source file to move.

  • $perm integer|string(optional) the permissions to apply to the moved file. this defaults to 0644 @since Symphony 2.7.0. It was 0777 in 2.6.x and less.

Returns

true if the file was moved and its permissions set as required. false otherwise.

static boolean validateString(array|string $string, array|string $rule)

Validate a string against a set of regular expressions.

Parameters
  • $string array|stringstring to operate on

  • $rule array|stringa single rule or array of rules

Returns

false if any of the rules in $rule do not match any of the strings in $string, return true otherwise.

static string validateURL(string $url)

Check that a string is a valid URL.

Parameters
  • $url stringstring to operate on

Returns

a blank string or a valid URL

static boolean validateXML(string $data, mixed $errors, boolean $isFile, XsltProcess $xsltProcessor, string $encoding, pointer $&$errors)

Checks an xml document for well-formedness.

Parameters
  • $data stringfilename, xml document as a string, or arbitrary string

  • $&$errors pointerpointer to an array which will contain any validation errors

  • $isFile boolean(optional) if this is true, the method will attempt to read from a file, $data instead.

  • $xsltProcessor XsltProcess(optional) if set, the validation will be done using this XSLT processor rather than the built in XML parser. the default is null.

  • $encoding string(optional) if no XML header is expected, than this should be set to match the encoding of the XML

Returns

true if there are no errors in validating the XML, false otherwise.

static string wrapInCDATA(string $value)

Wrap a value in CDATA tags for XSL output of non encoded data, only if not already wrapped.

Parameters
  • $value stringThe string to wrap in CDATA

Returns

The wrapped string

static boolean writeFile(string $file, mixed $data, integer|string $perm, string $mode, boolean $trim)

Create a file at the input path with the (optional) input permissions with the input content. This function will ignore errors in opening, writing, closing and changing the permissions of the resulting file. If opening or writing the file fail then this will return false. This method calls General::checkFileWritable() which properly checks for permissions.

Uses
  • General::checkFileWritable()
Parameters
  • $file stringthe path of the file to write.

  • $data mixedthe data to write to the file.

  • $perm integer|string(optional) the permissions as an octal number to set set on the resulting file. this defaults to 0644 (if omitted or set to null)

  • $mode string(optional) the mode that the file should be opened with, defaults to 'w'. See modes at http://php.net/manual/en/function.fopen.php

  • $trim boolean(optional) removes tripple linebreaks

Returns

true if the file is successfully opened, written to, closed and has the required permissions set. false, otherwise.

Symphony • Open Source XSLT CMS

Server Requirements

  • PHP 5.3-5.6 or 7.0-7.3
  • PHP's LibXML module, with the XSLT extension enabled (--with-xsl)
  • MySQL 5.5 or above
  • An Apache or Litespeed webserver
  • Apache's mod_rewrite module or equivalent

Compatible Hosts

Sign in

Login details