PHP Class Piwik\Common

This is the only non-Tracker class loaded by the **\/piwik.php** file.
Afficher le fichier Open project: piwik/piwik Class Usage Examples

Méthodes publiques

Свойство Type Description
$isCliMode

Méthodes publiques

Méthode Description
convertUserIdToVisitorIdBin ( $userId ) : string Converts a User ID string to the Visitor ID Binary representation.
convertVisitorIdToBin ( string $id ) : string This function will convert the input string to the binary representation of the ID but it will throw an Exception if the specified input ID is not correct
destroy ( mixed &$var ) Marks an orphaned object for garbage collection.
extractCountryCodeFromBrowserLanguage ( string $browserLanguage, array $validCountries, boolean $enableLanguageToCountryGuess ) : array Returns list of valid country codes
extractLanguageAndRegionCodeFromBrowserLanguage ( string $browserLanguage, array $validLanguages = [] ) : string Returns the language and region string, based only on the Browser 'accepted language' information.
extractLanguageCodeFromBrowserLanguage ( string $browserLanguage, array $validLanguages = [] ) : string Returns the language and region string, based only on the Browser 'accepted language' information.
forceDotAsSeparatorForDecimalPoint ( float | string $value ) : string Force the separator for decimal point to be a dot. See https://github.com/piwik/piwik/issues/6435 If for instance a German locale is used it would be a comma otherwise.
generateUniqId ( ) : string Returns a 32 characters long uniq ID
getBrowserLanguage ( string | null $browserLang = null ) : string Returns the browser language code, eg. "en-gb,en;q=0.5"
getCampaignParameters ( ) : array Returns the list of Campaign parameter names that will be read to classify a visit as coming from a Campaign
getClassLineage ( string $class ) : string[] Returns the list of parent classes for the given class.
getContinent ( string $country ) : string Returns the continent of a given country
getContinentsList ( ) : array Returns list of continent codes
getCountriesList ( boolean $includeInternalCodes = false ) : array Returns list of valid country codes
getCountry ( string $lang, boolean $enableLanguageToCountryGuess, string $ip ) : string Returns the visitor country based on the Browser 'accepted language' information, but provides a hook for geolocation via IP address.
getCurrentLocationProviderId ( ) Returns the ID of the current LocationProvider (see UserCountry plugin code) from the Tracker cache.
getLanguageToCountryList ( ) : array Returns a list of language to country mappings.
getLanguagesList ( ) : array Returns the list of valid language codes.
getLastJsonError ( ) : string Returns a human readable error message in case an error occcurred during the last json encode/decode.
getProviderNames ( ) : array Returns list of provider names
getRandomString ( integer $length = 16, string $alphabet = "abcdefghijklmnoprstuvwxyz0123456789" ) : string Generate random string.
getRequestVar ( string $varName, string | null $varDefault = null, string | null $varType = null, array | null $requestArrayToUse = null ) : mixed Gets a sanitized request parameter by name from the $_GET and $_POST superglobals.
getSqlStringFieldsArray ( array | string $fields ) : string Returns a string with a comma separated list of placeholders for use in an SQL query. Used mainly to fill the `IN (.
hasJsonErrorOccurred ( ) : boolean Detects whether an error occurred during the last json encode/decode.
hash ( string $str, boolean $raw_output = false ) : string Configurable hash() algorithm (defaults to md5)
hashStringToInt ( string $string ) : integer Hashes a string into an integer which should be very low collision risks
hex2bin ( string $str ) : string Convert hexadecimal representation into binary data.
isActionsPluginEnabled ( )
isGoalPluginEnabled ( ) * Tracker
isPhpCgiType ( ) : boolean Returns true if PHP is executed as CGI type.
isPhpCliMode ( ) : boolean Returns true if PHP was invoked from command-line interface (shell)
isRunningConsoleCommand ( ) : boolean Returns true if the current request is a console command, eg.
isXmlHttpRequest ( ) : boolean Returns true if the request is an AJAX request.
json_decode ( string $json, boolean $assoc = false ) : mixed JSON decode wrapper - missing or broken in some php 5.x versions
json_encode ( mixed $value ) : string JSON encode wrapper - missing or broken in some php 5.x versions
mb_strlen ( string $string ) : integer Multi-byte strlen() - works with UTF-8
mb_strtolower ( string $string ) : string Multi-byte strtolower() - works with UTF-8.
mb_substr ( string $string, integer $start ) : string Multi-byte substr() - works with UTF-8.
prefixTable ( string $table ) : string Returns a prefixed table name.
prefixTables ( ) : array Returns an array containing the prefixed table names of every passed argument.
printDebug ( $info = '' )
sanitizeInputValue ( string $value ) : string Sanitize a single input value and removes line breaks, tabs and null characters.
sanitizeInputValues ( mixed $value, boolean $alreadyStripslashed = false ) : mixed Sanitizes a string to help avoid XSS vulnerabilities.
sanitizeLineBreaks ( string $value ) : string
sanitizeNullBytes ( string $value ) : string
sendHeader ( string $header, boolean $replace = true ) Sets outgoing header.
sendResponseCode ( integer $code ) Sends the given response code if supported.
stringEndsWith ( $haystack, $needle )
unprefixTable ( string $table ) : string Removes the prefix from a table name and returns the result.
unsanitizeInputValue ( string $value ) : string Unsanitizes a single input value and returns the result.
unsanitizeInputValues ( string | array $value ) : string | array Unsanitizes one or more values and returns the result.

Méthodes protégées

Méthode Description
checkValidLanguagesIsSet ( $validLanguages ) : array

Private Methods

Méthode Description
sanitizeString ( $value ) : string Sanitize a single input value

Method Details

checkValidLanguagesIsSet() protected static méthode

protected static checkValidLanguagesIsSet ( $validLanguages ) : array
$validLanguages
Résultat array

convertUserIdToVisitorIdBin() public static méthode

Converts a User ID string to the Visitor ID Binary representation.
public static convertUserIdToVisitorIdBin ( $userId ) : string
$userId
Résultat string

convertVisitorIdToBin() public static méthode

This is used when building segments containing visitorId which could be an invalid string therefore throwing Unexpected PHP error [pack(): Type H: illegal hex digit i] severity [E_WARNING] It would be simply to silent fail the pack() call above but in all other cases, we don't expect an error, so better be safe and get the php error when something unexpected is happening
public static convertVisitorIdToBin ( string $id ) : string
$id string
Résultat string binary string

destroy() public static méthode

For more information: {@link https://github.com/piwik/piwik/issues/374}
public static destroy ( mixed &$var )
$var mixed The object to destroy.

extractCountryCodeFromBrowserLanguage() public static méthode

Returns list of valid country codes
public static extractCountryCodeFromBrowserLanguage ( string $browserLanguage, array $validCountries, boolean $enableLanguageToCountryGuess ) : array
$browserLanguage string
$validCountries array Array of valid countries
$enableLanguageToCountryGuess boolean (if true, will guess country based on language that lacks region information)
Résultat array Array of 2 letter ISO codes

extractLanguageAndRegionCodeFromBrowserLanguage() public static méthode

* The language tag is defined by ISO 639-1 * The region tag is defined by ISO 3166-1
public static extractLanguageAndRegionCodeFromBrowserLanguage ( string $browserLanguage, array $validLanguages = [] ) : string
$browserLanguage string Browser's accepted langauge header
$validLanguages array array of valid language codes. Note that if the array includes "fr" then it will consider all regional variants of this language valid, such as "fr-ca" etc.
Résultat string 2 letter ISO 639 code 'es' (Spanish) or if found, includes the region as well: 'es-ar'

extractLanguageCodeFromBrowserLanguage() public static méthode

* The language tag is defined by ISO 639-1
public static extractLanguageCodeFromBrowserLanguage ( string $browserLanguage, array $validLanguages = [] ) : string
$browserLanguage string Browser's accepted langauge header
$validLanguages array array of valid language codes
Résultat string 2 letter ISO 639 code 'es' (Spanish)

forceDotAsSeparatorForDecimalPoint() public static méthode

Force the separator for decimal point to be a dot. See https://github.com/piwik/piwik/issues/6435 If for instance a German locale is used it would be a comma otherwise.
public static forceDotAsSeparatorForDecimalPoint ( float | string $value ) : string
$value float | string
Résultat string

generateUniqId() public static méthode

Returns a 32 characters long uniq ID
public static generateUniqId ( ) : string
Résultat string 32 chars

getBrowserLanguage() public static méthode

Returns the browser language code, eg. "en-gb,en;q=0.5"
public static getBrowserLanguage ( string | null $browserLang = null ) : string
$browserLang string | null Optional browser language, otherwise taken from the request header
Résultat string

getCampaignParameters() public static méthode

Returns the list of Campaign parameter names that will be read to classify a visit as coming from a Campaign
public static getCampaignParameters ( ) : array
Résultat array array( 0 => array( ... ) // campaign names parameters 1 => array( ... ) // campaign keyword parameters );

getClassLineage() public static méthode

Returns the list of parent classes for the given class.
public static getClassLineage ( string $class ) : string[]
$class string A class name.
Résultat string[] The list of parent classes in order from highest ancestor to the descended class.

getContinent() public static méthode

Returns the continent of a given country
public static getContinent ( string $country ) : string
$country string 2 letters iso code
Résultat string Continent (3 letters code : afr, asi, eur, amn, ams, oce)

getContinentsList() public static méthode

Returns list of continent codes
See also: Piwik\Intl\Data\Provider\RegionDataProvider::getContinentList()
Deprecation: Use Piwik\Intl\Data\Provider\RegionDataProvider instead.
public static getContinentsList ( ) : array
Résultat array Array of 3 letter continent codes

getCountriesList() public static méthode

Returns list of valid country codes
See also: Piwik\Intl\Data\Provider\RegionDataProvider::getCountryList()
Deprecation: Use Piwik\Intl\Data\Provider\RegionDataProvider instead.
public static getCountriesList ( boolean $includeInternalCodes = false ) : array
$includeInternalCodes boolean
Résultat array Array of (2 letter ISO codes => 3 letter continent code)

getCountry() public static méthode

Returns the visitor country based on the Browser 'accepted language' information, but provides a hook for geolocation via IP address.
public static getCountry ( string $lang, boolean $enableLanguageToCountryGuess, string $ip ) : string
$lang string browser lang
$enableLanguageToCountryGuess boolean If set to true, some assumption will be made and detection guessed more often, but accuracy could be affected
$ip string
Résultat string 2 letter ISO code

getCurrentLocationProviderId() public static méthode

Returns the ID of the current LocationProvider (see UserCountry plugin code) from the Tracker cache.
public static getCurrentLocationProviderId ( )

getLanguageToCountryList() public static méthode

See also: Piwik\Intl\Data\Provider\LanguageDataProvider::getLanguageToCountryList()
Deprecation: Use Piwik\Intl\Data\Provider\LanguageDataProvider instead.
public static getLanguageToCountryList ( ) : array
Résultat array Array of two letter ISO language codes mapped with two letter ISO country codes: `array('fr' => 'fr') // French => France`

