Skip to content

functions_system_functions

Daniel Spors edited this page Nov 14, 2024 · 5 revisions

Functions in file system_functions.php

detectEnvironment

Autodetect DEV envrironment. This is done by searching up the folder tree for a file named .scavixwdf.dev. If present, switchToDev is called. Note: This function is called automatically, so please just dont call it!

Definition: public function detectEnvironment($directory)

Returns: void

Parameters:

  • string $directory Starting point to search for

setEnvironment

Sets the environment Possible values are ENVIRONMENT_DEV, ENVIRONMENT_BETA, ENVIRONMENT_SANDBOX or ENVIRONMENT_LIVE

Definition: public function setEnvironment($value)

Returns: void

Parameters:

  • string $value The new value

getEnvironment

Returns the currently set environment Possible values are ENVIRONMENT_DEV, ENVIRONMENT_BETA, ENVIRONMENT_SANDBOX or ENVIRONMENT_LIVE

Definition: public function getEnvironment()

Returns: string The current environment

switchToDev

Shortcut for setEnvironment(ENVIRONMENT_DEV); see there for more details

Definition: public function switchToDev()

Returns: void

switchToBeta

Shortcut for setEnvironment(ENVIRONMENT_BETA); see there for more details

Definition: public function switchToBeta()

Returns: void

switchToSandbox

Shortcut for setEnvironment(ENVIRONMENT_SANDBOX); see there for more details

Definition: public function switchToSandbox()

Returns: void

switchToLive

Shortcut for setEnvironment(ENVIRONMENT_LIVE); see there for more details

Definition: public function switchToLive()

Returns: void

isDev

Checks current environment Checks if current environment is ENVIRONMENT_DEV

Definition: public function isDev()

Returns: bool true or false

isBeta

Checks current environment Checks if current environment is ENVIRONMENT_BETA

Definition: public function isBeta()

Returns: bool true or false

isSandbox

Checks current environment Checks if current environment is ENVIRONMENT_SANDBOX

Definition: public function isSandbox()

Returns: bool true or false

isLive

Checks current environment Checks if current environment is ENVIRONMENT_LIVE

Definition: public function isLive()

Returns: bool true or false

isNotLive

Checks current environment Checks if current environment is not ENVIRONMENT_LIVE

Definition: public function isNotLive()

Returns: bool true or false

isDevOrBeta

Checks current environment Checks if current environment is ENVIRONMENT_DEV or ENVIRONMENT_BETA

Definition: public function isDevOrBeta()

Returns: bool true or false

cfg_set

Sets a config value. uses given arguments for key path like this:

cfg_set('system','use_cfg','really',true);	
// will set	
$CONFIG['system']['use_cfg']['really'] = true;	

measured performance agains direct assignment: it is about 5 times slower on a Windows7 x64 system with 8GB RAM. But for 1000 calls it just needs 5ms, so just leave me alone with that.

Definition: public function cfg_set($args)

Returns: void

Parameters:

  • mixed $args Path to setting and value

cfg_setd

Sets a config value only if it has not been set See cfg_set() for usage and performance thoughts

Definition: public function cfg_setd($args)

Returns: void

Parameters:

  • mixed $args Path to setting and value

cfg_add

Adds an entry to a config value array See cfg_set() for usage and performance thoughts

Definition: public function cfg_add($args)

Returns: void

Parameters:

  • mixed $args Path to setting and value

cfg_get

Gets a config value. See cfg_set() for usage and performance thoughts

Definition: public function cfg_get($args)

Returns: mixed Config value

Parameters:

  • mixed $args Path to setting

cfg_getd

Gets a config value and uses the last argument given as default if it is not set. See cfg_set() for usage and performance thoughts

Definition: public function cfg_getd($args)

Returns: mixed Config value

Parameters:

  • mixed $args Path to setting and default value

cfg_del

Deletes a config value See cfg_set() for usage and performance thoughts

Definition: public function cfg_del($args)

Returns: void

Parameters:

  • mixed $args Path to setting

cfg_check

Checks if a config is set and throws an exception if not. Last argument will be used as exception message. See cfg_set() for usage and performance thoughts

Definition: public function cfg_check($args)

Returns: void

Parameters:

  • mixed $args Path to setting

add_resource_dir

Adds a resource dir

Definition: public function add_resource_dir($path, $url, $append_nc=true, $ext=false)

