State Class
Files
/engine/class.www-state.php
Introduction
State class is one of the core classes of Wave Framework. State holds a lot of information about the server, configuration as well as current request. State class can be used separately from Wave Framework, but is generally not recommended, since it is tailored for use with Wave Framework.
State object is also used by Wave Framework to load configuration - from '/config.ini' file - to State data variable, so that it can be used and accessed by Wave Framework MVC classes. By default State class has a number of data variables loaded by default, to make sure that State can work even when no configuration file is loaded.
State carries additional functionality: it includes a State Messenger as well as wrappers for creating and destroying sessions and cookies, returning translations and sitemap information and more. To learn more about specific functionality of State when used through MVC objects of Wave Framework, you should look into "State and Configuration" feature guide
The rest of this document details the use of Logger class in general, often outside the scope of how Wave Framework itself uses the class. This information is useful only to developers who intend to develop core of Wave Framework or use the class independently in another project.
Using State class
While it is unlikely that State class can be of use outside Wave Framework, below is an example of how to create a new State object. State object is created with a Configuration array and some of these Configuration keys can affect the functionality of PHP (State will attempt to change PHP settings accordingly).
require('/engine/class.www-state.php');
// Configuration should be an array
$state=new WWW_State($config);
State class is automatically used by WWW_API objects. When creating a new WWW_API object, then you can send the State class like this:
require('/engine/class.www-api.php');
$api=new WWW_API($state);
State defines it's own default data and then loads the $config on top of that data. Most of State data variables are directly related to data loaded from /config.ini file and it is recommended to read more about these settings from Configuration documentation.
To change a state value, you can do this:
// Change a single setting
$state->setState('my-key','my-value');
// Change multiple settings at the same time with array of key and value pairs
$state->setState($config);
State Settings with Additional Functionality
timezone
This also changes PHP's default timezone through date_default_timezone_set() function.
output-compression
This value can be set to 'deflate' or 'gzip'. But if the request making user agent does not notify the server that it supports gzip or deflate, then State automatically keeps this value set to false.
Rest of the functionality of State class is too specific to Wave Framework API and it will be covered more in the feature guides.
State Class Parameters
public $data=array()
This is the primary variable of State class and it carries representation of the system configuration, both loaded from /config.ini file as well as initialized from environmental server variables.
Overview of variables set in $data array:
- 404-image-placeholder - True or false flag for whether placeholder 404 image is used.
- 404-view - View keyword that is loaded when URL Controller cannot find a page.
- access-control - This is set as the access-control header for all requests.
- apc - True or false flag for whether the system attempts to use APC PHP accelerator.
- api-logging - If this is set to false, then API logging is not used. Otherwise this should be an array of logging flags.
- api-permissions - Array of currently set API permissions used whenever permissions are checked.
- api-profile - Currently used API profile, this is set by the API.
- api-public-profile - API profile name that is considered public.
- api-public-token - If this is set to 1, then a public API token is required to be sent with all web forms.
- api-versions - This is an array of enabled API versions.
- cache-database - Cache database configuration that consists of cache table, cache address, timestamp and data column names.
- cache-database-address-column - Database cache address/index column.
- cache-database-data-column - Column in database cache table that stores cache.
- cache-database-errors - True or false setting whether cache database calls register errors.
- cache-database-host - Cache database host address.
- cache-database-name - Cache database name.
- cache-database-password - Cache database user password.
- cache-database-persistent - If database cache connection is persistent.
- cache-database-table-name - Cache database table name.
- cache-database-timestamp-column - Cache database timestamp column that stores timestamps of cache entries.
- cache-database-type - The database type of cache connection, either mysql, sqlite, mssql, oracle, postgresql.
- cache-database-username - Cache database username.
- client-ip - IP address of the client that makes the request, this is detected by the system and takes into account proxies.
- client-user-agent - Client user agent string that makes the request.
- content-security-policy - This is the content security policy rule for loading external content.
- database-errors - True or false flag for whether database errors are logged.
- database-host - Database host name.
- database-name - Database name.
- database-password - Database access password
- database-persistent - True or false flag for whether database connection is persistent.
- database-type - Database type, either mysql, sqlite, mssql, oracle, postgresql.
- database-username - Database access username.
- developer - True or false flag whether developer mode is active.
- developer-ip - Configuration setting for developer IP address.
- developer-user-agent - Configuration setting for developer user agent.
- directory-data - Location of Filesystem '/data/' folder which is used to store filesystem database files.
- directory-filesystem - Root location of Filesystem folder itself.
- directory-keys - Filesystem location for keys file, used for certificates.
- directory-static - Filesystem folder for static files.
- directory-system - Root folder of the system.
- directory-tmp - Filesystem folder for temporary files.
- directory-user - Filesystem folder of user folder.
- dynamic-color-whitelist - Comma separated list of background colors allowed to be used with on-demand image loading.
- dynamic-filter-whitelist - Comma separated list of filters allowed to be used with on-demand image loading.
- dynamic-image-filters - True or false flag for whether dynamic image filters are allowed.
- dynamic-image-loading - True or false flag for whether dynamic image loading is allowed at all.
- dynamic-max-size - Maximum pixel size of dynamically loaded picture width and height.
- dynamic-position-whitelist - Comma separated list of picture positions allowed to be used with on-demand image loading.
- dynamic-quality-whitelist - Comma separated list of image quality settings allowed to be used with on-demand image loading.
- dynamic-resource-loading - True or false flag for whether dynamic resource loading is supported.
- dynamic-size-whitelist - Comma separated list of image resolutions allowed to be used with on-demand image loading.
- enforce-first-language-url - True or false flag for whether language node is required as part of the request URL.
- enforce-url-end-slash - True or false flag for whether end URL slash is required as part of the request URL.
- errors-reporting - This is the current error-reporting level, either 'off', 'critical' or 'full'.
- errors-trace - This sets if the entire trace log is written to error files if errors are encountered.
- errors-verbose - Defines whether system prints out full error details for the request
- file-robots - Robots command string for file downloads.
- fingerprint - Fingerprint string about the user agent that made the request, only used if session fingerprinting is used.
- forbidden-extensions - Array of file extensions that cannot be requested over HTTP.
- frame-permissions - This is used for the header that states if a URL can be used from a frame or not.
- headers-set - This is the list of headers to be set. Value assigns whether it should replace previously set header like that or not.
- headers-unset - This is the list of headers that should be moved.
- home-view - View keyword that is considered for 'home' or 'root' pages. This is the URL that is considered the home view from Sitemap file.
- http-accept - Array of types user agent accepts as the response.
- http-accept-charset - Array of charsets accepted by the user agent.
- http-accept-encoding - Array of character encodings accepted by the user agent.
- http-accept-language - Array of language keywords accepted by the user agent.
- http-authentication-ip - Comma-separated list of IP addresses that are allowed to log-in through HTTP authentication.
- http-authentication-password - HTTP authentication password.
- http-authentication-username - HTTP authentication username.
- http-do-not-track - True or false flag whether the user agent allows to be tracked or not.
- http-content-length - Content length of the HTTP request.
- http-content-type - Content type of the HTTP request.
- http-host - HTTP host of the server.
- http-if-modified-since - If-modified-since date if user agent sends the request with the value.
- http-input - Data stream if sent with the request, such as when sending an XML with POST.
- http-referrer - This carries the URL where the request came from. This is not sent with some browsers at all times or proxies.
- http-request-method - Request method used for current HTTP request. Usually GET or POST, but also HEAD.
- https-mode - True or false flag for whether current request uses HTTPS or not.
- image-extensions - Array of picture extensions that are served through Image Handler.
- image-robots - Robots command string for pictures.
- index-url-cache-timeout - Cache lifetime for URL Controller requests, for solving URL's.
- index-view-cache-timeout - Default cache lifetime for View Controller requests.
- internal-logging - If this is set to false, then internal logging is not used. Otherwise this should be an array of logging flags.
- language - Currently detected language.
- languages - Array of language keywords used by the system.
- limiter - True or false flag for whether HTTP request limiter is used or not.
- limiter-authentication - True or false flag for whether HTTP authentication is used.
- limiter-blacklist - Comma-separated list of IP addresses that are blocked from making HTTP requests.
- limiter-https - True or false flag for whether HTTPS is required for requests.
- limiter-load - True or false flag for whether server load limiter is used.
- limiter-referrer - If this is set and referrer Limiter is used, then this is used to match against the domain names or throws a forbidden message otherwise.
- limiter-request - True or false flag for whether HTTP request rate-limiter is used or not.
- limiter-whitelist - Comma-separated list of IP addresses that are allowed to make HTTP requests.
- locale - This is a locale category and keyword, such as 'en_GB'.
- memcache - True or false setting whether Memcache is used.
- memcache-host - Memcache server address.
- memcache-port - Memcache port number.
- memory-limit - This is the current memory limit as it is defined in Configuration, if set.
- output-compression - Currently used output compression mode.
- project-author - Project author that is used by View Controller meta tag.
- project-copyright - Project copyright information that is used by View Controller meta tag.
- project-title - Project title that is used by View Controller meta title.
- request-id - Unique HTTP request ID.
- request-time - Request timestamp.
- request-true - True request URI.
- request-uri - Request URI.
- resource-cache-timeout - Lifetime of resource cache.
- resource-extensions - Array of extensions that will be loaded through Resource Handler.
- resource-robots - Robots command string for resources.
- robots - Universal robots command string.
- robots-cache-timeout - Cache lifetime of robots.txt files.
- server-ip - Server IP address.
- server-name - Defined server name.
- server-port - Defined server port.
- session-data - This holds data from session storage or temporary data before it is stored in session storage.
- session-original-data - This is the session data at the start of the request, used for comparing.
- session-domain - Session cookie domain.
- session-fingerprint - True or false flag for whether sessions are tied to IP and browser fingerprint.
- session-fingerprint-key - Key value that the fingerprint will be stored under in sessions.
- session-http-only - Whether session cookie is HTTP-only or not.
- session-id - This holds the current session ID, if sessions are active.
- session-lifetime - Duration of seconds for how long sessions should last, defaults to server value of 'session.gc-maxlifetime'.
- session-name - Session name keyword.
- session-path - Session cookie path.
- session-permissions-key - Keyword that is used for storing permissions.
- session-regenerate - The amount of seconds after which session ID is regenerated automatically.
- session-secure - Whether session cookie is only usable over HTTPS.
- session-timestamp-key - Keyword in sessions that stores session timestamp.
- session-token-key - Keyword in sessions that store public request token.
- session-user-key - Keyword that is used for storing user account data.
- sitemap - Array of current language sitemap data.
- sitemap-cache-timeout - Cache lifetime of sitemap.xml files.
- sitemap-raw - Raw sitemap data in an array.
- storage - This holds temporary global storage that can be written to and read through Factory.
- test-database-host - Test database host name.
- test-database-name - Test database name.
- test-database-password - Test database access password
- test-database-type - Test database type, either mysql, sqlite, mssql, oracle, postgresql.
- test-database-username - Test database access username
- testing
- True or false value about whether a test is currently being run or not. This is set to true when run through Test Suite.
- time-limit - This is the current time limit as it is defined in Configuration, if set.
- timezone - Currently used timezone.
- translations - Array of translations of current language.
- trusted-proxies - Array of trusted proxy IP addresses.
- url-base - Base URL that is used for HTML views and resource locations.
- url-web - Web root URL node, in case system is not installed in root of the website.
- user-data - Array of user data.
- user-permissions - Array of user permissions.
- version - This holds the application version number.
- view - Currently used view.
- view-headers - This holds headers that will be set by View Controller.
public $databaseConnection=false
This should hold Database class and connection data, if used.
private $sessionHandler=false
This holds the session handler for session management. This is a WWW_Sessions class from '/engine/class.www-sessions.php' file.
private $sessionStarted=false
This is an internal variable that State uses to check if it has already validated sessions or not.
private $messenger=false
This holds the 'keyword' or 'passkey' of currently used State Messenger .
private $messengerData=array()
This holds State Messenger data as an array.
private $tools=false
This holds system Tool Class object, if it exists.
State Class Methods
The methods of State class are considered 'final' mainly due to them being core and expected by Wave Framework API and Factory classes.
final public function __construct($config=array()){
Construction of State object initializes the defaults for $data variable. A lot of the data is either loaded from /config.ini file or initialized based on server environment variables. Fingerprint string is also created during construction as well as input data loaded from XML or JSON strings, if sent with POST directly.
final public function __destruct()
When State class is not used anymore, then State Messenger data - if set - is written to Filesystem based on the State Messenger key. This method also calls the commit-session method, if it has not been called yet.
final public function getState($input)
This is the basic call to return a State variable from the object. If this method is called without any variables, then the entire State array is returned. You can send one or more key variables to this method to return a specific key from State. If you send multiple parameters then this method attempts to find keys of a key in case the State variable is an array itself. $input variable is only used within State class itself. Method returns null for keys that have not been set.
final public function setState($input)
This method is used to set a variables in the State object. If an array is passed as the first parameter, then multiple State variables are set at the same time. You can also send multiple parameters with this method to set values of multidimensional arrays stored in State, such as sending two different keys and a value as the third parameter. $input variable is only used within State class itself.
final private function stateChanged($variable,$value=true)
This is a private method used internally whenever configuration is changed. It has checks for cases when a variable is changed that carries additional functionality such as when changing the timezone or output compression. For example, if output compression is set, but not supported by user agent that is making the request, then output suppression is turned off.
final public function commitHeaders()
This function is called before output is pushed to browser by the API or when State object is not used anymore. This method is not accessible to Factory class, but it is not private.
final public function getTranslations($language=false,$keyword=false,$subkeyword=false)
This method returns an array of currently active translations, or for a language set with $language variable. If $keyword is also set, then it returns a specific translation with that keyword from $language translations. If $keyword is an array, then $subkeyword can be used to return specific translation from that keyword.
final public function getContent($name,$language=false)
This method includes or reads in a file from '/resources/content/' folder $name is the modified filename that can also include subfolders, but without the language prefix and without extension in the filename itself. If $language is not defined then currently active language is used.
final public function getSitemapRaw($language=false,$keyword=false)
This method returns an array of currently active sitemap, or a sitemap for a language set with $language variable. If $keyword is also set, then it returns a specific sitemap node with that keyword from $language sitemap file. This method returns the original, non-modified sitemap that has not been parsed for use with URL Controller.
final public function getSitemap($language=false,$keyword=false)
This returns sitemap array that is modified for use with View Controller and other parts of the system. It returns sitemap for current language or a language set with $language variable and can return a specific sitemap node based on $keyword.
final public function stateMessenger($address,$overwrite=false)
This method initializes State Messenger by giving it an address and assigning the file that State Messenger will be stored under. If the file already exists and $overwrite is not turned on, then it automatically loads contents of that file from Filesystem.
final public function setMessengerData($data,$value=false)
This writes data to State Messenger . $data is the key and $value is the value of the key. $data can also be an array of keys and values, in which case multiple values are set at the same time.
final public function unsetMessengerData($key=false)
This method removes key from State Messenger based on value of $key. If $key is not set, then the entire State Messenger data is cleared.
final public function getMessengerData($key=false,$remove=true)
This method returns data from State messenger. It either returns all the data from initialized state messenger, or just a $key from it. If $remove is set, then data is also set for deletion after it has been accessed.
final public function setUser($data)
This method sets user data array in session. This is a simple helper function used for holding user-specific data for a web service. $data is an array of user data.
final public function getUser($key=false)
This either returns the entire user data array or just a specific $key of user data from the session.
final public function unsetUser()
This unsets user data and removes the session of user data.
final public function setPermissions($permissions)
This method sets an array of $permissions or a comma-separated string of permissions for the current user permissions session.
final public function getPermissions()
This method returns an array of currently set user permissions from the session.
final public function checkPermissions($permission)
This checks for an existence of permissions in the user permissions session array or in the API profile permissions setting. $permissions is either a comma-separated string of permissions to be checked, or an array. This method returns false when one of those permission keys is not set in the permissions session. Method returns true, if $permissions exist in the permissions session array.
final public function unsetPermissions()
This unsets permissions data from session similarly to how unsetUser() method unsets user data from session.
final public function getPublicToken($regenerate=false,$forced=false)
This method returns the currently active public token that is used to increase security against cross-site-request-forgery attacks. This method returns false if user session is not populated, in which case public token is not needed. $regenerate sets if the token should be regenerated if it already exists, this invalidates forms when Back button is used after submitting data, but is more secure. $forced is used to force token generation even if no user session is active.
final public function checkPublicToken()
This method is useful when 'api-public-token' setting is off in configuration, but you still want to protect your API method from public API requests from XSS and other attacks. This returns false if the provided public API token is incorrect.
final public function startSession($configuration=false)
This method validates current session data and checks for lifetime as well as session fingerprint. It notifies session handler if any changes have to be made. Custom session configuration can be sent with a variable. Parameters are as follows:
- name - Session cookie name.
- lifetime - Session cookie lifetime.
- path - URL path for session cookie.
- domain - Domain for session cookie.
- secure - Whether session cookie is for secure connections only.
- http-only - Whether session cookie is for HTTP requests only and unavailable for scripts.
- user-key - Session key for storing user data.
- permissions-key - Session key for storing user permissions.
- fingerprint-key - Session key for storing session fingerprint.
- timestamp-key - Session key for storing session timestamp.
- token-key - Session key for public request tokens for protecting against replay attacks.
- fingerprint - Session key for session fingerprinting for protecting against replay attacks.
final public function regenerateSession($deleteOld=true)
This method regenerates ongoing session with a new ID. $deleteOld, if set, deletes the previous session.
final public function setSession($key=false,$value=false)
This method sets a session variable $key with a value $value. If $key is an array of keys and values, then multiple session variables are set at once.
final public function getSession($key=false)
This method returns $key value from session data. If $key is an array of keys, then it can return multiple variables from session at once. If $key is not set, then entire session array is returned. Method returns null for keys that have not been set.
final public function unsetSession($key=false)
This method unsets $key value from current session. If $key is an array of keys, then multiple variables can be unset at once. If $key is not set at all, then this simply destroys the entire session.
final public function setCookie($key,$value,$configuration=array())
This method sets a cookie with $key and a $value. $configuration is an array of cookie parameters that can be set. Parameters are as follows:
- timeout - This is how many seconds, since the moment cookie is created, it will not be deleted.
- expire - This is how many seconds, since the moment cookie is created, it will not be deleted. This is different from default PHP setcookie() call that just asks the timestamp. If this value is sent, then 'timeout' value will be ignored entirely.
- path - Web root path where the cookie is valid. By default the web root of the system is used.
- domain - Domain which applies to the cookie. Default is the current system domain.
- secure - Whether cookie is set only over secure connection.
- httponly - Whether cookie can be only accessed over HTTP and not with JavaScript.
final public function getCookie($key)
This method returns a cookie value with the set $key. $key can also be an array of keys, in which case multiple cookie values are returned in an array. Method returns null for keys that have not been set.
final public function unsetCookie($key)
This method unsets a cookie with the set key of $key. If $key is an array, then it can remove multiple cookies at once.
final public function setHeader($header,$replace=true)
This is a simple wrapper function for setting a header. $header is the header string to be sent and $replace is a true-false flag about whether previous similar header should be replaced or not.
final public function unsetHeader($header)
This method is a wrapper function for simply removing a previously set header. $header is the header that should be removed.
final public function callTool($type,$arg1=false,$arg2=false)
This method loads tools object if it doesn't exist yet and then allows to call various methods of the tool. You can call filesystem cleaner, indexer or a file-size calculator (and each work recursively) and counter.
final public function terminal($command)
This method is wrapper function for making terminal calls. It attempts to detect what terminal is available on the system, if any, and then execute the call and return the results of the call.