getLanguagesList() public static méthode

See also: Piwik\Intl\Data\Provider\LanguageDataProvider::getLanguageList()
Deprecation: Use Piwik\Intl\Data\Provider\LanguageDataProvider instead.
public static getLanguagesList ( ) : array
Résultat array Array of two letter ISO codes mapped with their associated language names (in English). E.g. `array('en' => 'English', 'ja' => 'Japanese')`.

getLastJsonError() public static méthode

Returns an empty string in case there was no error.
public static getLastJsonError ( ) : string
Résultat string

getProviderNames() public static méthode

Returns list of provider names
public static getProviderNames ( ) : array
Résultat array Array of ( dnsName => providerName )

getRandomString() public static méthode

Do not use for security related purposes (the string is not truly random).
public static getRandomString ( integer $length = 16, string $alphabet = "abcdefghijklmnoprstuvwxyz0123456789" ) : string
$length integer string length
$alphabet string characters allowed in random string
Résultat string random string with given length

getRequestVar() public static méthode

Use this function to get request parameter values. **_NEVER use $_GET and $_POST directly._** If the variable cannot be found, and a default value was not provided, an exception is raised. _See {@link sanitizeInputValues()} to learn more about sanitization._
public static getRequestVar ( string $varName, string | null $varDefault = null, string | null $varType = null, array | null $requestArrayToUse = null ) : mixed
$varName string Name of the request parameter to get. By default, we look in `$_GET[$varName]` and `$_POST[$varName]` for the value.
$varDefault string | null The value to return if the request parameter cannot be found or has an empty value.
$varType string | null Expected type of the request variable. This parameters value must be one of the following: `'array'`, `'int'`, `'integer'`, `'string'`, `'json'`. If `'json'`, the string value will be `json_decode`-d and then sanitized.
$requestArrayToUse array | null The array to use instead of `$_GET` and `$_POST`.
Résultat mixed The sanitized request parameter.

