PiwikTracker.php
Client to record visits, page views, Goals, Ecommerce activity (product views, add to carts, Ecommerce orders) in a Piwik server. This is a PHP Version of the piwik.js standard Tracking API. For more information, see http://piwik.org/docs/tracking-api/
This class requires: - json extension (json_decode, json_encode) - CURL or STREAM extensions (to issue the http request to Piwik)
- Category
- Piwik
- License
- released under BSD License http://www.opensource.org/licenses/bsd-license.php
- Link
- http://piwik.org/docs/tracking-api/
- Package
- PiwikTracker
Functions
Piwik_getUrlTrackGoal( $idSite, $idGoal, float $revenue = 0.0) : stringHelper function to quickly generate the URL to track a goal.
| Name | Type | Description |
|---|---|---|
| $idSite | ||
| $idGoal | ||
| $revenue | float |
| Type | Description |
|---|---|
| string |
\PiwikTracker
Properties
Methods

__construct(int $idSite, string $apiUrl = '') : voidBuilds a PiwikTracker object, used to track visits, pages and Goal conversions for a specific website, by using the Piwik Tracking API.
| Name | Type | Description |
|---|---|---|
| $idSite | int | Id site to be tracked |
| $apiUrl | string | "http://example.org/piwik/" or "http://piwik.example.org/" If set, will overwrite PiwikTracker::$URL |

addEcommerceItem(string $sku, string $name = '', string | array $category = '', float | int $price = 0.0, int $quantity = 1) : voidAdds an item in the Ecommerce order.
This should be called before doTrackEcommerceOrder(), or before doTrackEcommerceCartUpdate(). This function can be called for all individual products in the cart (or order). SKU parameter is mandatory. Other parameters are optional (set to false if value not known). Ecommerce items added via this function are automatically cleared when doTrackEcommerceOrder() or getUrlTrackEcommerceOrder() is called.
| Name | Type | Description |
|---|---|---|
| $sku | string | (required) SKU, Product identifier |
| $name | string | (optional) Product name |
| $category | string | array | (optional) Product category, or array of product categories (up to 5 categories can be specified for a given product) |
| $price | float | int | (optional) Individual product price (supports integer and decimal prices) |
| $quantity | int | (optional) Product quantity. If not specified, will default to 1 in the Reports |
| Exception | Description |
|---|---|
| \Exception |

disableCookieSupport() : voidBy default, PiwikTracker will read third party cookies from the response and sets them in the next request.
This can be disabled by calling this function.

doBulkTrack() : stringSends all stored tracking actions at once.
Only has an effect if bulk tracking is enabled.
To enable bulk tracking, call enableBulkTracking().
| Type | Description |
|---|---|
| string | Response |
| Exception | Description |
|---|---|
| \Exception |

doTrackAction(string $actionUrl, string $actionType) : mixedTracks a download or outlink
| Name | Type | Description |
|---|---|---|
| $actionUrl | string | URL of the download or outlink |
| $actionType | string | Type of the action: 'download' or 'link' |
| Type | Description |
|---|---|
| mixed | Response or true if using bulk request |

