1. $ mkdir myproject
    2. $ cd myproject
    3. $ curl -s https://microbe.barbichette.net/require | php
      • $ php microbe.php core setup web
      • $ php microbe.php core setup config
      • $ php microbe.php core setup tree
      • $ php microbe.php core setup samples
    • http://…/microbe.php
    • <?php
      require_once __DIR__ . DIRECTORY_SEPARATOR . 'microbe.php';
      boot('web'); // boot('cli');

events

Functions

  • listen ( string $evt Closure $func array $data ) : void

    Register an event listener. The optional third argument is custom data array which will be passed to the function as second argument when the event is fired.

    • $evt string

      Event name.

    • $func Closure

      Listener function, which will accept two arguments: event data and listener data.

    • $data array

      Listener data.

  • dispatch ( string $evt array $data ) : array | null

    Dispatch an event to all the listeners, with optional event data.

    • $evt string

      Event name.

    • $data array

      Optional event data.

  • register_filter ( string $filter Closure $func ) : void

    Register a filter listener.

    • $filter string

      Filter name.

    • $func Closure

      Listener function, which will accept the data to filter as unique argument.

  • filter ( string $filter mixed $data array $args ) : mixed

    Dispatch a filter request to all the filter listeners.

    • $filter string

      Filter name.

    • $data mixed

      Data which will be send and processed by the listeners.

    • $args array

      Additional arguments, unchanged on each filter call.

  • register_thing ( string $thing mixed $data string | null $key ) : void

    Register an entry of something in memory (e.g. an array or an object describing anything). The collection will be able to be retrieved with <get_registered_things()>.

    • $thing string

      Thing type.

    • $data mixed

      Data to store.

    • $key string | null

      Save thing in array as $key. If null, the things array will be considerated as a numeric array.

  • unregister_things ( string $thing ) : void

    Remove all registered things of type $thing.

    • $thing string

      Thing type.

  • get_registered_things ( string $thing ) : array

    Returns all registered things of type $thing.

    • $thing string

      Thing type.

  • get_registered_thing ( string $thing string | null $prop mixed $value int | string | null $key int | null $index ) : mixed

    Returns the registered thing where its array or object's $prop equals $value.

    • $thing string

      Thing type.

    • $prop string | null

      Thing's property name.

    • $value mixed

      Property value.

    • $key int | string | null

      Key of the thing.

    • $index int | null

      Index of the thing. The array will be forced as a numerical-array.

Variables

  • array $_LISTENERS

    Global variable containing registered listeners for events management system.

  • array $_FILTERS

    Global variable containing registered listeners for filters management system.

const

Functions

  • def ( string | array $k mixed | null $value ) : void

    Define one or several constants, if they are not already defined.

    • $k string | array

      Key, or Key/Value array.

    • $value mixed | null

      Value, if $k is a single key.

acl

Functions

  • is_valid_permission_status ( mixed $status ) : bool

    Check if the permission status is one of the valid ACL_* constants.

    • $status mixed

      Status to check.

  • register_acl_permission ( string $name string | null $title string | null $description string | null $icon bool $default ) : void

    Register an ACL permission, which will be used to edit permissions of a user or a role.

    • $name string

      Internal name of the permission.

    • $title string | null

      Pretty name/title of the permission.

    • $description string | null

      Detailled description of what the permission allows to do.

    • $icon string | null

      Icon name representing the permission.

    • $default bool

      Default value of the permission: ACL_ALLOWED or ACL_DISALLOWED.

  • get_registered_acl_permissions ( ) : array

    Returns the registered ACL permissions.

  • get_registered_acl_permission ( string $name ) : object | null

    Returns a specific registered ACL permission.

    • $name string

      Internal name of the permission.

  • register_acl_validator ( string $name Closure $func ) : void

    Register a ACL validator function, used to check if the current visitor is allowed to perform an action.

    • $name string

      Name of the validator source (e.g. user_role).

    • $func Closure

      Function called to validate the action. This function should accept one argument: the permission name. Then, the function should return a boolean meaning if the current visitor was allowed to perform the action requiring the permission, or not.

  • get_registered_acl_validators ( ) : array

    Returns registered ALC validators.

  • is_allowed ( string | array $permission ) : bool

    Execute registered ACL validators to ask them if the current visitor is allowed to perform the action requiring the permission(s).

    • $permission string | array

      Permission(s) name(s).

  • is_disallowed ( string | array $permission ) : bool

    Do the exact opposite of <is_allowed()>.

    • $permission string | array

      Permission(s) name(s).

  • assert_allowed ( string | array $permission string | null $redirect bool $login bool $throwIfLoggedIn ) : mixed

    Check if the user is allowed to perform the action requiring the permission(s). If it's OK, the function returns nothing. If it's not, the user will be either:

    Redirected to $redirect if provided;

    Shown a 403 error.

    • $permission string | array

      Permission(s) name(s).

    • $redirect string | null

      Redirect URL.

    • $login bool

      If true, user will be redirected to login page.

    • $throwIfLoggedIn bool

      If true, and if user is logged in, the user will be shown a 403 error even if $redirect is not not null or $login is true.

actions

Functions

  • get_action_param ( ) : string

    Get the action parameter name.

  • set_action_param ( string $param ) : void

    Set the action parameter name (default is 'action').

    • $param string

      Parameter name.

  • get_current_action_name ( ) : string

    Get the currently requested action name.

  • action ( array | string $name Closure $callback ) : void

    Register an action, known as a controller $_GET/$_POST drived.

    • $name array | string

      Name(s) of the action(s) (value of get(get_action_param())).

    • $callback Closure

      Function to execute if the action is ran.

  • default_action ( Closure $callback ) : void

    Register the default action, an alias of default_action('', ...).

    • $callback Closure

      Function to execute if the action is ran.

auth

Functions

  • get_auth_cookie_name ( ) : string

    Returns the authentication cookie name. This name can be set with the sibling function <set_auth_cookie_name>.

  • set_auth_cookie_name ( string $name ) : void

    Set the authentication cookie name.

    • $name string

      New name of the cookie. If null, the default name hardcoded in <get_auth_cookie_name> will be used.

  • set_auth_cookie_lifetime ( int | null $lifetime ) : void

    Set authentication cookie default lifetime. This behaviour can be bypassed when setting authentication token (e.g. for unremembered logins).

    • $lifetime int | null

      TTL in seconds

  • register_user_getter ( Closure $callback ) : void

    Register user getter callback function. This function will be called when calling <get_logged_in_user>, with the authenticated token as parameter.

    • $callback Closure

      Function to call from <get_logged_in_user>.

  • set_auth_token ( string | null $token int | null $lifetime ) : void

    Set authentication token. The token will be stored in a cookie named with <get_auth_cookie_name>, with the lifetime given in second parameter, or the one set with <set_auth_cookie_lifetime> or finally two month as hardcoded.

    • $token string | null

      Token to store. If null, cookie will be cleared (aka logout) - cf <clear_auth_token>.

    • $lifetime int | null

      TTL in seconds

  • clear_auth_token ( ) : void

    Clear authentication token cookie. Used for logout.

  • get_auth_token ( ) : string | null

    Returns authentication token currently stored in cookie, or null.

  • register_not_logged_in_redirect ( string | null $redirect ) : void

    Registers the default url where the user will be redirected when asserting login (<assert_logged_in>).

    • $redirect string | null

      URL to redirect. If null, an exception may be thrown if <assert_logged_in> needs it.

  • get_logged_in_user ( ) : mixed

    Try to get the authentication token, then try to call the user getter function defined with <register_user_getter> with the token as unique parameter. If this function is not defined, an exception will be thrown. If the user is not logged in, null will be returned. In other cases, the function result will be returned.

  • is_logged_in ( ) : boolean

    Check if the user is logged in, based on <get_logged_in_user> and returns the corresponding boolean.

  • assert_logged_in ( string | null $redirect ) : mixed

    Check if the user is logged in. If yes, the user got from the function defined by <register_user_getter> will be returned. If not, three cases:

    $redirect is null: the user will get a HTTP 403 error.

    $redirect = ':login': the user will be redirected to the defined URL with <register_not_logged_in_redirect>.

    $redirect = ':json': a JSON error with 'unauthorized' as message will be echoed.

    $redirect is different: the user will be redirected to this URL.

    • $redirect string | null

      [description]

backup

Functions

  • get_backup_target ( bool $abs ) : string

    Returns backup target directory.

    • $abs bool

      As absolute path (useful if relative path is set in config file).

  • get_backuped_files ( string | null $target ) : array

    Returns backuped files.

    • $target string | null

      Backup target directory.

  • backup ( ) : array

    Run backup.

bundles

Functions

  • get_bundles ( bool $refresh ) : array

    Returns an array containing the defined bundles.

    • $refresh bool

      Refresh the bundles. If false (default), it will get the bundles infos from the ones stored in memory.

  • get_bundles_dirs ( ) : array

    Returns all bundles directories, for each synonym available.

  • bundle_exists ( string $name bool | boolean $refresh ) : bool

    Check if a bundle exists or not.

    • $name string

      Bundle name.

    • $refresh bool | boolean

      Refresh the bundle info stored in memory.

  • get_bundle ( string $name bool $refresh array $synonym ) : null | object

    Returns information about a bundle.

    • $name string

      Name of the bundle.

    • $refresh bool

      Refresh bundle info, or get information previously stored in memory.

    • $synonym array

      Synonym used (bundle folder).

  • get_bundles_files ( string $type ) : array

    Returns all files of a specific type (helpers, ctrl, etc.) of all bundles.

    • $type string

      Type of file (helpers, ctrl, etc.).

  • include_bundles_files ( string $type bool $once ) : void

    Includes all files of a specific type (helpers, ctrl, etc.) of all bundles.

    • $type string

      Type of file (helpers, ctrl, etc.).

    • $once bool

      Require once instead of simply require.

cache

Functions

  • cached ( int | string | DateInterval | null $ttl bool $json bool $jsonObject string $mode ) : Microbe_Cached

    * @param string $key Cache key.

    • $ttl int | string | DateInterval | null

      Time-to-live.

    • $json bool

      Parse and stringify as JSON.

    • $jsonObject bool

      Parse the JSON as an object. If false, it will be parsed as an array.

    • $mode string

      Saving mode (only "file" is handled yet).

cfg

Functions

  • load_config ( ) : void

    Load the configuration file and store it to the global variable '$_CONFIG'.

  • load_config_file ( string $path ) : array

    Load specific configuration file and returns the processed array.

    • $path string

      Path to the configuration file.

  • process_config ( ) : array

    Process the configuration array to replace the special variables:

    The string '{@...}' will be replaced by the corresponding config entry;

    The string '%env(dev,staging)' will be replaced by the boolean true if the environment is one of those listed ('dev' or 'staging', here);

  • process_config_references ( string $str ) : string

    Process a string to replace all configuration references identified with "{@...}".

    • $str string

      String to process.

  • cfg ( string $var mixed $value ) : mixed

    Get/Set configuration entry.

    • $var string

      Entry name, separated with dots for walking deeply in the config array. The first column (the part before the first dot) should start with '@'. If not, the full path will be prefixed with '@app', corresponding to the app's specific entries. By default, a missing configuration entry will exit the code with an error. To get a silent null instead, the path should be prefixed with a '~'.

    • $value mixed

      To set the value, specify anything different than the default value. It should be any JSON stringifyable value.

  • _cfg ( string $var ) : void

    Echo configuration value

    • $var string

      Entry name, like in <cfg()>.

  • __cfg ( string $var ) : void

    Echo an escaped configuration value

    • $var string

      Entry name, like in <cfg()>.

  • stored ( string $var mixed $value ) : mixed

    Store some data during the processing of the request, using the configuration function, inside the <@stored> configuration section.

    • $var string

      Entry name, separated with dots for walking deeply in the config array.

    • $value mixed

      To set the value, specify anything different than the default value. It should be any JSON stringifyable value.

  • db_cfg ( string $name mixed $value ) : mixed

    Get/Set configuration entry from database key/value table.

    • $name string

      Key of the entry to get or set.

    • $value mixed

      Value to store in database. If null, no change will be done and the existing value in database will be returned.

  • db_cfg_set ( string $name mixed $value ) : void

    Set configuration entry from database key/value table. If $value is null, the configuration entry will be deleted.

    • $name string

      Key of the entry to set.

    • $value mixed

      Value to store in database. If null, the entry will only be deleted.

  • _db_cfg ( string $name ) : void

    Echo configuration value from database key/value table.

    • $name string

      Key of the entry to get or set.

  • __db_cfg ( string $name ) : void

    Echo an escaped configuration value from database key/value table.

    • $name string

      Key of the entry to get or set.

  • db_cfg_delete ( string $name bool $dropIfEmpty ) : void

    Delete a configuration entry from database key/value table.

    • $name string

      Entry key.

    • $dropIfEmpty bool

      Drop the config table if there is no more entry.

Variables

  • array $_CONFIG

    Global variable of the configuration entries.

cookies

Functions

  • cookie ( string $name mixed $value int | null $lifetime string | null $samesite bool | null $secure bool $httponly string | null $domain ) : mixed

    Get/Set a cookie.

    • $name string

      Name of the cookie.

    • $value mixed

      Value to set. If null, the current value of the cookie will be returned.

    • $lifetime int | null

      TTL of the cookie in seconds.

    • $samesite string | null

      Samesite property for the cookie: 'None', 'Lax' or 'Strict'.

    • $secure bool | null

      Ask to the browser to send the cookie only through HTTPS.

    • $httponly bool

      If true, will disallow JavaScript to read the cookie.

    • $domain string | null

      Domain name. If null, it will be set to the top-level domain name.

  • define_cookie ( string $name string | null $cookieName int | string $ttl bool $multiple string $domain Closure | null $modifier ) : void

    Define a cookie configuration for further usage with <defined_cookie> and Microbe_Cookie instance.

    • $name string

      Name of the cookie configuration.

    • $cookieName string | null

      Name of the cookie. If null, $name will be used. In case of multiple cookie, the cookie index is defined in the name using the substring Microbe_Cookie::IDX_SUBSTRING.

    • $ttl int | string

      Cookie's time-to-live in seconds or a duration string.

    • $multiple bool

      Multiple cookie or not?

    • $domain string

      Domain configuration: 'current' or 'top'.

    • $modifier Closure | null

      Modifier callback function, which will be applied on cookie's values.

  • defined_cookie ( string $name ) : Microbe_Cookie | null

    Get a defined cookie's Microbe_Cookie instance.

    • $name string

      Name of the cookie configuration.

  • get_defined_cookies ( ) : array

    Get the defined cookies.

  • set_defined_cookies ( array $cookies ) : void

    Set the defined cookies.

    • $cookies array

      Key-value array containing Microbe_Cookie instances.

db

