PiwikTracker.php

Show: PublicProtectedPrivateinherited
Table of Contents
Piwik - Open source web analytics

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

functionPiwik_getUrlTrackGoal( $idSite,  $idGoal, float $revenue = 0.0) : string

Helper function to quickly generate the URL to track a goal.

Parameters
NameTypeDescription
$idSite
$idGoal
$revenuefloat
Returns
TypeDescription
string
functionPiwik_getUrlTrackPageView( $idSite, string $documentTitle = '') : string

Helper function to quickly generate the URL to track a page view.

Parameters
NameTypeDescription
$idSite
$documentTitlestring
Returns
TypeDescription
string

\PiwikTracker

Package: PiwikTracker
PiwikTracker implements the Piwik Tracking API.

Properties

>VPropertypublicstring $URL = ''
static
Piwik base URL, for example http://example.org/piwik/ Must be set before using the class by calling PiwikTracker::$URL = 'http://yourwebsite.org/piwik/';
Default value''Details
Type
string

Methods

methodpublic__construct(int $idSite, string $apiUrl = '') : void

Builds a PiwikTracker object, used to track visits, pages and Goal conversions for a specific website, by using the Piwik Tracking API.

Parameters
NameTypeDescription
$idSiteint

Id site to be tracked

$apiUrlstring

"http://example.org/piwik/" or "http://piwik.example.org/" If set, will overwrite PiwikTracker::$URL

methodpublicaddEcommerceItem(string $sku, string $name = '', string | array $category = '', float | int $price = 0.0, int $quantity = 1) : void

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

Parameters
NameTypeDescription
$skustring

(required) SKU, Product identifier

$namestring

(optional) Product name

$categorystring | array

(optional) Product category, or array of product categories (up to 5 categories can be specified for a given product)

$pricefloat | int

(optional) Individual product price (supports integer and decimal prices)

$quantityint

(optional) Product quantity. If not specified, will default to 1 in the Reports

Throws
ExceptionDescription
\Exception
methodpublicdisableCookieSupport() : void

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

methodpublicdoBulkTrack() : string

Sends all stored tracking actions at once.

Only has an effect if bulk tracking is enabled.

To enable bulk tracking, call enableBulkTracking().

Returns
TypeDescription
stringResponse
Throws
ExceptionDescription
\Exception
methodpublicdoTrackAction(string $actionUrl, string $actionType) : mixed

Tracks a download or outlink

Parameters
NameTypeDescription
$actionUrlstring

URL of the download or outlink

$actionTypestring

Type of the action: 'download' or 'link'

Returns
TypeDescription
mixedResponse or true if using bulk request
methodpublicdoTrackEcommerceCartUpdate(float $grandTotal) : mixed

Tracks 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).

Parameters
NameTypeDescription
$grandTotalfloat