Returns: void

Parameters:

  • string $path Path in local filesystem

  • string $url Relative URL how this can be reached

  • string $append_nc Use nocache handling true|false

  • string $ext Pipe (|) separated list of filename extensions

prepend_resource_dir

Prepends a resource dir

Definition: public function prepend_resource_dir($path, $url, $append_nc=true, $ext=false)

Returns: void

Parameters:

  • string $path Path in local filesystem

  • string $url Relative URL how this can be reached

  • string $append_nc Use nocache handling true|false

  • string $ext Pipe (|) separated list of filename extensions

add_wdfresource_dir

Adds a WdfResource controlled resource dir

Definition: public function add_wdfresource_dir($path, $append_nc=true, $ext=false)

Returns: void

Parameters:

  • string $path Path in local filesystem

  • string $append_nc Use nocache handling true|false

  • string $ext Pipe (|) separated list of filename extensions

prepend_wdfresource_dir

Prepends a WdfResource controlled resource dir

Definition: public function prepend_wdfresource_dir($path, $append_nc=true, $ext=false)

Returns: void

Parameters:

  • string $path Path in local filesystem

  • string $append_nc Use nocache handling true|false

  • string $ext Pipe (|) separated list of filename extensions

setAppVersion

Sets the application version. Use this when you update your app to a new version. It will create a new nocache argument too so that all dependent files will be reloaded by your clients. Will also affect minify module!

Definition: public function setAppVersion($major, $minor, $build, $codename, $nc_salt=false)

Returns: void

Parameters:

  • int $major Major version

  • int $minor Minor version

  • int $build Build number

  • string $codename Codename (like 'alpha' or 'woohoo-wdf')

  • string $nc_salt Optional string to salt the nocache argument

updateAppNC

Updates the nc part of the global 'APP_VERSION'.

Definition: public function updateAppNC($nc_salt)

Returns: void

Parameters:

  • string $nc_salt Value to salt the NC with

getAppVersion

Gets the application version. If key is given, returns that part only.

Definition: public function getAppVersion($key=false)

Returns: mixed Version array or the requested part of it

Parameters:

  • string $key 'major','minor','build' or 'codename'

isSSL

Check if SSL is in use Returns true when the current request is SSL secured, else false

Definition: public function isSSL()

Returns: bool true or false

urlScheme

Returns current URL scheme That is one of http, https, http:// or https://

Definition: public function urlScheme($append_slashes=false)

Returns: string The current scheme

Parameters:

  • bool $append_slashes If true appends '//' to the result

system_ensure_path_ending

Ensures that the given path ends with a directory separator As Windows works fine with '/' and all others use '/' we just use that instead of DIRECTORY_SEPARATOR. That one actually makes problems in some cases.

Definition: public function system_ensure_path_ending($path, $make_realpath=false)

Returns: void

Parameters:

  • string $path Path to be checked

  • bool $make_realpath If true calls realpath() on the $path

starts_with

Checks if a string starts with another one. Shortcut for the lazy ones: return strpos($string,$start) === 0 You may also call this function with more parameters. In that case will check if $string starts with any of the given strings: $hit = starts_with('hello world','wow','rl','hello');

Definition: public function starts_with($string, $start)

Returns: bool true or false

Parameters:

  • string $string String to check

  • string $start The start to be checked

starts_iwith

SHORTCUT starts_with() but ignoring the case

ends_with

Checks if a string ends with another one. Shortcut for the lazy ones: return substr($string,strlen($string)-strlen($end)) == $end You may also call this function with more parameters. In that case will check if $string ends with any of the given strings: $hit = ends_with('hello world','wow','rl','ld');

Definition: public function ends_with($string, $end)

Returns: bool true or false

Parameters:

  • string $string String to check

  • string $end The end to be checked

ends_iwith

Checks if a string ends with another one. Same as ends_with but ignores case.

Definition: public function ends_iwith($string, $end)

Returns: bool true or false

Parameters:

  • string $string String to check

  • string $end The end to be checked

is_in

Tests if the first given argument is one of the others. Use like this: is_in('nice','Hello','nice','World') This is a shortcut for in_array('nice',array('Hello','nice','World')).

Definition: public function is_in($args)

Returns: bool true or false

Parameters:

  • mixed $args Needle and values to compare with

contains

