aboutsummaryrefslogtreecommitdiffstats
path: root/public/catalog/controller/extension/advertise/google.php
blob: aa4241088dafd6c1e82d5bb4d186706f8e70234c (plain)
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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
<?php

use \googleshopping\traits\StoreLoader;
use \googleshopping\traits\LibraryLoader;

class ControllerExtensionAdvertiseGoogle extends Controller {
    use StoreLoader;
    use LibraryLoader;

    private $store_id = 0;

    public function __construct($registry) {
        parent::__construct($registry);

        if (getenv("ADVERTISE_GOOGLE_STORE_ID")) {
            $this->store_id = (int)getenv("ADVERTISE_GOOGLE_STORE_ID");
        } else {
            $this->store_id = (int)$this->config->get('config_store_id');
        }

        $this->loadStore($this->store_id);
    }

    public function google_global_site_tag(&$route, &$data, &$output) {
        // In case the extension is disabled, do nothing
        if (!$this->setting->get('advertise_google_status')) {
            return;
        }

        // If there is no tracker, do nothing
        if (!$this->setting->has('advertise_google_conversion_tracker')) {
            return;
        }

        $tracker = $this->setting->get('advertise_google_conversion_tracker');

        // Insert the tags before the closing <head> tag
        $output = str_replace('</head>', $tracker['google_global_site_tag'] . '</head>', $output);
    }

    public function before_checkout_success(&$route, &$data) {
        // In case the extension is disabled, do nothing
        if (!$this->setting->get('advertise_google_status')) {
            return;
        }

        // If there is no tracker, do nothing
        if (!$this->setting->has('advertise_google_conversion_tracker')) {
            return;
        }

        // In case there is no order, do nothing
        if (!isset($this->session->data['order_id'])) {
            return;
        }

        if (!$this->registry->has('googleshopping')) {
            $this->loadLibrary($this->store_id);
        }

        $this->load->model('checkout/order');
        $this->load->model('extension/advertise/google');

        $order_info = $this->model_checkout_order->getOrder($this->session->data['order_id']);

        $tracker = $this->setting->get('advertise_google_conversion_tracker');
        $currency = $order_info['currency_code'];
        
        $total = $this->googleshopping->convertAndFormat($order_info['total'], $currency);

        $search = array(
            '{VALUE}',
            '{CURRENCY}'
        );

        $replace = array(
            $total,
            $currency
        );

        $snippet = str_replace($search, $replace, $tracker['google_event_snippet']);

        // Store the snippet to display it in the order success view
        $tax = 0;
        $shipping = 0;
        $coupon = $this->model_extension_advertise_google->getCoupon($order_info['order_id']);

        foreach ($this->model_checkout_order->getOrderTotals($order_info['order_id']) as $order_total) {
            if ($order_total['code'] == 'shipping') {
                $shipping += $this->googleshopping->convertAndFormat($order_total['value'], $currency);
            }

            if ($order_total['code'] == 'tax') {
                $tax += $this->googleshopping->convertAndFormat($order_total['value'], $currency);
            }
        }

        $order_products = $this->model_checkout_order->getOrderProducts($order_info['order_id']);

        foreach ($order_products as &$order_product) {
            $order_product['option'] = $this->model_checkout_order->getOrderOptions($order_info['order_id'], $order_product['order_product_id']);
        }

        $purchase_data = array(
            'transaction_id' => $order_info['order_id'],
            'value' => $total,
            'currency' => $currency,
            'tax' => $tax,
            'shipping' => $shipping,
            'items' => $this->model_extension_advertise_google->getRemarketingItems($order_products, $order_info['store_id']),
            'ecomm_prodid' => $this->model_extension_advertise_google->getRemarketingProductIds($order_products, $order_info['store_id'])
        );

        if ($coupon !== null) {
            $purchase_data['coupon'] = $coupon;
        }

        $this->googleshopping->setEventSnippet($snippet);
        $this->googleshopping->setPurchaseData($purchase_data);
    }