Cart grandTotal (typically the sum of all items' prices)

Returns
TypeDescription
mixedResponse or true if using bulk request
methodpublicdoTrackEcommerceOrder(string | int $orderId, float $grandTotal, float $subTotal = 0.0, float $tax = 0.0, float $shipping = 0.0, float $discount = 0.0) : mixed

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

Parameters
NameTypeDescription
$orderIdstring | 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.

$grandTotalfloat

(required) Grand Total revenue of the transaction (including tax, shipping, etc.)

$subTotalfloat

(optional) Sub total amount, typically the sum of items prices for all items in this order (before Tax and Shipping costs are applied)

$taxfloat

(optional) Tax amount for this order

$shippingfloat

(optional) Shipping amount for this order

$discountfloat

(optional) Discounted amount in this order

Returns
TypeDescription
mixedResponse or true if using bulk request
methodpublicdoTrackGoal(int $idGoal, float $revenue = 0.0) : mixed

Records a Goal conversion

Parameters
NameTypeDescription
$idGoalint

Id Goal to record a conversion

$revenuefloat

Revenue for this conversion

Returns
TypeDescription
mixedResponse or true if using bulk request
methodpublicdoTrackPageView(string $documentTitle) : mixed

Tracks a page view

Parameters
NameTypeDescription
$documentTitlestring

Page title as it will appear in the Actions > Page titles report

Returns
TypeDescription
mixedResponse string or true if using bulk requests.
methodpublicdoTrackSiteSearch(string $keyword, string $category = '', int $countResults = false) : mixed

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

Parameters
NameTypeDescription
$keywordstring

Searched query on the site

$categorystring

Optional, Search engine category if applicable

$countResultsint

results displayed on the search result page. Used to track "zero result" keywords.

Returns
TypeDescription
mixedResponse or true if using bulk requests.
methodpublicenableBulkTracking() : void

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

methodpublicgetAttributionInfo() : string

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

Returns
TypeDescription
stringJSON Encoded string containing the Referer information for Goal conversion attribution. Will return false if the cookie could not be found
Details
See
getAttributionInfo()  
methodprotectedgetBaseUrl() : void

Returns the base URL for the piwik server.

methodpublicgetCustomVariable(int $id, string $scope = 'visit') : mixed

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

Parameters
NameTypeDescription
$idint

Custom Variable integer index to fetch from cookie. Should be a value from 1 to 5

$scopestring

Custom variable scope. Possible values: visit, page

Returns
TypeDescription
mixedAn array with this format: array( 0 => CustomVariableName, 1 => CustomVariableValue ) or false
Throws
ExceptionDescription
\Exception
Details
See
getCustomVariable()  
methodpublicgetRequestTimeout() : void

Returns the maximum number of seconds the tracker will spend waiting for a response from Piwik.

Defaults to 600 seconds.

methodprotectedgetTimestamp() : string | int

Returns current timestamp, or forced timestamp/datetime if it was set

Returns
TypeDescription
string | int
methodpublicgetUrlTrackAction(string $actionUrl, string $actionType) : string

Builds URL to track a new action.

Parameters
NameTypeDescription
$actionUrlstring

URL of the download or outlink

$actionTypestring

Type of the action: 'download' or 'link'

Returns
TypeDescription
stringURL to piwik.php with all parameters set to track an action
Details
See
\doTrackAction()  
methodpublicgetUrlTrackGoal(int $idGoal, float $revenue = 0.0) : string

Builds URL to track a goal with idGoal and revenue.

Parameters
NameTypeDescription
$idGoalint

Id Goal to record a conversion

$revenuefloat

Revenue for this conversion

Returns
TypeDescription
stringURL to piwik.php with all parameters set to track the goal conversion
Details
See
\doTrackGoal()  
methodpublicgetUrlTrackPageView(string $documentTitle = '') : string

Builds URL to track a page view.

Parameters
NameTypeDescription
$documentTitlestring

Page view name as it will appear in Piwik reports

Returns
TypeDescription
stringURL to piwik.php with all parameters set to track the pageview
Details
See
\doTrackPageView()  
methodpublicgetUrlTrackSiteSearch(string $keyword, string $category, int $countResults) : string

Builds URL to track a site search.

Parameters
NameTypeDescription
$keywordstring
$categorystring
$countResultsint
Returns
TypeDescription
string
Details
See
\doTrackSiteSearch()  
methodpublicgetVisitorId() : string

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

Returns
TypeDescription
string16 hex chars visitor ID string
methodpublicsetAttributionInfo(string $jsonEncoded) : void

Sets 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()

Parameters
NameTypeDescription
$jsonEncodedstring

JSON encoded array containing Attribution info

Throws
ExceptionDescription
\Exception
Details
See
getAttributionInfo() in https://github.com/piwik/piwik/blob/master/js/piwik.js  
methodpublicsetBrowserHasCookies(bool $bool) : void

Sets if the browser supports cookies This is reported in "List of plugins" report in Piwik.

Parameters
NameTypeDescription
$boolbool
methodpublicsetBrowserLanguage(string $acceptLanguage) : void

Sets the Browser language.

Used to guess visitor countries when GeoIP is not enabled

Parameters
NameTypeDescription
$acceptLanguagestring

For example "fr-fr"

methodpublicsetCity(string $city) : void

Sets 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().

Parameters
NameTypeDescription
$citystring
methodpublicsetCountry(string $country) : void

Sets 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().

Parameters
NameTypeDescription
$countrystring
methodpublicsetCustomVariable(int $id, string $name, string $value, string $scope = 'visit') : void

Sets Visit Custom Variable.

See http://piwik.org/docs/custom-variables/

Parameters
NameTypeDescription
$idint

Custom variable slot ID from 1-5

$namestring

Custom variable name

$valuestring

Custom variable value

$scopestring

Custom variable scope. Possible values: visit, page

Throws
ExceptionDescription
\Exception
methodpublicsetDebugStringAppend(string $string) : void

Will append a custom string at the end of the Tracking request.

Parameters
NameTypeDescription
$stringstring
methodpublicsetEcommerceView(string $sku = '', string $name = '', string | array $category = '', float $price = 0.0) : void

Sets 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)

