Completed
Push — development ( eb9524...db4517 )
by Andrij
28:49 queued 02:09
created

Lib_seo::makeOrderForGoogle()   B

Complexity

Conditions 4
Paths 3

Size

Total Lines 30
Code Lines 18

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 30
rs 8.5806
cc 4
eloc 18
nc 3
nop 1
1
<?php
2
3
if (!defined('BASEPATH')) {
4
    exit('No direct script access allowed');
5
}
6
7
/**
8
 * ImageCMS
9
 * Seo module
10
 * Create keywords and description
11
 */
12
class Lib_seo
13
{
0 ignored issues
show
introduced by
Opening brace of a class must be on the same line as the definition
Loading history...
14
15
    /**
16
     * @var bool
17
     */
18
    protected $orderJustMacked = FALSE;
19
20
    /**
21
     * @var array
22
     */
23
    public $origin_arr;
24
25
    /**
26
     * @var array
27
     */
28
    public $modif_arr;
29
30
    /**
31
     * @var int
32
     */
33
    public $min_word_length = 3;
34
35
    /**
36
     * @var int
37
     */
38
    public $desc_chars = 160;
39
40
    /**
41
     * GA custom params
42
     * @var array
43
     */
44
    private $custom = [];
45
46
    /**
47
     * Lib_seo constructor.
48
     */
49
    public function __construct() {
50
51
        if (CI::$APP->session->flashdata('makeOrderForGA') == true) {
52
            $this->orderJustMacked = TRUE;
53
        }
54
55
        CI::$APP->load->library('DX_Auth');
56
57
        if (CI::$APP->dx_auth->is_logged_in()) {
58
            $this->setCustomParams('userId', md5(CI::$APP->dx_auth->get_user_id()));
59
        }
60
    }
61
62
    /**
63
     * @param array $settings
64
     */
65
    public function init($settings) {
66
67
        $CI = &get_instance();
68
        if (!strstr($CI->uri->uri_string(), 'shop/order/view')) {
69
            $CI->template->registerJsScript($this->renderGA($settings));
0 ignored issues
show
Documentation introduced by
$settings is of type array, but the function expects a null|string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
70
        }
71
        $CI->template->registerJsScript($this->renderYaMetrica($settings), 'after');
0 ignored issues
show
Documentation introduced by
$settings is of type array, but the function expects a null|string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
72
        $CI->template->registerJsScript($this->renderYandexWebmaster($settings));
73
        $CI->template->registerJsScript($this->renderGoogleWebmaster($settings));
74
    }
75
76
    /**
77
     * Create keywords from text
78
     * @param string $text
79
     * @param bool $as_array
80
     * @return array|string
81
     */
82
    public function get_keywords($text, $as_array = FALSE) {
83
84
        $text = strip_tags($text);
85
        $text = mb_strtolower($text, 'utf-8');
86
        $this->explode_str_on_words($text);
87
        $this->count_words();
88
        $arr = array_slice($this->modif_arr, 0, 30);
89
90
        if ($as_array === FALSE) {
91
            return implode(', ', array_keys($arr));
92
        } else {
93
            return $arr;
94
        }
95
    }
96
97
    /**
98
     * @param string $text
99
     * @return string
100
     */
101
    public function get_description($text) {
102
103
        $delete = [';', '"', '&mdash', '&nbsp;'];
104
105
        $tags = get_html_translation_table(HTML_ENTITIES);
106
107
        foreach ($tags as $v) {
108
            $text = str_replace($v, '', $text);
109
        }
110
111
        $text = str_replace($delete, '', $text);
112
        $text = str_replace("\n", ' ', $text);
113
        $text = str_replace("\r", ' ', $text);
114
115
        return trim(mb_substr(strip_tags(stripslashes($text)), 0, 255, 'utf-8'));
116
    }
117
118
    /**
119
     * Explode text on words
120
     * @param string $text
121
     * @return array
122
     */
123
    public function explode_str_on_words($text) {
124
125
        $search = ["'ё'",
126
            "'<script[^>]*?>.*?</script>'si",
127
            "'<[\/\!]*?[^<>]*?>'si",
128
            "'([\r\n])[\s]+'",
129
            "'&(quot|#34);'i",
130
            "'&(amp|#38);'i",
131
            "'&(lt|#60);'i",
132
            "'&(gt|#62);'i",
133
            "'&(nbsp|#160);'i",
134
            "'&(iexcl|#161);'i",
135
            "'&(cent|#162);'i",
136
            "'&(pound|#163);'i",
137
            "'&(copy|#169);'i",
138
            "'&#(\d+);'i"
139
        ];
140
        $replace = ['е',
141
            ' ',
142
            ' ',
143
            '\\1 ',
144
            '" ',
145
            ' ',
146
            ' ',
147
            ' ',
148
            ' ',
149
            chr(161),
150
            chr(162),
151
            chr(163),
152
            chr(169),
153
            'chr(\\1)'
154
        ];
155
156
        $text = preg_replace($search, $replace, $text);
157
        $del_symbols = [',', '.', ';', ':', '"', '#', '\$', '%', '^',
158
            '!', '@', '`', '~', '*', '-', '=', '+', '\\',
159
            '|', '/', '>', '<', '(', ')', '&', '?', '¹', "\t",
160
            "\r", "\n", '{', '}', '[', ']', "'", '“', '”', '•',
161
            ' как ', ' для ', ' что ', ' или ', ' это ', ' этих ',
162
            'всех ', ' вас ', ' они ', ' оно ', ' еще ', ' когда ',
163
            ' где ', ' эта ', ' лишь ', ' уже ', ' вам ', ' нет ',
164
            ' если ', ' надо ', ' все ', ' так ', ' его ', ' чем ',
165
            ' даже ', ' мне ', ' есть ', ' раз ', ' два ', 'raquo', 'laquo',
166
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'mdash'
167
        ];
168
        $text = str_replace($del_symbols, ' ', $text);
169
        $text = preg_replace('( +)', ' ', $text);
170
        $this->origin_arr = explode(' ', trim($text));
171
        return $this->origin_arr;
172
    }
173
174
    /**
175
     * Count words in text
176
     */
177
    public function count_words() {
178
179
        $tmp_arr = [];
180
        foreach ($this->origin_arr as $val) {
181
            if (strlen(utf8_decode($val)) >= $this->min_word_length) {
182
                $val = mb_strtolower($val, 'utf-8');
183
184
                if (array_key_exists($val, $tmp_arr)) {
185
                    $tmp_arr[$val]++;
186
                } else {
187
                    $tmp_arr[$val] = 1;
188
                }
189
            }
190
        }
191
        $this->modif_arr = $tmp_arr;
192
    }
193
194
    /**
195
     * @param null|string $GAid
196
     * @return string
197
     */
198
    public function renderGA($GAid = null) {
199
200
        /* Show Google Analytics code if some value inserted in admin panel */
201
        if ($GAid['google_analytics_id']) {
202
            if ($this->getCustomParams()) {
203
                $custom = ', ' . $this->getCustomParams();
204
            }
205
206
            if ($GAid['google_analytics_ee'] == 1) {
207
                $require = "ga('require', 'ec');";
208
            } else {
209
                $require = "ga('require', 'ecommerce', 'ecommerce.js');";
210
            }
211
            $ga = "<script>
212
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
213
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
214
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
215
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');
216
217
  ga('create', '{$GAid['google_analytics_id']}', 'auto' $custom);
218
  ga('require', 'displayfeatures');
219
  ga('send', 'pageview');
220
  
221
  $require
222
223
</script>";
224
225
            return $ga;
226
        }
227
    }
228
229
    /**
230
     * @param null|SProducts $model
231
     * @param null|string $GAid
232
     * @return string
0 ignored issues
show
Documentation introduced by
Should the return type not be string|null?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
233
     */
234
    public function renderGAForCart($model = null, $GAid = null) {
235
236
        /* Show Google Analytics code if some value inserted in admin panel */
237
        if ($GAid['google_analytics_id']) {
238
            if ($this->getCustomParams()) {
239
                $custom = ', ' . $this->getCustomParams();
240
            }
241
            $require = $GAid['google_analytics_ee'] == '1' ? "ga('require', 'ec');" : "ga('require', 'ecommerce', 'ecommerce.js');";
242
243
            $ga = "<script>
244
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
245
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
246
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
247
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');
248
249
  ga('create', '{$GAid['google_analytics_id']}', 'auto' $custom);
250
  ga('require', 'displayfeatures');
251
  ga('send', 'pageview');
252
  
253
  $require";
254
            /* @var $model SOrders */
255
            if ($model && $this->orderJustMacked && $GAid['google_analytics_ee'] !== '1') {
256
                if ($model->getSDeliveryMethods()) {
257
                    $affiliation = $model->getSDeliveryMethods()->getName();
258
                }
259
                $ga .= "
260
            ga('ecommerce:addTransaction', {
261
  'id': '" . $model->getId() . "',
262
  'affiliation': '" . $affiliation . "',
263
  'revenue': '" . $model->getTotalPrice() . "',
264
  'shipping': '',
265
  'tax': '',
266
});";
267
268
                foreach ($model->getSOrderProductss() as $item) {
269
                    /* @var $product SProducts */
270
                    $product = $item->getSProducts();
271
                    foreach ($product->getProductVariants() as $v) {
272
                        if ($v->getid() == $item->getVariantId()) {
273
                            $Variant = $v;
274
                            break;
275
                        }
276
                    }
277
                    $ga .= "ga('ecommerce:addItem', {
278
    'id': '" . $model->getId() . "',
279
    'name': '" . encode($product->getName()) . ' ' . encode($item->getVariantName()) . "',
280
    'sku': '" . encode($Variant->getNumber()) . "',
281
    'category': '" . encode($product->getMainCategory()->getName()) . "',
282
    'price': '" . $item->toCurrency() . "',
283
    'quantity': '" . $item->getQuantity() . "',
284
  });";
285
                }
286
                $ga .= "ga('ecommerce:send');";
287
            }
288
            $ga .= '</script>';
289
290
            return $ga;
291
        }