Tests if the first given argument contains one of the others. First argument may be an array or a string. If array, all entries will be checked for equality with at least one of the other given arguments. If string, contains performs a stripos check with each other given argument and returns true if at least one matched. Use like this:

contains(array('Hello','nice','World'),'some','other','nice','words'); // true	
contains('Hello nice World','some','other','nice','words'); // true	
contains('Hello nice World','some','other','words'); // false	

Definition: public function contains($args)

Returns: bool true or false

Parameters:

  • mixed $args Needle and values to compare with

array_val

Returns array value at key if it exists, else default is returned. This is shortcut for $val = (array_key_exists($key,$array) && $array[$key])?$array[$key]:$default;

Definition: public function array_val($array, $key, $default=null)

Returns: mixed Result or $default

Parameters:

  • array $array The source array

  • mixed $key The key to be checked

  • mixed $default Default value to return if array does not contain key

array_val_is

Checks if an array contains key and if the value is needle This is shortcut for

if( array_key_exists($key,$array) && $array[$key]==$needle  )	
...;	

Definition: public function array_val_is($array, $key, $needle)

Returns: bool true or false

Parameters:

  • array $array The source array

  • mixed $key The key to be checked

  • mixed $needle The value to check against

system_is_ajax_call

Tests if 'we are' currently handling an ajax request This is done by checking the $_SERVER variable and the request_id. We set the request_id in plain requests in the SESSION and add it to AJAX requests so we can compare those two here.

Definition: public function system_is_ajax_call()

Returns: bool true or false

strip_only

Strips given tags from string See http://www.php.net/manual/en/function.strip-tags.php#93567

Definition: public function strip_only($str, $tags)

Returns: string|array cleaned up string

Parameters:

  • string $str String to strip

  • array $tags Tags to be stripped

uniord

Returns the ordinal number for a char Code 'stolen' from php.net ;) The following uniord function is simpler and more efficient than any of the ones suggested without depending on mbstring or iconv. It's also more validating (code points above U+10FFFF are invalid; sequences starting with 0xC0 and 0xC1 are invalid overlong encodings of characters below U+0080), though not entirely validating, so it still assumes proper input. See http://de3.php.net/manual/en/function.ord.php#77905

Definition: public function uniord($c)

Returns: int|bool The ORD code

Parameters:

  • string $c Character to get ORD of

unicode_cleanup_rtl

Here's a PHP function which does just that when given a UTF-8 encoded string. It's probably not the best way to do it, but it works: See http://www.iamcal.com/understanding-bidirectional-text/ Uncommented PDF correction because it's too weak and kills some currency symbols in CurrencyFormat::Format

Definition: public function unicode_cleanup_rtl($data)

Returns: string Cleaned up string

Parameters:

  • string $data String to be cleaned up

utf8_clean

Cleans an UTF8 string See http://stackoverflow.com/a/3742879

Definition: public function utf8_clean($str)

Returns: string The clean string

Parameters:

  • string $str String to clean

get_ip_address

Return the client's IP address Quite some logic to get that behind load-balancers and some proxies, but works fine now ;)

Definition: public function get_ip_address()

Returns: string IP address

classpath_add

Add a path to the classpath for autoloading classes You can add complete trees with this when letting $recursive be true.

Definition: public function classpath_add($path, $recursive=true, $part=false)

Returns: void

Parameters:

  • string $path folder name

  • bool $recursive add subfolders too?

  • string $part INTERNAL, let default to false

system_glob

Find pathnames matching a pattern. glob() cant be used directly in foreach when open_basedir is set. See https://bugs.php.net/bug.php?id=47358 and glob

Definition: public function system_glob($pattern, $flags)

Returns: array An array containing the matched files/directories, an empty array if no file matched

Parameters:

  • string $pattern The pattern. No tilde expansion or parameter substitution is done.

  • int $flags Valid flags: see glob

system_glob_rec

Lists all files of a directory recursively. Note that default pattern in . thus only listing files with a dot in the name. If you change that to '*' everything will be returned. We use . a common filter for all files (yes, we know that this is wrong).

Definition: public function system_glob_rec($directory, $pattern)

Returns: array Listing of all files

Parameters:

  • string $directory Directory name

  • string $pattern Filename pattern

system_walk_files

Searches files in a given directory and calls a callback function for each file.

Definition: public function system_walk_files($folder, $pattern, $callback, $recursive=true)

