OXID eShop CE  4.9.6
 All Classes Files Functions Variables Pages
oxutils.php
Go to the documentation of this file.
1 <?php
2 
6 require_once getShopBasePath() . "core/smarty/Smarty.class.php";
7 
12 class oxUtils extends oxSuperCfg
13 {
14 
20  protected $_iCurPrecision = null;
21 
29  protected $_sPermanentCachePattern = "/c_fieldnames_|c_tbdsc_|_allfields_/";
30 
36  protected $_sLanguageCachePattern = "/c_langcache_/i";
37 
43  protected $_sMenuCachePattern = "/c_menu_/i";
44 
50  protected $_aLockedFileHandles = array();
51 
57  protected $_aFileCacheContents = array();
58 
64  protected $_blIsSe = null;
65 
71  protected $_aStaticCache;
72 
78  protected $_blSeoIsActive = null;
79 
90  public function strMan($sVal, $sKey = null)
91  {
92  $oEncryptor = oxNew('oxEncryptor');
93  $sKey = $sKey ? $sKey : $this->getConfig()->getConfigParam('sConfigKey');
94 
95  return $oEncryptor->encrypt($sVal, $sKey);
96  }
97 
108  public function strRem($sVal, $sKey = null)
109  {
110  $oDecryptor = oxNew('oxDecryptor');
111  $sKey = $sKey ? $sKey : $this->getConfig()->getConfigParam('sConfigKey');
112 
113  return $oDecryptor->decrypt($sVal, $sKey);
114  }
115 
123  public function getArrFldName($sName)
124  {
125  return str_replace(".", "__", $sName);
126  }
127 
136  public function assignValuesFromText($sIn, $dVat = null)
137  {
138  $aRet = array();
139  $aPieces = explode('@@', $sIn);
140  while (list($sKey, $sVal) = each($aPieces)) {
141  if ($sVal) {
142  $aName = explode('__', $sVal);
143  if (isset($aName[0]) && isset($aName[1])) {
144  $aRet[] = $this->_fillExplodeArray($aName, $dVat);
145  }
146  }
147  }
148 
149  return $aRet;
150  }
151 
159  public function assignValuesToText($aIn)
160  {
161  $sRet = "";
162  reset($aIn);
163  while (list($sKey, $sVal) = each($aIn)) {
164  $sRet .= $sKey;
165  $sRet .= "__";
166  $sRet .= $sVal;
167  $sRet .= "@@";
168  }
169 
170  return $sRet;
171  }
172 
180  public function currency2Float($sValue)
181  {
182  $fRet = $sValue;
183  $iPos = strrpos($sValue, ".");
184  if ($iPos && ((strlen($sValue) - 1 - $iPos) < 2 + 1)) {
185  // replace decimal with ","
186  $fRet = substr_replace($fRet, ",", $iPos, 1);
187  }
188  // remove thousands
189  $fRet = str_replace(array(" ", "."), "", $fRet);
190 
191  $fRet = str_replace(",", ".", $fRet);
192 
193  return (float) $fRet;
194  }
195 
203  public function string2Float($sValue)
204  {
205  $fRet = str_replace(" ", "", $sValue);
206  $iCommaPos = strpos($fRet, ",");
207  $iDotPos = strpos($fRet, ".");
208  if (!$iDotPos xor !$iCommaPos) {
209  if (substr_count($fRet, ",") > 1 || substr_count($fRet, ".") > 1) {
210  $fRet = str_replace(array(",", "."), "", $fRet);
211  } else {
212  $fRet = str_replace(",", ".", $fRet);
213  }
214  } else {
215  if ($iDotPos < $iCommaPos) {
216  $fRet = str_replace(".", "", $fRet);
217  $fRet = str_replace(",", ".", $fRet);
218  }
219  }
220  // remove thousands
221  $fRet = str_replace(array(" ", ","), "", $fRet);
222 
223  return (float) $fRet;
224  }
225 
233  public function isSearchEngine($sClient = null)
234  {
235  if (is_null($this->_blIsSe)) {
236  $this->setSearchEngine(null, $sClient);
237  }
238 
239  return $this->_blIsSe;
240  }
241 
250  public function setSearchEngine($blIsSe = null, $sClient = null)
251  {
252  if (isset($blIsSe)) {
253  $this->_blIsSe = $blIsSe;
254 
255  return;
256  }
257  startProfile("isSearchEngine");
258 
259  $myConfig = $this->getConfig();
260  $blIsSe = false;
261 
262  if (!($myConfig->getConfigParam('iDebug') && $this->isAdmin())) {
263  $aRobots = $myConfig->getConfigParam('aRobots');
264  $aRobots = is_array($aRobots) ? $aRobots : array();
265 
266  $aRobotsExcept = $myConfig->getConfigParam('aRobotsExcept');
267  $aRobotsExcept = is_array($aRobotsExcept) ? $aRobotsExcept : array();
268 
269  $sClient = $sClient ? $sClient : strtolower(getenv('HTTP_USER_AGENT'));
270  $blIsSe = false;
271  $aRobots = array_merge($aRobots, $aRobotsExcept);
272  foreach ($aRobots as $sRobot) {
273  if (strpos($sClient, $sRobot) !== false) {
274  $blIsSe = true;
275  break;
276  }
277  }
278  }
279 
280  $this->_blIsSe = $blIsSe;
281 
282  stopProfile("isSearchEngine");
283  }
284 
295  public function isValidEmail($sEmail)
296  {
297  $oMailValidator = oxNew('oxMailValidator');
298 
299  return $oMailValidator->isValidEmail($sEmail);
300  }
301 
309  public function loadAdminProfile($aInterfaceProfiles)
310  {
311  // improved #533
312  // checking for available profiles list
313  if (is_array($aInterfaceProfiles)) {
314  //checking for previous profiles
315  $sPrevProfile = oxRegistry::get("oxUtilsServer")->getOxCookie('oxidadminprofile');
316  if (isset($sPrevProfile)) {
317  $aPrevProfile = @explode("@", trim($sPrevProfile));
318  }
319 
320  //array to store profiles
321  $aProfiles = array();
322  foreach ($aInterfaceProfiles as $iPos => $sProfile) {
323  $aProfileSettings = array($iPos, $sProfile);
324  $aProfiles[] = $aProfileSettings;
325  }
326  // setting previous used profile as active
327  if (isset($aPrevProfile[0]) && isset($aProfiles[$aPrevProfile[0]])) {
328  $aProfiles[$aPrevProfile[0]][2] = 1;
329  }
330 
331  oxRegistry::getSession()->setVariable("aAdminProfiles", $aProfiles);
332 
333  return $aProfiles;
334  }
335 
336  return null;
337  }
338 
347  public function fRound($sVal, $oCur = null)
348  {
349  startProfile('fround');
350 
351  //cached currency precision, this saves about 1% of execution time
352  $iCurPrecision = null;
353  if (!defined('OXID_PHP_UNIT')) {
354  $iCurPrecision = $this->_iCurPrecision;
355  }
356 
357  if (is_null($iCurPrecision)) {
358  if (!$oCur) {
359  $oCur = $this->getConfig()->getActShopCurrencyObject();
360  }
361 
362  $iCurPrecision = $oCur->decimal;
363  $this->_iCurPrecision = $iCurPrecision;
364  }
365 
366  // if < 5.3.x this is a workaround for #36008 bug in php - incorrect round() & number_format() result (R)
367  static $dprez = null;
368  if (!$dprez) {
369  $prez = @ini_get("precision");
370  if (!$prez || $prez > 12) {
371  $prez = 12;
372  }
373  $dprez = pow(10, -$prez);
374  }
375  stopProfile('fround');
376 
377  return round($sVal + $dprez * ($sVal >= 0 ? 1 : -1), $iCurPrecision);
378  }
379 
387  public function toStaticCache($sName, $sContent, $sKey = null)
388  {
389  // if it's an array then we add
390  if ($sKey) {
391  $this->_aStaticCache[$sName][$sKey] = $sContent;
392  } else {
393  $this->_aStaticCache[$sName] = $sContent;
394  }
395  }
396 
404  public function fromStaticCache($sName)
405  {
406  if (isset($this->_aStaticCache[$sName])) {
407  return $this->_aStaticCache[$sName];
408  }
409 
410  return null;
411  }
412 
418  public function cleanStaticCache($sCacheName = null)
419  {
420  if ($sCacheName) {
421  unset($this->_aStaticCache[$sCacheName]);
422  } else {
423  $this->_aStaticCache = null;
424  }
425  }
426 
434  public function toPhpFileCache($sKey, $mContents)
435  {
436  //only simple arrays are supported
437  if (is_array($mContents) && ($sCachePath = $this->getCacheFilePath($sKey, false, 'php'))) {
438 
439  // setting meta
440  $this->setCacheMeta($sKey, array("serialize" => false, "cachepath" => $sCachePath));
441 
442  // caching..
443  $this->toFileCache($sKey, $mContents);
444  }
445  }
446 
454  public function fromPhpFileCache($sKey)
455  {
456  // setting meta
457  $this->setCacheMeta($sKey, array("include" => true, "cachepath" => $this->getCacheFilePath($sKey, false, 'php')));
458 
459  return $this->fromFileCache($sKey);
460  }
461 
469  public function getCacheMeta($sKey)
470  {
471  return isset($this->_aFileCacheMeta[$sKey]) ? $this->_aFileCacheMeta[$sKey] : false;
472  }
473 
480  public function setCacheMeta($sKey, $aMeta)
481  {
482  // cache meta data
483  $this->_aFileCacheMeta[$sKey] = $aMeta;
484  }
485 
496  public function toFileCache($sKey, $mContents, $iTtl = 0)
497  {
498  $aCacheData['content'] = $mContents;
499  $aMeta = $this->getCacheMeta($sKey);
500  if ($iTtl) {
501  $aCacheData['ttl'] = $iTtl;
502  $aCacheData['timestamp'] = oxRegistry::get("oxUtilsDate")->getTime();
503  }
504  $this->_aFileCacheContents[$sKey] = $aCacheData;
505 
506  // looking for cache meta
507  $sCachePath = isset($aMeta["cachepath"]) ? $aMeta["cachepath"] : $this->getCacheFilePath($sKey);
508 
509  return ( bool ) $this->_lockFile($sCachePath, $sKey);
510  }
511 
519  public function fromFileCache($sKey)
520  {
521  if (!array_key_exists($sKey, $this->_aFileCacheContents)) {
522  $sRes = null;
523 
524  $aMeta = $this->getCacheMeta($sKey);
525  $blInclude = isset($aMeta["include"]) ? $aMeta["include"] : false;
526  $sCachePath = isset($aMeta["cachepath"]) ? $aMeta["cachepath"] : $this->getCacheFilePath($sKey);
527 
528  // trying to lock
529  $this->_lockFile($sCachePath, $sKey, LOCK_SH);
530 
531  clearstatcache();
532  if (is_readable($sCachePath)) {
533  $sRes = $blInclude ? $this->_includeFile($sCachePath) : $this->_readFile($sCachePath);
534  }
535 
536  if (isset($sRes['ttl']) && $sRes['ttl'] != 0) {
537  $iTimestamp = $sRes['timestamp'];
538  $iTtl = $sRes['ttl'];
539 
540  $iTime = oxRegistry::get("oxUtilsDate")->getTime();
541  if ($iTime > $iTimestamp + $iTtl) {
542  return null;
543  }
544  }
545  // release lock
546  $this->_releaseFile($sKey, LOCK_SH);
547 
548  // caching
549  $this->_aFileCacheContents[$sKey] = $sRes;
550  }
551 
552  return $this->_aFileCacheContents[$sKey]['content'];
553  }
554 
562  protected function _readFile($sFilePath)
563  {
564  $sRes = file_get_contents($sFilePath);
565 
566  return $sRes ? unserialize($sRes) : null;
567  }
568 
576  protected function _includeFile($sFilePath)
577  {
578  $_aCacheContents = null;
579  include $sFilePath;
580 
581  return $_aCacheContents;
582  }
583 
592  protected function _processCache($sKey, $mContents)
593  {
594  // looking for cache meta
595  $aCacheMeta = $this->getCacheMeta($sKey);
596  $blSerialize = isset($aCacheMeta["serialize"]) ? $aCacheMeta["serialize"] : true;
597 
598  if ($blSerialize) {
599  $mContents = serialize($mContents);
600  } else {
601  $mContents = "<?php\n//automatically generated file\n//" . date("Y-m-d H:i:s") . "\n\n\$_aCacheContents = " . var_export($mContents, true) . "\n?>";
602  }
603 
604  return $mContents;
605  }
606 
611  public function commitFileCache()
612  {
613  if (!empty($this->_aLockedFileHandles[LOCK_EX])) {
614  startProfile("!__SAVING CACHE__! (warning)");
615  foreach ($this->_aLockedFileHandles[LOCK_EX] as $sKey => $rHandle) {
616  if ($rHandle !== false && isset($this->_aFileCacheContents[$sKey])) {
617 
618  // #0002931A truncate file once more before writing
619  ftruncate($rHandle, 0);
620 
621  // writing cache
622  fwrite($rHandle, $this->_processCache($sKey, $this->_aFileCacheContents[$sKey]));
623 
624  // releasing locks
625  $this->_releaseFile($sKey);
626  }
627  }
628 
629  stopProfile("!__SAVING CACHE__! (warning)");
630 
631  //empty buffer
632  $this->_aFileCacheContents = array();
633  }
634  }
635 
645  protected function _lockFile($sFilePath, $sIdent, $iLockMode = LOCK_EX)
646  {
647  $rHandle = isset($this->_aLockedFileHandles[$iLockMode][$sIdent]) ? $this->_aLockedFileHandles[$iLockMode][$sIdent] : null;
648  if ($rHandle === null) {
649 
650  $blLocked = false;
651  $rHandle = @fopen($sFilePath, "a+");
652 
653  if ($rHandle !== false) {
654 
655  if (flock($rHandle, $iLockMode | LOCK_NB)) {
656  if ($iLockMode === LOCK_EX) {
657  // truncate file
658  $blLocked = ftruncate($rHandle, 0);
659  } else {
660  // move to a start position
661  $blLocked = fseek($rHandle, 0) === 0;
662  }
663  }
664 
665  // on failure - closing and setting false..
666  if (!$blLocked) {
667  fclose($rHandle);
668  $rHandle = false;
669  }
670  }
671 
672  // in case system does not support file locking
673  if (!$blLocked && $iLockMode === LOCK_EX) {
674 
675  // clearing on first call
676  if (count($this->_aLockedFileHandles) == 0) {
677  clearstatcache();
678  }
679 
680  // start a blank file to inform other processes we are dealing with it.
681  if (!(file_exists($sFilePath) && !filesize($sFilePath) && abs(time() - filectime($sFilePath) < 40))) {
682  $rHandle = @fopen($sFilePath, "w");
683  }
684  }
685 
686  $this->_aLockedFileHandles[$iLockMode][$sIdent] = $rHandle;
687  }
688 
689  return $rHandle;
690  }
691 
700  protected function _releaseFile($sIdent, $iLockMode = LOCK_EX)
701  {
702  $blSuccess = true;
703  if (isset($this->_aLockedFileHandles[$iLockMode][$sIdent]) &&
704  $this->_aLockedFileHandles[$iLockMode][$sIdent] !== false
705  ) {
706 
707  // release the lock and close file
708  $blSuccess = flock($this->_aLockedFileHandles[$iLockMode][$sIdent], LOCK_UN) &&
709  fclose($this->_aLockedFileHandles[$iLockMode][$sIdent]);
710  unset($this->_aLockedFileHandles[$iLockMode][$sIdent]);
711  }
712 
713  return $blSuccess;
714  }
715 
721  public function oxResetFileCache()
722  {
723  $aFiles = glob($this->getCacheFilePath(null, true) . '*');
724  if (is_array($aFiles)) {
725  // delete all the files, except cached tables field names
726  $aFiles = preg_grep($this->_sPermanentCachePattern, $aFiles, PREG_GREP_INVERT);
727  foreach ($aFiles as $sFile) {
728  @unlink($sFile);
729  }
730  }
731  }
732 
738  public function resetTemplateCache($aTemplates)
739  {
740  $sSmartyDir = oxRegistry::get("oxUtilsView")->getSmartyDir();
741  //$aFiles = glob( $this->getCacheFilePath( null, true ) . '*' );
742  $aFiles = glob($sSmartyDir . '*');
743 
744  if (is_array($aFiles) && is_array($aTemplates) && count($aTemplates)) {
745  // delete all template cache files
746  foreach ($aTemplates as &$sTemplate) {
747  $sTemplate = preg_quote(basename(strtolower($sTemplate), '.tpl'));
748  }
749 
750  $sPattern = sprintf("/%%(%s)\.tpl\.php$/i", implode('|', $aTemplates));
751  $aFiles = preg_grep($sPattern, $aFiles);
752 
753  if (is_array($aFiles)) {
754  foreach ($aFiles as $sFile) {
755  @unlink($sFile);
756  }
757  }
758  }
759 
760  }
761 
765  public function resetLanguageCache()
766  {
767  $aFiles = glob($this->getCacheFilePath(null, true) . '*');
768  if (is_array($aFiles)) {
769  // delete all language cache files
770  $sPattern = $this->_sLanguageCachePattern;
771  $aFiles = preg_grep($sPattern, $aFiles);
772  foreach ($aFiles as $sFile) {
773  @unlink($sFile);
774  }
775  }
776  }
777 
781  public function resetMenuCache()
782  {
783  $aFiles = glob($this->getCacheFilePath(null, true) . '*');
784  if (is_array($aFiles)) {
785  // delete all menu cache files
786  $sPattern = $this->_sMenuCachePattern;
787  $aFiles = preg_grep($sPattern, $aFiles);
788  foreach ($aFiles as $sFile) {
789  @unlink($sFile);
790  }
791  }
792  }
793 
803  public function getRemoteCachePath($sRemote, $sLocal)
804  {
805  clearstatcache();
806  if (file_exists($sLocal) && filemtime($sLocal) && filemtime($sLocal) > time() - 86400) {
807  return $sLocal;
808  }
809  $hRemote = @fopen($sRemote, "rb");
810  $blSuccess = false;
811  if (isset($hRemote) && $hRemote) {
812  $hLocal = fopen($sLocal, "wb");
813  stream_copy_to_stream($hRemote, $hLocal);
814  fclose($hRemote);
815  fclose($hLocal);
816  $blSuccess = true;
817  } else {
818  // try via fsockopen
819  $aUrl = @parse_url($sRemote);
820  if (!empty($aUrl["host"])) {
821  $sPath = $aUrl["path"];
822  if (empty($sPath)) {
823  $sPath = "/";
824  }
825  $sHost = $aUrl["host"];
826 
827  $hSocket = @fsockopen($sHost, 80, $iErrorNumber, $iErrStr, 5);
828  if ($hSocket) {
829  fputs($hSocket, "GET " . $sPath . " HTTP/1.0\r\nHost: $sHost\r\n\r\n");
830  $headers = stream_get_line($hSocket, 4096, "\r\n\r\n");
831  if (($hLocal = @fopen($sLocal, "wb")) !== false) {
832  rewind($hLocal);
833  // does not copy all the data
834  // stream_copy_to_stream($hSocket, $hLocal);
835  fwrite($hLocal, stream_get_contents($hSocket));
836  fclose($hLocal);
837  fclose($hSocket);
838  $blSuccess = true;
839  }
840  }
841  }
842  }
843  if ($blSuccess || file_exists($sLocal)) {
844  return $sLocal;
845  }
846 
847  return false;
848  }
849 
855  public function canPreview()
856  {
857  $blCan = null;
858  if (($sPrevId = oxRegistry::getConfig()->getRequestParameter('preview')) &&
859  ($sAdminSid = oxRegistry::get("oxUtilsServer")->getOxCookie('admin_sid'))
860  ) {
861 
862  $sTable = getViewName('oxuser');
863  $oDb = oxDb::getDb();
864  $sQ = "select 1 from $sTable where MD5( CONCAT( " . $oDb->quote($sAdminSid) . ", {$sTable}.oxid, {$sTable}.oxpassword, {$sTable}.oxrights ) ) = " . oxDb::getDb()->quote($sPrevId);
865  $blCan = (bool) $oDb->getOne($sQ);
866  }
867 
868  return $blCan;
869  }
870 
876  public function getPreviewId()
877  {
878  $sAdminSid = oxRegistry::get("oxUtilsServer")->getOxCookie('admin_sid');
879  if (($oUser = $this->getUser())) {
880  return md5($sAdminSid . $oUser->getId() . $oUser->oxuser__oxpassword->value . $oUser->oxuser__oxrights->value);
881  }
882  }
883 
889  public function checkAccessRights()
890  {
891  $myConfig = $this->getConfig();
892 
893  $blIsAuth = false;
894 
895  $sUserID = oxRegistry::getSession()->getVariable("auth");
896 
897  // deleting admin marker
898  oxRegistry::getSession()->setVariable("malladmin", 0);
899  oxRegistry::getSession()->setVariable("blIsAdmin", 0);
900  oxRegistry::getSession()->deleteVariable("blIsAdmin");
901  $myConfig->setConfigParam('blMallAdmin', false);
902  //#1552T
903  $myConfig->setConfigParam('blAllowInheritedEdit', false);
904 
905  if ($sUserID) {
906  // escaping
907  $oDb = oxDb::getDb();
908  $sRights = $oDb->getOne("select oxrights from oxuser where oxid = " . $oDb->quote($sUserID));
909 
910  if ($sRights != "user") {
911  // malladmin ?
912  if ($sRights == "malladmin") {
913  oxRegistry::getSession()->setVariable("malladmin", 1);
914  $myConfig->setConfigParam('blMallAdmin', true);
915 
916  //#1552T
917  //So far this blAllowSharedEdit is Equal to blMallAdmin but in future to be solved over rights and roles
918  $myConfig->setConfigParam('blAllowSharedEdit', true);
919 
920  $sShop = oxRegistry::getSession()->getVariable("actshop");
921  if (!isset($sShop)) {
922  oxRegistry::getSession()->setVariable("actshop", $myConfig->getBaseShopId());
923  }
924  $blIsAuth = true;
925  } else {
926  // Shopadmin... check if this shop is valid and exists
927  $sShopID = $oDb->getOne("select oxid from oxshops where oxid = " . $oDb->quote($sRights));
928  if (isset($sShopID) && $sShopID) {
929  // success, this shop exists
930 
931  oxRegistry::getSession()->setVariable("actshop", $sRights);
932  oxRegistry::getSession()->setVariable("currentadminshop", $sRights);
933  oxRegistry::getSession()->setVariable("shp", $sRights);
934 
935  // check if this subshop admin is evil.
936  if ('chshp' == oxRegistry::getConfig()->getRequestParameter('fnc')) {
937  // dont allow this call
938  $blIsAuth = false;
939  } else {
940  $blIsAuth = true;
941 
942  $aShopIdVars = array('actshop', 'shp', 'currentadminshop');
943  foreach ($aShopIdVars as $sShopIdVar) {
944  if ($sGotShop = oxRegistry::getConfig()->getRequestParameter($sShopIdVar)) {
945  if ($sGotShop != $sRights) {
946  $blIsAuth = false;
947  break;
948  }
949  }
950  }
951  }
952  }
953  }
954  // marking user as admin
955  oxRegistry::getSession()->setVariable("blIsAdmin", 1);
956  }
957  }
958 
959  return $blIsAuth;
960  }
961 
971  public function seoIsActive($blReset = false, $sShopId = null, $iActLang = null)
972  {
973  if (!is_null($this->_blSeoIsActive) && !$blReset) {
974  return $this->_blSeoIsActive;
975  }
976 
977  $myConfig = $this->getConfig();
978 
979  if (($this->_blSeoIsActive = $myConfig->getConfigParam('blSeoMode')) === null) {
980  $this->_blSeoIsActive = true;
981 
982  $aSeoModes = $myConfig->getconfigParam('aSeoModes');
983  $sActShopId = $sShopId ? $sShopId : $myConfig->getActiveShop()->getId();
984  $iActLang = $iActLang ? $iActLang : (int) oxRegistry::getLang()->getBaseLanguage();
985 
986  // checking special config param for active shop and language
987  if (is_array($aSeoModes) && isset($aSeoModes[$sActShopId]) && isset($aSeoModes[$sActShopId][$iActLang])) {
988  $this->_blSeoIsActive = (bool) $aSeoModes[$sActShopId][$iActLang];
989  }
990  }
991 
992  return $this->_blSeoIsActive;
993  }
994 
1002  public function isValidAlpha($sField)
1003  {
1004  return (boolean) getStr()->preg_match('/^[a-zA-Z0-9_]*$/', $sField);
1005  }
1006 
1014  protected function _simpleRedirect($sUrl, $sHeaderCode)
1015  {
1016  $oHeader = oxNew("oxHeader");
1017  $oHeader->setHeader($sHeaderCode);
1018  $oHeader->setHeader("Location: $sUrl");
1019  $oHeader->setHeader("Connection: close");
1020  $oHeader->sendHeader();
1021  }
1022 
1028  public function redirectOffline($iHeaderCode = 302)
1029  {
1030  $sUrl = $this->getConfig()->getShopUrl() . 'offline.html';
1031  $this->redirect($sUrl, false, $iHeaderCode);
1032  }
1033 
1043  public function redirect($sUrl, $blAddRedirectParam = true, $iHeaderCode = 302)
1044  {
1045  //preventing possible cyclic redirection
1046  //#M341 and check only if redirect parameter must be added
1047  if ($blAddRedirectParam && oxRegistry::getConfig()->getRequestParameter('redirected')) {
1048  return;
1049  }
1050 
1051  if ($blAddRedirectParam) {
1052  $sUrl = $this->_addUrlParameters($sUrl, array('redirected' => 1));
1053  }
1054 
1055  $sUrl = str_ireplace("&amp;", "&", $sUrl);
1056 
1057  switch ($iHeaderCode) {
1058  case 301:
1059  $sHeaderCode = "HTTP/1.1 301 Moved Permanently";
1060  break;
1061  case 500:
1062  $sHeaderCode = "HTTP/1.1 500 Internal Server Error";
1063  break;
1064  case 302:
1065  default:
1066  $sHeaderCode = "HTTP/1.1 302 Found";
1067  }
1068 
1069  $this->_simpleRedirect($sUrl, $sHeaderCode);
1070 
1071  try { //may occur in case db is lost
1072  $this->getSession()->freeze();
1073  } catch (oxException $oEx) {
1074  $oEx->debugOut();
1075  //do nothing else to make sure the redirect takes place
1076  }
1077 
1078  if (defined('OXID_PHP_UNIT')) {
1079  return;
1080  }
1081 
1082  $this->showMessageAndExit('');
1083  }
1084 
1093  public function showMessageAndExit($sMsg)
1094  {
1095  $this->getSession()->freeze();
1096  $this->commitFileCache();
1097 
1098  if (defined('OXID_PHP_UNIT')) {
1099  return;
1100  }
1101 
1102 
1103  exit($sMsg);
1104  }
1105 
1111  public function setHeader($sHeader)
1112  {
1113  header($sHeader);
1114  }
1115 
1124  protected function _addUrlParameters($sUrl, $aParams)
1125  {
1126  $sDelimiter = ((getStr()->strpos($sUrl, '?') !== false)) ? '&' : '?';
1127  foreach ($aParams as $sName => $sVal) {
1128  $sUrl = $sUrl . $sDelimiter . $sName . '=' . $sVal;
1129  $sDelimiter = '&';
1130  }
1131 
1132  return $sUrl;
1133  }
1134 
1146  protected function _fillExplodeArray($aName, $dVat = null)
1147  {
1148  $myConfig = $this->getConfig();
1149  $oObject = new stdClass();
1150  $aPrice = explode('!P!', $aName[0]);
1151 
1152  if (($myConfig->getConfigParam('bl_perfLoadSelectLists') && $myConfig->getConfigParam('bl_perfUseSelectlistPrice') && isset($aPrice[0]) && isset($aPrice[1])) || $this->isAdmin()) {
1153 
1154  // yes, price is there
1155  $oObject->price = isset($aPrice[1]) ? $aPrice[1] : 0;
1156  $aName[0] = isset($aPrice[0]) ? $aPrice[0] : '';
1157 
1158  $iPercPos = getStr()->strpos($oObject->price, '%');
1159  if ($iPercPos !== false) {
1160  $oObject->priceUnit = '%';
1161  $oObject->fprice = $oObject->price;
1162  $oObject->price = substr($oObject->price, 0, $iPercPos);
1163  } else {
1164  $oCur = $myConfig->getActShopCurrencyObject();
1165  $oObject->price = str_replace(',', '.', $oObject->price);
1166  $oObject->fprice = oxRegistry::getLang()->formatCurrency($oObject->price * $oCur->rate, $oCur);
1167  $oObject->priceUnit = 'abs';
1168  }
1169 
1170  // add price info into list
1171  if (!$this->isAdmin() && $oObject->price != 0) {
1172  $aName[0] .= " ";
1173 
1174  $dPrice = $this->_preparePrice($oObject->price, $dVat);
1175 
1176  if ($oObject->price > 0) {
1177  $aName[0] .= "+";
1178  }
1179  //V FS#2616
1180  if ($dVat != null && $oObject->priceUnit == 'abs') {
1181  $oPrice = oxNew('oxPrice');
1182  $oPrice->setPrice($oObject->price, $dVat);
1183  $aName[0] .= oxRegistry::getLang()->formatCurrency($dPrice * $oCur->rate, $oCur);
1184  } else {
1185  $aName[0] .= $oObject->fprice;
1186  }
1187  if ($oObject->priceUnit == 'abs') {
1188  $aName[0] .= " " . $oCur->sign;
1189  }
1190  }
1191  } elseif (isset($aPrice[0]) && isset($aPrice[1])) {
1192  // A. removing unused part of information
1193  $aName[0] = getStr()->preg_replace("/!P!.*/", "", $aName[0]);
1194  }
1195 
1196  $oObject->name = $aName[0];
1197  $oObject->value = $aName[1];
1198 
1199  return $oObject;
1200  }
1201 
1210  protected function _preparePrice($dPrice, $dVat)
1211  {
1212  $blCalculationModeNetto = $this->_isPriceViewModeNetto();
1213 
1214  $oCurrency = $this->getConfig()->getActShopCurrencyObject();
1215 
1216  $blEnterNetPrice = $this->getConfig()->getConfigParam('blEnterNetPrice');
1217  if ($blCalculationModeNetto && !$blEnterNetPrice) {
1218  $dPrice = round(oxPrice::brutto2Netto($dPrice, $dVat), $oCurrency->decimal);
1219  } elseif (!$blCalculationModeNetto && $blEnterNetPrice) {
1220  $dPrice = round(oxPrice::netto2Brutto($dPrice, $dVat), $oCurrency->decimal);
1221  }
1222 
1223  return $dPrice;
1224  }
1225 
1231  protected function _isPriceViewModeNetto()
1232  {
1233  $blResult = (bool) $this->getConfig()->getConfigParam('blShowNetPrice');
1234  $oUser = $this->_getArticleUser();
1235  if ($oUser) {
1236  $blResult = $oUser->isPriceViewModeNetto();
1237  }
1238 
1239  return $blResult;
1240  }
1241 
1247  protected function _getArticleUser()
1248  {
1249  if ($this->_oUser) {
1250  return $this->_oUser;
1251  }
1252 
1253  return $this->getUser();
1254  }
1255 
1263  public function oxMimeContentType($sFileName)
1264  {
1265  $sFileName = strtolower($sFileName);
1266  $iLastDot = strrpos($sFileName, '.');
1267 
1268  if ($iLastDot !== false) {
1269  $sType = substr($sFileName, $iLastDot + 1);
1270  switch ($sType) {
1271  case 'gif':
1272  $sType = 'image/gif';
1273  break;
1274  case 'jpeg':
1275  case 'jpg':
1276  $sType = 'image/jpeg';
1277  break;
1278  case 'png':
1279  $sType = 'image/png';
1280  break;
1281  default:
1282  $sType = false;
1283  break;
1284  }
1285  }
1286 
1287  return $sType;
1288  }
1289 
1296  public function logger($sText, $blNewline = false)
1297  {
1298  $myConfig = $this->getConfig();
1299 
1300  if ($myConfig->getConfigParam('iDebug') == -2) {
1301  if (gettype($sText) != 'string') {
1302  $sText = var_export($sText, true);
1303  }
1304  $sLogMsg = "----------------------------------------------\n{$sText}" . (($blNewline) ? "\n" : "") . "\n";
1305  $this->writeToLog($sLogMsg, "log.txt");
1306  }
1307 
1308  }
1309 
1317  public function strRot13($sStr)
1318  {
1319  $sFrom = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
1320  $sTo = 'nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM';
1321 
1322  return strtr($sStr, $sFrom, $sTo);
1323  }
1324 
1334  public function getCacheFilePath($sCacheName, $blPathOnly = false, $sExtension = 'txt')
1335  {
1336 
1337  $sVersionPrefix = 'pe';
1338 
1339  $sPath = realpath($this->getConfig()->getConfigParam('sCompileDir'));
1340 
1341  if (!$sPath) {
1342  return false;
1343  }
1344 
1345  return $blPathOnly ? "{$sPath}/" : "{$sPath}/ox{$sVersionPrefix}c_{$sCacheName}." . $sExtension;
1346  }
1347 
1355  public function getLangCache($sCacheName)
1356  {
1357  $aLangCache = null;
1358  $sFilePath = $this->getCacheFilePath($sCacheName);
1359  if (file_exists($sFilePath) && is_readable($sFilePath)) {
1360  include $sFilePath;
1361  }
1362 
1363  return $aLangCache;
1364  }
1365 
1374  public function setLangCache($sCacheName, $aLangCache)
1375  {
1376  $sCache = "<?php\n\$aLangCache = " . var_export($aLangCache, true) . ";\n?>";
1377  $blRes = file_put_contents($this->getCacheFilePath($sCacheName), $sCache, LOCK_EX);
1378 
1379  return $blRes;
1380  }
1381 
1389  public function checkUrlEndingSlash($sUrl)
1390  {
1391  if (!getStr()->preg_match("/\/$/", $sUrl)) {
1392  $sUrl .= '/';
1393  }
1394 
1395  return $sUrl;
1396  }
1397 
1406  public function writeToLog($sLogMessage, $sLogFileName)
1407  {
1408  $sLogDist = $this->getConfig()->getLogsDir() . $sLogFileName;
1409  $blOk = false;
1410 
1411  if (($oHandle = fopen($sLogDist, 'a')) !== false) {
1412  fwrite($oHandle, $sLogMessage);
1413  $blOk = fclose($oHandle);
1414  }
1415 
1416  return $blOk;
1417  }
1418 
1424  public function handlePageNotFoundError($sUrl = '')
1425  {
1426  $this->setHeader("HTTP/1.0 404 Not Found");
1427  if (oxRegistry::getConfig()->isUtf()) {
1428  $this->setHeader("Content-Type: text/html; charset=UTF-8");
1429  }
1430 
1431  $sReturn = "Page not found.";
1432  try {
1433  $oView = oxNew('oxUBase');
1434  $oView->init();
1435  $oView->render();
1436  $oView->setClassName('oxUBase');
1437  $oView->addTplParam('sUrl', $sUrl);
1438  if ($sRet = oxRegistry::get("oxUtilsView")->getTemplateOutput('message/err_404.tpl', $oView)) {
1439  $sReturn = $sRet;
1440  }
1441  } catch (Exception $e) {
1442  }
1443  $this->showMessageAndExit($sReturn);
1444  }
1445 
1453  public function extractDomain($sHost)
1454  {
1455  $oStr = getStr();
1456  if (!$oStr->preg_match('/[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}/', $sHost) &&
1457  ($iLastDot = strrpos($sHost, '.')) !== false
1458  ) {
1459  $iLen = $oStr->strlen($sHost);
1460  if (($iNextDot = strrpos($sHost, '.', ($iLen - $iLastDot + 1) * -1)) !== false) {
1461  $sHost = trim($oStr->substr($sHost, $iNextDot), '.');
1462  }
1463  }
1464 
1465  return $sHost;
1466  }
1467 }