/
oxutils.php
1491 lines (1324 loc) · 45.4 KB
/
oxutils.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
/**
* This file is part of OXID eShop Community Edition.
*
* OXID eShop Community Edition is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* OXID eShop Community Edition is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OXID eShop Community Edition. If not, see <http://www.gnu.org/licenses/>.
*
* @link http://www.oxid-esales.com
* @copyright (C) OXID eSales AG 2003-2014
* @version OXID eShop CE
*/
/**
* Includes Smarty engine class.
*/
require_once getShopBasePath()."core/smarty/Smarty.class.php";
/**
* General utils class
*
*/
class oxUtils extends oxSuperCfg
{
/**
* Cached currency precision
*
* @var int
*/
protected $_iCurPrecision = null;
/**
* Some files, like object structure should not be deleted, because they are changed rarely
* and each regeneration eats additional page load time. This array keeps patterns of file
* names which should not be deleted on regular cache cleanup
*
* @var string
*/
protected $_sPermanentCachePattern = "/c_fieldnames_|c_tbdsc_|_allfields_/";
/**
* Pattern used to filter needed to remove language cache files.
*
* @var string
*/
protected $_sLanguageCachePattern = "/c_langcache_/i";
/**
* Pattern used to filter needed to remove admin menu cache files.
*
* @var string
*/
protected $_sMenuCachePattern = "/c_menu_/i";
/**
* File cache contents.
*
* @var array
*/
protected $_aLockedFileHandles = array();
/**
* Local cache
*
* @var array
*/
protected $_aFileCacheContents = array();
/**
* Search engine indicator
*
* @var bool
*/
protected $_blIsSe = null;
/**
* Return a single instance of this class
*
* @deprecated since v5.0 (2012-08-10); Use oxRegistry::getUtils() instead.
*
* @return oxUtils
*/
public static function getInstance()
{
return oxRegistry::getUtils();
}
/**
* Statically cached data
*
* @var array
*/
protected $_aStaticCache;
/**
* Seo mode marker - SEO is active or not
*
* @var bool
*/
protected $_blSeoIsActive = null;
/**
* Strips magic quotes
*
* @return null
*/
public function stripGpcMagicQuotes()
{
if (!get_magic_quotes_gpc()) {
return;
}
$_REQUEST = self::_stripQuotes($_REQUEST);
$_POST = self::_stripQuotes($_POST);
$_GET = self::_stripQuotes($_GET);
$_COOKIE = self::_stripQuotes($_COOKIE);
}
/**
* OXID specific string manipulation method
*
* @param string $sVal string
* @param string $sKey key
*
* @return string
*/
public function strMan( $sVal, $sKey = null )
{
$sKey = $sKey ? $sKey : $this->getConfig()->getConfigParam('sConfigKey');
$sVal = "ox{$sVal}id";
$sKey = str_repeat( $sKey, strlen( $sVal ) / strlen( $sKey ) + 5 );
$sVal = $this->strRot13( $sVal );
$sVal = $sVal ^ $sKey;
$sVal = base64_encode ( $sVal );
$sVal = str_replace( "=", "!", $sVal );
return "ox_$sVal";
}
/**
* OXID specific string manipulation method
*
* @param string $sVal string
* @param string $sKey key
*
* @return string
*/
public function strRem( $sVal, $sKey = null )
{
$sKey = $sKey ? $sKey : $this->getConfig()->getConfigParam('sConfigKey');
$sKey = str_repeat( $sKey, strlen( $sVal ) / strlen( $sKey ) + 5 );
$sVal = substr( $sVal, 3 );
$sVal = str_replace( '!', '=', $sVal );
$sVal = base64_decode( $sVal );
$sVal = $sVal ^ $sKey;
$sVal = $this->strRot13( $sVal );
return substr( $sVal, 2, -2 );
}
/**
* Returns string witch "." symbols were replaced with "__".
*
* @param string $sName String to search replaceable char
*
* @return string
*/
public function getArrFldName( $sName )
{
return str_replace( ".", "__", $sName);
}
/**
* Takes a string and assign all values, returns array with values.
*
* @param string $sIn Initial string
* @param float $dVat Article VAT (optional)
*
* @return array
*/
public function assignValuesFromText( $sIn, $dVat = null )
{
$aRet = array();
$aPieces = explode( '@@', $sIn );
while ( list( $sKey, $sVal ) = each( $aPieces ) ) {
if ( $sVal ) {
$aName = explode( '__', $sVal );
if ( isset( $aName[0] ) && isset( $aName[1] ) ) {
$aRet[] = $this->_fillExplodeArray( $aName, $dVat );
}
}
}
return $aRet;
}
/**
* Takes an array and builds again a string. Returns string with values.
*
* @param array $aIn Initial array of strings
*
* @return string
*/
public function assignValuesToText( $aIn)
{
$sRet = "";
reset( $aIn );
while (list($sKey, $sVal) = each($aIn)) {
$sRet .= $sKey;
$sRet .= "__";
$sRet .= $sVal;
$sRet .= "@@";
}
return $sRet;
}
/**
* Returns formatted currency string, according to formatting standards.
*
* @param string $sValue Formatted price
*
* @return float
*/
public function currency2Float( $sValue)
{
$fRet = $sValue;
$iPos = strrpos( $sValue, ".");
if ($iPos && ((strlen($sValue)-1-$iPos) < 2+1)) {
// replace decimal with ","
$fRet = substr_replace( $fRet, ",", $iPos, 1);
}
// remove thousands
$fRet = str_replace( array(" ","."), "", $fRet);
$fRet = str_replace( ",", ".", $fRet);
return (float) $fRet;
}
/**
* Returns formatted float, according to formatting standards.
*
* @param string $sValue Formatted price
*
* @return float
*/
public function string2Float( $sValue)
{
$fRet = str_replace( " ", "", $sValue);
$iCommaPos = strpos( $fRet, ",");
$iDotPos = strpos( $fRet, ".");
if (!$iDotPos xor !$iCommaPos) {
if (substr_count( $fRet, ",") > 1 || substr_count( $fRet, ".") > 1) {
$fRet = str_replace( array(",","."), "", $fRet);
} else {
$fRet = str_replace( ",", ".", $fRet);
}
} else if ( $iDotPos < $iCommaPos ) {
$fRet = str_replace( ".", "", $fRet);
$fRet = str_replace( ",", ".", $fRet);
}
// remove thousands
$fRet = str_replace( array(" ",","), "", $fRet);
return (float) $fRet;
}
/**
* Checks if current web client is Search Engine. Returns true on success.
*
* @param string $sClient user browser agent
*
* @return bool
*/
public function isSearchEngine( $sClient = null )
{
if (is_null($this->_blIsSe)) {
$this->setSearchEngine( null, $sClient );
}
return $this->_blIsSe;
}
/**
* Sets if current web client is Search Engine.
*
* @param bool $blIsSe sets if Search Engine is on
* @param string $sClient user browser agent
*
* @return null
*/
public function setSearchEngine( $blIsSe = null, $sClient = null )
{
if (isset($blIsSe)) {
$this->_blIsSe = $blIsSe;
return;
}
startProfile("isSearchEngine");
$myConfig = $this->getConfig();
$blIsSe = false;
if ( !( $myConfig->getConfigParam( 'iDebug' ) && $this->isAdmin() ) ) {
$aRobots = $myConfig->getConfigParam( 'aRobots' );
$aRobots = is_array( $aRobots )?$aRobots:array();
$aRobotsExcept = $myConfig->getConfigParam( 'aRobotsExcept' );
$aRobotsExcept = is_array( $aRobotsExcept )?$aRobotsExcept:array();
$sClient = $sClient?$sClient:strtolower( getenv( 'HTTP_USER_AGENT' ) );
$blIsSe = false;
$aRobots = array_merge( $aRobots, $aRobotsExcept );
foreach ( $aRobots as $sRobot ) {
if ( strpos( $sClient, $sRobot ) !== false ) {
$blIsSe = true;
break;
}
}
}
$this->_blIsSe = $blIsSe;
stopProfile("isSearchEngine");
}
/**
* User email validation function. Returns true if email is OK otherwise - false;
* Syntax validation is performed only.
*
* @param string $sEmail user email
*
* @return bool
*/
public function isValidEmail( $sEmail )
{
$blValid = true;
if ( $sEmail != 'admin' ) {
$sEmailTpl = "/^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/i";
$blValid = ( getStr()->preg_match( $sEmailTpl, $sEmail ) != 0 );
}
return $blValid;
}
/**
* Parses profile configuration, loads stored info in cookie
*
* @param array $aInterfaceProfiles ($myConfig->getConfigParam( 'aInterfaceProfiles' ))
*
* @return null
*/
public function loadAdminProfile($aInterfaceProfiles)
{
// improved #533
// checking for available profiles list
if ( is_array( $aInterfaceProfiles ) ) {
//checking for previous profiles
$sPrevProfile = oxRegistry::get("oxUtilsServer")->getOxCookie('oxidadminprofile');
if (isset($sPrevProfile)) {
$aPrevProfile = @explode("@", trim($sPrevProfile));
}
//array to store profiles
$aProfiles = array();
foreach ( $aInterfaceProfiles as $iPos => $sProfile) {
$aProfileSettings = array($iPos, $sProfile);
$aProfiles[] = $aProfileSettings;
}
// setting previous used profile as active
if (isset($aPrevProfile[0]) && isset($aProfiles[$aPrevProfile[0]])) {
$aProfiles[$aPrevProfile[0]][2] = 1;
}
oxSession::setVar("aAdminProfiles", $aProfiles);
return $aProfiles;
}
return null;
}
/**
* Rounds the value to currency cents. This method does NOT format the number.
*
* @param string $sVal the value that should be rounded
* @param object $oCur Currency Object
*
* @return float
*/
public function fRound($sVal, $oCur = null)
{
startProfile('fround');
//cached currency precision, this saves about 1% of execution time
$iCurPrecision = null;
if (! defined('OXID_PHP_UNIT')) {
$iCurPrecision = $this->_iCurPrecision;
}
if (is_null($iCurPrecision)) {
if ( !$oCur ) {
$oCur = $this->getConfig()->getActShopCurrencyObject();
}
$iCurPrecision = $oCur->decimal;
$this->_iCurPrecision = $iCurPrecision;
}
// if < 5.3.x this is a workaround for #36008 bug in php - incorrect round() & number_format() result (R)
static $dprez = null;
if (!$dprez) {
$prez = @ini_get("precision");
if (!$prez || $prez > 12 ) {
$prez = 12;
}
$dprez = pow(10, -$prez);
}
stopProfile('fround');
return round($sVal + $dprez * ( $sVal >= 0 ? 1 : -1 ), $iCurPrecision);
}
/**
* Stores something into static cache to avoid double loading
*
* @param string $sName name of the content
* @param mixed $sContent the content
* @param string $sKey optional key, where to store the content
*
* @return null
*/
public function toStaticCache( $sName, $sContent, $sKey = null )
{
// if it's an array then we add
if ( $sKey ) {
$this->_aStaticCache[$sName][$sKey] = $sContent;
} else {
$this->_aStaticCache[$sName] = $sContent;
}
}
/**
* Retrieves something from static cache
*
* @param string $sName name under which the content is stored in the static cache
*
* @return mixed
*/
public function fromStaticCache( $sName)
{
if ( isset( $this->_aStaticCache[$sName])) {
return $this->_aStaticCache[$sName];
}
return null;
}
/**
* Cleans all or specific data from static cache
*
* @param string $sCacheName Cache name
*
* @return null
*/
public function cleanStaticCache($sCacheName = null)
{
if ($sCacheName) {
unset($this->_aStaticCache[$sCacheName]);
} else {
$this->_aStaticCache = null;
}
}
/**
* Generates php file, which could later be loaded as include instead of parsed data.
* Currently this method supports simple arrays only.
*
* @param string $sKey Cache key
* @param mixed $mContents Cache contents. At this moment only simple array type is supported.
*
* @return null;
*/
public function toPhpFileCache( $sKey, $mContents )
{
//only simple arrays are supported
if ( is_array( $mContents ) && ( $sCachePath = $this->getCacheFilePath( $sKey, false, 'php' ) ) ) {
// setting meta
$this->setCacheMeta( $sKey, array( "serialize" => false, "cachepath" => $sCachePath ) );
// caching..
$this->toFileCache( $sKey, $mContents );
}
}
/**
* Includes cached php file and loads stored contents.
*
* @param string $sKey Cache key.
*
* @return null;
*/
public function fromPhpFileCache( $sKey )
{
// setting meta
$this->setCacheMeta( $sKey, array( "include" => true, "cachepath" => $this->getCacheFilePath( $sKey, false, 'php' ) ) );
return $this->fromFileCache( $sKey );
}
/**
* If available returns cache meta data array
*
* @param string $sKey meta data/cache key
*
* @return mixed
*/
public function getCacheMeta( $sKey )
{
return isset( $this->_aFileCacheMeta[$sKey] ) ? $this->_aFileCacheMeta[$sKey] : false;
}
/**
* Saves cache meta data (information)
*
* @param string $sKey meta data/cache key
* @param array $aMeta meta data array
*
* @return null
*/
public function setCacheMeta( $sKey, $aMeta )
{
// cache meta data
$this->_aFileCacheMeta[$sKey] = $aMeta;
}
/**
* Adds contents to cache contents by given key. Returns true on success.
* All file caches are supposed to be written once by commitFileCache() method.
*
* @param string $sKey Cache key
* @param mixed $mContents Contents to cache
* @param int $iTtl Time to live in seconds (0 for forever).
*
* @return bool
*/
public function toFileCache( $sKey, $mContents, $iTtl = 0 )
{
$aCacheData['content'] = $mContents;
$aMeta = $this->getCacheMeta( $sKey );
if ( $iTtl ) {
$aCacheData['ttl'] = $iTtl;
$aCacheData['timestamp'] = oxRegistry::get("oxUtilsDate")->getTime();
}
$this->_aFileCacheContents[$sKey] = $aCacheData;
// looking for cache meta
$sCachePath = isset( $aMeta["cachepath"] ) ? $aMeta["cachepath"] : $this->getCacheFilePath( $sKey );
return ( bool ) $this->_lockFile( $sCachePath, $sKey );
}
/**
* Fetches contents from file cache.
*
* @param string $sKey Cache key
*
* @return mixed
*/
public function fromFileCache( $sKey )
{
if ( !array_key_exists( $sKey, $this->_aFileCacheContents ) ) {
$sRes = null;
$aMeta = $this->getCacheMeta( $sKey );
$blInclude = isset( $aMeta["include"] ) ? $aMeta["include"] : false;
$sCachePath = isset( $aMeta["cachepath"] ) ? $aMeta["cachepath"] : $this->getCacheFilePath( $sKey );
// trying to lock
$this->_lockFile( $sCachePath, $sKey, LOCK_SH );
clearstatcache();
if ( is_readable( $sCachePath ) ) {
$sRes = $blInclude ? $this->_includeFile( $sCachePath ) : $this->_readFile( $sCachePath );
}
if ( isset( $sRes['ttl'] ) && $sRes['ttl'] != 0 ) {
$iTimestamp = $sRes['timestamp'];
$iTtl = $sRes['ttl'];
$iTime = oxRegistry::get("oxUtilsDate")->getTime();
if ( $iTime > $iTimestamp + $iTtl ) {
return null;
}
}
// release lock
$this->_releaseFile( $sKey, LOCK_SH );
// caching
$this->_aFileCacheContents[$sKey] = $sRes;
}
return $this->_aFileCacheContents[$sKey]['content'];
}
/**
* Reads and returns cache file contents
*
* @param string $sFilePath cache fiel path
*
* @return string
*/
protected function _readFile( $sFilePath )
{
$sRes = file_get_contents( $sFilePath );
return $sRes ? unserialize( $sRes ) : null;
}
/**
* Includes cache file
*
* @param string $sFilePath cache file path
*
* @return mixed
*/
protected function _includeFile( $sFilePath )
{
$_aCacheContents = null;
include $sFilePath;
return $_aCacheContents;
}
/**
* Serializes or writes php array for class file cache
*
* @param string $sKey cache key
* @param mixed $mContents cache data
*
* @return mixed
*/
protected function _processCache( $sKey, $mContents )
{
// looking for cache meta
$aCacheMeta = $this->getCacheMeta( $sKey );
$blSerialize = isset( $aCacheMeta["serialize"] ) ? $aCacheMeta["serialize"] : true;
if ( $blSerialize ) {
$mContents = serialize( $mContents );
} else {
$mContents = "<?php\n//automatically generated file\n//" . date( "Y-m-d H:i:s" ) . "\n\n\$_aCacheContents = " . var_export( $mContents, true ) . "\n?>";
}
return $mContents;
}
/**
* Writes all cache contents to file at once. This method was introduced due to possible
* race conditions. Cache is cleaned up after commit
*
* @return null;
*/
public function commitFileCache()
{
if ( count( $this->_aLockedFileHandles[LOCK_EX] ) ) {
startProfile("!__SAVING CACHE__! (warning)");
foreach ( $this->_aLockedFileHandles[LOCK_EX] as $sKey => $rHandle ) {
if ( $rHandle !== false && isset( $this->_aFileCacheContents[$sKey] ) ) {
// #0002931A truncate file once more before writing
ftruncate( $rHandle, 0 );
// writing cache
fwrite( $rHandle, $this->_processCache( $sKey, $this->_aFileCacheContents[$sKey] ) );
// releasing locks
$this->_releaseFile( $sKey );
}
}
stopProfile("!__SAVING CACHE__! (warning)");
//empty buffer
$this->_aFileCacheContents = array();
}
}
/**
* Locks cache file and returns its handle on success or false on failure
*
* @param string $sFilePath name of file to lock
* @param string $sIdent lock identifier
* @param int $iLockMode lock mode - LOCK_EX/LOCK_SH
*
* @return mixed lock file resource or false on error
*/
protected function _lockFile( $sFilePath, $sIdent, $iLockMode = LOCK_EX )
{
$rHandle = isset( $this->_aLockedFileHandles[$iLockMode][$sIdent] ) ? $this->_aLockedFileHandles[$iLockMode][$sIdent] : null;
if ( $rHandle === null ) {
$blLocked = false;
$rHandle = @fopen( $sFilePath, "a+" );
if ( $rHandle !== false ) {
if ( flock( $rHandle, $iLockMode | LOCK_NB ) ) {
if ( $iLockMode === LOCK_EX ) {
// truncate file
$blLocked = ftruncate( $rHandle, 0 );
} else {
// move to a start position
$blLocked = fseek( $rHandle, 0 ) === 0;
}
}
// on failure - closing and setting false..
if ( !$blLocked ) {
fclose( $rHandle );
$rHandle = false;
}
}
// in case system does not support file locking
if ( !$blLocked && $iLockMode === LOCK_EX ) {
// clearing on first call
if ( count( $this->_aLockedFileHandles ) == 0 ) {
clearstatcache();
}
// start a blank file to inform other processes we are dealing with it.
if (!( file_exists( $sFilePath ) && !filesize( $sFilePath ) && abs( time() - filectime( $sFilePath ) < 40 ) ) ) {
$rHandle = @fopen( $sFilePath, "w" );
}
}
$this->_aLockedFileHandles[$iLockMode][$sIdent] = $rHandle;
}
return $rHandle;
}
/**
* Releases file lock and returns release state
*
* @param string $sIdent lock ident
* @param int $iLockMode lock mode
*
* @return bool
*/
protected function _releaseFile( $sIdent, $iLockMode = LOCK_EX )
{
$blSuccess = true;
if ( isset( $this->_aLockedFileHandles[$iLockMode][$sIdent] ) &&
$this->_aLockedFileHandles[$iLockMode][$sIdent] !== false ) {
// release the lock and close file
$blSuccess = flock( $this->_aLockedFileHandles[$iLockMode][$sIdent], LOCK_UN ) &&
fclose( $this->_aLockedFileHandles[$iLockMode][$sIdent] );
unset( $this->_aLockedFileHandles[$iLockMode][$sIdent] );
}
return $blSuccess;
}
/**
* Removes most files stored in cache (default 'tmp') folder. Some files
* e.g. table files names description, are left. Excluded cache file name
* patterns are defined in oxUtils::_sPermanentCachePattern parameter
*
* @return null
*/
public function oxResetFileCache()
{
$aFiles = glob( $this->getCacheFilePath( null, true ) . '*' );
if ( is_array( $aFiles ) ) {
// delete all the files, except cached tables field names
$aFiles = preg_grep( $this->_sPermanentCachePattern, $aFiles, PREG_GREP_INVERT );
foreach ( $aFiles as $sFile ) {
@unlink( $sFile );
}
}
}
/**
* Removes smarty template cache for given templates
*
* @param array $aTemplates Template name array
*
* @return null
*/
public function resetTemplateCache($aTemplates)
{
$sSmartyDir = oxRegistry::get("oxUtilsView")->getSmartyDir();
//$aFiles = glob( $this->getCacheFilePath( null, true ) . '*' );
$aFiles = glob( $sSmartyDir . '*' );
if ( is_array( $aFiles ) && is_array( $aTemplates ) && count($aTemplates) ) {
// delete all template cache files
foreach ($aTemplates as &$sTemplate) {
$sTemplate = preg_quote(basename(strtolower($sTemplate), '.tpl'));
}
$sPattern = sprintf("/%%(%s)\.tpl\.php$/i", implode('|', $aTemplates));
$aFiles = preg_grep( $sPattern, $aFiles );
if (is_array( $aFiles ) ) {
foreach ( $aFiles as $sFile ) {
@unlink( $sFile );
}
}
}
}
/**
* Removes language constant cache
*
* @return null
*/
public function resetLanguageCache()
{
$aFiles = glob( $this->getCacheFilePath( null, true ) . '*' );
if ( is_array( $aFiles ) ) {
// delete all language cache files
$sPattern = $this->_sLanguageCachePattern;
$aFiles = preg_grep( $sPattern, $aFiles );
foreach ( $aFiles as $sFile ) {
@unlink( $sFile );
}
}
}
/**
* Removes admin menu cache
*
* @return null
*/
public function resetMenuCache()
{
$aFiles = glob( $this->getCacheFilePath( null, true ) . '*' );
if ( is_array( $aFiles ) ) {
// delete all menu cache files
$sPattern = $this->_sMenuCachePattern;
$aFiles = preg_grep( $sPattern, $aFiles );
foreach ( $aFiles as $sFile ) {
@unlink( $sFile );
}
}
}
/**
* If $sLocal file is older than 24h or does not exist, tries to
* download it from $sRemote and save it as $sLocal
*
* @param string $sRemote the file
* @param string $sLocal the address of the remote source
*
* @return mixed
*/
public function getRemoteCachePath($sRemote, $sLocal)
{
clearstatcache();
if ( file_exists( $sLocal ) && filemtime( $sLocal ) && filemtime( $sLocal ) > time() - 86400 ) {
return $sLocal;
}
$hRemote = @fopen( $sRemote, "rb");
$blSuccess = false;
if ( isset( $hRemote) && $hRemote ) {
$hLocal = fopen( $sLocal, "wb");
stream_copy_to_stream($hRemote, $hLocal);
fclose($hRemote);
fclose($hLocal);
$blSuccess = true;
} else {
// try via fsockopen
$aUrl = @parse_url( $sRemote);
if ( !empty( $aUrl["host"])) {
$sPath = $aUrl["path"];
if ( empty( $sPath ) ) {
$sPath = "/";
}
$sHost = $aUrl["host"];
$hSocket = @fsockopen( $sHost, 80, $iErrorNumber, $iErrStr, 5);
if ( $hSocket) {
fputs( $hSocket, "GET ".$sPath." HTTP/1.0\r\nHost: $sHost\r\n\r\n");
$headers = stream_get_line($hSocket, 4096, "\r\n\r\n");
if ( ( $hLocal = @fopen( $sLocal, "wb") ) !== false ) {
rewind($hLocal);
// does not copy all the data
// stream_copy_to_stream($hSocket, $hLocal);
fwrite ( $hLocal, stream_get_contents( $hSocket ) );
fclose( $hLocal );
fclose( $hSocket );
$blSuccess = true;
}
}
}
}
if ( $blSuccess || file_exists( $sLocal ) ) {
return $sLocal;
}
return false;
}
/**
* Checks if preview mode is ON
*
* @return bool
*/
public function canPreview()
{
$blCan = null;
if ( ( $sPrevId = oxConfig::getParameter( 'preview' ) ) &&
( $sAdminSid = oxRegistry::get("oxUtilsServer")->getOxCookie( 'admin_sid' ) ) ) {
$sTable = getViewName( 'oxuser' );
$oDb = oxDb::getDb();
$sQ = "select 1 from $sTable where MD5( CONCAT( ".$oDb->quote($sAdminSid).", {$sTable}.oxid, {$sTable}.oxpassword, {$sTable}.oxrights ) ) = ".oxDb::getDb()->quote($sPrevId);
$blCan = (bool) $oDb->getOne( $sQ );
}
return $blCan;
}
/**
* Returns id which is used for product preview in shop during administration
*
* @return string
*/
public function getPreviewId()
{
$sAdminSid = oxRegistry::get("oxUtilsServer")->getOxCookie( 'admin_sid' );
if ( ( $oUser = $this->getUser() ) ) {
return md5( $sAdminSid . $oUser->getId() . $oUser->oxuser__oxpassword->value . $oUser->oxuser__oxrights->value );
}
}
/**
* This function checks if logged in user has access to admin or not
*
* @return bool
*/
public function checkAccessRights()
{
$myConfig = $this->getConfig();
$blIsAuth = false;
$sUserID = oxSession::getVar( "auth");
// deleting admin marker
oxSession::setVar( "malladmin", 0);
oxSession::setVar( "blIsAdmin", 0);
oxSession::deleteVar( "blIsAdmin" );
$myConfig->setConfigParam( 'blMallAdmin', false );
//#1552T
$myConfig->setConfigParam( 'blAllowInheritedEdit', false );
if ( $sUserID) {
// escaping
$oDb = oxDb::getDb();
$sRights = $oDb->getOne("select oxrights from oxuser where oxid = ".$oDb->quote($sUserID));
if ( $sRights != "user") {
// malladmin ?
if ( $sRights == "malladmin") {
oxSession::setVar( "malladmin", 1);
$myConfig->setConfigParam( 'blMallAdmin', true );
//#1552T
//So far this blAllowSharedEdit is Equal to blMallAdmin but in future to be solved over rights and roles
$myConfig->setConfigParam( 'blAllowSharedEdit', true );
$sShop = oxSession::getVar( "actshop");
if ( !isset($sShop)) {
oxSession::setVar( "actshop", $myConfig->getBaseShopId());
}
$blIsAuth = true;
} else {
// Shopadmin... check if this shop is valid and exists
$sShopID = $oDb->getOne("select oxid from oxshops where oxid = " . $oDb->quote( $sRights ) );
if ( isset( $sShopID) && $sShopID) {
// success, this shop exists
oxSession::setVar( "actshop", $sRights);
oxSession::setVar( "currentadminshop", $sRights);
oxSession::setVar( "shp", $sRights);
// check if this subshop admin is evil.
if ('chshp' == oxConfig::getParameter( 'fnc' )) {
// dont allow this call
$blIsAuth = false;
} else {
$blIsAuth = true;
$aShopIdVars = array('actshop', 'shp', 'currentadminshop');
foreach ($aShopIdVars as $sShopIdVar) {
if ($sGotShop = oxConfig::getParameter( $sShopIdVar )) {