Sitemap   F
last analyzed

Complexity

Total Complexity 98

Size/Duplication

Total Lines 840
Duplicated Lines 4.88 %

Coupling/Cohesion

Components 1
Dependencies 8

Importance

Changes 0
Metric Value
dl 41
loc 840
rs 1.76
c 0
b 0
f 0
wmc 98
lcom 1
cbo 8

23 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 20 3
A build_xml_map_regenerated() 0 4 1
A build_xml_map() 0 21 5
A _create_map() 0 30 4
B initialize() 0 40 5
A robotsCheck() 0 7 1
B getPagesCategories() 13 49 8
B not_blocked_url() 0 40 10
B getAllPages() 13 41 6
A _get_lang_prefix() 0 8 3
B getShopCategories() 5 42 7
A getShopBrands() 5 28 5
B getShopProducts() 5 30 6
B generate_xml() 0 39 8
A saveSiteMaps() 0 20 5
A createMainSitemap() 0 14 2
A _deinstall() 0 4 1
A _install() 0 5 2
A adminAutoload() 0 30 1
A gzip() 0 5 1
A index() 0 20 1
B sitemap_ul() 0 35 8
B ping_google() 0 46 5

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like Sitemap often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Sitemap, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
use CMSFactory\Events;
4
use core\models\Route;
5
use core\src\CoreFactory;
6
7
if (!defined('BASEPATH')) {
8
    exit('No direct script access allowed');
9
}
10
11
/**
12
 * Image CMS
13
 *
14
 * Sitemap Module
15
 * @property Sitemap_model $sitemap_model
16
 * @property Lib_category lib_category
17
 * @property smart_filter smart_filter
18
 */