Returns: void

Parameters:

  • mixed $folder Folder to search

  • mixed $pattern fnmatch pattern

  • mixed $callback Function to call for each file. If callback return false, the search will stop.

  • mixed $recursive If true, recursively searches subfolders

can_rewrite

Checks if WDF_FEATURES_REWRITE is on You can set it in .htaccess with SetEnv WDF_FEATURES_REWRITE on Note that this check is case sensitive, so 'on' really means 'on' and not 'On' or '1'!

Definition: public function can_rewrite()

Returns: bool true or false

can_nocache

Checks if WDF_FEATURES_NOCACHE is on You can set it in .htaccess with SetEnv WDF_FEATURES_NOCACHE on Note that this check is case sensitive, so 'on' really means 'on' and not 'On' or '1'!

Definition: public function can_nocache()

Returns: bool true or false

natksort

Natural sorts an array by it's keys. This is a slightly modified version of one found in the PHP documentation. See http://www.php.net/manual/en/function.ksort.php#54319

Definition: public function natksort($array)

Returns: void

Parameters:

  • array $array Array to be sorted

force_array

Wraps something into an array if needed. If fact does this: return is_array($data)?$data:array($data); Note that for is_null($data) force_array will return an empty []

Definition: public function force_array($data, $empty_for_null=true)

Returns: array The resulting array

Parameters:

  • mixed $data Anything you want to be an array if it is not aready

  • bool $empty_for_null If true and $data is null it will return [], else will return [null]

castObject

Casts an object to another type. There are situations where PHP provides you with stdClasses where you want your own type. This function casts any object into another one:

class SomeClass { public $someProperty; }	
class SomeOtherClass { }	
$std = json_decode('{"someProperty":"someValue"}');	
$typed = castObject($std,'SomeClass');	
$othertyped = castObject($typed,'SomeOtherClass');	

See stackoverflow: Convert/cast an stdClass object to another class

Definition: public function castObject($instance, $className)

Returns: object Typed object

Parameters:

  • object $instance Object of any type

  • string $className Classname of the type you want

get_class_simple

Returns the classname for the given object. This function ignores all namespace stuff and only return the good old classname. Not sure if we will need it for a longer time, but in fact it IS needed for namespace redesign.

Definition: public function get_class_simple($object, $lower_case=false)

Returns: string Simplified classname

Parameters:

  • object|string $object The object to get the classname from

  • bool $lower_case What do you think?

is_assoc

Checks if an array is associative. Stolen from stackoverflow.com

Definition: public function is_assoc($array)

Returns: bool true if $array contains at least one key that is not numeric

Parameters:

  • array $array Input array

ifnull

Returns the first property of an object that is not null. Requires at least two parameters. The first must be an object or array to check. All others represent property/key names that shall be checked for existance.

$data = array('name'=>'helloworld','display_name'=>'Hello World!');	
$result = ifnull($data,'email','username','display_name','name');	
// $result is now "Hello World!"	

Definition: public function ifnull($args)

Returns: mixed The first non-null value or null of none found

Parameters:

  • mixed $args Subject and property names to check for values

sif

DEPRECATED Not widely used, modern PHP offers better syntactic sugar Shorthand IF function. This function is something similar to the ?: syntax for IF control structures. Complicated to explain, here's a sample:

$a = true ? 1 : true ? 2 : 3;    // -> 2	
$a = true ? 1 : (true ? 2 : 3);  // -> 1	
$b = sif(true,1,sif(true,2,3));  // -> 1	

So we use sif to get readable code in a one-liner.

avail

Returns true if an object's/array's property/key is set. avail is a shorthand function to recursively check if an object property or array key is present and set. It needs at least two arguments: The object/array to check and a property/key to check. If you want to check more deeply just add more arguments. In fact using avail is equivalent to using and == true. See this sample and you will understand:

$o = new stdClass();	
$o->attributes = new stdClass();	
$o->attributes->url = 'http://www.scavix.com';	
$a = [];	
$a['system']['atad'] = 'wrong order';	
if( avail($o,'attributes','url') )	
log_debug("URL",$o->attributes->url);	
if( isset($o) && is_object($o->attributes) && isset($o->attributes->url) && $o->attributes->url )	
log_debug("URL",$o->attributes->url);	
if( avail($a,'system','data') )	
log_debug("SysData",$a['system']['data']);	
if( isset($a) && is_array($a['system']) && isset($a['system']['data']) && $a['system']['data'] )	
log_debug("SysData",$a['system']['data']);	