    public function google_dynamic_remarketing_purchase(&$route, &$data, &$output) {
        // In case the extension is disabled, do nothing
        if (!$this->setting->get('advertise_google_status')) {
            return;
        }

        // If the library has not been loaded, or if there is no snippet, do nothing
        if (!$this->registry->has('googleshopping') || $this->googleshopping->getEventSnippet() === null || $this->googleshopping->getPurchaseData() === null) {
            return;
        }

        $data['send_to'] = $this->googleshopping->getEventSnippetSendTo();

        $purchase_data = $this->googleshopping->getPurchaseData();

        $data['transaction_id'] = $purchase_data['transaction_id'];
        $data['value'] = $purchase_data['value'];
        $data['currency'] = $purchase_data['currency'];
        $data['tax'] = $purchase_data['tax'];
        $data['shipping'] = $purchase_data['shipping'];
        $data['items'] = json_encode($purchase_data['items']);
        $data['ecomm_prodid'] = json_encode($purchase_data['ecomm_prodid']);
        $data['ecomm_totalvalue'] = $purchase_data['value'];

        $purchase_snippet = $this->load->view('extension/advertise/google_dynamic_remarketing_purchase', $data);

        // Insert the snippet after the output
        $output = str_replace('</body>', $this->googleshopping->getEventSnippet() . $purchase_snippet . '</body>', $output);
    }

    public function google_dynamic_remarketing_home(&$route, &$data, &$output) {
        // In case the extension is disabled, do nothing
        if (!$this->setting->get('advertise_google_status')) {
            return;
        }

        // If we are not on the home page, do nothing
        if (isset($this->request->get['route']) && $this->request->get['route'] != $this->config->get('action_default')) {
            return;
        }

        if (!$this->registry->has('googleshopping')) {
            $this->loadLibrary($this->store_id);
        }

        if (null === $this->googleshopping->getEventSnippetSendTo()) {
            return;
        }

        $data = array();
        $data['send_to'] = $this->googleshopping->getEventSnippetSendTo();

        $snippet = $this->load->view('extension/advertise/google_dynamic_remarketing_home', $data);

        // Insert the snippet after the output
        $output = str_replace('</body>', $snippet . '</body>', $output);
    }

    public function google_dynamic_remarketing_searchresults(&$route, &$data, &$output) {
        // In case the extension is disabled, do nothing
        if (!$this->setting->get('advertise_google_status')) {
            return;
        }

        // If we are not on the search page, do nothing
        if (!isset($this->request->get['route']) || $this->request->get['route'] != 'product/search' || !isset($this->request->get['search'])) {
            return;
        }

        if (!$this->registry->has('googleshopping')) {
            $this->loadLibrary($this->store_id);
        }

        if (null === $this->googleshopping->getEventSnippetSendTo()) {
            return;
        }

        $data = array();
        $data['send_to'] = $this->googleshopping->getEventSnippetSendTo();
        $data['search_term'] = $this->request->get['search'];

        $snippet = $this->load->view('extension/advertise/google_dynamic_remarketing_searchresults', $data);

        // Insert the snippet after the output
        $output = str_replace('</body>', $snippet . '</body>', $output);
    }

    public function google_dynamic_remarketing_category(&$route, &$data, &$output) {
        // In case the extension is disabled, do nothing
        if (!$this->setting->get('advertise_google_status')) {
            return;
        }

        // If we are not on the search page, do nothing
        if (!isset($this->request->get['route']) || $this->request->get['route'] != 'product/category') {
            return;
        }

        if (!$this->registry->has('googleshopping')) {
            $this->loadLibrary($this->store_id);
        }

        if (null === $this->googleshopping->getEventSnippetSendTo()) {
            return;
        }

        if (isset($this->request->get['path'])) {
            $parts = explode('_', $this->request->get['path']);
            $category_id = (int)end($parts);
        } else if (isset($this->request->get['category_id'])) {
            $category_id = (int)$this->request->get['category_id'];
        } else {
            $category_id = 0;
        }

        $this->load->model('extension/advertise/google');

        $data = array();
        $data['send_to'] = $this->googleshopping->getEventSnippetSendTo();
        $data['description'] = str_replace('"', '\\"', $this->model_extension_advertise_google->getHumanReadableOpenCartCategory($category_id));

        $snippet = $this->load->view('extension/advertise/google_dynamic_remarketing_category', $data);

        // Insert the snippet after the output
        $output = str_replace('</body>', $snippet . '</body>', $output);
    }

