/
seo.class.php
executable file
·1176 lines (1085 loc) · 43.5 KB
/
seo.class.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
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
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* CubeCart v6
* ========================================
* CubeCart is a registered trade mark of CubeCart Limited
* Copyright CubeCart Limited 2017. All rights reserved.
* UK Private Limited Company No. 5323904
* ========================================
* Web: http://www.cubecart.com
* Email: sales@cubecart.com
* License: GPL-3.0 https://www.gnu.org/licenses/quick-guide-gplv3.html
*/
/**
* Language controller
*
* @author Technocrat
* @author Al Brookbanks
* @since 5.0.0
*/
class SEO
{
/**
* Category directories
*
* @var array of strings
*/
private $_cat_dirs = array();
/**
* Category paths
*
* @var array of strings
*/
private $_cat_path = null;
/**
* Dynamic URL sections
*
* @var array of strings
*/
private $_dynamic_sections = array('prod', 'cat', 'doc');
/**
* SEO url extension
*
* @var string
*/
private $_extension = '';
/**
* Ignored URL sections
*
* @var array of strings
*/
private $_ignored = array(
'account', 'addressbook', 'basket', 'checkout', 'complete', 'confirm', 'download', 'downloads', 'gateway', 'logout', 'profile', 'receipt', 'recover', 'recovery', 'remote', 'vieworder', 'plugin', 'unsubscribe'
);
/**
* Rewrite URL Absolute?
*
* @var bool
*/
private $_rewrite_url_absolute = false;
/**
* Meta data
*
* @var array
*/
private $_meta_data = array();
/**
* Sitemap XML handle
*
* @var handle
*/
private $_sitemap_xml = false;
/**
* Static URL sections
*
* @var array of strings
*/
private $_static_sections = array('recover', 'saleitems', 'certificates', 'trackback', 'contact', 'search', 'login', 'register');
/**
* SSL URL
*
* @var string
*/
private $_sitemap_base_url = '';
/**
* Standard Dynamic URL
*
* @var string
*/
private $_url = '';
/**
* Class instance
*
* @var instance
*/
protected static $_instance;
const TAGS_DEFAULT = 0;
const TAGS_MERGE = 1;
const TAGS_REPLACE = 2;
const PCRE_REQUEST_URI = '(.*/)?[\w\-\_]+.[a-z]+\?_a\=([\w]+)\&(amp;)?([\w]+)\=([\w\-\_]+)([^"\']*)';
public $_a = '';
##############################################
public function __construct()
{
// Allow hooks to append to private variables via array_merge
// e.g.
// Dynamic
// $new_dynamic_sections = array('dynamic1', 'dynamic2', 'dynamic3');
// $this->_dynamic_sections = array_merge($this->_dynamic_sections, $new_dynamic_sections);
// Static
// $new_static_sections = array('static1', 'static2', 'static3');
// $this->_static_sections = array_merge($this->_static_sections, $new_static_sections);
foreach ($GLOBALS['hooks']->load('class.seo.construct') as $hook) {
include $hook;
}
$this->_sitemap_base_url = $GLOBALS['config']->get('config', 'ssl')=='1' ? preg_replace('#^http://#', 'https://', $GLOBALS['config']->get('config', 'standard_url')) : $GLOBALS['config']->get('config', 'standard_url');
self::_checkModRewrite();
if($GLOBALS['config']->has('config', 'seo_ext')) {
$this->_extension = $GLOBALS['config']->get('config', 'seo_ext');
} else {
$this->_extension = '.html';
}
// Build an array of ALL categories
$this->_getCategoryList();
//If URL is an SEO
if (preg_match('#^'.self::PCRE_REQUEST_URI.'$#Sui', $_SERVER['REQUEST_URI'], $match)) {
if (!in_array($match[2], $this->_ignored)) {
//Generate SEO URL
$seo_url = html_entity_decode($this->generatePath($match[5], $match[2], $match[4], true));
if(!empty($match[6]) && $match[6][0]=='&'){
$match[6][0]='?';
$seo_url.=$match[6];
}
//If the SEO URL != to the current URL
if (str_replace($GLOBALS['rootRel'], '', $_SERVER['REQUEST_URI']) != $seo_url) {
//Push the user to that URL
httpredir($seo_url);
}
}
}
}
/**
* Setup the instance (singleton)
*
* @return SEO
*/
public static function getInstance()
{
if (!(self::$_instance instanceof self)) {
self::$_instance = new self();
}
return self::$_instance;
}
//=====[ Public ]=======================================
/**
* Add another element to the ignored url segments
*
* @param string $string
*/
public function addIgnore($string)
{
if (!empty($string)) {
$this->_ignored[] = $string;
}
}
/**
* Build SEO URL
*
* @param string $type
* @param string $item_id
* @param string $amp
* @return string
*/
public function buildURL($type, $item_id = false, $amp = '&', $absolute = true)
{
// Some SEO paths are not stored in the database
$url = ($absolute) ? $GLOBALS['storeURL'].'/' : $GLOBALS['rootRel'];
if (!$item_id && in_array($type, $this->_static_sections)) {
if (($item = $GLOBALS['db']->select('CubeCart_seo_urls', array('path'), array('type' => $type, 'redirect' => 0), false, 1, false, false)) !== false) {
foreach ($GLOBALS['hooks']->load('class.seo.buildurl.static_sections') as $hook) {
include $hook;
}
return $url.$item[0]['path'];
} else {
return $url.$this->setdbPath($type, '', '', false).$this->_extension;
}
} elseif (($item = $GLOBALS['db']->select('CubeCart_seo_urls', array('path'), array('type' => $type, 'item_id' => $item_id, 'redirect' => 0), false, 1, false, false)) !== false) {
foreach ($GLOBALS['hooks']->load('class.seo.buildurl.dynamic_url') as $hook) {
include $hook;
}
return $url.$item[0]['path'];
} else {
return $url.$this->setdbPath($type, $item_id, '', false);
}
}
/**
* Delete SEO URL
*
* @param string $type
* @param string $item_id
* @return bool
*/
public function delete($type, $item_id)
{
if (in_array($type, $this->_dynamic_sections) && is_numeric($item_id)) {
return $GLOBALS['db']->delete('CubeCart_seo_urls', array('type' => $type, 'item_id' => $item_id));
}
return false;
}
/**
* Put the META data to the GUI
*/
public function displayMetaData()
{
$GLOBALS['smarty']->assign('META_DESCRIPTION', $this->meta_description());
$GLOBALS['smarty']->assign('META_TITLE', $this->meta_title());
}
/**
* Create full URL
*
* @param string $url
* @param bool $process
* @return string
*/
public function fullURL($url, $process = false)
{
if (!empty($url) && !preg_match('#^([a-z]+:|\"|\'|\#|\?)#Si', $url)) {
if ($process) {
$url = $GLOBALS['storeURL'] . (($GLOBALS['rootRel'] != '/') ? '/'. str_replace($GLOBALS['rootRel'], '', $url) : '/'.$url);
} elseif (substr($url, 0, strlen($GLOBALS['rootRel'])) != $GLOBALS['rootRel']) {
$url = $GLOBALS['rootRel'].$url;
}
}
return $url;
}
/**
* Generate SEO path
*
* @param string $id
* @param string $type
* @param string $key
* @param string $absolute
* @param string $extension
* @return string
*/
public function generatePath($id = null, $type = null, $key = null, $absolute = false)
{
$prefix = '';
$type = strtolower($type);
if (!isset($GLOBALS['db']) || !is_object($GLOBALS['db'])) {
$GLOBALS['db'] = Database::getInstance();
}
if (in_array($type, $this->_static_sections)) { /*! Static */
if (($existing = $GLOBALS['db']->select('CubeCart_seo_urls', 'path', array('type' => $type, 'redirect' => 0), false, 1, false, false)) !== false) {
$path = $existing[0]['path'];
} else {
/* Force static English SEO paths until we have improved SEO for languages */
$current_language = $GLOBALS['language']->current();
$reset_language = false;
if ($current_language!=='en-GB') {
$GLOBALS['language']->change('en-GB');
$GLOBALS['language']->loadDefinitions('default');
$reset_language = true;
}
$path = (!empty($GLOBALS['language']->navigation['seo_path_'.$type])) ? $GLOBALS['language']->navigation['seo_path_'.$type] : $type;
if ($reset_language) {
$GLOBALS['language']->change($current_language);
}
}
} else { /*! Dynamic */
switch ($type) {
case 'cat':
case 'category':
case 'viewcat':
// check its not been made already
$custom = false;
if (($existing = $GLOBALS['db']->select('CubeCart_seo_urls', array('path', 'custom'), array('type' => 'cat', 'item_id' => $id, 'redirect' => 0), false, 1, false, false)) !== false) {
$path = $existing[0]['path'];
$custom = (bool)$existing[0]['custom'];
} elseif (is_numeric($id) && isset($this->_cat_dirs[$id])) {
$path = $this->getDirectory($id);
} elseif (!isset($this->_cat_dirs[$id])) {
// new category won't be in cache so it needs rebuilding
$GLOBALS['cache']->delete('seo.category.list');
$this->_getCategoryList();
$path = $this->getDirectory($id);
// If try from cache fails...
if(empty($path)) {
$this->_getCategoryList(true, true);
$path = $this->getDirectory($id);
}
} else {
// last panic resort which shouldn't happen
$path = 'cat'.$id;
}
if ($GLOBALS['config']->get('config', 'seo_cat_add_cats') == 0 && !$custom) {
// Get last part of path
$cat_parts = explode('/', $path);
$path = array_pop($cat_parts);
}
break;
case 'doc':
case 'document':
case 'viewdoc':
// check its not been made already
if (($existing = $GLOBALS['db']->select('CubeCart_seo_urls', 'path', array('type' => 'doc', 'item_id' => $id, 'redirect' => 0), false, 1, false, false)) !== false) {
$path = $existing[0]['path'];
} else {
$docs = $GLOBALS['db']->select('CubeCart_documents', array('doc_name'), array('doc_id' => $id));
$path = $docs[0]['doc_name'];
}
break;
case 'prod':
case 'product':
case 'viewprod':
// check its not been made already
if (($existing = $GLOBALS['db']->select('CubeCart_seo_urls', 'path', array('type' => 'prod', 'item_id' => $id, 'redirect' => 0), false, 1, false, false)) !== false) {
$path = $existing[0]['path'];
} elseif (($prods = $GLOBALS['db']->select('CubeCart_inventory', array('product_id', 'name', 'cat_id'), array('product_id' => (int)$id), false, 1)) !== false) {
if ($GLOBALS['config']->get('config', 'seo_add_cats')==0) {
$path = $prods[0]['name'];
} else {
$cat_directory = '';
if (($cats = $GLOBALS['db']->select('CubeCart_category_index', array('cat_id'), array('product_id' => (int)$id), array('primary' => 'DESC'), 1)) !== false) {
$prods[0]['cat_id'] = $cats[0]['cat_id'];
}
$cat_directory = $this->getDirectory($prods[0]['cat_id']);
if ($GLOBALS['config']->get('config', 'seo_add_cats')==1) {
// Get first part of path
$cat_parts = explode('/', $cat_directory);
$cat_directory = array_shift($cat_parts);
}
}
$path = empty($cat_directory) ? $prods[0]['name'] : $cat_directory.'/'.$prods[0]['name'];
}
break;
default:
$this->_url = 'index.php?_a=' . $type . '&' . $key . '=' . $id;
return $this->_url;
}
}
$path = SEO::_safeUrl($path);
// If path exists without .html but setting has .html enabled we mustn't add it!
return $existing ? $this->_getBaseUrl($absolute).$path : $this->_getBaseUrl($absolute).$this->_handleExtension($path);
}
/**
* Get SEO URLs from the DB
*
* @param string $type
* @param string $item_id
* @return string
*/
public function getdbPath($type, $item_id)
{
if (($item = $GLOBALS['db']->select('CubeCart_seo_urls', array('path'), array('type' => $type, 'item_id' => $item_id, 'redirect' => 0), false, 1, false, false)) !== false) {
return $item[0]['path'];
} else {
return '';
}
}
/**
* Create item URL
*
* @param string $path
* @param string $url
* @param bool $url
*/
public function getItem($path, $url = false)
{
if (isset($_GET['seo_path'])) {
unset($_GET['seo_path']);
}
if (!empty($path)) {
if (($item = $GLOBALS['db']->select('CubeCart_seo_urls', false, array('path' => $path), false, 1, false, false)) !== false) {
if(in_array($item[0]['redirect'],array('301','302'))) {
httpredir($GLOBALS['storeURL'].'/'.$this->getdbPath($item[0]['type'], $item[0]['item_id']), '', false, (int)$item[0]['redirect']);
}
$item_vars = $this->_getItemVars($item[0]['type'], $item[0]['item_id']);
foreach ($GLOBALS['hooks']->load('class.seo.getitem.parameters') as $hook) {
include $hook;
}
$_GET = (is_array($_GET)) ? array_merge($item_vars, $_GET) : $item_vars;
if ($url) {
return $GLOBALS['storeURL'].'/index.php?'.http_build_query($_GET);
} else {
return true;
}
} else {
$_GET['_a'] = '404';
}
} else {
httpredir('index.php');
}
}
/**
* Get items redirects
*
* @param string $type
* @param string $item_id
*/
public function getRedirects($type, $item_id)
{
if(ctype_digit($item_id) && !empty($type)) {
return $GLOBALS['db']->select('CubeCart_seo_urls', false, array('type'=> $type, 'item_id' => $item_id, 'redirect' => '>0'), false, 1, false, false);
}
return false;
}
/**
* Create meta description
*
* @param string $cat_id
* @param string $link
* @param string $glue
* @param string $append
* @param string $custom
*
* @return string
*/
public function getDirectory($cat_id, $link = false, $glue = '/', $append = false, $custom = true, &$noLoops = array())
{
if (is_numeric($cat_id)) {
if(!$this->_cat_dirs) {
$this->_getCategoryList(true, true);
}
$category = (isset($this->_cat_dirs[$cat_id])) ? $this->_cat_dirs[$cat_id] : false;
if (!empty($category)) {
// Prevent never-ending loops!
if (in_array($cat_id, $noLoops)) {
trigger_error('Cat Loop Detected! Cat Path: '.implode(' -> ', $noLoops).'.', E_USER_WARNING);
return false;
}
$noLoops[] = $cat_id;
if ($link) {
$this->_cat_path[] = '<a href="'.$GLOBALS['storeURL'].'/index.php?_a=category&cat_id='.(int)$category['cat_id'].'">'.$category['cat_name'].'</a>';
} else {
$this->_cat_path[] = (empty($category['path']) || empty($custom) ? $category['cat_name'] : $category['path']);
}
if (is_numeric($category['cat_parent_id']) && $category['cat_parent_id'] != 0) {
$this->_cat_path[] = $this->getDirectory($category['cat_parent_id'], $link, $glue, $append, $custom, $noLoops);
}
krsort($this->_cat_path);
if ($append) {
$this->_cat_path[] = $append;
}
$path = implode($glue, $this->_cat_path);
$this->_cat_path = null;
return $path;
}
}
return false;
}
/**
* Get the SEO extension
*
* @return string
*/
public function getExtension()
{
return $this->_extension;
}
/**
* Create meta description
*
* @param string $glue
* @return string
*/
public function meta_description()
{
if ($GLOBALS['config']->has('config', 'seo_metadata') && $GLOBALS['config']->get('config', 'seo_metadata') && !empty($this->_meta_data['description'])) {
switch ((int)$GLOBALS['config']->get('config', 'seo_metadata')) {
case self::TAGS_MERGE:
if ($GLOBALS['config']->get('config', 'store_meta_description') && $this->_meta_data['description']) {
$description[] = $this->_meta_data['description'];
$description[] = $GLOBALS['config']->get('config', 'store_meta_description');
} elseif ($this->_meta_data['description']) {
$description = $this->_meta_data['description'];
} else {
$description = $GLOBALS['config']->get('config', 'store_meta_description');
}
break;
case self::TAGS_REPLACE:
$description = $this->_meta_data['description'];
break;
}
return (is_array($description)) ? implode(' ', $description) : $description;
} else {
return $GLOBALS['config']->get('config', 'store_meta_description');
}
}
/**
* Make Meta title
*
* @param string $glue
* @return string
*/
public function meta_title($glue = ' - ')
{
// Return the title
if ($GLOBALS['config']->has('config', 'seo_metadata')) {
if (!empty($this->_meta_data['title'])) {
$title[1] = $this->_meta_data['title'];
}
}
if ((int)$GLOBALS['config']->get('config', 'seo_metadata')!==self::TAGS_DEFAULT && !isset($title[1]) && isset($this->_meta_data['name'])) {
$title[2] = $this->_meta_data['name'];
}
if ((int)$GLOBALS['config']->get('config', 'seo_metadata')!==self::TAGS_REPLACE && $GLOBALS['config']->get('config', 'store_title')!=='') {
$title[69] = $GLOBALS['config']->get('config', 'store_title');
}
if (isset($title) && is_array($title)) {
ksort($title);
return implode($glue, $title);
} else {
return false;
}
}
/**
* Parse query string
*
* @param string $query
* @return string
*/
public function queryString($query)
{
$query = trim($query);
if (!empty($query)) {
$question = true;
// Get any exists in variables
if (isset($this->_url) && !empty($this->_url)) {
//This is already being done else where
//parse_str(html_entity_decode($this->_url), $existing_vars);
if (strpos($this->_url, '?') !== false) {
$question = false;
}
}
// Get query string variables
parse_str(html_entity_decode($query), $vars);
//$vars = (isset($existing_vars) && is_array($existing_vars)) ? array_merge($existing_vars, $vars) : $vars;
foreach ($vars as $key => $var) {
if (substr($key, 0, 1) == '#') {
unset($vars[$key]);
}
}
// Get URL elements
if (!empty($vars)) {
if ($question) {
$append[] = '?'.http_build_query($vars);
} else {
$append[] = '&'.http_build_query($vars);
}
}
$fragment = parse_url($query, PHP_URL_FRAGMENT);
if (!empty($fragment)) {
$append[] = '#'. $fragment;
}
if (is_array($append)) {
return implode('', $append);
}
}
return $query;
}
/**
* Rebuild category listings
*/
public function rebuildCategoryList()
{
$this->_getCategoryList(true);
}
/**
* Rewrite URL
*
* @param string $html
* @param bool $html
* @return bool
*/
public function rewriteUrls($html, $absolute = false)
{
$this->_rewrite_url_absolute = $absolute;
$search = '#(href|action)=["\'](.*/)?[\w]+.[a-z]+\?_a\=([\w]+)\&(amp;)?([\w]+)\=([\w\-\_]+)([^"\']*)["\']#Si';
$rule1 = preg_replace_callback($search, array(&$this, '_callbackRule1'), $html);
$search = '#(href|src|background)=([\"\'])([^\"]*)([\"\'])#Sui';
return preg_replace_callback($search, array(&$this, '_callbackRule2'), $rule1);
}
/**
* Generate a safe SEO URL
*
* @param string $path
* @return string
*/
public static function sanitizeSEOPath($path)
{
return SEO::_safeUrl($path);
}
/**
* Can we use SEO?
*
* @param string $path
* @return bool/string
*/
public function SEOable($path)
{
$path = preg_replace('@index.php$@', '', $path); // remove index.php if last chars in URL
$seo_ext = $GLOBALS['config']->get('config', 'seo_ext');
if (strpos($path, 'index.php?_a=category&search') !== false) {
$path = str_replace('index.php?', 'search'.$seo_ext.'?', $path);
return $path;
} elseif (($pos = strpos($path, 'index.php?_a=search')) !== false) {
if (strlen($path) == $pos + 19) {
$path = str_replace('index.php?_a=search', 'search'.$seo_ext, $path);
} else {
$path = str_replace('index.php?_a=search&', 'search'.$seo_ext.'?', $path);
}
return $path;
}
if (preg_match('#^(.*/)?[\w]+.[a-z]+\?_a\=([\w]+)(?:\&(amp;)?([\w\[\]]+)\=([\w\-\_]+)([^"\']*))$#iS', $path, $match)) {
if (in_array($match[2], $this->_static_sections)) {
if (!empty($match[4]) && !empty($match[5])) {
$match[6] = $match[6].'&'.$match[4].'='.$match[5];
}
}
return $this->generatePath($match[5], $match[2], $match[4], true).$this->queryString($match[6]);
} else {
return $path;
}
}
/**
* Set a DB path
*
* @param string $type
* @param int $item_id
* @param string $path
* @param bool $bool
* @param bool $show_error
* @return bool/string
*/
public function setdbPath($type, $item_id, $path, $bool = true, $show_error = true, $status_code = 0)
{
// Check dynamic $type has an valid $item_id
if(in_array($type, $this->_dynamic_sections) && (int)$item_id <= 0) {
return false;
}
if (!empty($path)) {
$path = SEO::_safeUrl($path);
}
if($status_code!==0) {
if($GLOBALS['db']->count('CubeCart_seo_urls', 'id', "`path` = '$path'") > 0) {
return false;
} else {
return $GLOBALS['db']->insert('CubeCart_seo_urls', array('type' => $type, 'item_id' => $item_id, 'path' => $this->_handleExtension($path), 'custom' => 1, 'redirect' => $status_code));
}
} elseif (in_array($type, array_merge($this->_dynamic_sections, $this->_static_sections))) {
$custom = 1;
// if path is empty or already taken generate one
if (empty($path) || $GLOBALS['db']->count('CubeCart_seo_urls', 'id', "`path` = '$path' AND `type` = '$type' AND `item_id` <> $item_id") > 0) {
// send warning if in use
if (!empty($path)) {
if ($show_error) {
$GLOBALS['gui']->setError($GLOBALS['language']->settings['seo_path_taken'], true);
}
}
// try to generate
$path = $this->generatePath($item_id, $type, null, false);
$custom = 0;
}
if (empty($path)) {
return ($bool) ? false : '';
}
$existing = $GLOBALS['db']->select('CubeCart_seo_urls', array('id', 'path'), array('type' => $type, 'item_id' => $item_id), false, 1, false, false);
if ($existing) {
$match = false;
$path = $this->_handleExtension($path);
if($path !== $this->_extension) {
foreach($existing as $e) {
if($e['path']==$path) {
$match = true;
$GLOBALS['db']->update('CubeCart_seo_urls', array('redirect' => 0), array('id' => $e['id']));
} else {
$GLOBALS['db']->update('CubeCart_seo_urls', array('redirect' => 301), array('id' => $e['id']));
}
}
if(!$match) {
$GLOBALS['db']->insert('CubeCart_seo_urls', array('redirect' => 0, 'type' => $type, 'item_id' => $item_id, 'path' => $path, 'custom' => $custom));
}
}
} else {
// Check for duplicate path
if (!$GLOBALS['db']->select('CubeCart_seo_urls', false, array('path' => $path), false, 1, false, false)) {
$GLOBALS['db']->insert('CubeCart_seo_urls', array('type' => $type, 'item_id' => $item_id, 'path' => $this->_handleExtension($path), 'custom' => $custom));
if(empty($this->_extension) && in_array($type, $this->_static_sections)) { // Backward compatibility
$GLOBALS['db']->insert('CubeCart_seo_urls', array('type' => $type, 'item_id' => $item_id, 'path' => $this->_handleExtension($path).'.html', 'redirect' => 301));
}
} else {
// Force unique path is it's already taken
$unique_id = substr($type, 0, 1).$item_id;
$GLOBALS['db']->insert('CubeCart_seo_urls', array('type' => $type, 'item_id' => $item_id, 'path' => $this->_handleExtension($path, '-'.$unique_id), 'custom' => $custom));
$GLOBALS['gui']->setError($GLOBALS['language']->settings['seo_path_taken'], true);
}
}
return $bool ? true : $path;
} else {
trigger_error('Invalid SEO path type '.$type.'.', E_USER_NOTICE);
return false;
}
}
/**
* Set all metadata
*
* @param array $meta_data
* @return bool
*/
public function set_meta_data($meta_data)
{
if (!empty($meta_data) && is_array($meta_data)) {
$default = array('name' => '', 'path' => '', 'title' => '', 'description' => '');
$meta_data = array_merge($default, $this->_meta_data, $meta_data);
foreach ($meta_data as $key => $value) {
$this->_meta_data[$key] = $value;
}
return true;
}
return false;
}
/**
* Create sitemap
*
* @return bool
*/
public function sitemap()
{
// Generate a Sitemap Protocol v0.9 compliant sitemap (http://sitemaps.org)
$this->_sitemap_xml = new XML();
$this->_sitemap_xml->startElement('urlset', array('xmlns' => 'http://www.sitemaps.org/schemas/sitemap/0.9'));
$this->_sitemap_link(array('url' => $this->_sitemap_base_url.'/index.php'));
# Sale Items
if ($GLOBALS['config']->get('config', 'catalogue_sale_mode')!=='0' && $GLOBALS['config']->get('config', 'catalogue_sale_mode')!=='2') {
$this->_sitemap_link(array('url' => $this->_sitemap_base_url.'/index.php?_a=saleitems'));
}
# Gift Certificates
if ($GLOBALS['config']->get('gift_certs', 'status')=='1') {
$this->_sitemap_link(array('url' => $this->_sitemap_base_url.'/index.php?_a=certificates'));
}
$queryArray = array(
'category' => $GLOBALS['db']->select('CubeCart_category', array('cat_id'), array('status' => '1')),
'product' => $GLOBALS['db']->select('CubeCart_inventory', array('product_id', 'updated'), array('status' => '1')),
'document' => $GLOBALS['db']->select('CubeCart_documents', array('doc_id'), array('doc_parent_id' => '0', 'doc_status' => 1)),
);
foreach ($queryArray as $type => $results) {
if ($results) {
foreach ($results as $record) {
switch ($type) {
case 'category':
$id = $record['cat_id'];
$key = 'cat_id';
break;
case 'product':
$id = $record['product_id'];
$key = 'product_id';
break;
case 'document':
$id = $record['doc_id'];
$key = 'doc_id';
break;
}
$this->_sitemap_link(array('key' => $key, 'id' => $id), $record['updated'], $type);
}
}
}
foreach ($GLOBALS['hooks']->load('class.seo.sitemap') as $hook) {
include $hook;
}
$sitemap = $this->_sitemap_xml->getDocument(true);
if (function_exists('gzencode')) {
// Compress the file if GZip is enabled
$filename = CC_ROOT_DIR.'/sitemap.xml.gz';
$mapdata = gzencode($sitemap, 9, FORCE_GZIP);
if (file_exists(CC_ROOT_DIR.'/sitemap.xml')) {
unlink(CC_ROOT_DIR.'/sitemap.xml');
}
} else {
$filename = CC_ROOT_DIR.'/sitemap.xml';
$mapdata = $sitemap;
if (file_exists(CC_ROOT_DIR.'/sitemap.xml.gz')) {
unlink(CC_ROOT_DIR.'/sitemap.xml.gz');
}
}
if (file_put_contents($filename, $mapdata)) {
if ($GLOBALS['config']->get('config', 'offline')=='0') {
// Ping Google
$request = new Request('www.google.com', '/webmasters/sitemaps/ping');
$request->setMethod('get');
$request->setData(array('sitemap' => $this->_sitemap_base_url.'/'.basename($filename)));
$request->send();
}
return true;
}
return false;
}
/**
* Unset a DB path
*
* @param string $type
* @param int $item_id
* @return bool
*/
public function unsetdbPath($type, $item_id)
{
return $GLOBALS['db']->update('CubeCart_seo_urls', array('redirect' => 301), array('type' => $type, 'item_id' => $item_id, 'redirect' => 0));
}
//=====[ Private ]=======================================
/**
* Get SEO path from standard one
*
* @return string
*/
private function _callbackRule1($matches)
{
$base_path = $this->_getBaseUrl($this->_rewrite_url_absolute);
return $matches[1].'="'.$base_path.$this->generatePath($matches[6], $matches[3], $matches[5]).$this->queryString($matches[7]).'"';
}
/**
* Add base path onto SEO path
*
* @return string
*/
private function _callbackRule2($matches)
{
return $matches[1].'='.$matches[2].$this->fullURL($matches[3], $this->_rewrite_url_absolute).$matches[4];
}
/**
* Create .htaccess exists and write if not
*
* @return bool
*/
private static function _checkModRewrite()
{
$cache_id = 'seo_check';
if (!isset($GLOBALS['cache']) || !is_object($GLOBALS['cache']) || $GLOBALS['cache']->read($cache_id)) {
return false;
} else {
$htaccess_path = CC_ROOT_DIR.'/.htaccess';
$htaccess_content = '##### START CubeCart .htaccess #####
### GZIP Compression ###
<ifmodule mod_deflate.c>
AddOutputFilterByType DEFLATE text/text text/html text/plain text/xml text/css application/x-javascript application/javascript
</ifmodule>
### Files Expiration ###
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType text/html "access 0 seconds"
ExpiresDefault "access 7 days"
</IfModule>
### File Security ###
<FilesMatch "\.(htaccess)$">
Order Allow,Deny
Deny from all
</FilesMatch>
### Apache directory listing rules ###
DirectoryIndex index.php index.htm index.html
IndexIgnore *
<ifModule mod_headers.c>
Header always append X-Frame-Options SAMEORIGIN
</ifModule>
### Rewrite rules for SEO functionality ###
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase '.CC_ROOT_REL.'
##### START v4 SEO URL BACKWARD COMPATIBILITY #####
RewriteCond %{QUERY_STRING} (.*)$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule cat_([0-9]+)(\.[a-z]{3,4})?(.*)$ index.php?_a=category&cat_id=$1&%1 [NC]
RewriteCond %{QUERY_STRING} (.*)$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule prod_([0-9]+)(\.[a-z]{3,4})?$ index.php?_a=product&product_id=$1&%1 [NC]
RewriteCond %{QUERY_STRING} (.*)$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule info_([0-9]+)(\.[a-z]{3,4})?$ index.php?_a=document&doc_id=$1&%1 [NC]
RewriteCond %{QUERY_STRING} (.*)$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule tell_([0-9]+)(\.[a-z]{3,4})?$ index.php?_a=product&product_id=$1&%1 [NC]
RewriteCond %{QUERY_STRING} (.*)$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule _saleItems(\.[a-z]+)?(\?.*)?$ index.php?_a=saleitems&%1 [NC,L]
##### END v4 SEO URL BACKWARD COMPATIBILITY #####
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !='.CC_ROOT_REL.'favicon.ico
RewriteRule ^(.*)?$ index.php?seo_path=$1 [L,QSA]
</IfModule>
### Default store 404 page ###
ErrorDocument 404 '.CC_ROOT_REL.'index.php
## Override default 404 error document for missing page resources ##
<FilesMatch "\.(gif|jpe?g|png|ico|css|js|svg|webp)$">
ErrorDocument 404 "<html></html>
</FilesMatch>
##### END CubeCart .htaccess #####';
if (!file_exists($htaccess_path)) {
if (!file_put_contents($htaccess_path, $htaccess_content)) {
die('<p>Failed to create .htaccess file for Search Engine Friendly URL\'s. Please create this file in the stores root directory with the following content.</p><textarea style="width: 400px; height: 300px;" readonly>'.$htaccess_content.'</textarea>');
}
$GLOBALS['cache']->write('1', $cache_id);
httpredir();
} else {
$current_contents = file_get_contents($htaccess_path);
if (!strstr($current_contents, 'seo_path')) {
$htaccess_content = $current_contents."\r\n\r\n".$htaccess_content;
if (!file_put_contents($htaccess_path, $htaccess_content)) {
die('<p>Failed to update existing .htaccess file for Search Engine Friendly URL\'s. Please edit this file in the stores root directory with the following content.</p><textarea style="width: 400px; height: 300px;" readonly>'.$htaccess_content.'</textarea>');
}
$GLOBALS['cache']->write('1', $cache_id);
httpredir();
}
}
}
}
/**
* Get the base url
*
* @param bool $full_urls
* @return string
*/
private function _getBaseUrl($full_urls = false)
{