Functions

  • db_config ( ) : object | null

    Returns the database config as an object.

  • db_dsn ( ) : string | null

    Returns the DSN string of the database connection.

  • db_setup ( string $ref object | null $config boolean $forceRenew ) : PDO | null

    Create a PDO object based on the entries in configuration.

    • $ref string

      The database reference. Default is 'main'.

    • $config object | null

      The configuration object. Default is the one set in the configuration file, for the current environment.

    • $forceRenew boolean

      Force renewal of PDO object.

  • db_get_last_pdo_connect_error ( ) : string | null

    Get last PDO connection error if available.

  • db_dbh ( string $ref ) : PDO | null

    Get the current PDO object, and try to instanciate one if not created yet.

    • $ref string

      The database reference. Default is 'main'.

  • db_is_connected ( string $ref ) : bool

    Check if the PDO instance is initialized or can be initialized.

    • $ref string

      The database reference. Default is 'main'.

  • db_get_arg_type ( mixed $arg string $k string $sql ) : int

    Get the PDO argument type, based on the given value, before binding it to the PDOStatement.

    • $arg mixed

      Value to check.

    • $k string

      Optional parameter key, for debugging purpose.

    • $sql string

      Optional SQL query, for debugging purpose.

  • db_esc ( mixed $str ) : string

    Escape the parameter value for usage in MySQL strings.

    • $str mixed

      Value.

  • db_is_valid_field_format ( string $fieldName ) : bool

    Check if the format of the field name is a proper MySQL table or column name. Only the format will be checked. Not the field existence. It can be used to protect a query from SQL injection, when the table name or the column name can be passed through a form.

    • $fieldName string

      Table or column name.

  • db_assert_field_format ( string $fieldName ) : string

    Check if the format of the field name is a proper MySQL table or column name using <db_is_valid_field_format> to avoid SQL injection. If the format is invalid, an exception will be thrown.

    • $fieldName string

      Table or column name.

  • db_is_valid_comparator ( string $cmp ) : bool

    Check if the given string is a valid SQL comparator.

    • $cmp string

      Possible comparator string.

  • db_assert_comparator ( string $cmp ) : string

    Check if the given string is a valid SQL comparator. If the format is invalid, an exception will be thrown.

    • $cmp string

      Possible comparator string.

  • db_query ( string $sql array $vars string $ref ) : PDOStatement | null

    Prepare the PDOStatement based on the SQL query and the given variables.

    • $sql string

      The SQL query.

    • $vars array

      A key/value associative array with the variables to replace in the query. Note: the variables should be prefixed with a semicolon in the SQL.

    • $ref string

      The database reference. Default is 'main'.

  • db_last_query ( ) : string | null

    Returns the last query if available.

  • db_last_statement ( ) : PDOStatement | null

    Returns the last PDO statement if available.

  • db_compute_sql ( string $sql array $params ) : string

    Compute SQL with parameters and returns a ready-to-use query.

    • $sql string

      SQL query.

    • $params array

      Parameters to be applyed on query.

  • db_execute_dump ( string $path ) : void

    Read a SQL file and execute queries.

    • $path string

      Path to the SQL file.

  • db_dump ( string $path ) : void

    Create a dump file of the database.

    • $path string

      Destination SQL file path.

  • db_get_size ( ) : int

    Get database's size.

  • db_get_tables ( bool $countRows bool $assocArray ) : array

    Get database's tables infos.

    • $countRows bool

      Returns number of rows for each table.

    • $assocArray bool

      Returns an associative array with table name as key.

  • db_drop_all_tables ( bool $dropForeignKeys ) : void

    Delete all tables.

    • $dropForeignKeys bool

      First, drop all foreign keys, or not.

  • db_get_all_foreign_keys ( ) : void

    Get all foreign keys from the database.

  • db_drop_all_foreign_keys ( ) : void

    Delete all foreign keys from the database.

  • db_table_exists ( string $tableName ) : bool

    Check if the table exists.

    • $tableName string

      Table name.

  • db_column_exists ( string $tableName string $columnName ) : bool

    Check if the column exists in given table.

    • $tableName string

      Table name.

    • $columnName string

      Column name.

  • db_fetch_all ( string $sql array $vars Closure | null $modifier ) : array

    Execute a <db_query> and fetch all the rows as an object.

    • $sql string

      SQL Query.

    • $vars array

      Query variables.

    • $modifier Closure | null

      An optional modifier callback, called on each row. The modifier should take the $row as unique argument, and return the modified $row.

  • db_fetch_one ( string $sql array $vars Closure | null $modifier ) : object | null

    Execute <db_fetch_all> and returns the first row. Note that this function doesn't assert that the SQL query limits the result to only one result, so the calling to <db_fetch_all> will be very long if the SQL is not adapted.

    • $sql string

      SQL Query.

    • $vars array

      Query variables.

    • $modifier Closure | null

      An optional modifier callback, called on each row. The modifier should take the $row as unique argument, and return the modified $row.

  • db_fetch_value ( string $sql array $vars Closure | null $modifier ) : mixed

    Fetch the first column's value of the first row of the database query, after calling <db_fetch_one>.

    • $sql string

      SQL Query.

    • $vars array

      Query variables.

    • $modifier Closure | null

      An optional modifier callback, called on each row. The modifier should take the $row as unique argument, and return the modified $row.

  • db_fetch_values ( string $sql array $vars Closure | null $modifier ) : array

    Fetch the first column's value for every row returned by <db_fetch_all>.

    • $sql string

      SQL Query.

    • $vars array

      Query variables.

    • $modifier Closure | null

      An optional modifier callback, called on each row. The modifier should take the $row as unique argument, and return the modified $row.

  • db_id ( string $ref ) : int | null

    Returns the last insert ID.

    • $ref string

      The database reference. Default is 'main'.

  • db_uid ( string $tableName string $fieldName ) : string

    Generate a UID unique in the table $tableName.

    • $tableName string

      Table name.

    • $fieldName string

      UID field name (default 'uid').

  • db_slug ( string $tableName string | null $text int | string | null $originalId string $slugFieldName string $idFieldName string $where ) : string

    Generate a unique slug in the table $tableName. It can be based on a specified string ($text) which will be sanitized and shortened, and optionaly can take in account an original ID for the object which will get its slug (should be provided if the slug may not change).

    • $tableName string

      Table name.

    • $text string | null

      Base text (default, a random SHA-1 string).

    • $originalId int | string | null

      ID of the object which should take the slug.

    • $slugFieldName string

      Slug field name (default 'slug').

    • $idFieldName string

      ID field name (default 'id').

    • $where string

      Additional WHERE conditions.

  • db_now ( ) : string

    Returns a ready-to-use "Y-m-d H:i:s" now time string for database usage.

  • db_field_exists ( string $tableName string | null $columnName ) : bool

    Check if the table exists, and optionnaly if the column in this table exists.

    • $tableName string

      Table name to check.

    • $columnName string | null

      If not null, will also check if the column name exists in this table.

  • db_foreign_keys_check ( bool $check ) : void

    Set FOREIGN_KEY_CHECKS to the specified value.

    • $check bool

      Check or not.

  • db_build_where ( array $conditions ) : array

    Build a WHERE clause based on a key/value array, where the value can be represented by a scalar value which should match, or an array or an object with the properties 'comparision' and 'value'. The 'comparision' should be one of those tested in <db_is_valid_comparator>.

    • $conditions array

      Key/Value array with the conditions.

  • db_last_position ( string $tableName array $where string $positionColumnName ) : int

    Get the last (maximum) position for a given rows set.

    • $tableName string

      Table name.

    • $where array

      Where conditions as a key/value array.

    • $positionColumnName string

      Column name of the position (default 'position').

  • db_next_position ( string $tableName array $where string $positionColumnName ) : int

    Get the last (maximum) position for a given rows set, and at 1.

    • $tableName string

      Table name.

    • $where array

      Where conditions as a key/value array.

    • $positionColumnName string

      Column name of the position (default 'position').

  • db_set_position ( string $tableName int | string $itemId int | string $position array $where string $positionColumnName string $idColumnName ) : void

    Set a new position for a given element in a rows set.

    • $tableName string

      Table name.

    • $itemId int | string

      ID of the item we want to move.

    • $position int | string

      New position to set, as an index or a special position string: 'first', 'last', 'up' and 'down'.

    • $where array

      Where conditions as a key/value array.

    • $positionColumnName string

      Column name of the position (default 'position').

    • $idColumnName string

      Column name of the ID (default 'id').

  • db_clean_positions ( string $tableName array $where string $positionColumnName string $idColumnName ) : void

    Cleanup the positions for the given set.

    • $tableName string

      Table name.

    • $where array

      Where conditions as a key/value array.

    • $positionColumnName string

      Column name of the position (default 'position').

    • $idColumnName string

      Column name of the ID (default 'id').

  • db_search ( string $q string $mode array | null $includeTables int $queryOffset int | null $limitOffset ) : array

    Search in database, in all columns of all tables (or specified with $tables).

    • $q string

      Search term.

    • $mode string

      Search mode: equals, like or like_jokers.

    • $includeTables array | null

      Tables included for search.

    • $queryOffset int

      Select query offset.

    • $limitOffset int | null

      Select query limit (null for unlimited).

  • get_entity_id ( mixed $entity string | null $className string $propName bool $throw ) : int | null

    Returns the ID of a given entity. It will not check if the $entity is the proper entity, but returns an integer corresponding to what seems to be the ID, or null if the $entity cannot be matched to an integer or an object or a Microbe_Entity instance containing an ID.

    • $entity mixed

      [description]

    • $className string | null

      Name of the associated class. If given, the method fetchOneMixed will be called.

    • $propName string

      Property name.

    • $throw bool

      Throw exception if unable to get the ID.

  • db ( string | null $tableName string | null $alias ) : Microbe_Query_Builder

    Returns a new Microbe_Query_Builder instance, which can be instanciated with a specific table name and alias.

    • $tableName string | null

      Name of the first/main DB table.

    • $alias string | null

      Alias of this table.

  • db_migrations ( ) : array

    Returns an array containing the migrations files informations.

  • db_migration ( string $name ) : object | null

    Returns a database migration description, with parsed queries.

    • $name string

      Name of the migration.

  • db_split_queries ( ) : array

    Split queries separated with semicolons.

  • db_run_migration ( string $name string $side bool $standalone ) : void

    Execute a migration.

    • $name string

      Name of the migration

    • $side string

      Migration direction: 'up' or 'down'.

    • $standalone bool

      Execute only this migration if true. If false, all the missing previous migrations will be also run.

  • db_current_migration ( string | bool | null $name ) : string | null

    Get/Set the current migration name.

    • $name string | bool | null

      Optional name of the migration. If false, the current migration will be reset to none.

  • db_create_db_or_user_setup ( string $rootUser string $rootPassword string $ref ) : array

    Setup the database configuration for creating other MySQL databases and/or users.

    • $rootUser string

      The privileged-user's name.

    • $rootPassword string

      The privileged-user's password.

    • $ref string

      The database reference. Default is 'setupdb'.

  • db_create_user ( string $rootUser string $rootPassword ) : void

    Try to create the MySQL user.

    • $rootUser string

      The privileged-user's name.

    • $rootPassword string

      The privileged-user's password.

  • db_create_db ( ) : void

    Try to create the MySQL database.

deploy

Functions

  • deploy ( bool | null $log ) : void

    Deploy (git pull).

    • $log bool | null

      Log result. If null, config value is used.

  • get_last_commit ( ) : object

    Get the last commit information.

deprecated

Functions

  • deprecated ( string $funcName string $type string $reason ) : void

    Display a deprecation message.

    • $funcName string

      Function name.

    • $type string

      Type of error: warning or fatal.

    • $reason string

      String representing the error and/or the migration.

  • warning_deprecated ( string $funcName string $reason ) : void

    Display a warning deprecation message.

    • $funcName string

      Function name.

    • $reason string

      String representing the error and/or the migration.

  • fatal_deprecated ( string $funcName string $reason ) : void

    Display a fatal deprecation message.

    • $funcName string

      Function name.

    • $reason string

      String representing the error and/or the migration.

  • dev_cookie_name ( ) : void

    <DEPRECATED> / // ============================================================================= // ----------------------------------------------------------------------------- // -- {# Ending DEPRECATED #} -- // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- // -- {# Beginning DEV #} -- // ----------------------------------------------------------------------------- // ============================================================================= // ---{ Functions }------------------------------------------------------------- /** Returns the name of the cookie used for developer tools authentication.

  • dev_is_allowed ( bool $checkCookie ) : bool

    Check if the current visitor is allowed to access dev tools.

    • $checkCookie bool

      Check also if the cookie allows dev access.

  • dev_console ( ) : void

    Generate the console page for developers.

  • dev_render_console ( array $vars ) : void

    Render the HTML of the console page for developers.

    • $vars array

      Template variables.

dom

Functions

  • dom ( string $tag ) : Microbe_DOM_Element

    Returns a Microbe_DOM_Element, helping to build HTML elements.

    • $tag string

      Tag name, optionnaly containing classes and ID as . and # suffixes.

  • get_pagination_numbers ( int $page int $total ) : array

    Returns an array containing the useful pages numbers, and null entries for ellipsis.

    • $page int

      Current page number.

    • $total int

      Total pages.

  • pagination ( string $var string | null $url int $totalItems int $itemsPerPage ) : Microbe_Pagination

    Create a Microbe_Pagination instance.

    • $var string

      Variable name.

    • $url string | null

      Url format (default: url('.', [ $var => '{{page}}' ])).

    • $totalItems int

      Total items of the collection.

    • $itemsPerPage int

      Items shown per page.

emails

Functions

  • is_valid_email_address ( mixed $email ) : boolean

    Check if the email address is valid.

    • $email mixed

      String supposed to be an email address.

  • parse_email_addresses ( string $str ) : array

    Parse several email addresses using <parse_email_address> for each one.

    • $str string

      String to parse.

  • parse_email_address ( string $str ) : object

    Parse an email address, with optionally the name and the address.

    • $str string

      String to parse.

  • get_email_address_user_name ( string $str bool $formatted ) : string | null

    Parse email address, get its left part, and optionnaly tries to format the username.

    • $str string

      String to parse (perhaps an email address).

    • $formatted bool

      Tries to format the username.

  • obfuscate_email_address ( string $email ) : string

    Obfuscate the characters of an email address except the two firsts of the username and the @... part.

    • $email string

      Email address

  • register_email_carrier ( string $name Closure $func ) : void

    Register an email carrier.

    • $name string

      Name of the carrier.

    • $func Closure

      Function called when sending an email through this carrier. $func should take three arguments:

      object $cfg

      object $opts

      string $body

      array $embeddedImages

  • get_current_email_carrier ( ) : object | null

    Returns the email carrier object currently in use.

  • send_email ( ) : bool

    Send an email.

  • process_embedded_email_body ( string $body boolean $debug ) : object

    Process the body string, to find the src="@cid{...}" or src="@base64{...}" images and process it. An object with the new body and the @cid attachments will be returned. The @cid will be replaced by a src="cid:{sha1_of_the_path}", and this identifier will be returned as a key of the returned attachments, with the file path as a value. The @base64 images will be replaced by an inline src, base64 encoded.

    • $body string

      Body string.

    • $debug boolean

      If the debug mode is enabled, the image will be kept unchanged, to be able to see it in a browser display.

  • get_stored_emails ( string $ym ) : array

    Returns an array of stored emails (years-months or HTML files).

    • $ym string

      Year-Month. If not provided, available years-months will be returned instead of HTML files.

env