    public function google_dynamic_remarketing_product(&$route, &$data, &$output) {
        // In case the extension is disabled, do nothing
        if (!$this->setting->get('advertise_google_status')) {
            return;
        }

        // If we do not know the viewed product, do nothing
        if (!isset($this->request->get['product_id']) || !isset($this->request->get['route']) || $this->request->get['route'] != 'product/product') {
            return;
        }

        $this->load->model('catalog/product');

        $product_info = $this->model_catalog_product->getProduct((int)$this->request->get['product_id']);

        // If product does not exist, do nothing
        if (!$product_info) {
            return;
        }

        if (!$this->registry->has('googleshopping')) {
            $this->loadLibrary($this->store_id);
        }

        if (null === $this->googleshopping->getEventSnippetSendTo()) {
            return;
        }

        $this->load->model('extension/advertise/google');

        $category_name = $this->model_extension_advertise_google->getHumanReadableCategory($product_info['product_id'], $this->store_id);

        $option_map = $this->model_extension_advertise_google->getSizeAndColorOptionMap($product_info['product_id'], $this->store_id);

        $data = array();
        $data['send_to'] = $this->googleshopping->getEventSnippetSendTo();
        $data['option_map'] = json_encode($option_map);
        $data['brand'] = $product_info['manufacturer'];
        $data['name'] = $product_info['name'];
        $data['category'] = str_replace('"', '\\"', $category_name);

        $snippet = $this->load->view('extension/advertise/google_dynamic_remarketing_product', $data);

        // Insert the snippet after the output
        $output = str_replace('</body>', $snippet . '</body>', $output);
    }

    public function google_dynamic_remarketing_cart(&$route, &$data, &$output) {
        // In case the extension is disabled, do nothing
        if (!$this->setting->get('advertise_google_status')) {
            return;
        }

        // If we are not on the cart page, do nothing
        if (!isset($this->request->get['route']) || $this->request->get['route'] != 'checkout/cart') {
            return;
        }

        if (!$this->registry->has('googleshopping')) {
            $this->loadLibrary($this->store_id);
        }

        if (null === $this->googleshopping->getEventSnippetSendTo()) {
            return;
        }

        $this->load->model('catalog/product');
        $this->load->model('extension/advertise/google');

        $data = array();
        $data['send_to'] = $this->googleshopping->getEventSnippetSendTo();
        $data['ecomm_totalvalue'] = $this->cart->getTotal();
        $data['ecomm_prodid'] = json_encode($this->model_extension_advertise_google->getRemarketingProductIds($this->cart->getProducts(), $this->store_id));
        $data['items'] = json_encode($this->model_extension_advertise_google->getRemarketingItems($this->cart->getProducts(), $this->store_id));

        $snippet = $this->load->view('extension/advertise/google_dynamic_remarketing_cart', $data);

        // Insert the snippet after the output
        $output = str_replace('</body>', $snippet . '</body>', $output);
    }

    public function cron($cron_id = null, $code = null, $cycle = null, $date_added = null, $date_modified = null) {
        $this->loadLibrary($this->store_id);

        if (!$this->validateCRON()) {
            // In case this is not a CRON task
            return;
        }

        $this->load->language('extension/advertise/google');

        // Reset taxes to use the store address and zone
        $this->tax->setShippingAddress($this->config->get('config_country_id'), $this->config->get('config_zone_id'));
        $this->tax->setPaymentAddress($this->config->get('config_country_id'), $this->config->get('config_zone_id'));
        $this->tax->setStoreAddress($this->config->get('config_country_id'), $this->config->get('config_zone_id'));

        $this->googleshopping->cron();
    }

    protected function validateCRON() {
        if (!$this->setting->get('advertise_google_status')) {
            // In case the extension is disabled, do nothing
            return false;
        }

        if (!$this->setting->get('advertise_google_gmc_account_selected')) {
            return false;
        }

        if (!$this->setting->get('advertise_google_gmc_shipping_taxes_configured')) {
            return false;
        }

        try {
            if (count($this->googleshopping->getTargets($this->store_id)) === 0) {
                return false;
            }
        } catch (\RuntimeException $e) {
            return false;
        }

        if (isset($this->request->get['cron_token']) && $this->request->get['cron_token'] == $this->config->get('advertise_google_cron_token')) {
            return true;
        }

        if (defined('ADVERTISE_GOOGLE_ROUTE')) {
            return true;
        }

        return false;
    }
}