19
class Sitemap extends MY_Controller
20
{
21
22
    /**
23
     * Blocked urls array
24
     * @var array
25
     */
26
    public $blocked_urls = [];
27
28
    /**
29
     * Frequency for brands pages
30
     * @var string
31
     */
32
    public $brands_changefreq = 'daily';
33
34
    /**
35
     * Priority for brands pages
36
     * @var int
37
     */
38
    public $brands_priority = '1';
39
40
    /**
41
     * Frequency for categories pages
42
     * @var string
43
     */
44
    public $categories_changefreq = 'daily'; // priority for subcategories pages
45
46
    /**
47
     * Priority for categories
48
     * @var int
49
     */
50
    public $cats_priority = '1';
51
52
    /**
53
     * Default frequency
54
     * @var string
55
     */
56
    public $changefreq = 'daily';
57
58
    /**
59
     * Default lang
60
     * @var array
61
     */
62
    public $default_lang = [];
63
64
    /**
65
     * Gzip level
66
     * @var int
67
     */
68
    public $gzip_level = 0;
69
70
    /**
71
     * Sitemap items
72
     * @var array
73
     */
74
    public $items = [];
75
76
    /**
77
     * Langs array
78
     * @var array
79
     */
80
    public $langs = [];
81
82
    /**
83
     * Frequency for main page
84
     * @var string
85
     */
86
    public $main_page_changefreq = 'daily';
87
88
    /**
89
     * Priority for main page
90
     * @var int
91
     */
92
    public $main_page_priority = '1';
93
94
    /**
95
     * Max url tag count
96
     * @var int
97
     */
98
    private $max_url_count = 30000;
99
100
    /**
101
     * Frequency for pages
102
     * @var string
103
     */
104
    public $pages_changefreq = 'daily';
105
106
    /**
107
     * Priority for pages
108
     * @var int
109
     */
110
    public $pages_priority = '1';
111
112
    /**
113
     * Frequency for products categories pages
114
     * @var string
115
     */
116
    public $products_categories_changefreq = 'daily';
117
118
    /**
119
     * Priority for products categories pages
120
     * @var int
121
     */
122
    public $products_categories_priority = '1';
123
124
    /**
125
     * Frequency for products pages
126
     * @var string
127
     */
128
    public $products_changefreq = 'daily';
129
130
    /**
131
     * Priority for products pages
132
     * @var int
133
     */
134
    public $products_priority = '1';
135
136
    /**
137
     * Frequency for products sub categiries pages
138
     * @var string
139
     */
140
    public $products_sub_categories_changefreq = 'daily';
141
142
    /**
143
     * Priority for products sub categories pages
144
     * @var int
145
     */
146
    public $products_sub_categories_priority = '1';
147
148
    /**
149
     * Sitemap result
150
     * @var string
151
     */
152
    public $result = '';
153
154
    /**
155
     * Path to folder where site_maps files exists
156
     * @var string
157
     */
158
    private $site_map_folder_path = './uploads/sitemaps';
159
160
    /**
161
     * Path to saved sitemap file
162
     * @var string
163
     */
164
    private $sitemap_path = './uploads/sitemaps/sitemap.xml';
165
166
    /**
167
     * Frequency for sub categories pages
168
     * @var string
169
     */
170
    public $sub_categories_changefreq = 'daily';
171
172
    /**
173
     * Priority for subcategories pages
174
     * @var int
175
     */
176
    public $sub_cats_priority = '1';
177
178
    /**
179
     * Sitemap constructor.
180
     */
181
    public function __construct() {
182
183
        parent::__construct();
184
        $lang = new MY_Lang();
185
        $lang->load('sitemap');
186
187
        $this->load->module('core');
188
        $this->load->model('sitemap_model');
189
        $this->langs = CoreFactory::getConfiguration()->getLanguages();
190
        $this->default_lang = CoreFactory::getConfiguration()->getDefaultLanguage();
191
        if (uri_string() == 'sitemap.xml') {
192
            $this->build_xml_map();
193
            exit();
194
        }
195
196
        if (uri_string() == 'sitemapRegenerate.xml') {
197
            $this->build_xml_map_regenerated();
198
            exit();
199
        }
200
    }
201
202
    public function build_xml_map_regenerated() {
203
204
        $this->build_xml_map(TRUE);
205
    }
206
207
    /**
208
     * Create and display sitemap xml
209
     * @param bool $regenerate
210
     */
211
    public function build_xml_map($regenerate = FALSE) {
212
213
        $settings = $this->sitemap_model->load_settings();
214
215
        // Generate new or use saved map
216
        if ((int) $settings['generateXML'] || $regenerate) {
217
            $this->_create_map();
218
        } else {
219
            if (file_exists($this->sitemap_path)) {
220
                $this->result = file_get_contents($this->sitemap_path);
221
            } else {
222
                $this->_create_map();
223
            }
224
        }
225
226
        // Show Site Map
227
        if ($this->result) {
228
            header('content-type: text/xml');
229
            echo $this->result;
230
        }
231
    }
232
233
    /**
234
     * Create map
235
     */
236
    public function _create_map() {
237
238
        if ($this->robotsCheck()) {
239
            $this->initialize();
240
241
            // Add main pagez
242
            $this->items[] = [
243
                              'loc'        => site_url(),
244
                              'changefreq' => $this->main_page_changefreq,
245
                              'priority'   => $this->main_page_priority,
246
                              'lastmod'    => date('Y-m-d', time()),
247
                             ];
248
            $this->getPagesCategories();
249
            $this->getAllPages();
250
251
            if (SHOP_INSTALLED) {
252
253
                $this->getShopCategories();
254
                $this->getShopBrands();
255
                $this->getShopProducts();
256
257
                $this->load->module('smart_filter');
258
                if (method_exists($this->smart_filter, 'attachPages')) {
259
                    $this->smart_filter->attachPages($this);
260
                }
261
            }
262
        }
263
        $this->result = $this->generate_xml($this->items);
264
        return $this->result;
265
    }
266
267
    /**
268
     * Initialize module settings
269
     */
270
    public function initialize() {
271
272
        // Get sitemap values
273
        $priorities = $this->sitemap_model->getPriorities();
274
        $changfreq = $this->sitemap_model->getChangefreq();
275
        $blocked_urls = $this->sitemap_model->getBlockedUrls();
276
277
        // Initialize priorities
278
        if ($priorities) {
279
            $this->main_page_priority = $priorities['main_page_priority'];
280
            $this->cats_priority = $priorities['cats_priority'];
281
            $this->pages_priority = $priorities['pages_priority'];
282
            $this->sub_cats_priority = $priorities['sub_cats_priority'];
283
            $this->products_priority = $priorities['products_priority'];
284
            $this->products_categories_priority = $priorities['products_categories_priority'];
285
            $this->products_sub_categories_priority = $priorities['products_sub_categories_priority'];
286
            $this->brands_priority = $priorities['brands_priority'];
287
        }
288
289
        // Initialize changfreq
290
        if ($changfreq) {
291
            $this->main_page_changefreq = $changfreq['main_page_changefreq'];
292
            $this->categories_changefreq = $changfreq['categories_changefreq'];
293
            $this->products_categories_changefreq = $changfreq['products_categories_changefreq'];
294
            $this->products_sub_categories_changefreq = $changfreq['products_sub_categories_changefreq'];
295
            $this->pages_changefreq = $changfreq['pages_changefreq'];
296
            $this->products_changefreq = $changfreq['product_changefreq'];
297
            $this->brands_changefreq = $changfreq['brands_changefreq'];
298
            $this->sub_categories_changefreq = $changfreq['sub_categories_changefreq'];
299
        }
300
301
        // Initialize Blocked urls
302
        if ($blocked_urls) {
303
            foreach ($blocked_urls as $url) {
304
                $this->blocked_urls[] = $url['url'];
305
            }
306
        }
307
308
        return $this;
309
    }
310
311
    /**
312
     * Check robots
313
     * @return boolean
314
     */
315
    public function robotsCheck() {
316
317
        return (bool) $this->db->get('settings')
318
            ->row()
319
            ->robots_status;
320
321
    }
322
323
    /**
324
     * Get pages categories
325
     */
326
    private function getPagesCategories() {
327
328
        // Add categories to sitemap urls.
329
        $categories = $this->lib_category->unsorted();
330
331
        foreach ($categories as $category) {
332
333
            if ((int) $category['parent_id']) {
334
                $changefreq = $this->sub_categories_changefreq;
335
                $priority = $this->sub_cats_priority;
336
            } else {
337
                $changefreq = $this->categories_changefreq;
338
                $priority = $this->cats_priority;
339
            }
340
341
            // create date
342 View Code Duplication
            if ($category['updated'] > 0) {
343
                $date = date('Y-m-d', $category['updated']);
344
            } else {
345
                $date = date('Y-m-d', $category['created']);
346
            }
347
348
            if ($this->not_blocked_url($category['path_url'])) {
349
350
                $this->items[] = [
351
                                  'loc'        => site_url($category['path_url']),
352
                                  'changefreq' => $changefreq,
353
                                  'priority'   => $priority,
354
                                  'lastmod'    => $date,
355
                                 ];
356
            }
357
358
            // Add links to categories in all langs.
359
            foreach ($this->langs as $lang_indentif => $lang) {
360
                if ($lang['id'] != $this->default_lang['id']) {
361
                    $url = $lang_indentif . '/' . $category['path_url'];
362 View Code Duplication
                    if ($this->not_blocked_url($url)) {
363
                        $this->items[] = [
364
                                          'loc'        => site_url($url),
365
                                          'changefreq' => $changefreq,
366
                                          'priority'   => $priority,
367
                                          'lastmod'    => $date,
368
                                         ];
369
                    }
370
                }
371
            }
372
373
        }
374
    }
375
376
    /**
377
     * Chech is url blocked
378
     * @param string $url
379
     * @return boolean
380
     */
381
    public function not_blocked_url($url) {
382
383
        if (!in_array($url, $this->blocked_urls) && !in_array(substr($url, 0, -1), $this->blocked_urls)) {
384
            foreach ($this->blocked_urls as $blocked_url) {
385
                $url = str_replace(site_url(), '', $url);
386
387
                if (mb_strpos($url, '/') === 0) {
388
                    $url = substr($url, 1);
389
                }
390
391
                if (mb_strrpos($url, '/') === (mb_strlen($url) - 1)) {
392
                    $url = substr($url, 0, -1);
393
                }
394
395
                $url_length = mb_strlen($blocked_url);
396
                $last_symbol = substr($blocked_url, $url_length - 1);
397
                $first_symbol = substr($blocked_url, 0, 1);
398
                $blocked_url_tpm = str_replace('*', '', $blocked_url);
399
400
                if ($last_symbol == '*') {
401
                    $url_position = mb_strpos($url, $blocked_url_tpm);
402
                    if ($url_position === 0) {
403
                        return FALSE;
404
                    }
405
                }
406
407
                if ($first_symbol == '*') {
408
                    $must_be_in_pos = (int) mb_strlen($url) - (int) mb_strlen($blocked_url_tpm);
409
                    $url_position = mb_strrpos($url, $blocked_url_tpm);
410
                    if ($must_be_in_pos == $url_position) {
411
                        return FALSE;
412
                    }
413
                }
414
            }
415
416
            return TRUE;
417
        } else {
418
            return FALSE;
419
        }
420
    }
421
422
    /**
423
     * Get all content pages
424
     */
425
    private function getAllPages() {
426
427
        // Get all pages
428
        $pages = $this->sitemap_model->get_all_pages();
429
430
        foreach ($pages as $page) {
431
432
            // create page url
433
            if ($page['lang'] == $this->default_lang['id']) {
434
                $url = site_url($page['full_url']);
435
                $url_page = $page['full_url'];
436
            } else {
437
                $prefix = $this->_get_lang_prefix($page['lang']);
438
                $url_page = $prefix . '/' . $page['full_url'];
439
                $url = site_url($url_page);
440
            }
441
442
            // create date
443 View Code Duplication
            if ($page['updated'] > 0) {
444
                $date = date('Y-m-d', $page['updated']);
445
            } else {
446
                $date = date('Y-m-d', $page['created']);
447
            }
448
449
            if ($page['cat_url'] == '') {
450
                $c_priority = $this->cats_priority;
451
            } else {
452
                $c_priority = $this->pages_priority;
453
            }
454
455 View Code Duplication
            if ($this->not_blocked_url($url_page)) {
456
                $this->items[] = [
457
                                  'loc'        => $url,
458
                                  'changefreq' => $this->pages_changefreq,
459
                                  'priority'   => $c_priority,
460
                                  'lastmod'    => $date,
461
                                 ];
462
            }
463
464
        }
465
    }
466
467
    /**
468
     * Get language prefix by lang id
469
     * @param int $id
470
     * @return int|string
471
     */
472
    private function _get_lang_prefix($id) {
473
474
        foreach ($this->langs as $k => $v) {
475
            if ($v['id'] === $id) {
476
                return $k;
477
            }
478
        }
479
    }
480
481
    /**
482
     * Get products categories
483
     */
484
    private function getShopCategories() {
485
486
        // Get Shop Categories
487
        $shop_categories = $this->sitemap_model->get_shop_categories();
488
489
        // Add categories to Site Map
490
        foreach ($shop_categories as $shopCategory) {
491
492
            if ($this->sitemap_model->categoryIsActive($shopCategory['id'])) {
493
494
                $localeSegment = $shopCategory['locale'] == self::defaultLocale() ? '' : $shopCategory['locale'] . '/';
495
496
                $url = $localeSegment . Route::createRouteUrl($shopCategory['url'], $shopCategory['parent_url'], Route::TYPE_SHOP_CATEGORY);
497
                if ($this->not_blocked_url($url)) {
498
499
                    // Check if category is subcategory
500
                    if ((int) $shopCategory['parent_id']) {
501
                        $changefreq = $this->products_sub_categories_changefreq;
502
                        $priority = $this->products_sub_categories_priority;
503
                    } else {
504
                        $changefreq = $this->products_categories_changefreq;
505
                        $priority = $this->products_categories_priority;
506
                    }
507
508
                    // create date
509 View Code Duplication
                    if ($shopCategory['updated'] > 0) {
510
                        $date = date('Y-m-d', $shopCategory['updated']);
511
                    } else {
512
                        $date = date('Y-m-d', $shopCategory['created']);
513
                    }
514
515
                    $this->items[] = [
516
                                      'loc'        => site_url($url),
517
                                      'changefreq' => $changefreq,
518
                                      'priority'   => $priority,
519
                                      'lastmod'    => $date,
520
                                     ];
521
522
                }
523
            }
524
        }
525
    }
526
527
    /**
528
     * Get products brands
529
     */
530
    private function getShopBrands() {
531
532
        // Get Shop Brands
533
        $shop_brands = $this->sitemap_model->get_shop_brands();
534
535
        // Add Shop Brand to Site Map
536
        foreach ($shop_brands as $shopbr) {
537
538
            $localeSegment = $shopbr['locale'] == self::defaultLocale() ? '' : $shopbr['locale'] . '/';
539
540
            $url = site_url($localeSegment . 'shop/brand/' . $shopbr['url']);
541
            if ($this->not_blocked_url($localeSegment . 'shop/brand/' . $shopbr['url'])) {
542
                // create date
543 View Code Duplication
                if ($shopbr['updated'] > 0) {
544
                    $date = date('Y-m-d', $shopbr['updated']);
545
                } else {
546
                    $date = date('Y-m-d', $shopbr['created']);
547
                }
548
                $this->items[] = [
549
                                  'loc'        => $url,
550
                                  'changefreq' => $this->brands_changefreq,
551
                                  'priority'   => $this->brands_priority,
552
                                  'lastmod'    => $date,
553
                                 ];
554
555
            }
556
        }
557
    }
558
559
    /**
560
     * Get products
561
     */
562
    private function getShopProducts() {
563
564
        // Get Shop products
565
        $shop_products = $this->sitemap_model->get_shop_products();
566
567
        // Add Shop products to Site Map
568
        foreach ($shop_products as $shopprod) {
569
            if ($this->sitemap_model->categoryIsActive($shopprod['category_id'])) {
570
571
                $localeSegment = $shopprod['locale'] == self::defaultLocale() ? '' : $shopprod['locale'] . '/';
572
                $url = site_url($localeSegment . Route::createRouteUrl($shopprod['url'], $shopprod['parent_url'], Route::TYPE_PRODUCT));
573
574
                if ($this->not_blocked_url($localeSegment . Route::createRouteUrl($shopprod['url'], $shopprod['parent_url'], Route::TYPE_PRODUCT))) {
575
576 View Code Duplication
                    if ($shopprod['updated'] > 0) {
577
                        $date = date('Y-m-d', $shopprod['updated']);
578
                    } else {
579
                        $date = date('Y-m-d', $shopprod['created']);
580
                    }
581
                    $this->items[] = [
582
                                      'loc'        => $url,
583
                                      'changefreq' => $this->products_changefreq,
584
                                      'priority'   => $this->products_priority,
585
                                      'lastmod'    => $date,
586
                                     ];
587
588
                }
589
            }
590
        }
591
    }
592
593
    /**
594
     * Generate xml
595
     * @param array $items
596
     * @return string
597
     */
598
    private function generate_xml(array $items = []) {
599
600
        $data = '';
601
602
        $site_maps = [];
603
        $url_count = 0;
604
605
        while ($item = current($items)) {
606
            if ($url_count < $this->max_url_count) {
607
                $data .= "<url>\n";
608
                foreach ($item as $k => $v) {
609
                    if ($v != '') {
610
                        $data .= "\t<$k>" . htmlspecialchars($v) . "</$k>\n";
611
                    }
612
                }
613
                $data .= "</url>\n";
614
615
                next($items);
616
            } else {
617
                $site_maps[] = "<\x3Fxml version=\"1.0\" encoding=\"UTF-8\"\x3F>\n<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n" . $data . "\t</urlset>";
618
                $url_count = 0;
619
                $data = '';
620
            }
621
            $url_count++;
622
        }
623
624
        if ($data && $site_maps) {
625
            $site_maps[] = "<\x3Fxml version=\"1.0\" encoding=\"UTF-8\"\x3F>\n<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n" . $data . "\t</urlset>";
626
        }
627
628
        if ($site_maps) {
629
            $this->saveSiteMaps($site_maps);
630
            $result = $this->createMainSitemap($site_maps);
631
        } else {
632
            $result = "<\x3Fxml version=\"1.0\" encoding=\"UTF-8\"\x3F>\n<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n" . $data . "\t</urlset>";
633
        }
634
635
        return $result;
636
    }
637
638
    /**
639
     * Save several sitemaps files
640
     * @param array $site_maps - array of sitemaps data
641
     */
642
    private function saveSiteMaps($site_maps) {
643
644
        if (!is_dir($this->site_map_folder_path)) {
645
            mkdir($this->site_map_folder_path, 0777);
646
        }
647
648
        foreach (glob($this->site_map_folder_path . '/sitemap*') as $site_map_file) {
649
            chmod($site_map_file, 0777);
650
            unlink($site_map_file);
651
        }
652
653
        foreach ($site_maps as $number => $site_map) {
654
            if ($site_map) {
655
                $number++;
656
                $site_map_path = $this->site_map_folder_path . "/sitemap{$number}.xml";
657
                file_put_contents($site_map_path, $site_map);
658
                chmod($site_map_path, 0777);
659
            }
660
        }
661
    }
662
663
    /**
664
     * Create main sitemap file
665
     * @param array $site_maps - array of sitemaps data
666
     * @return string
667
     */
668
    private function createMainSitemap($site_maps) {
669
670
        foreach ($site_maps as $number => $site_map) {
671
            $number++;
672
            $site_map_url = site_url(str_replace('./', '', $this->site_map_folder_path . "/sitemap{$number}.xml"));
673
            $data .= '<sitemap><loc>' . $site_map_url . '</loc></sitemap>';
674
        }
675
676
        $result = '<?xml version="1.0" encoding="UTF-8"?><sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . $data . '</sitemapindex>';
677
678
        file_put_contents($this->site_map_folder_path . '/sitemap.xml', $result);
679
        chmod($this->site_map_folder_path . '/sitemap.xml', 0777);
680
        return $result;
681
    }
682
683
    /**
684
     * Deinstall module
685
     */
686
    public function _deinstall() {
687
688
        return $this->sitemap_model->deinstallModule();
689
    }
690
691
    /**
692
     * Install module
693
     */
694
    public function _install() {
695
696
        $robotsCheck = $this->robotsCheck() ? 1 : 0;
697
        return $this->sitemap_model->installModule($robotsCheck);
698
    }
699
700
    public static function adminAutoload() {
701
702
        parent::adminAutoload();
703
704
        // Set listeners on page pre update to set url
705
        Events::create()->setListener('setUpdatedUrl', 'ShopAdminProducts:preEdit');
706
        Events::create()->onAdminPagePreEdit()->setListener('setUpdatedUrl');
707
        Events::create()->onAdminCategoryPreUpdate()->setListener('setUpdatedUrl');
708
        Events::create()->onShopCategoryPreEdit()->setListener('setUpdatedUrl');
709
        Events::create()->onShopBrandPreEdit()->setListener('setUpdatedUrl');
710
711
        Events::create()->onShopProductCreate()->setListener('ping_google');
712
        Events::create()->onShopProductUpdate()->setListener('ping_google');
713
        Events::create()->onShopProductDelete()->setListener('ping_google');
714
715
        Events::create()->onShopCategoryCreate()->setListener('ping_google');
716
        Events::create()->onShopCategoryEdit()->setListener('ping_google');
717
        Events::create()->onShopCategoryDelete()->setListener('ping_google');
718
719
        Events::create()->onShopBrandCreate()->setListener('ping_google');
720
        Events::create()->onShopBrandEdit()->setListener('ping_google');
721
        Events::create()->onShopBrandDelete()->setListener('ping_google');
722
723
        Events::create()->onAdminPageCreate()->setListener('ping_google');
724
        Events::create()->onAdminPageUpdate()->setListener('ping_google');
725
        Events::create()->onAdminPageDelete()->setListener('ping_google');
726
727
        Events::create()->onAdminCategoryCreate()->setListener('ping_google');
728
        Events::create()->onAdminCategoryUpdate()->setListener('ping_google');
729
    }
730
731
    /**
732
     * Gzip generate
733
     */
734
    public function gzip() {
735
736
        $this->_create_map();
737
        echo gzencode($this->result, $this->gzip_level);
738
    }
739
740
    /**
741
     * Show sitemap for categories
742
     */
743
    public function index() {
744
745
        $this->template->registerMeta('ROBOTS', 'NOINDEX, NOFOLLOW');
746
        $categories = $this->lib_category->_build();
747
748
        $pages = $this->db
749
            ->get_where(
750
                'content',
751
                [
752
                 'category'        => 0,
753
                 'lang'            => $this->config->item('cur_lang'),
754
                 'publish_date <=' => time(),
755
                 'post_status'     => 'publish',
756
                ]
757
            )
758
            ->result_array();
759
760
        $this->template->assign('content', $this->sitemap_ul($categories, $pages));
761
        $this->template->show();
762
    }
763
764
    /**
765
     * Display sitemap ul list
766
     * @param array $items - site map items
767
     * @param array $pages_without_category
768
     * @return string
769
     */
770
    public function sitemap_ul($items = [], $pages_without_category = []) {
771
772
        $out = '<ul class="sitemap">';
773
774
        foreach ($items as $item) {
775
            if (isset($item['path_url'])) {
776
                $url = $item['path_url'];
777
            } elseif (isset($item['full_url'])) {
778
                $url = $item['full_url'];
779
            }
780
781
            $out .= '<li>' . anchor($url, $item['name']) . '</li>';
782
783
            // Get category pages
784
            if (isset($item['path_url'])) {
785
                $pages = $this->sitemap_model->get_cateogry_pages($item['id']);
786
787
                if ($pages) {
788
                    $out .= $this->sitemap_ul($pages);
789
                }
790
            }
791
792
            if (count($item['subtree']) > 0) {
793
                $out .= $this->sitemap_ul($item['subtree']);
794
            }
795
        }
796
797
        foreach ($pages_without_category as $page) {
798
            $out .= '<li>' . anchor($page['url'], $page['title']) . '</li>';
799
        }
800
801
        $out .= '</ul>';
802
803
        return $out;
804
    }
805
806
    /**
807
     * Send xml to google
808
     * return $code if send (200 = ok) else 'false'
809
     * @return bool|mixed
810
     */
811
    public static function ping_google() {
812
813
        // Checking is used server is local
814
815
        $ci = &get_instance();
816
        if (strstr($ci->input->server('SERVER_NAME'), '.loc')) {
817
            return FALSE;
818
        }
819
820
        $ci->db->select('settings');
821
        $ci->db->where('name', 'sitemap');
822
        $query = $ci->db->get('components', 1)->row_array();
823
824
        $settings = unserialize($query['settings']);
825
826
        // Check if turn off sending site map
827
        if (!$settings['sendSiteMap']) {
828
            return FALSE;
829
        }
830
831
        // Checking time permission(1 hour passed from last send) to send ping
832
        if ((time() - $settings['lastSend']) / (60 * 60) >= 1) {
833
834
            $ch = curl_init();
835
836
            curl_setopt($ch, CURLOPT_URL, 'http://www.google.com/webmasters/tools/ping?sitemap=' . site_url() . '/sitemap.xml');
837
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
838
839
            curl_exec($ch);
840
            $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
841
842
            curl_close($ch);
843
844
            if ($code == '200') {
845
                // Update settings, set lastSend time
846
                $settings['lastSend'] = time();
847
                $ci->db->limit(1);
848
                $ci->db->where('name', 'sitemap');
849
                $ci->db->update('components', ['settings' => serialize($settings)]);
850
851
            }
852
853
            return $code;
854
        }
855
        return false;
856
    }
857
858
}
859
860
/* End of file sitemap.php */