PHP Class Piwik\Common

This is the only non-Tracker class loaded by the **\/piwik.php** file.
ファイルを表示 Open project: piwik/piwik Class Usage Examples

Public Properties

Property Type Description
$isCliMode

Public Methods

Method 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.

Protected Methods

Method Description
checkValidLanguagesIsSet ( $validLanguages ) : array

Private Methods

Method Description
sanitizeString ( $value ) : string Sanitize a single input value

Method Details

checkValidLanguagesIsSet() protected static method

protected static checkValidLanguagesIsSet ( $validLanguages ) : array
$validLanguages
return array

convertUserIdToVisitorIdBin() public static method

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

convertVisitorIdToBin() public static method

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
return string binary string

destroy() public static method

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 method

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)
return array Array of 2 letter ISO codes

extractLanguageAndRegionCodeFromBrowserLanguage() public static method

* 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.
return string 2 letter ISO 639 code 'es' (Spanish) or if found, includes the region as well: 'es-ar'

extractLanguageCodeFromBrowserLanguage() public static method

* 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
return string 2 letter ISO 639 code 'es' (Spanish)

forceDotAsSeparatorForDecimalPoint() public static method

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
return string

generateUniqId() public static method

Returns a 32 characters long uniq ID
public static generateUniqId ( ) : string
return string 32 chars

getBrowserLanguage() public static method

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
return string

getCampaignParameters() public static method

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

getClassLineage() public static method

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

getContinent() public static method

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

getContinentsList() public static method

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
return array Array of 3 letter continent codes

getCountriesList() public static method

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
return array Array of (2 letter ISO codes => 3 letter continent code)

getCountry() public static method

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
return string 2 letter ISO code

getCurrentLocationProviderId() public static method

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

getLanguageToCountryList() public static method

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

getLanguagesList() public static method

See also: Piwik\Intl\Data\Provider\LanguageDataProvider::getLanguageList()
Deprecation: Use Piwik\Intl\Data\Provider\LanguageDataProvider instead.
public static getLanguagesList ( ) : array
return 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 method

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

getProviderNames() public static method

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

getRandomString() public static method

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
return string random string with given length

getRequestVar() public static method

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`.
return mixed The sanitized request parameter.

getSqlStringFieldsArray() public static method

..)` 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._
return string The placeholder string, e.g. `"?, ?, ?"`.

hasJsonErrorOccurred() public static method

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

hash() public static method

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
return string Hash string

hashStringToInt() public static method

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

hex2bin() public static method

!! 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
return string

isActionsPluginEnabled() public static method

public static isActionsPluginEnabled ( )

isGoalPluginEnabled() public static method

* Tracker
public static isGoalPluginEnabled ( )

isPhpCgiType() public static method

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

isPhpCliMode() public static method

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

isRunningConsoleCommand() public static method

./console xx:yy or php console xx:yy
public static isRunningConsoleCommand ( ) : boolean
return boolean

isXmlHttpRequest() public static method

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

json_decode() public static method

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
return mixed

json_encode() public static method

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

mb_strlen() public static method

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

mb_strtolower() public static method

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

mb_substr() public static method

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
return string

prefixTable() public static method

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"
return string The prefixed name, ie "piwik-production_log_visit".

prefixTables() public static method

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

printDebug() public static method

public static printDebug ( $info = '' )

sanitizeInputValue() public static method

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

sanitizeInputValues() public static method

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.
return mixed The sanitized value.

sanitizeLineBreaks() public static method

public static sanitizeLineBreaks ( string $value ) : string
$value string
return string Line breaks and line carriage removed

sanitizeNullBytes() public static method

public static sanitizeNullBytes ( string $value ) : string
$value string
return string Null bytes removed

sendHeader() public static method

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 method

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

stringEndsWith() public static method

public static stringEndsWith ( $haystack, $needle )

unprefixTable() public static method

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".
return string The unprefixed table name, eg "log_visit".

unsanitizeInputValue() public static method

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

unsanitizeInputValues() public static method

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.
return string | array The unsanitized data.

Property Details

$isCliMode public_oe static_oe property

public static $isCliMode