Parameters
NameTypeDescription
$skustring

Product SKU being viewed

$namestring

Product Name being viewed

$categorystring | 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.

$pricefloat

Specify the price at which the item was displayed

methodpublicsetForceVisitDateTime(string $dateTime) : void

Overrides 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()

Parameters
NameTypeDescription
$dateTimestring

Date with the format 'Y-m-d H:i:s', or a UNIX timestamp

Details
See
\setTokenAuth()  
methodpublicsetGenerationTime(int $timeMs) : void

Sets the time that generating the document on the server side took.

Parameters
NameTypeDescription
$timeMsint

Generation time in ms

methodpublicsetIdSite(int $idSite) : void

Sets the current site ID.

Parameters
NameTypeDescription
$idSiteint
methodpublicsetIp(string $ip) : void

Overrides IP address

Allowed only for Super User, must be used along with setTokenAuth()

Parameters
NameTypeDescription
$ipstring

IP string, eg. 130.54.2.1

Details
See
\setTokenAuth()  
methodpublicsetLatitude(float $lat) : void

Sets 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().

Parameters
NameTypeDescription
$latfloat
methodpublicsetLocalTime(string $time) : void

Sets local visitor time

Parameters
NameTypeDescription
$timestring

HH:MM:SS format

methodpublicsetLongitude(float $long) : void

Sets 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().

Parameters
NameTypeDescription
$longfloat
methodpublicsetNewVisitorId() : void

Sets the current visitor ID to a random new one.

methodpublicsetPageCharset(string $charset = '') : void

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

Parameters
NameTypeDescription
$charsetstring
methodpublicsetPlugins(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) : void

Sets visitor browser supported plugins

Parameters
NameTypeDescription
$flashbool
$javabool
$directorbool
$quickTimebool
$realPlayerbool
$pdfbool
$windowsMediabool
$gearsbool
$silverlightbool
methodpublicsetRegion(string $region) : void

Sets 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().

Parameters
NameTypeDescription
$regionstring
methodpublicsetRequestTimeout(int $timeout) : void

Sets the maximum number of seconds that the tracker will spend waiting for a response from Piwik.

Parameters
NameTypeDescription
$timeoutint
Throws
ExceptionDescription
\Exception
methodpublicsetResolution(int $width, int $height) : void

Sets user resolution width and height.

Parameters
NameTypeDescription
$widthint
$heightint
methodpublicsetTokenAuth(string $token_auth) : void

Some 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

Parameters
NameTypeDescription
$token_authstring

token_auth 32 chars token_auth string

methodpublicsetUrl(string $url) : void

Sets the current URL being tracked

Parameters
NameTypeDescription
$urlstring

Raw URL (not URL encoded)

methodpublicsetUrlReferrer(string $url) : void

Sets the URL referrer used to track Referrers details for new visits.

Parameters
NameTypeDescription
$urlstring

Raw URL (not URL encoded)

methodpublicsetUserAgent(string $userAgent) : void

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

Parameters
NameTypeDescription
$userAgentstring
methodpublicsetVisitorId(string $visitorId) : void

Forces 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().

Parameters
NameTypeDescription
$visitorIdstring

16 hexadecimal characters visitor ID, eg. "33c31e01394bdc63"

Throws
ExceptionDescription
\Exception
Details
See
\setTokenAuth()  
Documentation was generated by phpDocumentor 2.0.0a12.