292
    }
293
294
    /**
295
     * @param null|string $YaMetricaId
296
     * @return string
297
     */
298
    public function renderYaMetrica($YaMetricaId = null) {
299
300
        $YandexMetrik = '';
301
        if ($YaMetricaId['yandex_metric']) {
302
            $YandexMetrik = '<!-- Yandex.Metrika counter -->
303
304
                    <script type="text/javascript">
305
                    (function (d, w, c) {
306
                        (w[c] = w[c] || []).push(function() {
307
                            try {
308
                                w.yaCounter24267703 = new Ya.Metrika({id:"' . $YaMetricaId['yandex_metric'] . '",
309
                                        webvisor:true,
310
                                        clickmap:true,
311
                                        trackLinks:true,
312
                                        accurateTrackBounce:true});
313
                            } catch(e) { }
314
                        });
315
316
                        var n = d.getElementsByTagName("script")[0],
317
                            s = d.createElement("script"),
318
                            f = function () { n.parentNode.insertBefore(s, n); };
319
                        s.type = "text/javascript";
320
                        s.async = true;
321
                        s.src = (d.location.protocol == "https:" ? "https:" : "http:") + "//mc.yandex.ru/metrika/watch.js";
322
323
                        if (w.opera == "[object Opera]") {
324
                            d.addEventListener("DOMContentLoaded", f, false);
325
                        } else { f(); }
326
                    })(document, window, "yandex_metrika_callbacks");
327
                    </script>
328
                    <noscript><div><img src="//mc.yandex.ru/watch/' . $YaMetricaId['yandex_metric'] . '" style="position:absolute; left:-9999px;" alt="" /></div></noscript>
329
        <!-- /Yandex.Metrika counter -->';
330
        }
331
        return $YandexMetrik;
332
    }
