-
-
Notifications
You must be signed in to change notification settings - Fork 438
/
Copy pathGa.php
345 lines (324 loc) · 10.9 KB
/
Ga.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
<?php
/**
* OpenMage
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available at https://opensource.org/license/osl-3-0-php
*
* @category Mage
* @package Mage_GoogleAnalytics
* @copyright Copyright (c) 2006-2020 Magento, Inc. (https://www.magento.com)
* @copyright Copyright (c) 2022 The OpenMage Contributors (https://www.openmage.org)
* @license https://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
/**
* GoogleAnalitics Page Block
*
* @category Mage
* @package Mage_GoogleAnalytics
*/
class Mage_GoogleAnalytics_Block_Ga extends Mage_Core_Block_Template
{
/**
* @deprecated after 1.4.1.1
* @see self::_getOrdersTrackingCode()
* @return string
*/
public function getQuoteOrdersHtml()
{
return '';
}
/**
* @deprecated after 1.4.1.1
* self::_getOrdersTrackingCode()
* @return string
*/
public function getOrderHtml()
{
return '';
}
/**
* @deprecated after 1.4.1.1
* @see _toHtml()
* @return string
*/
public function getAccount()
{
return '';
}
/**
* Get a specific page name (may be customized via layout)
*
* @return string
*/
public function getPageName()
{
return $this->_getData('page_name') ?? '';
}
/**
* Render regular page tracking javascript code
* The custom "page name" may be set from layout or somewhere else. It must start from slash.
*
* @param string $accountId
* @return string
*/
protected function _getPageTrackingCode($accountId)
{
/** @var Mage_GoogleAnalytics_Helper_Data $helper */
$helper = $this->helper('googleanalytics');
if ($helper->isUseUniversalAnalytics()) {
return $this->_getPageTrackingCodeUniversal($accountId);
}
return $this->_getPageTrackingCodeAnalytics($accountId);
}
/**
* Render regular page tracking javascript code
* The custom "page name" may be set from layout or somewhere else. It must start from slash.
*
* @param string $accountId
* @return string
*/
protected function _getPageTrackingCodeUniversal($accountId)
{
return "
ga('create', '{$this->jsQuoteEscape($accountId)}', 'auto');
" . $this->_getAnonymizationCode() . "
ga('send', 'pageview');
";
}
/**
* Render regular page tracking javascript code
* The custom "page name" may be set from layout or somewhere else. It must start from slash.
*
* @link http://code.google.com/apis/analytics/docs/gaJS/gaJSApiBasicConfiguration.html#_gat.GA_Tracker_._trackPageview
* @link http://code.google.com/apis/analytics/docs/gaJS/gaJSApi_gaq.html
* @param string $accountId
* @return string
*/
protected function _getPageTrackingCodeAnalytics($accountId)
{
$pageName = trim($this->getPageName());
$optPageURL = '';
if ($pageName && preg_match('/^\/.*/i', $pageName)) {
$optPageURL = ", '{$this->jsQuoteEscape($pageName)}'";
}
return "
_gaq.push(['_setAccount', '{$this->jsQuoteEscape($accountId)}']);
" . $this->_getAnonymizationCode() . "
_gaq.push(['_trackPageview'{$optPageURL}]);
";
}
/**
* Render information about specified orders and their items
*
* @return string
* @throws Mage_Core_Model_Store_Exception
*/
protected function _getOrdersTrackingCode()
{
/** @var Mage_GoogleAnalytics_Helper_Data $helper */
$helper = $this->helper('googleanalytics');
if ($helper->isUseAnalytics4()) {
return $this->_getOrdersTrackingCodeAnalytics4();
} elseif ($helper->isUseUniversalAnalytics()) {
return $this->_getOrdersTrackingCodeUniversal();
}
return $this->_getOrdersTrackingCodeAnalytics();
}
/**
* Render information about specified orders and their items
*
* @return string
* @throws Mage_Core_Model_Store_Exception
*/
protected function _getOrdersTrackingCodeUniversal()
{
$orderIds = $this->getOrderIds();
if (empty($orderIds) || !is_array($orderIds)) {
return;
}
$collection = Mage::getResourceModel('sales/order_collection')
->addFieldToFilter('entity_id', ['in' => $orderIds]);
$result = [];
$result[] = "ga('require', 'ecommerce')";
foreach ($collection as $order) {
$result[] = sprintf(
"ga('ecommerce:addTransaction', {
'id': '%s',
'affiliation': '%s',
'revenue': '%s',
'tax': '%s',
'shipping': '%s'
});",
$order->getIncrementId(),
$this->jsQuoteEscape(Mage::app()->getStore()->getFrontendName()),
$order->getBaseGrandTotal(),
$order->getBaseTaxAmount(),
$order->getBaseShippingAmount()
);
foreach ($order->getAllVisibleItems() as $item) {
$result[] = sprintf(
"ga('ecommerce:addItem', {
'id': '%s',
'sku': '%s',
'name': '%s',
'category': '%s',
'price': '%s',
'quantity': '%s'
});",
$order->getIncrementId(),
$this->jsQuoteEscape($item->getSku()),
$this->jsQuoteEscape($item->getName()),
null, // there is no "category" defined for the order item
$item->getBasePrice(),
$item->getQtyOrdered()
);
}
$result[] = "ga('ecommerce:send');";
}
return implode("\n", $result);
}
/**
* @return string
* @throws Mage_Core_Model_Store_Exception
*/
protected function _getOrdersTrackingCodeAnalytics4()
{
$orderIds = $this->getOrderIds();
if (empty($orderIds) || !is_array($orderIds)) {
return '';
}
$collection = Mage::getResourceModel('sales/order_collection')
->addFieldToFilter('entity_id', ['in' => $orderIds]);
$result = [];
/** @var Mage_Sales_Model_Order $order */
foreach ($collection as $order) {
$orderData = [
'currency' => $order->getBaseCurrencyCode(),
'transaction_id' => $order->getIncrementId(),
'value' => number_format($order->getBaseGrandTotal(), 2),
'coupon' => strtoupper($order->getCouponCode()),
'shipping' => number_format($order->getBaseShippingAmount(), 2),
'tax' => number_format($order->getBaseTaxAmount(), 2),
'items' => []
];
/** @var Mage_Sales_Model_Order_Item $item */
foreach ($order->getAllVisibleItems() as $item) {
$orderData['items'][] = [
'item_id' => $item->getSku(),
'item_name' => $item->getName(),
'quantity' => $item->getQtyOrdered(),
'price' => $item->getBasePrice(),
'discount' => $item->getBaseDiscountAmount()
];
}
$result[] = "gtag('event', 'purchase', " . json_encode($orderData, JSON_THROW_ON_ERROR) . ");";
}
return implode("\n", $result);
}
/**
* Render information about specified orders and their items
*
* @link http://code.google.com/apis/analytics/docs/gaJS/gaJSApiEcommerce.html#_gat.GA_Tracker_._addTrans
* @return string
* @throws Mage_Core_Model_Store_Exception
*/
protected function _getOrdersTrackingCodeAnalytics()
{
$orderIds = $this->getOrderIds();
if (empty($orderIds) || !is_array($orderIds)) {
return;
}
$collection = Mage::getResourceModel('sales/order_collection')
->addFieldToFilter('entity_id', ['in' => $orderIds]);
$result = [];
foreach ($collection as $order) {
if ($order->getIsVirtual()) {
$address = $order->getBillingAddress();
} else {
$address = $order->getShippingAddress();
}
$result[] = sprintf(
"_gaq.push(['_addTrans', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s']);",
$order->getIncrementId(),
$this->jsQuoteEscape(Mage::app()->getStore()->getFrontendName()),
$order->getBaseGrandTotal(),
$order->getBaseTaxAmount(),
$order->getBaseShippingAmount(),
$this->jsQuoteEscape(Mage::helper('core')->escapeHtml($address->getCity())),
$this->jsQuoteEscape(Mage::helper('core')->escapeHtml($address->getRegion())),
$this->jsQuoteEscape(Mage::helper('core')->escapeHtml($address->getCountry()))
);
foreach ($order->getAllVisibleItems() as $item) {
$result[] = sprintf(
"_gaq.push(['_addItem', '%s', '%s', '%s', '%s', '%s', '%s']);",
$order->getIncrementId(),
$this->jsQuoteEscape($item->getSku()),
$this->jsQuoteEscape($item->getName()),
null, // there is no "category" defined for the order item
$item->getBasePrice(),
$item->getQtyOrdered()
);
}
$result[] = "_gaq.push(['_trackTrans']);";
}
return implode("\n", $result);
}
/**
* Render IP anonymization code for page tracking javascript code
*
* @return string
*/
protected function _getAnonymizationCode()
{
if (!Mage::helper('googleanalytics')->isIpAnonymizationEnabled()) {
return '';
}
/** @var Mage_GoogleAnalytics_Helper_Data $helper */
$helper = $this->helper('googleanalytics');
if ($helper->isUseUniversalAnalytics()) {
return $this->_getAnonymizationCodeUniversal();
}
return $this->_getAnonymizationCodeAnalytics();
}
/**
* Render IP anonymization code for page tracking javascript universal analytics code
*
* @return string
*/
protected function _getAnonymizationCodeUniversal()
{
return "ga('set', 'anonymizeIp', true);";
}
/**
* Render IP anonymization code for page tracking javascript google analytics code
*
* @return string
*/
protected function _getAnonymizationCodeAnalytics()
{
return "_gaq.push (['_gat._anonymizeIp']);";
}
/**
* Is ga available
*
* @return bool
*/
protected function _isAvailable()
{
return Mage::helper('googleanalytics')->isGoogleAnalyticsAvailable();
}
/**
* Render GA tracking scripts
*
* @return string
*/
protected function _toHtml()
{
if (!$this->_isAvailable()) {
return '';
}
return parent::_toHtml();
}
}