Functions

  • get_valid_env ( ) : array

    Returns an array of valid environments names.

  • is_valid_env ( string $env ) : boolean

    Check if the given environment name is a valid one.

    • $env string

      Environment name.

  • get_env ( ) : string

    Get and returns the current environment, based on the '/ENV' file. If this file is not found, or empty, 'prod' will be returned.

  • set_env ( ) : void

    Set current environment via /ENV file.

  • is_env ( string... $envs ) : boolean

    Check if the current environment is one of those given in arguments.

    • $envs string...

      Environment name (or several, as different args).

  • get_root_dir ( ) : string

    Returns the directory where the framework's file is located, which is assumed to be the root directory of the project.

  • join_path ( string... $paths ) : string

    Join paths parts together, using the system's directory separator (/ or \), and returns the result.

    • $paths string...

      Paths parts as separated arguments.

  • get_path ( string... $paths ) : string

    Join paths parts together exactly like <join_path>, but prefixing the root directory got through <get_root_dir>.

    • $paths string...

      Paths parts as separated arguments.

  • get_vendor_dir ( string... $paths ) : string

    Returns the vendor directory.

    • $paths string...

      Optional sub-paths parts as separated arguments.

  • get_vendor_static_dir ( string... $paths ) : string

    Returns the vendor-static directory.

    • $paths string...

      Optional sub-paths parts as separated arguments.

  • get_src_dir ( string... $paths ) : string

    Returns the backend directory.

    • $paths string...

      Optional sub-paths parts as separated arguments.

  • get_ctrl_dir ( string... $paths ) : string

    Returns the controllers directory.

    • $paths string...

      Optional sub-paths parts as separated arguments.

  • get_data_dir ( string... $paths ) : string

    Returns the data directory.

    • $paths string...

      Optional sub-paths parts as separated arguments.

  • get_uploads_dir ( string... $paths string... $paths ) : string

    Returns the sessions directory.

    • $paths string...

      Optional sub-paths parts as separated arguments.

    • $paths string...

      Optional sub-paths parts as separated arguments.

  • get_cache_dir ( string... $paths ) : string

    Returns the cache directory.

    • $paths string...

      Optional sub-paths parts as separated arguments.

  • get_cache_file ( string... $parts ) : string

    Returns a cache file path.

    • $parts string...

      File name with extension, with optionaly some directories before.

  • get_tmp_dir ( string | null $sub ) : string

    Returns the directory path for the temporary files, optionaly with a subdirectory (which will be created if it doesn't exists).

    • $sub string | null

      Subdirectory name.

  • get_tmp_file ( string | null $name string | null $sub string | null $ext ) : string

    Returns a temporary file path.

    • $name string | null

      File name. Random string if empty.

    • $sub string | null

      Subdirectory name. Temp directory root if empty.

    • $ext string | null

      File extension.

  • include_dir ( string $dir bool $once ) : void

    Include all PHP files of a directory.

    • $dir string

      Directory path.

    • $once bool

      Default true. If true, the file will be required using 'require_once'. In other case, it will be 'require'.

  • include_root_files ( string $type bool $once ) : void

    Includes specific file type (helpers, ctrl, etc.) located at root.

    • $type string

      Type of file (helpers, ctrl, etc.).

    • $once bool

      Require once instead of simply require.

  • include_files ( string $type bool $once ) : void

    Includes specific files type (helpers, ctrl, etc.), from root and bundles.

    • $type string

      Type of file (helpers, ctrl, etc.).

    • $once bool

      Require once instead of simply require.

  • get_domain_name ( ) : string

    Returns the current domain name, aka HTTP hostname.

  • is_domain_name ( string $pattern ) : boolean

    Verify is the result of <get_domain_name> match with the string or the regex pattern given.

    • $pattern string

      String or regex pattern (beginning and ending with a slash, with optionnaly some letters at the end).

  • get_top_level_domain_name ( ) : string

    Returns the top level domain name (e.g. when <get_domain_name> will be 'foo.bar.tld' or 'john.doe.bar.tld', this function will return 'bar.tld'). This function can be useful with the cookies policies.

  • get_http_scheme ( ) : string

    Returns the current HTTP scheme: https:// or http://.

  • is_ssl ( ) : boolean

    Returns true if the current HTTP scheme is HTTPS. Else, false.

  • get_base_url ( ) : string

    Returns the base URL, based on the $_SERVER's SCRIPT_NAME. Generally, the server configuration should redirect every request (except for existing files) to the 'index.php'. This function retrieve the directory URL to the called file, so 'index.php' and returns it. If the app is working at the root of the server (at the domain name level), an empty string will be returned. Else, the subdirectories will be returned.

  • path_to_url ( string $path bool $host ) : string

    Convert an absolute path into a URL.

    • $path string

      Absolute path to a file or a directory.

    • $host bool

      Include host in URL.

  • url_to_path ( string $url string | bool $validateHost ) : string | null

    Convert a URL to a local path.

    • $url string

      URL to process.

    • $validateHost string | bool

      Validate the host if the URL contains one. If true, the current host will be used. If false, every host will be allowed. If a string, it should be a regexp.

  • get_request_url ( bool $full ) : string

    Returns the requested URL, as given by the server.

    • $full bool

      Returns the URL with scheme and domain, or only path.

  • get_referer_url ( ) : string | null

    Returns the referer URL if available.

  • get_request_path ( bool $trimmed ) : string

    Returns the current URL, without query strings.

    • $trimmed bool

      If true, trim the slashes.

  • get_relative_path ( string $path ) : string

    Returns the requested path, relatively to the project root. The given path should be located insidide the project folder.

    • $path string

      Absolute path to relativize.

  • get_relative_url ( bool $keepQueryString ) : string

    Returns the requested URL, based on <get_request_url>, relatively to the base URL of the app got using <get_base_url>.

    • $keepQueryString bool

      Keep or strip the query strings from the URL.

  • get_http_method ( ) : string

    Returns the HTTP method (GET, POST, PUT or DELETE).

  • is_http_method ( string $method ) : boolean

    Returns true if the current HTTP method is the one given.

    • $method string

      Method to compare.

  • is_post ( ) : boolean

    Returns true if the current HTTP method is POST.

  • is_xhr ( ) : boolean

    Returns true if the browser sent the headers of a XMLHTTPRequest, aka ajax request.

  • get_remote_ip ( ) : string | null

    Returns the client IP address, as given by the server.

  • get_user_agent ( ) : string | null

    Returns the user agent of the visitor.

  • get ( string | array | null $k string $method boolean $trim ) : mixed

    Get the variable given in argument from the POST or GET data. If the argument is an array of variable names, an associative array will be returned with all the corresponding values from POST or GET.

    • $k string | array | null

      Variable(s) name(s).

    • $method string

      Variables passing methods ('both', 'get' or 'post')

    • $trim boolean

      Trim string values.

  • get_queried ( string | array $k boolean $trim ) : mixed

    Getting the variable given in argument from the GET data. Does exactly the same as <get()>, but only get data from GET, not from POST.

    • $k string | array

      Variable(s) name(s).

    • $trim boolean

      Trim string values.

  • get_posted ( string | array $k boolean $trim ) : mixed

    Getting the variable given in argument from the POST data. Does exactly the same as <get()>, but only get data from POST, not from GET.

    • $k string | array

      Variable(s) name(s).

    • $trim boolean

      Trim string values.

  • get_func_casted ( string | array $k Closure $modifier bool $nullable array $nullValues string $method ) : mixed

    • $k string | array

      Key or array of keys to get with <get()>.

    • $modifier Closure

      Modifier function. Takes two params: the value and the key.

    • $nullable bool

      Returns null if string is empty.

    • $nullValues array

      Nullable values.

    • $method string

      Method used by <get>.

  • get_str ( string | array $k bool $trim bool $nullable string $method ) : null | string | object

    Get the variable(s), cast it to trimed string.

    • $k string | array

      Key or array of keys to get with <get()>.

    • $trim bool

      Trim the value.

    • $nullable bool

      Returns null if string is empty.

    • $method string

      Method used by <get>.

  • get_nullable_str ( string | array $k bool $trim ) : null | string | object

    Get the variable(s) with <get_str()>, but returns null as value if the string is empty.

    • $k string | array

      Key or array of keys to get with <get()>.

    • $trim bool

      Trim the value.

  • get_number ( string | array $k bool $int int | float | null $min int | float | null $max bool $nullable array $nullValues string $method ) : null | int | float | object

    Get the variable(s), cast it to a number.

    • $k string | array

      Key or array of keys to get with <get()>.

    • $int bool

      Don't allow floating values.

    • $min int | float | null

      Minimum value.

    • $max int | float | null

      Maximum value.

    • $nullable bool

      Returns null if string is empty.

    • $nullValues array

      Nullable values.

    • $method string

      Method used by <get>.

  • get_int ( string | array $k int | float | null $min int | float | null $max bool $nullable array $nullValues string $method ) : null | int | float | object

    Get the variable(s), cast it to an integer.

    • $k string | array

      Key or array of keys to get with <get()>.

    • $min int | float | null

      Minimum value.

    • $max int | float | null

      Maximum value.

    • $nullable bool

      Returns null if string is empty.

    • $nullValues array

      Nullable values.

    • $method string

      Method used by <get>.

  • get_nullable_int ( string | array $k int | float | null $min int | float | null $max array $nullValues string $method ) : null | int | float | object

    Get the variable(s), cast it to an integer, in nullable mode.

    • $k string | array

      Key or array of keys to get with <get()>.

    • $min int | float | null

      Minimum value.

    • $max int | float | null

      Maximum value.

    • $nullValues array

      Nullable values.

    • $method string

      Method used by <get>.

  • get_is ( string $k string $method ) : boolean

    Check if the given POST/GET param seems to be equivalent to a true, aka 1, (y)es or (t)rue.

    • $k string

      Variable name.

    • $method string

      Variables passing methods ('both', 'get' or 'post').

  • get_in ( string $k array $values mixed $default string $method ) : mixed

    Get the given POST/GET param and check if its value is one of those specified with $values. If not, $default will be returned.

    • $k string

      Variable name.

    • $values array

      Allowed values.

    • $default mixed

      Value returned.

    • $method string

      Variables passing methods ('both', 'get' or 'post').

  • get_date ( string $k ) : DateTime | null

    Get the POST/GET param $k and tries to build the DateTime object.

    • $k string

      Variable name.

  • get_datetime ( string $kd string | null $kt string | DateTimeZone | null $timezone ) : DateTime | null

    Get the POST/GET param $kd and tries to build the DateTime object. If $kt is given, it should corresponds to the time variable name.

    • $kd string

      Date or datetime variable name.

    • $kt string | null

      Time variable name.

    • $timezone string | DateTimeZone | null

      Optional timezone.

  • get_multiple ( string $k ) : array

    Get some query-string passed values, which use the same name. E.g. foo.html?a=foo&a=bar&b=john => a=[foo,bar]

    • $k string

      Variable name.

  • get_assoc_array ( string | array $k string $method ) : array

    Get the variable given in argument from the POST or GET data, then cast it to an associative array. If no variable match, or the value is not a valid associative array, an empty array will be returned.

    • $k string | array

      Variable name.

    • $method string

      Variables passing methods ('both', 'get' or 'post')

  • get_queried_assoc_array ( string | array $k ) : mixed

    Getting the variable given in argument from the GET data and cast it as an array. Does exactly the same as <get_assoc_array()>, but only get data from GET, not from POST.

    • $k string | array

      Variable(s) name(s).

  • get_posted_assoc_array ( string | array $k ) : mixed

    Getting the variable given in argument from the POST data and cast it as an array. Does exactly the same as <get_assoc_array()>, but only get data from POST, not from GET.

    • $k string | array

      Variable(s) name(s).

  • cast_posted_data ( mixed $data bool $trim string $separator string $key ) : mixed

    Execute <cast_data> on $_POST.

    • $data mixed

      Pattern of the data we are waiting for.

    • $trim bool

      Trim string values or not (default true)?

    • $separator string

      Chained keys separator (when default one may be found in one of the key names).

    • $key string

      Current walking key. Internal use only.

  • cast_queried_data ( mixed $data bool $trim string $separator string $key ) : mixed

    Execute <cast_data> on $_GET.

    • $data mixed

      Pattern of the data we are waiting for.

    • $trim bool

      Trim string values or not (default true)?

    • $separator string

      Chained keys separator (when default one may be found in one of the key names).

    • $key string

      Current walking key. Internal use only.

  • get_page_number ( mixed $page string $var int $default int | null $max int $min ) : int

    Get the queried or posted page number, and cast the value to get an integer between $min and $max, with a $default value.

    • $page mixed

      Value to process. If null, the value will be got from $_GET or $_POST with the key $var.

    • $var string

      Var name corresponding to the page number requested.

    • $default int

      Default page number.

    • $max int | null

      Maximum page number.

    • $min int

      Minimum page number.

  • validate ( array $fields boolean $dataAsArray ) : array

    Validate some GET/POST parameters based on the rules given in the array, then return the casted data and the errors if exists.

    • $fields array

      Numerical array containing each field and its rules, as a Closure getting the value as first parameter, and returning an error as a string or nothing if the rule passed. A special '@' key can be included, to cast the value. In this case, the return of the Closure will be the casted value.

    • $dataAsArray boolean

      Returns the data as an array instead of an object.

errors

Functions

  • register_custom_error_handler ( int $errorCode Closure $func array | null $environments ) : void

    Register a custom error callback function, based on an error code.

    • $errorCode int

      Error code: basically 403, 404 or 500.

    • $func Closure

      Callback function, executed when the $errorCode is thrown somewhere.

    • $environments array | null

      Option environments array: when the current environment is not in this list, the callback will not be called.

  • get_logged_errors_files ( string $type string | null $year string | null $month bool $reverse ) : array

    List error files.

    • $type string

      Type of error (500, 404, 403).

    • $year string | null

      Filter by year.

    • $month string | null

      Filter by month.

    • $reverse bool

      Reverse files (default true: recent first).

  • get_logged_errors ( string $type string $year string $month string $day int | null $limit bool $reverse ) : array

    Returns logged error for a specific error type and date.

    • $type string

      Type of error (500, 404, 403).

    • $year string

      File's year.

    • $month string

      File's month.

    • $day string

      File's day.

    • $limit int | null

      Limit results. Null for no limit.

    • $reverse bool

      Reverse results: recent first.

  • get_errors_file_path ( string $type string $year string $month string $day ) : string | null

    Returns path of error log file.

    • $type string

      Type of error (500, 404, 403).

    • $year string

      File's year.

    • $month string

      File's month.

    • $day string

      File's day.

  • log_error ( string $type string | null $message ) : void

    Log error in local file.

    • $type string

      Error type: 404, 403 or 500.

    • $message string | null

      Optional message.

  • parse_eror_line ( string $line ) : object

    Parse an error line got from a log file.

    • $line string

      Line as a string.

  • throw_403 ( string | null $message ) : void

    Throw a 403 error, with the registered custom handler or with a system message. Generally reached after a catching of an 'Microbe_Unauthorized_Exception'.

    • $message string | null

      Message to pass to the handler or to show in the system message.

  • throw_404 ( string | null $message ) : void

    Throw a 404 error, with the registered custom handler or with a system message. Generally reached after a catching of a 'Microbe_NotFound_Exception'.

    • $message string | null

      Message to pass to the handler or to show in the system message.

  • throw_500 ( array $err bool $isExternal string | null $message ) : void

    Throw a 500 error, with the registered custom handler or with a system message. Generally reached after a catching of any 'Exception' which is not an 'Microbe_Unauthorized_Exception' or an 'Microbe_NotFound_Exception'. In the case of an 'Microbe_Exception' which means an 'Exception' sent through this framework or the friends of it, $isExternal will stay false. When it's reached from an unmanaged Exception, $isExternal will be true.

    • $err array

      Error details, generally given from an 'Error' or an 'Exception' instance.

    • $isExternal bool

      Is it an error caught from a 'Microbe_Exception' or not?

    • $message string | null

      Message to pass in the $err array.

  • html_backtrace_file_path ( string | null $path int | null $line ) : string | null

    Generate the HTML string for a file path entry, separating the relative URL from root and the other part of the absolute path, then appending the line number.

    • $path string | null

      File path.

    • $line int | null

      Line number.

  • handle_error ( Exception | Error | int | null $exception ) : void

    Errors callback, used by <set_exception_handler>, <set_error_handler> and <register_shutdown_function>.

    • $exception Exception | Error | int | null

      Error, exception or exit code.

  • html_error_block ( string $str ) : string

    Returns a HTML string, representing a red <div/> with the $str message.

    • $str string

      Error message.

files

Functions

  • get_mkdir_chmod ( ) : int

    Returns 0755, aka the default new directory chmod.

  • get_new_file_chmod ( ) : int

    Returns 0644, aka the default new file chmod.

  • file_seems_ascii ( string $path ) : bool

    Check if the path or the file name extension is not one of known non-ASCII extensions.

    • $path string

      Path or file name.

  • guess_file_type ( string $path ) : string | null

    Returns file type based on extension.

    • $path string

      Path or file name.

  • rmkdir ( string $path ) : void

    Create recursively a directory.

    • $path string

      Path of directory to create

  • sanitize_filename ( string $name string $separator int $maxLength ) : string

    Sanitize a filename, removing special characters and accents, and shortifying the name if too long.

    • $name string

      Original file name.

    • $separator string

      Separator used in replacement of non-alphanumerical characters.

    • $maxLength int

      Maximum length of the part before the extension.

  • filename_seems_secure ( mixed $name ) : bool

    Check if a filename seems secure, without slashes, double dots, control characters, banned Windows characters and NULL character.

    • $name mixed

      Filename (should probably be a string).

  • hashed_filename ( string $str ) : string | null

    Returns a hashed string, suffixed optionnaly with an extension, in order to use as a filename. We replace the 'c' followed by a 'd', by a 'f' to avoid sometimes problematic 'cd'.

    • $str string

      String to hash.

  • bytes_unit ( float $size string $from string | null $to bool $asConfig ) : string

    Convert a size into a human-readable value. The input size and the output size can be one of those units:

    B: bytes

    KB: kilobytes

    MB: megabytes

    GB: gigabytes

    TB: terabytes

    PB: petabytes

    • $size float

      Size.

    • $from string

      Input unit.

    • $to string | null

      Output unit. If null, the detection will be made to find the most readable unit.

    • $asConfig bool

      Remove spaces and 'B', to make a string usable for PHP or server configuration.

  • size_string_to_bytes ( string | int | float $size ) : int

    Returns the bytes value of an input size, which can be suffixed with one of the units returned by <bytes_unit>. E.g. '345.67MB' will return 345670000.

    • $size string | int | float

      Size suffixed or not with a unit.

  • get_file_hash ( string $path bool $force string $algo bool $store ) : string

    Get hash for the given file.

    • $path string

      File path.

    • $force bool

      Force hash computing even if already stored.

    • $algo string

      Hashing algorithm.

    • $store bool

      Store computed hash.

  • get_file_extension ( string $f bool $dot bool $lower ) : string

    Returns the file's extension.

    • $f string

      File name or path.

    • $dot bool

      Prepend the dot before the extension. Default false.

    • $lower bool

      Lowercase the extension. Default false.

  • is_file_extension ( string $f string | array $ext ) : boolean

    Returns true if the file extension corresponds to the given one(s).

    • $f string

      File name or path.

    • $ext string | array

      Extension or array of extensions.

  • remove_extension ( string $f ) : string

    Removes a file's extension.

    • $f string

      File name or path.

  • get_path_owner ( string $path ) : array

    Returns an array containing the owner of a path (file or directory).

    • $path string

      Path to the file or directory.

  • get_path_perms_octal_string ( string $path ) : string | null

    Returns the file/directory permissions as octal string (0644, 0777, etc.).

    • $path string

      Path to the file or directory.

  • get_path_perms_readable_string ( string $path ) : string | null

    Returns the file/directory permissions as a human readable string.

    • $path string

      Path to the file or directory.

  • is_valid_subpath ( string $path string $root boolean $rootAllowed ) : boolean

    Check if a given path is a valid path to a file or a folder, and if this file is properly located inside a root directory.

    • $path string

      Path to be checked.

    • $root string

      Base directory.

    • $rootAllowed boolean

      Does $path can be $root itself?

  • get_file_name_parts ( string $f bool $includingDot ) : array

    Returns the file name as an array containing the name and the extension.

    • $f string

      File name.

    • $includingDot bool

      Include the extension's dot or not.

  • get_max_upload_size ( string | null $ctx ) : int

    Get the maximum upload size, based on the PHP configuration ('post_max_size' and 'upload_max_filesize'), and an optional configuration context defined with the configuration key '@upload.{ctx}.max_size'.

    • $ctx string | null

      Context.

  • get_max_config_upload_size ( ) : int | null

    Get the maximum upload size requested by configuration.

  • get_uploaded_files ( string $name bool $one ) : object | array | null

    Get uploaded files metadata, from $_FILES.

    • $name string

      Name of the posted file field.

    • $one bool

      If false (default), it will return the uploaded file metadata as an array of objects representing each uploaded file with the given post name.

  • get_uploaded_file ( string $name ) : object | null

    Get uploaded file metadata, from $_FILES, using <get_uploaded_files> with $one as true.

    • $name string

      Name of the posted file field.

  • save_uploaded_file ( object $file string $path bool $mkdir ) : bool

    Move the uploaded file from its temporary path to the given one, and create the subdirectories if asked and needed.

    • $file object

      File object got from <get_uploaded_file> or <get_uploaded_files>.

    • $path string

      Path where the file will be saved (new file's path).

    • $mkdir bool

      Make the (sub)directories if doesn't exists.

  • upload_file ( object $file array $opts ) : string

    Perform the file upload, based on the file object got from <get_uploaded_files>. If an error occur, an 'ErrorException' will be thrown. The options are the following:

    'path': The path of the new file.

    'keep_filename': If true, the 'path' will be considerated as a directory and the file will be stored inside this directory with its sanitized uploaded file name. If false, the 'path' will be kept as the new file path. Default: true.

    'keep_extension': If true, the extension of the uploaded will be kept, and the extension given in 'path' will be ignored. Default: true.

    'letters_folders_levels': Append X levels of letter folders (e.g. when 2: '/path/to/images/a/b/abc.jpg'). Missing folders will be created. Default: 0.

    'iterate_filename': Iterate to the file name if conflict. Default: true.

    'iterate_format': Iteration suffix format. Default: '_%s'.

    'default_folders_chmod': Default: the result of <get_mkdir_chmod>.

    'default_files_chmod': Default: the result of <get_new_file_chmod>.

    • $file object

      Upload file object.

    • $opts array

      Upload options.

  • get_unique_file_path ( string $path string $separator ) : string

    Check if $path is already a file. If yes, an increment will be added to the end of the name, before the extension.

    • $path string

      File path.

    • $separator string

      Separator between the filename and the iteration.

  • is_dir_empty ( string $dir ) : boolean

    Check if the directory $dir is empty or not.

    • $dir string

      Directory path.

  • get_folder_size ( string $path bool $readable ) : int | string

    Compute directory size.

    • $path string

      Directory path.

    • $readable bool

      Returns readable size or not.

  • rrmdir ( string $dir bool $deleteRoot Closure | null $filter string | null $rootDir ) : void

    Remove a directory and its files recursively.

    • $dir string

      Path to directory.

    • $deleteRoot bool

      Delete also the directory $dir itself.

    • $filter Closure | null

      Filter function, which will accept the path of the item processed. If this function returns true, the file or the directory will be deleted. If false, the item will be kept.

    • $rootDir string | null

      Path to the original directory (the initial value of $dir).

  • shortify_file_name ( string $name int | null $maxLength ) : string

    Make a file name shorter, by removing middle characters.

    • $name string

      File name.

    • $maxLength int | null

      Maximum length. If null, the file name will not be truncated.

  • force_download ( string $path ) : void

    Send a file to the browser, with proper headers to force the download.

    • $path string

      Path to the file

  • ls ( string $path bool $files bool $folders string | null $filter ) : array

    List files and folders inside a directory.

    • $path string

      Path to directory.

    • $files bool

      Retrieve files.

    • $folders bool

      Retrieve folders.

    • $filter string | null

      Filter regex.

  • get_files ( string $path string | null $filter ) : array

    List files inside a directory.

    • $path string

      Path to directory.

    • $filter string | null

      Filter regex.

  • get_folders ( string $path string | null $filter ) : array

    List folders inside a directory.

    • $path string

      Path to directory.

    • $filter string | null

      Filter regex.

  • tail_file ( string $path int $lines ) : array

    Read $lines lines from the end of the file.

    • $path string

      Path of file to read.

    • $lines int

      Number of lines to get.

  • head_file ( string $path int $lines ) : array

    Read $lines lines from the beginning of the file.

    • $path string

      Path of file to read.

    • $lines int

      Number of lines to get.

  • get_latest_modified_file_time ( string $dir ) : DateTime

    Returns the latest modified file time in a given directory.

    • $dir string

      Directory path.

  • get_file ( string $path ) : Microbe_File

    Returns a new instance of Microbe_File.

    • $path string

      Path to file.

forms

Functions

  • form ( string | null $name ) : Microbe_Form

    Returns a new Microbe_Form instance.

    • $name string | null

      Name of the form (useful for storing results).

  • form_field ( string $type Microbe_Form_Element | null $parent ) : Microbe_Form_Field

    Returns a new Microbe_Form_Field instance with a specific type.

    • $type string

      One of Microbe_Form_Field::T_*.

    • $parent Microbe_Form_Element | null

      Parent as a Microbe_Form_Element instance.

  • get_form ( string $name array $args ) : Microbe_Form

    Get a form defined in a form file (located in the forms folder of each bundle). The name of the form is the name of the file. The file has to return a Microbe_Form instance, and receive optional variables given by $args.

    • $name string

      Name of form file.

    • $args array

      Args passed to file before including it.

framework

Functions

  • get_microbe_file_path ( ) : string

    Returns the Microbe file path.

  • get_microbe_file_name ( ) : string

    Returns the Microbe file name.

  • microbe_version ( ) : object

    Returns the version and hashes of the framework.

  • get_microbe_version_meta_hash ( string $raw ) : string | null

    Parse the source code to find the meta hash.

    • $raw string

      Source code of the framework.

  • get_microbe_version_hash ( string $raw ) : string | null

    Parse the source code to find the source code hash.

    • $raw string

      Source code of the framework.

  • get_microbe_version_number ( string $raw ) : int | null

    Parse the source code to find the version number.

    • $raw string

      Source code of the framework.

  • get_microbe_version_date ( string $raw ) : DateTime | null

    Parse the source code to find the version date.

    • $raw string

      Source code of the framework.

  • microbe_api_url ( string $do array $args ) : string

    Generate an API URL for framework requests (e.g. Updates and Plugins Warehouse).

    • $do string

      Action to perform on the API.

    • $args array

      Optional query-string arguments.

  • get_available_updates ( ) : array | null

    Retrieve the available updates from the framework's API, based on current framework and plugins versions.

  • update_framework ( string $url ) : bool

    Perform an update on the framework itself.

    • $url string

      Download URL got from <get_available_updates>.

geo

Functions

  • dms_coordinate_to_decimal ( string | int $deg int | null $min float | null $sec string | null $dir ) : float

    Convert a coordinate given as a string or a set of degrees, minutes, seconds and direction, to a decimal coordinate.

    • $deg string | int

      Coordinate string (e.g. 1°2'3.456"W) or degrees as an integer.

    • $min int | null

      If $deg is not a string: the minutes.

    • $sec float | null

      If $deg is not a string: the seconds.

    • $dir string | null

      If $deg is not a string: the direction (N, S, W/O, E). $deg can also be signed, and $dir ignored.

  • dec_coordinate_to_dms ( string $type float $dec bool $asString int $round ) : string | object

    Convert a decimal coordinate to a string like 1°2'3.456"W.

    • $type string

      (lat)itude or (lon)gitude.

    • $dec float

      Decimal coordinate.

    • $asString bool

      Returns a string (default) or an object containing direction/degrees/minutes/seconds.

    • $round int

      Round the seconds.

  • dec_lat_to_dms ( float $dec bool $asString int $round ) : string | object

    Execute <dec_coordinate_to_dms()> with $type = 'lat'.

    • $dec float

      Decimal coordinate.

    • $asString bool

      Returns a string (default) or an object containing direction/degrees/minutes/seconds.

    • $round int

      Round the seconds.

  • dec_lon_to_dms ( float $dec bool $asString int $round ) : string | object

    Execute <dec_lon_to_dms()> with $type = 'lon'.

    • $dec float

      Decimal coordinate.

    • $asString bool

      Returns a string (default) or an object containing direction/degrees/minutes/seconds.

    • $round int

      Round the seconds.

  • get_coordinates_box ( float $lat float $lon int | null $radius ) : object

    Create a box of coordinates, based on a center latitude and longitude, optionaly enlarged with a radius. Based on: 1 latitude-deg = 110574 (meters) 1 longitude-deg = 111320 * cos(latitude) (meters)

    • $lat float

      Decimal latitude.

    • $lon float

      Decimal longitude.

    • $radius int | null

      Radius in meters.

images

Functions

  • is_image_path ( string $path array $extensions ) : bool

    Check if the given path extension corresponds to a valid image file.

    • $path string

      Path to the file.

    • $extensions array

      Array of allowed extensions.

  • get_pixel_image ( ) : string

    Returns raw data of a PNG image containing a single transparent pixel.

  • resize_image ( string $src string | null $dst int | null $width int | null $height string $mode int $outputQuality mixed $paddingColor bool $mkdir string $method ) : Imagick | null

    Resize an image.

    • $src string

      Source image path.

    • $dst string | null

      Destination path. If null, nothing is written, and the Imagick instance is returned.

    • $width int | null

      Destination width. If null, $width = $height. At least width or height must be provided.

    • $height int | null

      Destination height. If null, $height = $width. At least width or height must be provided.

    • $mode string

      Cropping mode (MB_IMAGE_RESIZE_*).

    • $outputQuality int

      Output quality (0-100).

    • $paddingColor mixed

      Padding color, when mode is "contains".

    • $mkdir bool

      Make directories recursively if needed.

    • $method string

      Image generation method: "imagick".

  • output_image_file ( string $path ) : void

    Read the image file with the proper content type. It will guess automatically the content type.

    • $path string

      Image path

  • image_create ( string $path ) : GdImage | null

    Load the GdImage instance from image path. It will guess automatically the file type.

    • $path string

      Image path

  • image_save ( GdImage $im string $path int $quality ) : void

    Save the GdImage to given path, guessing automatically the output file type.

    • $im GdImage

      GdImage instance.

    • $path string

      Destination path.

    • $quality int

      Image quality if appliable.

  • get_resized_image_path ( string $path int | null $width int | null $height string $mode int $outputQuality bool $force ) : string | null

    Resize an image and returns the path of the created file.

    • $path string

      Path of source image.

    • $width int | null

      Destination width. If null, $width = $height. At least width or height must be provided.

    • $height int | null

      Destination height. If null, $height = $width. At least width or height must be provided.

    • $mode string

      Cropping mode (MB_IMAGE_RESIZE_*).

    • $outputQuality int

      Output quality (0-100).

    • $force bool

      Force cache refreshing.

  • get_resized_image_url ( string $path int | null $width int | null $height string $mode int $outputQuality bool $force ) : string | null

    Resize an image width <get_resized_image_path()> and returns the URL of the created file.

    • $path string

      Path of source image.

    • $width int | null

      Destination width. If null, $width = $height. At least width or height must be provided.

    • $height int | null

      Destination height. If null, $height = $width. At least width or height must be provided.

    • $mode string

      Cropping mode (MB_IMAGE_RESIZE_*).

    • $outputQuality int

      Output quality (0-100).

    • $force bool

      Force cache refreshing.

  • get_thumbnail_path ( string $path int $size ) : string | null

    Create a thumbnail of an image image and returns its path.

    • $path string

      Path of source image.

    • $size int

      Thumbnail width and height.

  • get_thumbnail_url ( string $path int $size ) : string | null

    Create a thumbnail of an image image and returns its URL.

    • $path string

      Path of source image.

    • $size int

      Thumbnail width and height.

  • generate_random_image ( int $width null | int $height null | string $path int $maxShapes string $output ) : void

    Generate a random image.

    • $width int

      Width of image.

    • $height null | int

      Height of image. Default is equals to width.

    • $path null | string

      Path to save file. If null, the image will be rendered in the browser.

    • $maxShapes int

      Maximum number of shapes. More: the image will be more complex. Less: the image will be faster to render.

    • $output string

      Output mode. 'auto' will switch between direct rendering or saving to $path if provided. Possible values are:

      auto

      display: display in browser

      write: write to $path

      gd: returns GdImage instance

      raw: returns image's raw code

      base64: returns image base64-encoded

intl

Functions

  • get_accepted_locales ( ) : array

    Retrieve the accepted languages sent by the browser, parse it and try to match with the locales handled by the framework.

  • get_app_locales ( bool $force ) : array

    Returns an array containing the valid locales existing in the configuration file. The locale will be constructed from the countries and the languages codes, then the valid ones will be returned.

    • $force bool

      Force the renewing of the locales in the memory cache.

  • get_app_locale ( string $locale ) : null | object

    Returns a specific app locale. The returned locale will be one of the locales defined in the configuration file.

    • $locale string

      Locale code.

  • get_default_app_locale ( ) : null | object

    Get the app locales using <get_app_locales()> and returns the default one.

  • get_current_app_locale ( ) : null | object

    Returns the current locale, based on:

    user configured locale, stored in cookie;

    first valid browser's accepted locale;

    default locale.

  • set_current_app_locale ( string $locale ) : void

    Set current app locale in cookies.

    • $locale string

      Locale code.

  • get_translate_vars ( ) : array

    Returns translation variables.

  • set_translate_vars ( array $vars ) : void

    Set translation variables, which will be applied on each string passed to <t()>.

    • $vars array

      Key-value array of variables.

  • locale ( string | null $locale ) : void

    Declare current locale in use with <t()>.

    • $locale string | null

      Locale name.

  • get_translations_locale ( ) : string

    Returns the current locale name for translatable strings through <t()>.

  • t ( string | array $format array | string $vars string | null $fromLocale string | null $toLocale ) : string

    Translate a string, with an optional formatting of the string with the passed variables.

    • $format string | array

      String to translate. If an array is given, this array have to be a numerical-keys array with 1, 2 or 3 entries. If there is 1 entry, the format will be considered as non-array. If there is more entries, a parameter in $vars matching 'n', nb', 'num', 'number' or 'count' will be considered as a counter. If there is no match, the first parameter found will be considered. Then, with a 2-entries array, $format[0] = $format if counter is 1; $format[1] = $format if counter is 0 or > 1. With a 3-entries array: $format[0] = $format if counter is 0; $format[1] = $format if counter is 1; $format[2] = $format if counter is > 1.

    • $vars array | string

      Variables to process in string. If this is an associative array, the keys will be replaced in the string using brackets like: {foo} or {{foo}}. The double-bracket will be replaced by an escaped string. If string is provided, we assume $vars corresponds to $fromLocale.

    • $fromLocale string | null

      Locale to be translated to.

    • $toLocale string | null

      MMMMMMM.

  • _t ( string | array $format array $vars string | array $format array | string $vars string | null $fromLocale string | null $toLocale ) : void

    Translate a string, exactly like <t>, then echo the translation.

    • $format string | array

      String to translate.

    • $vars array

      Variables to process in the string. *

    • $format string | array

      String to translate.

    • $vars array | string

      Variables to process in string. If string is provided, we assume $vars corresponds to $fromLocale.

    • $fromLocale string | null

      Locale to be translated to.

    • $toLocale string | null

      MMMMMMM.

  • __t ( string | array $format array $vars string | array $format array | string $vars string | null $fromLocale string | null $toLocale ) : void

    Translate a string, exactly like <t>, escape it, then echo the translation.

    • $format string | array

      String to translate.

    • $vars array

      Variables to process in the string. *

    • $format string | array

      String to translate.

    • $vars array | string

      Variables to process in string. If string is provided, we assume $vars corresponds to $fromLocale.

    • $fromLocale string | null

      Locale to be translated to.

    • $toLocale string | null

      MMMMMMM.

  • get_translations ( string $locale bool $force ) : array

    Load the translation file and store translations in an array.

    • $locale string

      Locale code.

    • $force bool

      Force the refresh of the memory-saved translations.

  • set_translation ( string $locale string $format string $translation string $bundle bool $clear ) : void

    Store a translation entry in the bundle's translation file for the specified locale.

    • $locale string

      Locale code.

    • $format string

      Original text.

    • $translation string

      Translated text.

    • $bundle string

      Bundle name. Default is 'default'.

    • $clear bool

      Clear memory-saved translations for this locale.

  • store_intl_string ( string $str ) : void

    Sotre an internationalizable string, in a simple XML file.

    • $str string

      Translatable string.

  • get_countries ( ) : array

    Get the list of all handled countries.

  • get_country ( object | string $code ) : object | null

    Retrieve info about a specific country.

    • $code object | string

      Country object or code, with 2 (ISO 639-1) or 3 (ISO 639-2) character.

  • get_default_postcode_regex ( ) : string

    Returns the regex which can be used to validate a postcode. It will be a simple regex compatible with all countries.

  • is_postcode_valid ( mixed $postcode object | string | null $country ) : boolean

    Check if a postcode is valid. If country is provided

    • $postcode mixed

      Postcode to validate.

    • $country object | string | null

      Country object or code. If null, the default postcode regex will be used.

  • cast_phone_number ( mixed $number string | int $dialingCode ) : string | null

    Cast a given value to a phone number. If the value is not readable, null will be returned.

    • $number mixed

      Input phone number.

    • $dialingCode string | int

      Prefix automatically a dialing code.

  • is_valid_phone_number ( mixed $number ) : bool

    User the phone casting function to check if the phone number is valid.

    • $number mixed

      Input phone number.

  • cast_postcode ( mixed $postcode ) : string | null

    Check if a given value is a valid postcode and clean it.

    • $postcode mixed

      Possibily a postcode.

  • get_languages ( ) : array

    Get the list of all the handled languages.

  • get_language ( string $code ) : object | null

    Retrieve info about a specific language.

    • $code string

      Country code, with 2 (ISO 639-1) or 3 (ISO 639-2) character.

  • get_locales ( ) : array

    Retrieve all the possible languages combinations, aka lang mixed with countries where it can be spoken.

  • get_locale ( string $code ) : object | null

    Get a specific locale, based on its code (aka xxx-XXX).

    • $code string

      Locale code.

  • get_country_flag ( string $code boolean $url ) : string

    Get the flag of a country, as a SVG string, based on its 3-char code (aka ISO 639-2).

    • $code string

      3-char code of the country.

    • $url boolean

      Returns the string ready to include in a HTML src="" attribute.

log

Functions

  • slog ( string $name string $msg int | null $maxSize string | null $path ) : void

    Log something.

    • $name string

      Name of the log.

    • $msg string

      Message to log.

    • $maxSize int | null

      Max size of each log file. Null for unlimited.

    • $path string | null

      Path of the log file to write in (if using this parameter, will ignore $maxSize).

math

Functions

  • float_to_ratio ( float $n int | integer $tolerance ) : null | string

    Convert some floating number to a "human-readable" fraction/ratio.

    • $n float

      Floating number.

    • $tolerance int | integer

      Roundable tolerancy.

  • process_fractional_number ( string $fraction ) : float

    Process a string containing some fractional value (e.g. 50/100 returns 0.5).

    • $fraction string

      Fractional string.

net

Functions

  • url_uncached ( string $url string $param ) : string

    Returns given URL with a random parameter.

    • $url string

      URL to process.

    • $param string

      Random parameter name.

  • is_valid_url ( mixed $url bool $flex ) : bool

    Check if a URL seems valid.

    • $url mixed

      Something which should be a URL.

    • $flex bool

      Allows URLs without hosts.

  • fetch_urls_in_string ( string $str bool $validatePath string | null $regex ) : array

    Try to get all URLs in a specified string.

    • $str string

      String to process..

    • $validatePath bool

      Check if a local path can be matched.

    • $regex string | null

      Validate the URL with a custom regex.

  • extract_domain_name ( string $str ) : string

    • $str string

      URL or domain name.

  • extract_top_level_domain_name ( string $str ) : string

    • $str string

      Probable domain name.

  • is_valid_domain_name ( string $domain ) : boolean

    Check if a string is a valid domain name, including subdomains.

    • $domain string

      Probable domain name.

  • get_url_file_name ( string $url ) : string | null

    Tries to retrieve a file name from a given URL.

    • $url string

      URL.

  • curl ( string $url string $method string | array $data bool $json array $headers array $cookies int $maxRedirs bool $verifyCertificate string | null | bool $userAgent ) : mixed

    Execute a cURL request.

    • $url string

      Url to fetch.

    • $method string

      HTTP method (GET, POST, DELETE, etc.)

    • $data string | array

      Query strings to pass in URL if $method is GET, or postfields added to the request.

    • $json bool

      Parse result as JSON data.

    • $headers array

      Array of headers to pass to request.

    • $cookies array

      Array of cookies to pass to request.

    • $maxRedirs int

      Maximum number of redirects.

    • $verifyCertificate bool

      Verify peer certificate or not.

    • $userAgent string | null | bool

      User agent. If true, a standard user agent will be set.

  • curl_get ( string $url string | array $fields bool $json bool $verifyCertificate string | null $storePath array $headers string | null | bool $userAgent ) : mixed

    Perform a cURL GET request.

    • $url string

      Url to fetch.

    • $fields string | array

      Postfields added to the request.

    • $json bool

      Parse result as JSON data.

    • $verifyCertificate bool

      Verify peer certificate or not.

    • $storePath string | null

      Path where to store the result.

    • $headers array

      Array of headers to pass to request.

    • $userAgent string | null | bool

      User agent. If true, a standard user agent will be set.

  • curl_post ( string $url string | array $fields bool $json bool $verifyCertificate ) : mixed

    Perform a cURL POST request.

    • $url string

      Url to fetch.

    • $fields string | array

      Postfields added to the request.

    • $json bool

      Parse result as JSON data.

    • $verifyCertificate bool

      Verify peer certificate or not.

  • curl_last_error ( ) : string | null

    Returns the last cURL error (when used <curl_get> or <curl_post>).

  • curl_last_info ( string | null $key ) : mixed

    Returns the last cURL info (when used <curl_get> or <curl_post>).

    • $key string | null

      The key of the info to get.

  • curl_last_response ( ) : string | null

    Returns the last cURL response (when used <curl_get> or <curl_post>).

output

Functions

  • set_template_var ( string $k mixed $v ) : void

    Declare or update a global template variable.

    • $k string

      Name of the variable

    • $v mixed

      Value or new value of the variable.

  • set_template_vars ( array $vars bool $replace ) : void

    Set multiple global template variables.

    • $vars array

      Key/Value array container variables to declare/update.

    • $replace bool

      Replace

  • delete_template_var ( string $k ) : void

    Delete a global template variable.

    • $k string

      Key of the template variable to delete.

  • get_template_vars ( ) : array

    Returns all the global template variables.

  • get_template_var ( string $key ) : mixed

    Returns a specific global template variable value.

    • $key string

      Key of the template variable.

  • render ( string $tpl array $vars bool $return bool $preprocessAssets bool $dispatchEvents bool $throwMissing bool $close bool $ajax bool $updateGlobalVars bool $loadGlobalVars ) : string | null

    Render a template.

    If the given template path is prefixed with a '/', the path of the looked-up file will be relative to the project root. Else, it will be relative to the '/tpl' directory.

    If the path doesn't has a recognized extension (phtml, php, html or htm), the path will be suffixed with '.phtml';

    • $tpl string

      Template name/path.

    • $vars array

      Variables to inject to the template. They will be merged to the global template variables.

    • $return bool

      Returns the result as a string if true. Else, it will be echoed.

    • $preprocessAssets bool

      Preprocess the assets if needed, depending on the configuration. If false, the assets preprocessing will be fully skipped.

    • $dispatchEvents bool

      Dispatch the events or not.

    • $throwMissing bool

      Throw an error when the template file is missing.

    • $close bool

      Exit the code with <close()> after rendering.

    • $ajax bool

      Outputs a JSON oject containing the HTML and the underscored variables. Can be a boolean or 'auto'.

    • $updateGlobalVars bool

      Update global template vars with $vars.

    • $loadGlobalVars bool

      Load global template into template.

  • layout ( string $tpl array $vars ) : void

    Render a template with <render>, only if the current HTTP request is not a XMLHTTPRequest.

    • $tpl string

      Template name/path.

    • $vars array

      Variables to inject to the template.

  • widget ( string $name mixed $args bool $return ) : string | null

    Render a template traditionnaly located in 'widgets' subfolder. This is very close to <render()>, but with the purpose of reusable components taking simple arguments, or only one argument.

    • $name string

      Name of the template. If starting with a '@', a standard template path is expected. In other cases, the template will be looked for in the default bundle directory, under templates/widgets.

    • $args mixed

      Single argument, or key-value array containing several template variables.

    • $return bool

      Returns the template as a string, or echo it directly.

  • begin_tpl_part ( string $name ) : void

    Begin a template part, which can be reused in another part of the template.

    • $name string

      Name of the template part.

  • end_tpl_part ( ) : void

    Ends the template part and store the content without displaying it.

  • get_tpl_part ( string $name ) : string

    Returns the template part previously stored.

    • $name string

      Name of the template part.

  • tpl_part ( string $name ) : void

    Display the result of <get_tpl_part>.

    • $name string

      Name of the template part.

  • inline_render ( array | Closure $arg1 Closure | array | null $arg2 ) : string

    Render a template based on function echoing some HTML.

    • $arg1 array | Closure

      The template vars or the echoing function.

    • $arg2 Closure | array | null

      The echoing function or the template vars.

  • register_inline_template ( string $name Closure $code ) : void

    Register a template, based on a name and a source code as a string.

    • $name string

      Name of the template.

    • $code Closure

      Function echoing the template code (PHP/HTML).

  • get_inline_template ( string $name ) : Closure | null

    Returns an inline template rendering function, based on its name.

    • $name string

      Name of the inline template.

  • get_asset_path ( string $path ) : string

    Returns an absolute path corresponding to the asset given as argument.

    • $path string

      Asset's path, relative to the project, which can contains a bundle reference.

  • include_asset ( string $path array | null $attrs bool $return ) : string

    Generate the proper <link> or <script> code to include the given path.

    • $path string

      Path to asset file (absolute or relative to assets root).

    • $attrs array | null

      Array containing additional HTML attributes to append to the asset tag.

    • $return bool

      Returns as a string. If false (default), echo the HTML.

  • include_assets ( array $paths ) : array

    Generate the proper <link> or <script> code to include the given path.

    • $paths array

      Paths to assets files (absolute or relative to assets root).

  • require_asset ( string $name boolean $isRequired ) : void

    Ask for an asset. In the standard use case with a context template (e.g. homepage), loading the header and the footer with <layout>, this function can be executed immediatly before running <layout>('...header...'). Like this, if the header or the footer are using <is_asset_needed> with the proper asset name, this asset will be handled.

    • $name string

      Name of the asset.

    • $isRequired boolean

      Always true, except if you finaly want to disable this asset.

  • is_asset_required ( string $name ) : boolean

    Check if an asset is asked somewhere.

    • $name string

      Name of the asset.

  • get_assets_version_path ( ) : string

    Returns the path of the file containing the assets version number.

  • assets_version ( boolean $checkEnv ) : string

    Returns the current assets version number, as written in the assets version file.

    • $checkEnv boolean

      Check if the environment is excluded from assets caching (e.g. 'dev'). If yes, a random string will be returned instead of a specific number.

  • increment_assets_version ( int $by ) : void

    Increments the assets version number.

    • $by int

      Increment by how many? Default 1.

  • get_assets_latest_file_time_path ( ) : string

    Returns the path of the file containing the last asset file modified time.

  • get_assets_latest_file_time_stored ( ) : DateTime

    Returns the latest asset file modified time.

  • set_assets_latest_file_time_stored ( ) : void

    Set the latest asset file modified time.

  • get_assets_dirs ( ) : array

    Returns all assets directories (root and bundles ones).

  • get_latest_asset_modified_time ( ) : DateTime

    Get the DateTime of the latest asset file modification time.

  • preprocess_assets ( boolean $force ) : void

    Execute the assets preprocessors, like Stylus, SASS, LESS, etc.

    • $force boolean

      Preprocess even if it was already done before in this request.

  • require_js ( array $files bool $bind bool $minify bool $cached ) : void

    Require some JavaScript files in the proper <script/> tag(s).

    • $files array

      Array of relative paths to the *.js files from the root of the project. It can ends by a "/*" to load all the files contained in a specific directory.

    • $bind bool

      Bind the files together, instead of requiring them through separated <script/> tags.

    • $minify bool

      Minify a bit each files before binding. It will does nothing if the binding is not enabled.

    • $cached bool

      Always use the cache if the files were unchanged, or regenerate it each time.

  • declare_inline_css ( array $rules ) : void

    Declare some CSS rules, for further inline use (in style="...").

    • $rules array

      Key/Value CSS rules. The key is the name of the rule, and the value is a string containing some CSS declarations, or an associative array representing those declarations. E.g. ['bigtext'=>['font-size'=>'4rem']].

  • inline_css ( array $names boolean $returnValue ) : string | null

    Generate a style="..." attribute with the proper inline CSS declarations previously declared with <declare_inline_css>.

    • $names array

      Name or names of the rules to apply.

    • $returnValue boolean

      Returns the inline CSS if true, or echo the style attribute if true (default).

  • get_css_units ( ) : array

    Returns standard CSS units.

  • size_attr ( int $w int | null $h float $scale ) : void

    Echo an image size attribute.

    • $w int

      Original width of the image.

    • $h int | null

      Original height of the image. If null, the image will be considerated as a square of $w x $w.

    • $scale float

      Optional scale to apply on se size (default 1).

  • icon ( mixed $icon string | null $format ) : string

    Returns icon string, with the format given by cfg('@output.icons.format'), or a fallback.

    • $icon mixed

      Icon name.

    • $format string | null

      Icon format.

  • _icon ( mixed $icon string | null $format ) : void

    Echo icon string, generated with <icon()>.

    • $icon mixed

      Icon name.

    • $format string | null

      Icon format.

  • json ( array $data int $code bool $pretty bool $endingLineFeed ) : void

    Display a JSON string.

    • $data array

      Data to encode.

    • $code int

      HTTP Code.

    • $pretty bool

      Prettify JSON string or not.

    • $endingLineFeed bool

      Echo a \n after the JSON. Nicer for terminal display.

  • json_success ( array $data int $code bool $pretty ) : void

    Display a JSON string, with a property 'success' set to true.

    • $data array

      Optional data to encode.

    • $code int

      HTTP Code.

    • $pretty bool

      Prettify JSON string or not.

  • json_error ( string $error array $data int $code bool $pretty ) : void

    Display a JSON string, with a property 'success' set to false, and an 'error' code/message.

    • $error string

      Error added in the output JSON object.

    • $data array

      Optional data to encode.

    • $code int

      HTTP Code.

    • $pretty bool

      Prettify JSON string or not.

  • json_403 ( string $message ) : void

    Display a JSON error "unauthorized" with an optional message.

    • $message string

      Error message.

  • json_404 ( string $message ) : void

    Display a JSON error "not_found" with an optional message.

    • $message string

      Error message.

  • json_500 ( string $message ) : void

    Display a JSON error "internal_error" with an optional message.

    • $message string

      Error message.

  • redirect ( string $url array $vars int $code ) : void

    Redirect the user with a HTTP header 'Location'. The URL will be processed through <url> with the optional $vars.

    • $url string

      Location URL.

    • $vars array

      Optional URL query strings.

    • $code int

      HTTP code (default 302).

  • message ( string | null $html string $type string | null $title string | null $text string | null $before ) : void

    System message to show.

    • $html string | null

      HTML string to display.

    • $type string

      Message type for pre-styling. Can be one of: 'info', 'error' or 'success'.

    • $title string | null

      Title, set in a <h1> before the $html.

    • $text string | null

      Plain text to display. If $html and $text are provided, $text will be escaped then append after $html.

    • $before string | null

      HTML text to display at the beginning of the message's code.

  • output_download ( string $path string $contentType string | null $name bool $close bool $forceDownload string | null $data ) : void

    Send headers and readfile, to force download to the client.

    • $path string

      Path to the file.

    • $contentType string

      Content Type of the file.

    • $name string | null

      File name passed as header. If null, the basename of the path will be used.

    • $close bool

      Close the app immediatly after reading file?

    • $forceDownload bool

      Force download, or allows to render file inline.

    • $data string | null

      The raw data, in replacement of the path.

  • output_display_image ( string $path string | null $contentType ) : void

    Echo the content of an image file, with the proper headers.

    • $path string

      Path to the image file.

    • $contentType string | null

      Content type. If null, the function will try to get the proper mime type.

  • close ( ) : void

    Exit the current code whithout a 404 error.

routes

Functions

  • register_fallback_route ( Closure $func ) : void

    Register a callback function which will be called after trying every route, without success.

    • $func Closure

      Function called just before throwing a 404.

  • call_fallback_route ( ) : bool

    Call the optionnaly registered fallback function. If this function returns a true, the 404 will not be thrown directly.

  • register_before_any_route ( Closure $func ) : void

    Register a callback function which will be called before any route. This can be usefull, for example, to setup, from a helper or directly inside the index.php, a function which will be able to fill the global template variables.

    • $func Closure

      Function which will be called before executing a route.

  • register_url_modifier ( Closure $modifier ) : void

    Register a global modifier for URLs building.

    • $modifier Closure

      Closure called on each URL building. The unique and first parameter is the URL which is currently processed. The function must returns the URL, modified or not.

  • get_url_modifiers ( ) : array

    Returns the registered URLs modifiers.

  • apply_url_modifiers ( string $path ) : string

    Apply registered URL modifiers on a given path.

    • $path string

      Path to process.

  • register_route_filter ( Closure | null $callback ) : void

    Register a route filter. When a route will match with the current URL, the registered filters callbacks will be runned. If one of them returns false, the route will not be reached and the next one will be tried. The route filters are cleared automatically at the beginning of each controller files. The classic purpose of this behaviour is to apply all the routes of a controller file only on specific domain name, or only if there is a cookie registered, or only with some IP addresses.

    • $callback Closure | null

      Filter callback. A function which will take one argument: the Microbe class instance, in which are available GET/POST parameters, route arguments and the route path (aka the path given as first argument of <route>).

  • register_domain_route_filter ( string $pattern ) : void

    Shortcut to <register_route_filter>, to register a route filter which will check if the current domain name corresponds to the given pattern. If the pattern seems to be a regex (begins and ends with slashes), a regex comparisition will be done. Else, a strictly equal comparisition will be used.

    • $pattern string

      Domain name or regex to validate the current domain.

  • clear_route_filters ( ) : void

    Clear the registered route filters. This function is always called immediately before requiring a controller file.

  • get_route_filters ( ) : array

    Returns the registered route filters.

  • set_route_args ( array $args ) : void

    Set route arguments, prepended to route functions.

    • $args array

      Array of objects with 'name' and 'func' properties.

  • get_route_args ( ) : array

    Returns predefined route arguments.

  • add_route_arg ( string $name Closure $callback ) : void

    Add a route argument. A route argument is defined by its name (for further deletion purpose), and its callback function. The function should return the value which will be given as the route's function argument.

    • $name string

      Name of predefined argument.

    • $callback Closure

      Function executed to get the proper value.

  • delete_route_arg ( string $name ) : void

    Delete a specific route argument.

    • $name string

      Name of the argument

  • compute_route_args ( string | null $url array $urlArgs ) : array

    Compute predefined route args.

    • $url string | null

      Optional current URL, passed to args functions.

    • $urlArgs array

      Optional array containing URL arguments.

  • route ( string | array $path Closure $callback ) : void

    Add a route rule. The first argument is the path who have to match. The second argument is the callback which will be executed if the URL match. Before executing a route, the route filters registered with <register_route_filter> will be executed. If the $path is an array of paths, the separated routes will be declared for each item of the array. The path parts between chevrons will be considered as jokers, and returned in the Microbe instance. Note the behaviour of the parts between chevrons:

    '/foo/<var>' will match '/foo/abc' or '/foo/123', but not '/foo/abc/123';

    '/foo/<var>/bar' will match '/foo/abc/bar' or '/foo/abc/123' but not '/foo/abc/def/bar';

    '/foo/<*var>' will match '/foo/abc', 'foo/abc/def', 'foo/bar/abc/def/123', etc.

    '/foo/<var:bar>' will match '/foo/bar' only, and set the route argument 'var' to 'bar'. It's useful when using a paths array, to differenciate the different paths.

    • $path string | array

      Path of the URL which should match.

    • $callback Closure

      Function to call when the route match. This function will accept a Microbe instance as unique parameter.

  • url ( string $path array $args bool | boolean $host string | null $fallback ) : string

    Generate a URL. The $args argument can be skipped and replaced by the $host argument. Some special paths which can be given as first argument:

    '.': current path, with query strings;

    './': current path, without query strings;

    ':back': HTTP_REFERER if available, or $fallback, or '/';

    • $path string

      Path of the URL.

    • $args array

      Query String arguments.

    • $host bool | boolean

      Prepend the protocol and the hostname or not.

    • $fallback string | null

      Back-url fallback. Used with special path ':back'.

  • _url ( string $path array $args bool | boolean $host string | null $fallback ) : string

    Generate a URL using <url()>, then echo it.

    • $path string

      Path of the URL.

    • $args array

      Query String arguments.

    • $host bool | boolean

      Prepend the protocol and the hostname or not.

    • $fallback string | null

      Back-url fallback. Used with special path ':back'.

  • __url ( string $path array $args bool | boolean $host string | null $fallback ) : string

    Generate a URL using <url()>, then echo it, escaped.

    • $path string

      Path of the URL.

    • $args array

      Query String arguments.

    • $host bool | boolean

      Prepend the protocol and the hostname or not.

    • $fallback string | null

      Back-url fallback. Used with special path ':back'.

  • is_external_url ( string $url ) : bool

    Tries to check if the given URL is NOT pointing to the current site.

    • $url string

      URL to checj.

security

Functions

  • sha256 ( string $str ) : string

    Shortcut to the 'hash' sha256 function call.

    • $str string

      String to hash.

  • hashed ( string $algo string $str ) : string

    Hash some string with specified algorithm, but replace 'cd' with 'xd', to avoid issues when using part of the hashed string as a path folder (e.g. abcdef.jpg -> ab/cd/abcdef.jpg).

    • $algo string

      Algorithm.

    • $str string

      String to hash.

  • hashed_sha256 ( string $str ) : string

    Execute <hashed()> with algorithm SHA-256.

    • $str string

      String to hash.

  • hashed_sha1 ( string $str ) : string

    Execute <hashed()> with algorithm SHA-1.

    • $str string

      String to hash.

  • uid ( integer $len bool $password ) : string

    Generate a unique hexadecimal UID string of 64 character maximum.

    • $len integer

      Length of the UID (maximum: 64 character).

    • $password bool

      Use the <password> function instead of a SHA-256 hash. Note: the returned string will be [a-z0-9] instead of [a-f0-9].

  • is_uid ( mixed $value int | array $len ) : boolean

    Check if some value is formatted as a UID.

    • $value mixed

      Value to verify.

    • $len int | array

      Expected length (or array of lengths).

  • get_special_chars ( ) : void

    Returns special characters list as a string.

  • get_random_special_char ( ) : void

    Returns random special character.

  • password ( integer $len bool $useSpecials bool $changeCase ) : string

    Generate a pseudo-random password.

    • $len integer

      Length of the password.

    • $useSpecials bool

      Insert or not one special character.

    • $changeCase bool

      Use lowercase and uppercase letters.

  • numeric_password ( integer $len ) : string

    Generate a numeric password with the request length. Basically, it just runs the <password> function will only numbers in use.

    • $len integer

      Password length.

  • readable_password ( integer $len ) : string

    Create a syllabic password including numbers and special chars.

    • $len integer

      Length of the password. Should be odd. If not, it will be forced up.

  • get_password_conditions ( ) : object

    Generate standard conditions for password security. The conditions are configurable through some @app.secure.passwords... configuration entries.

  • is_secure_password ( string $password ) : boolean

    Check if a given password validate the conditions returned by <get_password_conditions()>.

    • $password string

      Password

  • short_uid ( string | Microbe_Entity | stdClass $uid integer $len ) : string

    Shortify a UID to a specified length.

    • $uid string | Microbe_Entity | stdClass

      Full UID, or a Microbe_Entity, or a stdClass containing a uid property.

    • $len integer

      Length to shortify to.

  • hash_password ( string $password ) : string

    Hash a password, using the configuration settings in the section @security.

    • $password string

      Password to hash.

  • is_valid_password ( object | array | string $obj string $password ) : boolean

    Hash a password, then check if this value corresponds to an entry 'password' of an array, an object or directly to the given string.

    • $obj object | array | string

      Object or array containing a key 'password', or a hashed password string.

    • $password string

      Password to hash and compare.

  • compute_password_score ( string $password int $minLength int $excellentLength ) : float

    Compute password strength score.

    • $password string

      Password to check.

    • $minLength int

      Minimum length (default 6).

    • $excellentLength int

      Excellent length (default 20).

  • security_check ( ) : array

    Performs a global security check and returns an array containing the result of each item of control.

session

Functions

  • session_setup ( ) : boolean

    Start the session if it was not already done.

  • get_session_var ( string $name ) : mixed

    Get a value from the global $_SESSION array.

    • $name string

      Name of the session var.

  • set_session_var ( string $name mixed | null $value ) : void

    Set some value for a specific session variable (aka global $_SESSION array).

    • $name string

      Name of the variable.

    • $value mixed | null

      Value to set.

  • delete_session_var ( string $name ) : void

    Delete a session variable (aka an entry of the global $_SESSION array).

    • $name string

      Name of the variable.

  • get_flash_vars ( ) : array

    Returns all the session flash variables.

  • set_flash_vars ( array | null $vars boolean $replace ) : void

    Define some flash variables.

    • $vars array | null

      Array representing the flash variables.

    • $replace boolean

      Replace all the flash variables. If false (default), the given $vars will be merged into the current variables.

  • set_flash_var ( string $name mixed | null $value ) : void

    Define a flash variable. This value, represented by a name, will be stored in the session until a standard call to <get_flash_var>.

    • $name string

      Name of the flash variable.

    • $value mixed | null

      Value of the variable.

  • delete_flash_var ( string $name ) : void

    Delete a flash variable.

    • $name string

      Name of the flash variable.

  • get_flash_var ( string $name boolean $delete ) : mixed

    Get a flash variable. If the second parameter stays at true, the variable will be deleted. The standard use case of a flash variable should be to be set on a request, then get and cleaned on the next request (e.g. form data/errors, global error message, etc.).

    • $name string

      Name of the flash variable.

    • $delete boolean

      Get the value, then delete the variable before the return. Default is true.

  • push_flash_message ( string $msg string $name integer $type ) : void

    Push a flash message. Basically, it will get, push then set a flash variable. If the value is empty or null, the message will be

    • $msg string

      Value to push.

    • $name string

      Name of the messages context.

    • $type integer

      Type of the message. Should be one of the MB_FLASH_MSG_* constants.

  • get_flash_messages ( string $name boolean $delete ) : array

    Returns the flash messages of the given context name. The result will be an array containing zero or more objects with two properties: the type (corresponding to one of the MB_FLASH_MSG_* constants) and the message as a string. If the second parameter is left as true, the flash messages will be deleted after the getting.

    • $name string

      Name of the messages context.

    • $delete boolean

      Get the value, then delete the messages before the return. Default is true.

setup

Functions

  • setup ( string | array $scopes ) : void

    Setup the framework's environment, with specific scope(s).

    • $scopes string | array

      Setup scope(s): web, or config, tree, samples.

  • setup_config ( ) : void

    Setup configuration.

  • setup_tree ( ) : void

    Setup tree.

  • setup_samples ( ) : void

    Setup samples.

  • get_setup_cfg_json ( ) : string

    Fire the event 'register_cfg_snippets' and merge all the results to create the sample configuration file based on those returned arrays, then returns this merging as a JSON string.

sitemap

Functions

  • register_sitemap_source ( string $name Closure $func int $priority ) : void

    Register Sitemap Source.

    • $name string

      String to encode.

    • $func Closure

      Function which will be executed to generate the sitemap. This function should returns an array of associative arrays containing keys:

      loc (mandatory);

      lastmod;

      changefreq;

      priority.

    • $priority int

      Priority: lower is the value, higher is the priority and sooner the links will appear in the sitemap.

  • get_registered_sitemap_sources ( ) : array

    Returns registered Sitemap Sources.

  • get_registered_sitemap_source ( string $sourceName ) : ?object

    Returns registered Sitemap Source.

    • $sourceName string

      Source name.

  • fetch_sitemap_links ( ) : array

    Execute Sitemap Sources functions to fetch all links.

  • generate_sitemap ( string $path ) : string

    Generate Sitemap based on registered Sitemap Sources.

    • $path string

      XML Sitemap output path.

  • get_existing_sitemaps ( bool $stats string $format string $dir ) : array

    Check all existing sitemaps.

    • $stats bool

      Include number of links.

    • $format string

      Regular expression used to match expected files.

    • $dir string

      Directory (based on project root) where the files are expected.

strings

Functions

  • esc ( mixed $s ) : string

    Encode HTML entities in a string.

    • $s mixed

      String to encode.

  • _esc ( mixed $s ) : void

    Echo the encoded HTML using <esc()>.

    • $s mixed

      String to escape.

  • unesc ( mixed $s ) : string

    Decode HTML entities from a string.

    • $s mixed

      String to decode.

  • _unesc ( mixed $s ) : void

    Echo the decoded HTML using <unesc()>.

    • $s mixed

      String to decode.

  • strip_blocks ( string $str ) : string

    Remove block tags from HTML string.

    • $str string

      String to clean.

  • is_str_safe ( mixed $str ) : bool

    Check if the string contains only simple characters, excluding special quotes, emojis, etc.

    Unicode letters with accents;

    Numbers;

    Everything else should be simple ASCII.

    • $str mixed

      Probably a string.

  • replace_params ( string $str array $params string $keyFormat ) : string

    Returns given string after replacement of key-value $params.

    • $str string

      String to process.

    • $params array

      Key-Value array of params to replace.

    • $keyFormat string

      String defining the format of the keys as specified in input string.

  • seems_base64 ( string $s ) : bool

    Check if the string seems to be a valid Base64 encoded string.

    • $s string

      String to be checked.

  • truncate_text ( string $str int | integer $maxLength string | bool | null $ellipsis ) : string

    Truncate a text word by word.

    • $str string

      Text to truncate.

    • $maxLength int | integer

      Maximum length of the returned text.

    • $ellipsis string | bool | null

      Add an ellipsis if the text was truncated. If null, nothing is appent. If true, the three-dots will be used. Else, the given string will be appent.

  • truncate_str ( string $str int | integer $maxLength string | bool | null $ellipsis ) : string

    Truncate a string without taking count of words.

    • $str string

      Text to truncate.

    • $maxLength int | integer

      Maximum length of the returned text.

    • $ellipsis string | bool | null

      Add an ellipsis if the text was truncated. If null, nothing is appent. If true, the three-dots will be used. Else, the given string will be appent.

  • sanitize_string ( string $str string $separator bool $keepExtension int | integer $maxLength ) : string

    Sanitize a string, removing accents and special character, and trimming it.

    • $str string

      String to sanitize.

    • $separator string

      Words separator (replacing all non alpha-numerical character).

    • $keepExtension bool

      Keep a file's extension.

    • $maxLength int | integer

      Shorten the string to a maximum length.

  • html_to_text ( string $html ) : string

    Convert some HTML to its pseudo equivalent Plain Text.

    • $html string

      Probably some HTML code.

  • cast_float ( mixed $value ) : float | null

    Clean and cast an unknown value to a float number. Returns null if the value is empty or totally invalid.

    • $value mixed

      Input value.

  • format ( mixed $something string $cast ) : string

    Cast some scalar value to a predefined format. Cast methods availables are:

    number

    int

    percentage

    hours

    • $something mixed

      Value to cast.

    • $cast string

      Cast method.

  • format_number ( mixed $something ) : string

    Format a number.

    • $something mixed

      Value to cast.

  • format_int ( mixed $something ) : string

    Format a number.

    • $something mixed

      Value to cast.

  • replace ( array $replacements string $haystack ) : string

    Replace a bucket of strings, based on a Key/Value array. If the key seems to be a regex (aka starting and ending with a /, with optional ending modifiers), a preg_replace will be used instead of a str_replace.

    • $replacements array

      Pattern/Value replacements array.

    • $haystack string

      Input string.

  • replace_last_occurence ( string $from string $to string $str ) : string

    Replace the last occurence of a substring.

    • $from string

      Substring to replace.

    • $to string

      Substring replacement.

    • $str string

      Full string.

  • seems_regex ( string $str ) : bool

    Check a string and returns true if it seems to contains standard regex delimiters with optional modifieds.

    • $str string

      String which could be a regex.

  • joker_to_regex ( string $str ) : string

    Convert a string with optional joker stars, to a regex.

    • $str string

      Input string.

  • enforce_utf8_str ( string $str ) : string

    Enforce a string is in UTF8.

    • $str string

      String to validate.

  • seems_utf8 ( string $str ) : bool

    Check a string and returns true if it seems to contains some UTF-8 character.

    • $str string

      String to verify.

  • remove_accents ( string $str ) : string

    Remove accents from a UTF-8 or ISO-8859-1 string.

    • $str string

      String to process.

  • unicode_bold ( string $str ) : string

    Returns a bolded unicode string.

    • $str string

      Input string.

  • create_word ( int $minSyllables int $maxSyllables bool $excludeConfusing ) : string

    Create an almost prononciable word, switching between vowels and consonants.

    • $minSyllables int

      Minimum number of syllables.

    • $maxSyllables int

      Maximum number of syllables.

    • $excludeConfusing bool

      Exclude confusing letters or not.

  • get_letter ( string | null $type bool $excludeConfusing ) : string

    Get a random letter, with optional choice between a vowel or a consonant.

    • $type string | null

      Can be 'vowel', 'consonant' or null for both.

    • $excludeConfusing bool

      Exclude confusing letters or not.

  • create_sentence ( int $minWords int $maxWords int $minSyllables int $maxSyllables bool $endDot ) : string

    Create a fake sentence.

    • $minWords int

      Minimum number of words in the sentence.

    • $maxWords int

      Maximum number of words in the sentence.

    • $minSyllables int

      Minimum number of syllables.

    • $maxSyllables int

      Maximum number of syllables.

    • $endDot bool

      Put a final dot or not?

  • create_paragraph ( int $minSentences int $maxSentences ) : string

    Create a paragraph containing some sentences.

    • $minSentences int

      Minimum number of sentences.

    • $maxSentences int

      Maximum number of sentences.

  • create_paragraphes ( int $minParagraphes int $maxParagraphes bool $html ) : string

    Create some paragraphes, returned as an array or a HTML string.

    • $minParagraphes int

      Minimum number of paragraphes.

    • $maxParagraphes int

      Maximum number of paragraphes.

    • $html bool

      Return as an HTML string or not.

  • get_random_name ( string | null $gender ) : object

    Get some random western's actor name.

    • $gender string | null

      Gender (male, female). Default: null = random.

  • sanitize_full_name ( string $name ) : string

    Tries to sanitize and normalize a full name (John Doe).

    • $name string

      Name.

  • minify_html ( string $html ) : string

    Remove useless spaces and comments in some HTML code.

    • $html string

      Unminified HTML code.

  • beautify_html ( string $html ) : string

    Beautify an HTML string, using the third-party Beautify_Html class.

    • $html string

      Ugly HTML code.

  • split_values ( string $str string $sep ) : array

    Split a string between values, by default using commas and/or semicolons as separator, then trim and remove empty values.

    • $str string

      Some string with optional .

    • $sep string

      Separator, as a regex or a simple substring.

  • increment_str ( string $str string $prefix string $suffix Closure | null $validate ) : string

    Increment a string, using a validation function.

    • $str string

      Base string.

    • $prefix string

      Prefix where {idx} is replaced by increment.

    • $suffix string

      Suffix where {idx} is replaced by increment.

    • $validate Closure | null

      Validation function, taking two arguments: the incremented string, and the index as integer.

  • explode_case ( string $str string | null $joint ) : array | string

    Explode the strings part, based on conventional case separators: camel-cased, dashes or underscores.

    • $str string

      Input string.

    • $joint string | null

      If given, this string will be used for an implode and a string will be returned instead of an array.

  • camel_case ( string $str ) : string

    Returns a camelCasedString.

    • $str string

      Input string.

  • pascal_case ( string $str ) : string

    Returns a PascalCasedString.

    • $str string

      Input string.

  • snake_case ( string $str bool $upper bool $upperWords ) : string

    Returns a snake_cased_string, a SNAKE_CASED_STRING or a Snake_Cased_String.

    • $str string

      Input string.

    • $upper bool

      Uppercase all the string.

    • $upperWords bool

      Uppercase the first letter of each word.

  • kebab_case ( string $str bool $upper ) : string

    Returns a kebab-cased-string, or a KEBAB-CASED-STRING.

    • $str string

      Input string.

    • $upper bool

      Uppercase all the string.

  • extract_quoted_substr ( string $str string $replacement string $quotes ) : array

    Extract quoted substrings from a string, and returns an object with the original string altered with unquoted $replacement, and the quotes as an array of objects containing the initial quoted text.

    • $str string

      Input string

    • $replacement string

      Replacement string, with a %d somewhere which will be replaced by the quote index.

    • $quotes string

      Quotes taken in account (default "').

  • parse_search_query ( string $q ) : object

    Parse a query which can have some words, and key/value pairs. E.g.: foo bar id:123

    • $q string

      Query terms.

system

Functions

  • guess_php_binary ( string | null $fallback ) : string | null

    Guess the location fo the PHP binary, ideally including the same PHP version.

    • $fallback string | null

      Fallback PHP binary path.

  • exec_php_file ( string $path array $vars bool $return string | null $binary ) : int | array

    Execute a PHP file using current PHP binary.

    • $path string

      Path of PHP file to execute.

    • $vars array

      Variables to pass as environment variables got in child via ($_SERVER).

    • $return bool

      Return execution response instead of echoing it.

    • $binary string | null

      Path of PHP binary. Default is guessed from PHP_BINARY.

  • exec_in_out ( string $cmd array $expect string | null $ending bool $showOutput ) : bool | string

    Execute an interactive command through <proc_open>, and wait for some of the entries of $expect, then answer it.

    • $cmd string

      Command to execute.

    • $expect array

      Simple array, containing associative arrays with the following enties:

      <in>, as a regex tested on each text row returned by the command.

      <out>, as the string to write in the <stdout>, as an input to the command.

    • $ending string | null

      An optional regex which indicates that we can consider the program is fully exectuted, so we don't have to wait the timeout of <stream_select>.

    • $showOutput bool

      Echo each result of the stream. Default false.

  • get_system_user_name_by_id ( int $id ) : string | null

    Returns the user or group name, from its system ID.

    • $id int

      System user/group ID

  • get_system_user_id ( ) : int | null

    Returns the current's process user ID.

  • get_system_user_name ( ) : string | null

    Returns the current's process user name.

tasks

Functions

  • register_task ( string $name Closure $func array $args bool $webEnabled bool $cliEnabled ) : void

    • $name string

      Name of the task.

    • $func Closure

      Function executed when the task is called. This function takes two arguments:

      string $ctx: The context ('web' or 'cli').

      object $args: An object containing arguments passed as command line parameter or query string.

    • $args array

      Arguments description, taking associative arrays with the following keys: string 'desc' and bool 'optional'.

    • $webEnabled bool

      Task is enabled on web context.

    • $cliEnabled bool

      Task is enabled on cli context.

  • assert_tasks_files ( array | null $tasks bool $force ) : void

    Assert if the standalone files for each task are created, and delete useless tasks files.

    • $tasks array | null

      Registered tasks. If null, tasks will be retrieved.

    • $force bool

      Force generation of files even if exists.

  • get_registered_tasks ( bool $assertFiles ) : array

    Returns registered tasks.

    • $assertFiles bool

      Execute assert_tasks_files() in order to control existence of standalone PHP files which execute the task.

  • get_registered_task ( string | null $uid string | null $bundle string | null $name ) : object | null

    Returns a specific registered task.

    • $uid string | null

      UID of the task.

    • $bundle string | null

      Bundle of the task (associated with $name).

    • $name string | null

      Name of the task (associated with $bundle).

  • generate_task_url ( string $taskUid ) : string | null

    Generate the callable URL for a specific task.

    • $taskUid string

      Task UID.

  • generate_task_cli_path ( string $taskUid ) : string

    Generate the shell command to execute the task through related CLI action.

    • $taskUid string

      Task UID.

  • execute_task ( string $taskUid string $ctx array $args ) : void

    Execute a specific task.

    • $taskUid string

      Task name or UID.

    • $ctx string

      Context: 'web' or 'cli'.

    • $args array

      Arguments passed to the task (usualy CLI arguments or query-strings).

time

Functions

  • microseconds ( ) : int

    Returns the <microtime> in microseconds (and not in seconds).

  • script_time ( ) : float

    Returns the time since the beginning of the script.

  • get_app_timezone ( ) : DateTimeZone

    Returns app timezone.

  • get_app_timezone_name ( ) : string

    Returns app timezone name.

  • get_system_timezone ( ) : DateTimeZone

    Returns system timezone.

  • get_system_timezone_name ( ) : string

    Returns system timezone name.

  • get_timezones ( bool $onlyIdentifiers ) : array

    Returns all timezones supported by system.

    • $onlyIdentifiers bool

      Returns a simple array of strings names instead of detailled info.

  • is_valid_timezone ( string $identifier ) : boolean

    Check if the given identifier is a valid timezone.

    • $identifier string

      Probably a timezone name.

  • _year ( ) : void

    Echo the current year.

  • seconds_to_duration ( int $seconds bool $overtimeSentence ) : string

    Convert a number of seconds to hh:mm:ss

    • $seconds int

      Number of seconds.

    • $overtimeSentence bool

      String returned if $seconds is over a day.

  • parse_duration ( int | string $str bool $asDateInterval ) : integer | DateInterval

    Parse a duration string, suffixed with one of those units: s(econds), m(inutes), h(ours), d(ays), w(eeks), y(ears). Note that there is no monthes unit for two reasons: first, there can be a conflict between minutes and monthes, and secondary, the conversion from month to seconds may vary a lot because of the variability of the month duration, from 28 to 31 days.

    • $str int | string

      Some string suffixed with a time unit.

    • $asDateInterval bool

      Returns DateInterval instance instead of an integer of seconds.

  • duration_to_date_interval ( int | string $str ) : DateInterval

    Parse a duration string, and create the corresponding PHP DateInterval.

    • $str int | string

      Some string suffixed with a time unit.

  • is_expired ( string | int | DateTimeInterface $what string | int | DateInterval $ttl ) : boolean

    Check if a file or a date is expired, based on given time-to-live.

    • $what string | int | DateTimeInterface

      Some date to check. Could be:

      DateTimeInterface instance;

      UNIX timestamp;

      String date, as "Y-m-d H:i:s";

      File path (the modified time will be checked).

    • $ttl string | int | DateInterval

      Time-to-live. Could be:

      Seconds as an integer;

      DateInterval instance;

      The DateInterval duration string (as "P...T...").

  • get_time_ago ( DateTimeInterface | string | int $dt DateTime | null $now bool $full int | string $limit bool $lower bool $translate string $textFormat ) : string

    Compute the time ago since a specified date and time.

    • $dt DateTimeInterface | string | int

      Date and time of the event. Can be a DateTime object, a string which can be parsed by the DateTime constructor, or a timestamp as an integer.

    • $now DateTime | null

      Now DateTime. Default, now.

    • $full bool

      Don't filter the fields (YMWDhms), so returns all the fields, even if they're zero.

    • $limit int | string

      Returns null if the delay is above the given limit, represented as seconds or a string duration.

    • $lower bool

      Returns lowercased.

    • $translate bool

      Returns lowercased.

    • $textFormat string

      Text format to be returned.

  • get_time_remaining ( DateTimeInterface | string | int $dt DateTime | null $now bool $full int | string $limit bool $lower bool $translate ) : string

    Execute a reversed <get_time_ago()> with labels adapted for the time remaining between the two dates.

    • $dt DateTimeInterface | string | int

      Date and time of the event. Can be a DateTime object, a string which can be parsed by the DateTime constructor, or a timestamp as an integer.

    • $now DateTime | null

      Now DateTime. Default, now.

    • $full bool

      Don't filter the fields (YMWDhms), so returns all the fields, even if they're zero.

    • $limit int | string

      Returns null if the delay is above the given limit, represented as seconds or a string duration.

    • $lower bool

      Returns lowercased.

    • $translate bool

      Returns lowercased.

  • get_monthes ( string | null $locale ) : array

    Returns the month names and numbers as an array containing monthes as objects, with those information:

    Index: integer number of the month (1 for january, 12 for december).

    $month->num: padded month number.

    $month->name: long name translated (e.g. February).

    $month->short: short name translated (e.g. Feb).

    • $locale string | null

      Locale name.

  • get_month_name ( DateTimeInterface | string | int $idx bool $short string | null $locale ) : string

    Get the month name based on its index.

    • $idx DateTimeInterface | string | int

      Index of the month ('08' or 8).

    • $short bool

      Returns the short name if true. Else, the long.

    • $locale string | null

      Locale name.

  • get_days ( string | null $locale ) : array

    Returns the days of week names and numbers as an array containing days as objects, with those information:

    Index: integer number of the day (1 for monday, 7 for sunday).

    $day->num: integer day number.

    $day->name: long name translated (e.g. Wednesday).

    $day->short: short name translated (e.g. Wed).

    • $locale string | null

      Locale name.

  • get_day_name ( DateTimeInterface | string | int $idx bool $short string | null $locale ) : string

    Get the day name based on its index.

    • $idx DateTimeInterface | string | int

      Index of the day ('5' or 5).

    • $short bool

      Returns the short name if true. Else, the long.

    • $locale string | null

      Locale name.

  • is_valid_datetime ( mixed $value string $format ) : boolean

    Check if a given value is a proper string representing a PHP date/time.

    • $value mixed

      Value to be checked.

    • $format string

      The format, with similar notation as PHP DateTime's format function.

  • build_datetime_from_form ( mixed $date mixed $time ) : DateTime

    Build a DateTime from two form inputs: YYYY-MM-DD and hh:mm:ss.

    • $date mixed

      Form date which should be YYYY-MM-DD.

    • $time mixed

      Form time which should be hh:mm:ss.

  • format_date ( string | int | DateTimeInterface $dt string $locale string $format bool | null $removeYear string $timezone ) : string

    Format the date based on given locale.

    • $dt string | int | DateTimeInterface

      Date.

    • $locale string

      Locale.

    • $format string

      Custom IntlDateFormatter pattern, or:

      short

      medium

      long

      full

    • $removeYear bool | null

      If true, year will be removed. If null, year will be removed if it's different from current year.

    • $timezone string

      Timezone. If null, the one got from $dt's DateTime instance will be used.

  • _format_date ( string | int | DateTime $dt string $locale ) : void

    Echo the formatted date based on given locale.

    • $dt string | int | DateTime

      Date.

    • $locale string

      Locale.

  • get_calendar_month_days ( int | string $year int | string $month bool $sundayFirst null | Closure $dataModifier string $url ) : object

    Returns an object containing the weeks and days of weeks of a given month, in order to be used to display a calendar.

    • $year int | string

      Requested year.

    • $month int | string

      Requested month.

    • $sundayFirst bool

      Is sunday first day of the week. If false (default), then monday is.

    • $dataModifier null | Closure

      Function executed for each day, to populate the "data" property.

    • $url string

      URL for previous/current/next monthes information.

utils

Functions

  • value_seems_true ( mixed $value ) : bool

    Check if a value seems to represent a true or not (e.g, '1', 'yes', etc.).

    • $value mixed

      Value to be checked.

  • dump ( mixed $something ) : string

    Returns the dump (aka 'var_dump') of a variable.

    • $something mixed

      Variable to dump.

  • object_id ( mixed $obj string $key ) : integer

    Check if the given object is an object and return its ID property as defined as key parameter, if exists, or null. If the given object is a scalar variable, check if this value is numeric and returns it (assuming it's already the ID). If nothing works, it will returns null.

    • $obj mixed

      Object, string or integer thing.

    • $key string

      ID key.

  • object_merge ( ) : object

    Merge several array and/or objects together, like array_merge, but type-tolerant.

  • restrict_keys ( array | object $thing array $keys ) : array | object

    Delete unwanted keys in array or object.

    • $thing array | object

      Array or object to process.

    • $keys array

      Allowed keys.

  • object_map ( Closure $func object $object ) : object

    Map an object, exactly like <array_map> does for arrays.

    • $func Closure

      Callback function executed for each item. The first parameter is the item itself. The second is the property name.

    • $object object

      Input object.

  • to_array ( array | object $d ) : array

    Convert recursively an array or an object to an array.

    • $d array | object

      Object/array to convert.

  • to_object ( array | object $d ) : object | array

    Convert recursively an array or an object to an object.

    • $d array | object

      Object/array to convert.

  • get_class_constants ( string $className string | null $filter Closure | null $func ) : array

    Get the constants defined in a specific class, optionaly altered by a regexp and/or a user function.

    • $className string

      Name of the class

    • $filter string | null

      Regular expression used for

    • $func Closure | null

      Alteration function.

  • create_ranges_from_indexes ( array $indexes ) : array

    Create an array containing object pairs with 'from' and 'to' index values, based on a unidimensional array containing all indexes. E.g. [ 2, 1, 3, 0, 2, 4, 8, 7 ] => [ { from: 0, to: 4 }, { from: 7, 8 } ]

    • $indexes array

      Array of indexes.

  • shuffle_assoc ( ) : array

    Shuffle an associative array, preserving keys.

  • is_int_val ( mixed $value ) : boolean

    Check if the given value is an integer, whatever it's inside a string or not.

    • $value mixed

      Value to verify.

  • is_float_val ( mixed $value ) : boolean

    Check if the given value is a float, whatever it's inside a string or not.

    • $value mixed

      Value to verify.

  • is_assoc_array ( mixed $arr ) : boolean

    Check if the given argument is an associative array, aka an array with non-numerical keys and/or some non-consecutive numerical keys.

    • $arr mixed

      Array to verify.

  • is_numeric_array ( mixed $arr ) : boolean

    Check if the given argument is an array with perfect consecutive numerical keys or not.

    • $arr mixed

      Array to verify.

  • array_filter_recursive ( array $arr Closure | null $callback bool $removeEmptyArrays ) : array

    Filter an array recursively.

    • $arr array

      Array to filter.

    • $callback Closure | null

      Function to execute on each leave. If the function is null, a boolean comparision will be made.

    • $removeEmptyArrays bool

      If true, the array without leaves will be removed. Else, the empty array will stay in place.

  • recursive ( array $arr string $childrenKey Closure $func int $depth ) : void

    Execute a function recursively on items of an array, looking for the children using a specific key.

    • $arr array

      Array of items.

    • $childrenKey string

      Key to look for on each item, to find its own children.

    • $func Closure

      Function to execute. This function will accept three parameters:

      the given child;

      its depth;

      its parents.

    • $depth int

      Current depth. Default starting depth is zero. It's used by the function itself to increment the depth while walking diving inside the array.

  • walk_data ( mixed $data string $key string $separator ) : mixed

    Walk through a recursive object and/or array to find the chained key, in which keys are separated by $separator (default '.'). E.g. walk_data([ 'a' => [ 'aa' => 'foo' ] ], 'a/aa', '/') => 'foo'

    • $data mixed

      Recursive object and/or array to walk through.

    • $key string

      Chained key.

    • $separator string

      Keys separator. Default '.'.

  • cast_data ( array $input mixed $data bool $trim string $separator string $key ) : mixed

    Cast a recursive data, using the pattern given as $data. E.g. $casted = cast_data($inputData, (object) [ 'name' => '?str', 'meta' => (object) [ 'categories' => '?str[]', 'url' => '?str', 'timestamp' => '?int', ], ]);

    • $input array

      Input value.

    • $data mixed

      Pattern of the data we are waiting for.

    • $trim bool

      Trim string values or not (default true)?

    • $separator string

      Chained keys separator (when default one may be found in one of the key names).

    • $key string

      Current walking key. Internal use only.

  • contrast_color ( string $hex bool $asRgb ) : string | array

    Returns the most contrasted color (white or black), based on a specified color.

    • $hex string

      Hexadecimal color. Hash is optional.

    • $asRgb bool

      Returns the result as an RGB triplet instead of an hexadecimal color.

  • unzip ( string $zipPath string $destPath ) : bool

    Uncompress a ZIP file into a destination folder.

    • $zipPath string

      ZIP file path.

    • $destPath string

      Folder where the zip should be unzip.

  • zip_folder ( string $folderPath string $zipPath Closure | null $filter ) : void

    Compress a folder into a ZIP file.

    • $folderPath string

      Folder which should be compressed.

    • $zipPath string

      ZIP file destination path.

    • $filter Closure | null

      Filter function.

visitor

Functions

  • guess_browser_by_user_agent ( string $userAgent ) : object | null

    Try to guess the browser and the version based on user agent.

    • $userAgent string

      User agent.

bootstrap

Functions

  • boot ( string $ctx ) : void

    Boot the application, with the given context:

    'web' should be used from 'index.php';

    'cli' will be used automatically when calling the framework's file from command line;

    'dev' will be used automatically when openning the framework's file directly from the web browser.

    • $ctx string

      Context name