getSqlStringFieldsArray() public static méthode

..)` part of a query.
public static getSqlStringFieldsArray ( array | string $fields ) : string
$fields array | string The names of the mysql table fields to bind, e.g. `array(fieldName1, fieldName2, fieldName3)`. _Note: The content of the array isn't important, just its length._
Résultat string The placeholder string, e.g. `"?, ?, ?"`.

hasJsonErrorOccurred() public static méthode

Detects whether an error occurred during the last json encode/decode.
public static hasJsonErrorOccurred ( ) : boolean
Résultat boolean

hash() public static méthode

Configurable hash() algorithm (defaults to md5)
public static hash ( string $str, boolean $raw_output = false ) : string
$str string String to be hashed
$raw_output boolean
Résultat string Hash string

hashStringToInt() public static méthode

Hashes a string into an integer which should be very low collision risks
public static hashStringToInt ( string $string ) : integer
$string string String to hash
Résultat integer Resulting int hash

hex2bin() public static méthode

!! Will emit warning if input string is not hex!!
See also: http://php.net/bin2hex
public static hex2bin ( string $str ) : string
$str string Hexadecimal representation
Résultat string

isActionsPluginEnabled() public static méthode

public static isActionsPluginEnabled ( )

isGoalPluginEnabled() public static méthode

* Tracker
public static isGoalPluginEnabled ( )

isPhpCgiType() public static méthode

Returns true if PHP is executed as CGI type.
public static isPhpCgiType ( ) : boolean
Résultat boolean true if PHP invoked as a CGI

isPhpCliMode() public static méthode

Returns true if PHP was invoked from command-line interface (shell)
public static isPhpCliMode ( ) : boolean
Résultat boolean true if PHP invoked as a CGI or from CLI

isRunningConsoleCommand() public static méthode

./console xx:yy or php console xx:yy
public static isRunningConsoleCommand ( ) : boolean
Résultat boolean

isXmlHttpRequest() public static méthode

Returns true if the request is an AJAX request.
public static isXmlHttpRequest ( ) : boolean
Résultat boolean

json_decode() public static méthode

JSON decode wrapper - missing or broken in some php 5.x versions
Deprecation:
public static json_decode ( string $json, boolean $assoc = false ) : mixed
$json string
$assoc boolean
Résultat mixed

json_encode() public static méthode

JSON encode wrapper - missing or broken in some php 5.x versions
Deprecation:
public static json_encode ( mixed $value ) : string
$value mixed
Résultat string

mb_strlen() public static méthode

Calls mb_substr if available and falls back to substr if not.
public static mb_strlen ( string $string ) : integer
$string string
Résultat integer

mb_strtolower() public static méthode

Calls mb_strtolower if available and falls back to strtolower if not.
public static mb_strtolower ( string $string ) : string
$string string
Résultat string

mb_substr() public static méthode

Calls mb_substr if available and falls back to substr if it's not.
public static mb_substr ( string $string, integer $start ) : string
$string string
$start integer
Résultat string

prefixTable() public static méthode

The table prefix is determined by the [database] tables_prefix INI config option.
public static prefixTable ( string $table ) : string
$table string The table name to prefix, ie "log_visit"
Résultat string The prefixed name, ie "piwik-production_log_visit".

prefixTables() public static méthode

Returns an array containing the prefixed table names of every passed argument.
public static prefixTables ( ) : array
Résultat array The prefixed names in an array.

printDebug() public static méthode

public static printDebug ( $info = '' )

sanitizeInputValue() public static méthode

Sanitize a single input value and removes line breaks, tabs and null characters.
public static sanitizeInputValue ( string $value ) : string
$value string
Résultat string sanitized input

sanitizeInputValues() public static méthode

This function is automatically called when {@link getRequestVar()} is called, so you should not normally have to use it. This function should be used when outputting data that isn't escaped and was obtained from the user (for example when using the |raw twig filter on goal names). _NOTE: Sanitized input should not be used directly in an SQL query; SQL placeholders should still be used._ **Implementation Details** - htmlspecialchars is used to escape text. - Single quotes are not escaped so **Piwik's amazing community** will still be **Piwik's amazing community**. - Use of the magic_quotes setting will not break this method. - Boolean, numeric and null values are not modified.
public static sanitizeInputValues ( mixed $value, boolean $alreadyStripslashed = false ) : mixed
$value mixed The variable to be sanitized. If an array is supplied, the contents of the array will be sanitized recursively. The keys of the array will also be sanitized.
$alreadyStripslashed boolean Implementation detail, ignore.
Résultat mixed The sanitized value.

sanitizeLineBreaks() public static méthode

public static sanitizeLineBreaks ( string $value ) : string
$value string
Résultat string Line breaks and line carriage removed

sanitizeNullBytes() public static méthode

public static sanitizeNullBytes ( string $value ) : string
$value string
Résultat string Null bytes removed

sendHeader() public static méthode

Sets outgoing header.
public static sendHeader ( string $header, boolean $replace = true )
$header string The header.
$replace boolean Whether to replace existing or not.

sendResponseCode() public static méthode

Sends the given response code if supported.
public static sendResponseCode ( integer $code )
$code integer Eg 204

stringEndsWith() public static méthode

public static stringEndsWith ( $haystack, $needle )

unprefixTable() public static méthode

The table prefix is determined by the [database] tables_prefix INI config option.
public static unprefixTable ( string $table ) : string
$table string The prefixed table name, eg "piwik-production_log_visit".
Résultat string The unprefixed table name, eg "log_visit".

unsanitizeInputValue() public static méthode

Unsanitizes a single input value and returns the result.
public static unsanitizeInputValue ( string $value ) : string
$value string
Résultat string unsanitized input

unsanitizeInputValues() public static méthode

This method should be used when you need to unescape data that was obtained from the user. Some data in Piwik is stored sanitized (such as site name). In this case you may have to use this method to unsanitize it in order to, for example, output it in JSON.
public static unsanitizeInputValues ( string | array $value ) : string | array
$value string | array The data to unsanitize. If an array is passed, the array is sanitized recursively. Key values are not unsanitized.
Résultat string | array The unsanitized data.

Property Details

$isCliMode public_oe static_oe property

public static $isCliMode