Definition: public function avail($args)

Returns: bool True if the requested data is available, else false

Parameters:

  • mixed $args Subject and path to check

ifavail

Returns the first property of an object that is available. See ifnull for a detailed description as this works the same way. Difference is that this only checks against null but also if a value is set (weak comparison against false).

Definition: public function ifavail($args)

Returns: mixed The first set value or null of none found

Parameters:

  • mixed $args Subject and property names to check for values

array_values_rec

SHORTCUT array_values on a multidimentional array

idn_to_utf8

INTERNAL Use own implementation if missing

array_first

Returns the first element of a given array.

Definition: public function array_first($array)

Returns: mixed The first element

Parameters:

  • array $array The array

array_last

Returns the last element of a given array.

Definition: public function array_last($array)

Returns: mixed The last element

Parameters:

  • array $array The array

sub_array

Returns part of an array.

Definition: public function sub_array($array, $keys)

Returns: mixed Array of keys to return values for

Parameters:

  • array $array The array

  • array $keys Array of keys you want to get

get_requested_file

Returns the last requested file from a given URL. Can handle "?wdf_route=" requests too, so is used in resource-collecting.

Definition: public function get_requested_file($url)

Returns: string The file path

Parameters:

  • string $url The URL to parse

getallheaders

INTERNAL Polyfill for https://www.php.net/manual/de/function.getallheaders.php

system_app_temp_dir

Returns the app-specific temp folder. Creates it with 777 if it doesn't exist

Definition: public function system_app_temp_dir($subfolder, $appendnc=true)

Returns: string The full path to the (sub-)folder

Parameters:

  • string $subfolder Subfolder under the temp folder

  • bool $appendnc Append the current nc to the folder so that data is gone when nc changes

system_mime_map

Returns an array of key-value pairs representing MIME types (keys) and file extensions (values).

Definition: public function system_mime_map()

Returns: array

system_mime_to_extension

Return file extension based on mimetype.

Definition: public function system_mime_to_extension($mime)

Returns: string|bool extendion or false

Parameters:

  • string $mime Given mime type

system_guess_mime

Guesses a MIME type from a filename based on the file extension.

Definition: public function system_guess_mime($filename)

Returns: string|false The detected MIME type or false

Parameters:

  • string $filename The filename to check

array_clean_assoc_or_sequence

Checks if an array contains only numeric keys and returns a valid 0-based indexed one if so. Samples:

$ar = array_clean_assoc_or_sequence(['a','b','c']); // ['a','b','c']	
$ar = array_clean_assoc_or_sequence([1=>'a',3=>'b',2=>'c']); // ['a','b','c']	
$ar = array_clean_assoc_or_sequence(['1'=>'a',3=>'b','2'=>'c']); // ['a','b','c']	
$ar = array_clean_assoc_or_sequence(['hallo'=>'a',3=>'b','2'=>'c']); // ['hallo'=>'a',3=>'b','2'=>'c']	

Definition: public function array_clean_assoc_or_sequence($array)

Returns: array Cleaned array

Parameters:

  • mixed $array Array to clean

system_get_caller

Returns information about a function caller. Searches the debug_backtrace to detect who called the caller of system_get_caller. Will skip all Scavix-Wdf related files.

Definition: public function system_get_caller($skip, $detailed=false)

Returns: array|string

Parameters:

  • mixed $skip Optional: Number of entries to skip

  • mixed $detailed Optional: Whether to return an array with keys 'location', 'caller' or location only (as string)

system_get_caller_by_type

Returns a specific function caller. Searches the debug_backtrace for an object of a given type (classname).

Definition: public function system_get_caller_by_type($classname)

Returns: object|null Object of the given type or null if not found

Parameters:

  • mixed $classname The classname to search for

system_get_cookie_values

Returns all values for a cookie given in a raw cookie string.

Definition: public function system_get_cookie_values($name, $raw_cookie_string)

Returns: array Array of cookie values

Parameters:

  • mixed $name Name of the cookie

  • mixed $raw_cookie_string Raw cookie string

json_validate

INTERNAL Polyfill for PHP < 8.3

stream_context_set_options

INTERNAL Polyfill for PHP < 8.3

Clone this wiki locally