333
334
    public function renderYandexWebmaster($YaWebmasterId = null) {
335
336
        $YaWebmaster = '';
337
        if ($YaWebmasterId['yandex_webmaster']) {
338
            $YaWebmaster = '<meta name=\'yandex-verification\' content=\'' . $YaWebmasterId['yandex_webmaster'] . '\' />';
339
        }
340
341
        return $YaWebmaster;
342
    }
343
344
    public function renderGoogleWebmaster($GWebmasterId = null) {
345
346
        $GWebmaster = '';
347
        if ($GWebmasterId['google_webmaster']) {
348
            $GWebmaster = '<meta name="google-site-verification" content="' . $GWebmasterId['google_webmaster'] . '" />';
349
        }
350
351
        return $GWebmaster;
352
    }
353
354
    public function getCustomParams($type = 'json') {
355
356
        if (empty($this->custom)) {
357
            return;
358
        }
359
        switch ($type) {
360
            case 'json':
361
                return json_encode($this->custom);
362
363
            default:
364
                return $this->custom;
365
        }
366
    }
367
368
    /**
369
     * @param string $name
370
     * @param string $val
371
     */
372
    public function setCustomParams($name, $val) {
373
374
        if ($name != '') {
375
            $this->custom[$name] = $val;
376
        }
377
    }
378
379
}
380
381
/* End of file lib_seo.php */