doTrackEcommerceCartUpdate(float $grandTotal) : mixedTracks a Cart Update (add item, remove item, update item).
On every Cart update, you must call addEcommerceItem() for each item (product) in the cart, including the items that haven't been updated since the last cart update. Items which were in the previous cart and are not sent in later Cart updates will be deleted from the cart (in the database).
| Name | Type | Description |
|---|---|---|
| $grandTotal | float | Cart grandTotal (typically the sum of all items' prices) |
| Type | Description |
|---|---|
| mixed | Response or true if using bulk request |

doTrackEcommerceOrder(string | int $orderId, float $grandTotal, float $subTotal = 0.0, float $tax = 0.0, float $shipping = 0.0, float $discount = 0.0) : mixedTracks an Ecommerce order.
If the Ecommerce order contains items (products), you must call first the addEcommerceItem() for each item in the order. All revenues (grandTotal, subTotal, tax, shipping, discount) will be individually summed and reported in Piwik reports. Only the parameters $orderId and $grandTotal are required.
| Name | Type | Description |
|---|---|---|
| $orderId | string | int | (required) Unique Order ID. This will be used to count this order only once in the event the order page is reloaded several times. orderId must be unique for each transaction, even on different days, or the transaction will not be recorded by Piwik. |
| $grandTotal | float | (required) Grand Total revenue of the transaction (including tax, shipping, etc.) |
| $subTotal | float | (optional) Sub total amount, typically the sum of items prices for all items in this order (before Tax and Shipping costs are applied) |
| $tax | float | (optional) Tax amount for this order |
| $shipping | float | (optional) Shipping amount for this order |
| $discount | float | (optional) Discounted amount in this order |
| Type | Description |
|---|---|
| mixed | Response or true if using bulk request |

doTrackGoal(int $idGoal, float $revenue = 0.0) : mixedRecords a Goal conversion
| Name | Type | Description |
|---|---|---|
| $idGoal | int | Id Goal to record a conversion |
| $revenue | float | Revenue for this conversion |
| Type | Description |
|---|---|
| mixed | Response or true if using bulk request |

doTrackPageView(string $documentTitle) : mixedTracks a page view
| Name | Type | Description |
|---|---|---|
| $documentTitle | string | Page title as it will appear in the Actions > Page titles report |
| Type | Description |
|---|---|
| mixed | Response string or true if using bulk requests. |

doTrackSiteSearch(string $keyword, string $category = '', int $countResults = false) : mixedTracks an internal Site Search query, and optionally tracks the Search Category, and Search results Count.
These are used to populate reports in Actions > Site Search.
| Name | Type | Description |
|---|---|---|
| $keyword | string | Searched query on the site |
| $category | string | Optional, Search engine category if applicable |
| $countResults | int | results displayed on the search result page. Used to track "zero result" keywords. |
| Type | Description |
|---|---|
| mixed | Response or true if using bulk requests. |

enableBulkTracking() : voidEnables the bulk request feature.
When used, each tracking action is stored until the doBulkTrack method is called. This method will send all tracking data at once.

getAttributionInfo() : stringReturns the currently assigned Attribution Information stored in a first party cookie.
This function will only work if the user is initiating the current request, and his cookies can be read by PHP from the $_COOKIE array.
| Type | Description |
|---|---|
| string | JSON Encoded string containing the Referer information for Goal conversion attribution. Will return false if the cookie could not be found |
- See
- getAttributionInfo()

getCustomVariable(int $id, string $scope = 'visit') : mixedReturns the currently assigned Custom Variable stored in a first party cookie.
This function will only work if the user is initiating the current request, and his cookies can be read by PHP from the $_COOKIE array.
| Name | Type | Description |
|---|---|---|
| $id | int | Custom Variable integer index to fetch from cookie. Should be a value from 1 to 5 |
| $scope | string | Custom variable scope. Possible values: visit, page |
| Type | Description |
|---|---|
| mixed | An array with this format: array( 0 => CustomVariableName, 1 => CustomVariableValue ) or false |
| Exception | Description |
|---|---|
| \Exception |
- See
- getCustomVariable()

getRequestTimeout() : voidReturns the maximum number of seconds the tracker will spend waiting for a response from Piwik.
Defaults to 600 seconds.

getTimestamp() : string | intReturns current timestamp, or forced timestamp/datetime if it was set
| Type | Description |
|---|---|
| string | int |

getUrlTrackAction(string $actionUrl, string $actionType) : stringBuilds URL to track a new action.
| Name | Type | Description |
|---|---|---|
| $actionUrl | string | URL of the download or outlink |
| $actionType | string | Type of the action: 'download' or 'link' |
| Type | Description |
|---|---|
| string | URL to piwik.php with all parameters set to track an action |
- See
- \doTrackAction()

getUrlTrackGoal(int $idGoal, float $revenue = 0.0) : stringBuilds URL to track a goal with idGoal and revenue.
| Name | Type | Description |
|---|---|---|
| $idGoal | int | Id Goal to record a conversion |
| $revenue | float | Revenue for this conversion |
| Type | Description |
|---|---|
| string | URL to piwik.php with all parameters set to track the goal conversion |
- See
- \doTrackGoal()

getUrlTrackPageView(string $documentTitle = '') : stringBuilds URL to track a page view.
| Name | Type | Description |
|---|---|---|
| $documentTitle | string | Page view name as it will appear in Piwik reports |
| Type | Description |
|---|---|
| string | URL to piwik.php with all parameters set to track the pageview |
- See
- \doTrackPageView()

getUrlTrackSiteSearch(string $keyword, string $category, int $countResults) : stringBuilds URL to track a site search.
| Name | Type | Description |
|---|---|---|
| $keyword | string | |
| $category | string | |
| $countResults | int |
| Type | Description |
|---|---|
| string |
- See
- \doTrackSiteSearch()

getVisitorId() : stringIf the user initiating the request has the Piwik first party cookie, this function will try and return the ID parsed from this first party cookie (found in $_COOKIE).
If you call this function from a server, where the call is triggered by a cron or script not initiated by the actual visitor being tracked, then it will return the random Visitor ID that was assigned to this visit object.
This can be used if you wish to record more visits, actions or goals for this visitor ID later on.
| Type | Description |
|---|---|
| string | 16 hex chars visitor ID string |

setAttributionInfo(string $jsonEncoded) : voidSets the attribution information to the visit, so that subsequent Goal conversions are properly attributed to the right Referrer URL, timestamp, Campaign Name & Keyword.
This must be a JSON encoded string that would typically be fetched from the JS API: piwikTracker.getAttributionInfo() and that you have JSON encoded via JSON2.stringify()
| Name | Type | Description |
|---|---|---|
| $jsonEncoded | string | JSON encoded array containing Attribution info |
| Exception | Description |
|---|---|
| \Exception |
- See
- getAttributionInfo() in https://github.com/piwik/piwik/blob/master/js/piwik.js

setBrowserHasCookies(bool $bool) : voidSets if the browser supports cookies This is reported in "List of plugins" report in Piwik.
| Name | Type | Description |
|---|---|---|
| $bool | bool |

setBrowserLanguage(string $acceptLanguage) : voidSets the Browser language.
Used to guess visitor countries when GeoIP is not enabled
| Name | Type | Description |
|---|---|---|
| $acceptLanguage | string | For example "fr-fr" |

setCity(string $city) : voidSets the city of the visitor.
If not used, Piwik may try to find the city using the visitor's IP address (if configured to do so).
Allowed only for Admin/Super User, must be used along with setTokenAuth().
| Name | Type | Description |
|---|---|---|
| $city | string |

setCountry(string $country) : voidSets the country of the visitor.
If not used, Piwik will try to find the country using either the visitor's IP address or language.
Allowed only for Admin/Super User, must be used along with setTokenAuth().
| Name | Type | Description |
|---|---|---|
| $country | string |

setCustomVariable(int $id, string $name, string $value, string $scope = 'visit') : voidSets Visit Custom Variable.
See http://piwik.org/docs/custom-variables/
| Name | Type | Description |
|---|---|---|
| $id | int | Custom variable slot ID from 1-5 |
| $name | string | Custom variable name |
| $value | string | Custom variable value |
| $scope | string | Custom variable scope. Possible values: visit, page |
| Exception | Description |
|---|---|
| \Exception |

setDebugStringAppend(string $string) : voidWill append a custom string at the end of the Tracking request.
| Name | Type | Description |
|---|---|---|
| $string | string |

setEcommerceView(string $sku = '', string $name = '', string | array $category = '', float $price = 0.0) : voidSets the current page view as an item (product) page view, or an Ecommerce Category page view.
This must be called before doTrackPageView() on this product/category page. It will set 3 custom variables of scope "page" with the SKU, Name and Category for this page view. Note: Custom Variables of scope "page" slots 3, 4 and 5 will be used.
On a category page, you may set the parameter $category only and set the other parameters to false.
Tracking Product/Category page views will allow Piwik to report on Product & Categories conversion rates (Conversion rate = Ecommerce orders containing this product or category / Visits to the product or category)
| Name | Type | Description |
|---|---|---|
| $sku | string | Product SKU being viewed |
| $name | string | Product Name being viewed |
| $category | string | array | Category being viewed. On a Product page, this is the product's category. You can also specify an array of up to 5 categories for a given page view. |
| $price | float | Specify the price at which the item was displayed |

setForceVisitDateTime(string $dateTime) : voidOverrides server date and time for the tracking requests.
By default Piwik will track requests for the "current datetime" but this function allows you to track visits in the past. All times are in UTC.
Allowed only for Super User, must be used along with setTokenAuth()
| Name | Type | Description |
|---|---|---|
| $dateTime | string | Date with the format 'Y-m-d H:i:s', or a UNIX timestamp |
- See
- \setTokenAuth()

setGenerationTime(int $timeMs) : voidSets the time that generating the document on the server side took.
| Name | Type | Description |
|---|---|---|
| $timeMs | int | Generation time in ms |

setIp(string $ip) : voidOverrides IP address
Allowed only for Super User, must be used along with setTokenAuth()
| Name | Type | Description |
|---|---|---|
| $ip | string | IP string, eg. 130.54.2.1 |
- See
- \setTokenAuth()

setLatitude(float $lat) : voidSets the latitude of the visitor.
If not used, Piwik may try to find the visitor's latitude using the visitor's IP address (if configured to do so).
Allowed only for Admin/Super User, must be used along with setTokenAuth().
| Name | Type | Description |
|---|---|---|
| $lat | float |

setLocalTime(string $time) : voidSets local visitor time
| Name | Type | Description |
|---|---|---|
| $time | string | HH:MM:SS format |

setLongitude(float $long) : voidSets the longitude of the visitor.
If not used, Piwik may try to find the visitor's longitude using the visitor's IP address (if configured to do so).
Allowed only for Admin/Super User, must be used along with setTokenAuth().
| Name | Type | Description |
|---|---|---|
| $long | float |

setPageCharset(string $charset = '') : voidBy default, Piwik expects utf-8 encoded values, for example for the page URL parameter values, Page Title, etc.
It is recommended to only send UTF-8 data to Piwik. If required though, you can also specify another charset using this function.
| Name | Type | Description |
|---|---|---|
| $charset | string |

setPlugins(bool $flash = false, bool $java = false, bool $director = false, bool $quickTime = false, bool $realPlayer = false, bool $pdf = false, bool $windowsMedia = false, bool $gears = false, bool $silverlight = false) : voidSets visitor browser supported plugins
| Name | Type | Description |
|---|---|---|
| $flash | bool | |
| $java | bool | |
| $director | bool | |
| $quickTime | bool | |
| $realPlayer | bool | |
| bool | ||
| $windowsMedia | bool | |
| $gears | bool | |
| $silverlight | bool |

setRegion(string $region) : voidSets the region of the visitor.
If not used, Piwik may try to find the region using the visitor's IP address (if configured to do so).
Allowed only for Admin/Super User, must be used along with setTokenAuth().
| Name | Type | Description |
|---|---|---|
| $region | string |

setRequestTimeout(int $timeout) : voidSets the maximum number of seconds that the tracker will spend waiting for a response from Piwik.
| Name | Type | Description |
|---|---|---|
| $timeout | int |
| Exception | Description |
|---|---|
| \Exception |

setResolution(int $width, int $height) : voidSets user resolution width and height.
| Name | Type | Description |
|---|---|---|
| $width | int | |
| $height | int |

setTokenAuth(string $token_auth) : voidSome Tracking API functionnality requires express authentication, using either the Super User token_auth, or a user with 'admin' access to the website.
The following features require access: - force the visitor IP - force the date & time of the tracking requests rather than track for the current datetime - force Piwik to track the requests to a specific VisitorId rather than use the standard visitor matching heuristic
| Name | Type | Description |
|---|---|---|
| $token_auth | string | token_auth 32 chars token_auth string |

setUrl(string $url) : voidSets the current URL being tracked
| Name | Type | Description |
|---|---|---|
| $url | string | Raw URL (not URL encoded) |

setUrlReferrer(string $url) : voidSets the URL referrer used to track Referrers details for new visits.
| Name | Type | Description |
|---|---|---|
| $url | string | Raw URL (not URL encoded) |

setUserAgent(string $userAgent) : voidSets the user agent, used to detect OS and browser.
If this function is not called, the User Agent will default to the current user agent.
| Name | Type | Description |
|---|---|---|
| $userAgent | string |

setVisitorId(string $visitorId) : voidForces the requests to be recorded for the specified Visitor ID rather than using the heuristics based on IP and other attributes.
This is typically used with the Javascript getVisitorId() function.
Allowed only for Admin/Super User, must be used along with setTokenAuth().
| Name | Type | Description |
|---|---|---|
| $visitorId | string | 16 hexadecimal characters visitor ID, eg. "33c31e01394bdc63" |
| Exception | Description |
|---|---|
| \Exception |
- See
- \setTokenAuth()