oxutils.php

Go to the documentation of this file.
00001 <?php
00002 
00006 require_once getShopBasePath() . "core/smarty/Smarty.class.php";
00007 
00012 class oxUtils extends oxSuperCfg
00013 {
00014 
00020     protected $_iCurPrecision = null;
00021 
00029     protected $_sPermanentCachePattern = "/c_fieldnames_|c_tbdsc_|_allfields_/";
00030 
00036     protected $_sLanguageCachePattern = "/c_langcache_/i";
00037 
00043     protected $_sMenuCachePattern = "/c_menu_/i";
00044 
00050     protected $_aLockedFileHandles = array();
00051 
00057     protected $_aFileCacheContents = array();
00058 
00064     protected $_blIsSe = null;
00065 
00071     protected $_aStaticCache;
00072 
00078     protected $_blSeoIsActive = null;
00079 
00090     public function strMan($sVal, $sKey = null)
00091     {
00092         $oEncryptor = oxNew('oxEncryptor');
00093         $sKey = $sKey ? $sKey : $this->getConfig()->getConfigParam('sConfigKey');
00094 
00095         return $oEncryptor->encrypt($sVal, $sKey);
00096     }
00097 
00108     public function strRem($sVal, $sKey = null)
00109     {
00110         $oDecryptor = oxNew('oxDecryptor');
00111         $sKey = $sKey ? $sKey : $this->getConfig()->getConfigParam('sConfigKey');
00112 
00113         return $oDecryptor->decrypt($sVal, $sKey);
00114     }
00115 
00123     public function getArrFldName($sName)
00124     {
00125         return str_replace(".", "__", $sName);
00126     }
00127 
00136     public function assignValuesFromText($sIn, $dVat = null)
00137     {
00138         $aRet = array();
00139         $aPieces = explode('@@', $sIn);
00140         while (list($sKey, $sVal) = each($aPieces)) {
00141             if ($sVal) {
00142                 $aName = explode('__', $sVal);
00143                 if (isset($aName[0]) && isset($aName[1])) {
00144                     $aRet[] = $this->_fillExplodeArray($aName, $dVat);
00145                 }
00146             }
00147         }
00148 
00149         return $aRet;
00150     }
00151 
00159     public function assignValuesToText($aIn)
00160     {
00161         $sRet = "";
00162         reset($aIn);
00163         while (list($sKey, $sVal) = each($aIn)) {
00164             $sRet .= $sKey;
00165             $sRet .= "__";
00166             $sRet .= $sVal;
00167             $sRet .= "@@";
00168         }
00169 
00170         return $sRet;
00171     }
00172 
00180     public function currency2Float($sValue)
00181     {
00182         $fRet = $sValue;
00183         $iPos = strrpos($sValue, ".");
00184         if ($iPos && ((strlen($sValue) - 1 - $iPos) < 2 + 1)) {
00185             // replace decimal with ","
00186             $fRet = substr_replace($fRet, ",", $iPos, 1);
00187         }
00188         // remove thousands
00189         $fRet = str_replace(array(" ", "."), "", $fRet);
00190 
00191         $fRet = str_replace(",", ".", $fRet);
00192 
00193         return (float) $fRet;
00194     }
00195 
00203     public function string2Float($sValue)
00204     {
00205         $fRet = str_replace(" ", "", $sValue);
00206         $iCommaPos = strpos($fRet, ",");
00207         $iDotPos = strpos($fRet, ".");
00208         if (!$iDotPos xor !$iCommaPos) {
00209             if (substr_count($fRet, ",") > 1 || substr_count($fRet, ".") > 1) {
00210                 $fRet = str_replace(array(",", "."), "", $fRet);
00211             } else {
00212                 $fRet = str_replace(",", ".", $fRet);
00213             }
00214         } else {
00215             if ($iDotPos < $iCommaPos) {
00216                 $fRet = str_replace(".", "", $fRet);
00217                 $fRet = str_replace(",", ".", $fRet);
00218             }
00219         }
00220         // remove thousands
00221         $fRet = str_replace(array(" ", ","), "", $fRet);
00222 
00223         return (float) $fRet;
00224     }
00225 
00233     public function isSearchEngine($sClient = null)
00234     {
00235         if (is_null($this->_blIsSe)) {
00236             $this->setSearchEngine(null, $sClient);
00237         }
00238 
00239         return $this->_blIsSe;
00240     }
00241 
00250     public function setSearchEngine($blIsSe = null, $sClient = null)
00251     {
00252         if (isset($blIsSe)) {
00253             $this->_blIsSe = $blIsSe;
00254 
00255             return;
00256         }
00257         startProfile("isSearchEngine");
00258 
00259         $myConfig = $this->getConfig();
00260         $blIsSe = false;
00261 
00262         if (!($myConfig->getConfigParam('iDebug') && $this->isAdmin())) {
00263             $aRobots = $myConfig->getConfigParam('aRobots');
00264             $aRobots = is_array($aRobots) ? $aRobots : array();
00265 
00266             $aRobotsExcept = $myConfig->getConfigParam('aRobotsExcept');
00267             $aRobotsExcept = is_array($aRobotsExcept) ? $aRobotsExcept : array();
00268 
00269             $sClient = $sClient ? $sClient : strtolower(getenv('HTTP_USER_AGENT'));
00270             $blIsSe = false;
00271             $aRobots = array_merge($aRobots, $aRobotsExcept);
00272             foreach ($aRobots as $sRobot) {
00273                 if (strpos($sClient, $sRobot) !== false) {
00274                     $blIsSe = true;
00275                     break;
00276                 }
00277             }
00278         }
00279 
00280         $this->_blIsSe = $blIsSe;
00281 
00282         stopProfile("isSearchEngine");
00283     }
00284 
00295     public function isValidEmail($sEmail)
00296     {
00297         $oMailValidator = oxNew('oxMailValidator');
00298 
00299         return $oMailValidator->isValidEmail($sEmail);
00300     }
00301 
00309     public function loadAdminProfile($aInterfaceProfiles)
00310     {
00311         // improved #533
00312         // checking for available profiles list
00313         if (is_array($aInterfaceProfiles)) {
00314             //checking for previous profiles
00315             $sPrevProfile = oxRegistry::get("oxUtilsServer")->getOxCookie('oxidadminprofile');
00316             if (isset($sPrevProfile)) {
00317                 $aPrevProfile = @explode("@", trim($sPrevProfile));
00318             }
00319 
00320             //array to store profiles
00321             $aProfiles = array();
00322             foreach ($aInterfaceProfiles as $iPos => $sProfile) {
00323                 $aProfileSettings = array($iPos, $sProfile);
00324                 $aProfiles[] = $aProfileSettings;
00325             }
00326             // setting previous used profile as active
00327             if (isset($aPrevProfile[0]) && isset($aProfiles[$aPrevProfile[0]])) {
00328                 $aProfiles[$aPrevProfile[0]][2] = 1;
00329             }
00330 
00331             oxRegistry::getSession()->setVariable("aAdminProfiles", $aProfiles);
00332 
00333             return $aProfiles;
00334         }
00335 
00336         return null;
00337     }
00338 
00347     public function fRound($sVal, $oCur = null)
00348     {
00349         startProfile('fround');
00350 
00351         //cached currency precision, this saves about 1% of execution time
00352         $iCurPrecision = null;
00353         if (!defined('OXID_PHP_UNIT')) {
00354             $iCurPrecision = $this->_iCurPrecision;
00355         }
00356 
00357         if (is_null($iCurPrecision)) {
00358             if (!$oCur) {
00359                 $oCur = $this->getConfig()->getActShopCurrencyObject();
00360             }
00361 
00362             $iCurPrecision = $oCur->decimal;
00363             $this->_iCurPrecision = $iCurPrecision;
00364         }
00365 
00366         // if < 5.3.x this is a workaround for #36008 bug in php - incorrect round() & number_format() result (R)
00367         static $dprez = null;
00368         if (!$dprez) {
00369             $prez = @ini_get("precision");
00370             if (!$prez || $prez > 12) {
00371                 $prez = 12;
00372             }
00373             $dprez = pow(10, -$prez);
00374         }
00375         stopProfile('fround');
00376 
00377         return round($sVal + $dprez * ($sVal >= 0 ? 1 : -1), $iCurPrecision);
00378     }
00379 
00387     public function toStaticCache($sName, $sContent, $sKey = null)
00388     {
00389         // if it's an array then we add
00390         if ($sKey) {
00391             $this->_aStaticCache[$sName][$sKey] = $sContent;
00392         } else {
00393             $this->_aStaticCache[$sName] = $sContent;
00394         }
00395     }
00396 
00404     public function fromStaticCache($sName)
00405     {
00406         if (isset($this->_aStaticCache[$sName])) {
00407             return $this->_aStaticCache[$sName];
00408         }
00409 
00410         return null;
00411     }
00412 
00418     public function cleanStaticCache($sCacheName = null)
00419     {
00420         if ($sCacheName) {
00421             unset($this->_aStaticCache[$sCacheName]);
00422         } else {
00423             $this->_aStaticCache = null;
00424         }
00425     }
00426 
00434     public function toPhpFileCache($sKey, $mContents)
00435     {
00436         //only simple arrays are supported
00437         if (is_array($mContents) && ($sCachePath = $this->getCacheFilePath($sKey, false, 'php'))) {
00438 
00439             // setting meta
00440             $this->setCacheMeta($sKey, array("serialize" => false, "cachepath" => $sCachePath));
00441 
00442             // caching..
00443             $this->toFileCache($sKey, $mContents);
00444         }
00445     }
00446 
00454     public function fromPhpFileCache($sKey)
00455     {
00456         // setting meta
00457         $this->setCacheMeta($sKey, array("include" => true, "cachepath" => $this->getCacheFilePath($sKey, false, 'php')));
00458 
00459         return $this->fromFileCache($sKey);
00460     }
00461 
00469     public function getCacheMeta($sKey)
00470     {
00471         return isset($this->_aFileCacheMeta[$sKey]) ? $this->_aFileCacheMeta[$sKey] : false;
00472     }
00473 
00480     public function setCacheMeta($sKey, $aMeta)
00481     {
00482         // cache meta data
00483         $this->_aFileCacheMeta[$sKey] = $aMeta;
00484     }
00485 
00496     public function toFileCache($sKey, $mContents, $iTtl = 0)
00497     {
00498         $aCacheData['content'] = $mContents;
00499         $aMeta = $this->getCacheMeta($sKey);
00500         if ($iTtl) {
00501             $aCacheData['ttl'] = $iTtl;
00502             $aCacheData['timestamp'] = oxRegistry::get("oxUtilsDate")->getTime();
00503         }
00504         $this->_aFileCacheContents[$sKey] = $aCacheData;
00505 
00506         // looking for cache meta
00507         $sCachePath = isset($aMeta["cachepath"]) ? $aMeta["cachepath"] : $this->getCacheFilePath($sKey);
00508 
00509         return ( bool ) $this->_lockFile($sCachePath, $sKey);
00510     }
00511 
00519     public function fromFileCache($sKey)
00520     {
00521         if (!array_key_exists($sKey, $this->_aFileCacheContents)) {
00522             $sRes = null;
00523 
00524             $aMeta = $this->getCacheMeta($sKey);
00525             $blInclude = isset($aMeta["include"]) ? $aMeta["include"] : false;
00526             $sCachePath = isset($aMeta["cachepath"]) ? $aMeta["cachepath"] : $this->getCacheFilePath($sKey);
00527 
00528             // trying to lock
00529             $this->_lockFile($sCachePath, $sKey, LOCK_SH);
00530 
00531             clearstatcache();
00532             if (is_readable($sCachePath)) {
00533                 $sRes = $blInclude ? $this->_includeFile($sCachePath) : $this->_readFile($sCachePath);
00534             }
00535 
00536             if (isset($sRes['ttl']) && $sRes['ttl'] != 0) {
00537                 $iTimestamp = $sRes['timestamp'];
00538                 $iTtl = $sRes['ttl'];
00539 
00540                 $iTime = oxRegistry::get("oxUtilsDate")->getTime();
00541                 if ($iTime > $iTimestamp + $iTtl) {
00542                     return null;
00543                 }
00544             }
00545             // release lock
00546             $this->_releaseFile($sKey, LOCK_SH);
00547 
00548             // caching
00549             $this->_aFileCacheContents[$sKey] = $sRes;
00550         }
00551 
00552         return $this->_aFileCacheContents[$sKey]['content'];
00553     }
00554 
00562     protected function _readFile($sFilePath)
00563     {
00564         $sRes = file_get_contents($sFilePath);
00565 
00566         return $sRes ? unserialize($sRes) : null;
00567     }
00568 
00576     protected function _includeFile($sFilePath)
00577     {
00578         $_aCacheContents = null;
00579         include $sFilePath;
00580 
00581         return $_aCacheContents;
00582     }
00583 
00592     protected function _processCache($sKey, $mContents)
00593     {
00594         // looking for cache meta
00595         $aCacheMeta = $this->getCacheMeta($sKey);
00596         $blSerialize = isset($aCacheMeta["serialize"]) ? $aCacheMeta["serialize"] : true;
00597 
00598         if ($blSerialize) {
00599             $mContents = serialize($mContents);
00600         } else {
00601             $mContents = "<?php\n//automatically generated file\n//" . date("Y-m-d H:i:s") . "\n\n\$_aCacheContents = " . var_export($mContents, true) . "\n?>";
00602         }
00603 
00604         return $mContents;
00605     }
00606 
00611     public function commitFileCache()
00612     {
00613         if (!empty($this->_aLockedFileHandles[LOCK_EX])) {
00614             startProfile("!__SAVING CACHE__! (warning)");
00615             foreach ($this->_aLockedFileHandles[LOCK_EX] as $sKey => $rHandle) {
00616                 if ($rHandle !== false && isset($this->_aFileCacheContents[$sKey])) {
00617 
00618                     // #0002931A truncate file once more before writing
00619                     ftruncate($rHandle, 0);
00620 
00621                     // writing cache
00622                     fwrite($rHandle, $this->_processCache($sKey, $this->_aFileCacheContents[$sKey]));
00623 
00624                     // releasing locks
00625                     $this->_releaseFile($sKey);
00626                 }
00627             }
00628 
00629             stopProfile("!__SAVING CACHE__! (warning)");
00630 
00631             //empty buffer
00632             $this->_aFileCacheContents = array();
00633         }
00634     }
00635 
00645     protected function _lockFile($sFilePath, $sIdent, $iLockMode = LOCK_EX)
00646     {
00647         $rHandle = isset($this->_aLockedFileHandles[$iLockMode][$sIdent]) ? $this->_aLockedFileHandles[$iLockMode][$sIdent] : null;
00648         if ($rHandle === null) {
00649 
00650             $blLocked = false;
00651             $rHandle = @fopen($sFilePath, "a+");
00652 
00653             if ($rHandle !== false) {
00654 
00655                 if (flock($rHandle, $iLockMode | LOCK_NB)) {
00656                     if ($iLockMode === LOCK_EX) {
00657                         // truncate file
00658                         $blLocked = ftruncate($rHandle, 0);
00659                     } else {
00660                         // move to a start position
00661                         $blLocked = fseek($rHandle, 0) === 0;
00662                     }
00663                 }
00664 
00665                 // on failure - closing and setting false..
00666                 if (!$blLocked) {
00667                     fclose($rHandle);
00668                     $rHandle = false;
00669                 }
00670             }
00671 
00672             // in case system does not support file locking
00673             if (!$blLocked && $iLockMode === LOCK_EX) {
00674 
00675                 // clearing on first call
00676                 if (count($this->_aLockedFileHandles) == 0) {
00677                     clearstatcache();
00678                 }
00679 
00680                 // start a blank file to inform other processes we are dealing with it.
00681                 if (!(file_exists($sFilePath) && !filesize($sFilePath) && abs(time() - filectime($sFilePath) < 40))) {
00682                     $rHandle = @fopen($sFilePath, "w");
00683                 }
00684             }
00685 
00686             $this->_aLockedFileHandles[$iLockMode][$sIdent] = $rHandle;
00687         }
00688 
00689         return $rHandle;
00690     }
00691 
00700     protected function _releaseFile($sIdent, $iLockMode = LOCK_EX)
00701     {
00702         $blSuccess = true;
00703         if (isset($this->_aLockedFileHandles[$iLockMode][$sIdent]) &&
00704             $this->_aLockedFileHandles[$iLockMode][$sIdent] !== false
00705         ) {
00706 
00707             // release the lock and close file
00708             $blSuccess = flock($this->_aLockedFileHandles[$iLockMode][$sIdent], LOCK_UN) &&
00709                          fclose($this->_aLockedFileHandles[$iLockMode][$sIdent]);
00710             unset($this->_aLockedFileHandles[$iLockMode][$sIdent]);
00711         }
00712 
00713         return $blSuccess;
00714     }
00715 
00721     public function oxResetFileCache()
00722     {
00723         $aFiles = glob($this->getCacheFilePath(null, true) . '*');
00724         if (is_array($aFiles)) {
00725             // delete all the files, except cached tables field names
00726             $aFiles = preg_grep($this->_sPermanentCachePattern, $aFiles, PREG_GREP_INVERT);
00727             foreach ($aFiles as $sFile) {
00728                 @unlink($sFile);
00729             }
00730         }
00731     }
00732 
00738     public function resetTemplateCache($aTemplates)
00739     {
00740         $sSmartyDir = oxRegistry::get("oxUtilsView")->getSmartyDir();
00741         //$aFiles = glob( $this->getCacheFilePath( null, true ) . '*' );
00742         $aFiles = glob($sSmartyDir . '*');
00743 
00744         if (is_array($aFiles) && is_array($aTemplates) && count($aTemplates)) {
00745             // delete all template cache files
00746             foreach ($aTemplates as &$sTemplate) {
00747                 $sTemplate = preg_quote(basename(strtolower($sTemplate), '.tpl'));
00748             }
00749 
00750             $sPattern = sprintf("/%%(%s)\.tpl\.php$/i", implode('|', $aTemplates));
00751             $aFiles = preg_grep($sPattern, $aFiles);
00752 
00753             if (is_array($aFiles)) {
00754                 foreach ($aFiles as $sFile) {
00755                     @unlink($sFile);
00756                 }
00757             }
00758         }
00759 
00760     }
00761 
00765     public function resetLanguageCache()
00766     {
00767         $aFiles = glob($this->getCacheFilePath(null, true) . '*');
00768         if (is_array($aFiles)) {
00769             // delete all language cache files
00770             $sPattern = $this->_sLanguageCachePattern;
00771             $aFiles = preg_grep($sPattern, $aFiles);
00772             foreach ($aFiles as $sFile) {
00773                 @unlink($sFile);
00774             }
00775         }
00776     }
00777 
00781     public function resetMenuCache()
00782     {
00783         $aFiles = glob($this->getCacheFilePath(null, true) . '*');
00784         if (is_array($aFiles)) {
00785             // delete all menu cache files
00786             $sPattern = $this->_sMenuCachePattern;
00787             $aFiles = preg_grep($sPattern, $aFiles);
00788             foreach ($aFiles as $sFile) {
00789                 @unlink($sFile);
00790             }
00791         }
00792     }
00793 
00803     public function getRemoteCachePath($sRemote, $sLocal)
00804     {
00805         clearstatcache();
00806         if (file_exists($sLocal) && filemtime($sLocal) && filemtime($sLocal) > time() - 86400) {
00807             return $sLocal;
00808         }
00809         $hRemote = @fopen($sRemote, "rb");
00810         $blSuccess = false;
00811         if (isset($hRemote) && $hRemote) {
00812             $hLocal = fopen($sLocal, "wb");
00813             stream_copy_to_stream($hRemote, $hLocal);
00814             fclose($hRemote);
00815             fclose($hLocal);
00816             $blSuccess = true;
00817         } else {
00818             // try via fsockopen
00819             $aUrl = @parse_url($sRemote);
00820             if (!empty($aUrl["host"])) {
00821                 $sPath = $aUrl["path"];
00822                 if (empty($sPath)) {
00823                     $sPath = "/";
00824                 }
00825                 $sHost = $aUrl["host"];
00826 
00827                 $hSocket = @fsockopen($sHost, 80, $iErrorNumber, $iErrStr, 5);
00828                 if ($hSocket) {
00829                     fputs($hSocket, "GET " . $sPath . " HTTP/1.0\r\nHost: $sHost\r\n\r\n");
00830                     $headers = stream_get_line($hSocket, 4096, "\r\n\r\n");
00831                     if (($hLocal = @fopen($sLocal, "wb")) !== false) {
00832                         rewind($hLocal);
00833                         // does not copy all the data
00834                         // stream_copy_to_stream($hSocket, $hLocal);
00835                         fwrite($hLocal, stream_get_contents($hSocket));
00836                         fclose($hLocal);
00837                         fclose($hSocket);
00838                         $blSuccess = true;
00839                     }
00840                 }
00841             }
00842         }
00843         if ($blSuccess || file_exists($sLocal)) {
00844             return $sLocal;
00845         }
00846 
00847         return false;
00848     }
00849 
00855     public function canPreview()
00856     {
00857         $blCan = null;
00858         if (($sPrevId = oxRegistry::getConfig()->getRequestParameter('preview')) &&
00859             ($sAdminSid = oxRegistry::get("oxUtilsServer")->getOxCookie('admin_sid'))
00860         ) {
00861 
00862             $sTable = getViewName('oxuser');
00863             $oDb = oxDb::getDb();
00864             $sQ = "select 1 from $sTable where MD5( CONCAT( " . $oDb->quote($sAdminSid) . ", {$sTable}.oxid, {$sTable}.oxpassword, {$sTable}.oxrights ) ) = " . oxDb::getDb()->quote($sPrevId);
00865             $blCan = (bool) $oDb->getOne($sQ);
00866         }
00867 
00868         return $blCan;
00869     }
00870 
00876     public function getPreviewId()
00877     {
00878         $sAdminSid = oxRegistry::get("oxUtilsServer")->getOxCookie('admin_sid');
00879         if (($oUser = $this->getUser())) {
00880             return md5($sAdminSid . $oUser->getId() . $oUser->oxuser__oxpassword->value . $oUser->oxuser__oxrights->value);
00881         }
00882     }
00883 
00889     public function checkAccessRights()
00890     {
00891         $myConfig = $this->getConfig();
00892 
00893         $blIsAuth = false;
00894 
00895         $sUserID = oxRegistry::getSession()->getVariable("auth");
00896 
00897         // deleting admin marker
00898         oxRegistry::getSession()->setVariable("malladmin", 0);
00899         oxRegistry::getSession()->setVariable("blIsAdmin", 0);
00900         oxRegistry::getSession()->deleteVariable("blIsAdmin");
00901         $myConfig->setConfigParam('blMallAdmin', false);
00902         //#1552T
00903         $myConfig->setConfigParam('blAllowInheritedEdit', false);
00904 
00905         if ($sUserID) {
00906             // escaping
00907             $oDb = oxDb::getDb();
00908             $sRights = $oDb->getOne("select oxrights from oxuser where oxid = " . $oDb->quote($sUserID));
00909 
00910             if ($sRights != "user") {
00911                 // malladmin ?
00912                 if ($sRights == "malladmin") {
00913                     oxRegistry::getSession()->setVariable("malladmin", 1);
00914                     $myConfig->setConfigParam('blMallAdmin', true);
00915 
00916                     //#1552T
00917                     //So far this blAllowSharedEdit is Equal to blMallAdmin but in future to be solved over rights and roles
00918                     $myConfig->setConfigParam('blAllowSharedEdit', true);
00919 
00920                     $sShop = oxRegistry::getSession()->getVariable("actshop");
00921                     if (!isset($sShop)) {
00922                         oxRegistry::getSession()->setVariable("actshop", $myConfig->getBaseShopId());
00923                     }
00924                     $blIsAuth = true;
00925                 } else {
00926                     // Shopadmin... check if this shop is valid and exists
00927                     $sShopID = $oDb->getOne("select oxid from oxshops where oxid = " . $oDb->quote($sRights));
00928                     if (isset($sShopID) && $sShopID) {
00929                         // success, this shop exists
00930 
00931                         oxRegistry::getSession()->setVariable("actshop", $sRights);
00932                         oxRegistry::getSession()->setVariable("currentadminshop", $sRights);
00933                         oxRegistry::getSession()->setVariable("shp", $sRights);
00934 
00935                         // check if this subshop admin is evil.
00936                         if ('chshp' == oxRegistry::getConfig()->getRequestParameter('fnc')) {
00937                             // dont allow this call
00938                             $blIsAuth = false;
00939                         } else {
00940                             $blIsAuth = true;
00941 
00942                             $aShopIdVars = array('actshop', 'shp', 'currentadminshop');
00943                             foreach ($aShopIdVars as $sShopIdVar) {
00944                                 if ($sGotShop = oxRegistry::getConfig()->getRequestParameter($sShopIdVar)) {
00945                                     if ($sGotShop != $sRights) {
00946                                         $blIsAuth = false;
00947                                         break;
00948                                     }
00949                                 }
00950                             }
00951                         }
00952                     }
00953                 }
00954                 // marking user as admin
00955                 oxRegistry::getSession()->setVariable("blIsAdmin", 1);
00956             }
00957         }
00958 
00959         return $blIsAuth;
00960     }
00961 
00971     public function seoIsActive($blReset = false, $sShopId = null, $iActLang = null)
00972     {
00973         if (!is_null($this->_blSeoIsActive) && !$blReset) {
00974             return $this->_blSeoIsActive;
00975         }
00976 
00977         $myConfig = $this->getConfig();
00978 
00979         if (($this->_blSeoIsActive = $myConfig->getConfigParam('blSeoMode')) === null) {
00980             $this->_blSeoIsActive = true;
00981 
00982             $aSeoModes = $myConfig->getconfigParam('aSeoModes');
00983             $sActShopId = $sShopId ? $sShopId : $myConfig->getActiveShop()->getId();
00984             $iActLang = $iActLang ? $iActLang : (int) oxRegistry::getLang()->getBaseLanguage();
00985 
00986             // checking special config param for active shop and language
00987             if (is_array($aSeoModes) && isset($aSeoModes[$sActShopId]) && isset($aSeoModes[$sActShopId][$iActLang])) {
00988                 $this->_blSeoIsActive = (bool) $aSeoModes[$sActShopId][$iActLang];
00989             }
00990         }
00991 
00992         return $this->_blSeoIsActive;
00993     }
00994 
01002     public function isValidAlpha($sField)
01003     {
01004         return (boolean) getStr()->preg_match('/^[a-zA-Z0-9_]*$/', $sField);
01005     }
01006 
01014     protected function _simpleRedirect($sUrl, $sHeaderCode)
01015     {
01016         $oHeader = oxNew("oxHeader");
01017         $oHeader->setHeader($sHeaderCode);
01018         $oHeader->setHeader("Location: $sUrl");
01019         $oHeader->setHeader("Connection: close");
01020         $oHeader->sendHeader();
01021     }
01022 
01028     public function redirectOffline($iHeaderCode = 302)
01029     {
01030         $sUrl = $this->getConfig()->getShopUrl() . 'offline.html';
01031         $this->redirect($sUrl, false, $iHeaderCode);
01032     }
01033 
01043     public function redirect($sUrl, $blAddRedirectParam = true, $iHeaderCode = 302)
01044     {
01045         //preventing possible cyclic redirection
01046         //#M341 and check only if redirect parameter must be added
01047         if ($blAddRedirectParam && oxRegistry::getConfig()->getRequestParameter('redirected')) {
01048             return;
01049         }
01050 
01051         if ($blAddRedirectParam) {
01052             $sUrl = $this->_addUrlParameters($sUrl, array('redirected' => 1));
01053         }
01054 
01055         $sUrl = str_ireplace("&amp;", "&", $sUrl);
01056 
01057         switch ($iHeaderCode) {
01058             case 301:
01059                 $sHeaderCode = "HTTP/1.1 301 Moved Permanently";
01060                 break;
01061             case 500:
01062                 $sHeaderCode = "HTTP/1.1 500 Internal Server Error";
01063                 break;
01064             case 302:
01065             default:
01066                 $sHeaderCode = "HTTP/1.1 302 Found";
01067         }
01068 
01069         $this->_simpleRedirect($sUrl, $sHeaderCode);
01070 
01071         try { //may occur in case db is lost
01072             $this->getSession()->freeze();
01073         } catch (oxException $oEx) {
01074             $oEx->debugOut();
01075             //do nothing else to make sure the redirect takes place
01076         }
01077 
01078         if (defined('OXID_PHP_UNIT')) {
01079             return;
01080         }
01081 
01082         $this->showMessageAndExit('');
01083     }
01084 
01093     public function showMessageAndExit($sMsg)
01094     {
01095         $this->getSession()->freeze();
01096         $this->commitFileCache();
01097 
01098         if (defined('OXID_PHP_UNIT')) {
01099             return;
01100         }
01101 
01102 
01103         exit($sMsg);
01104     }
01105 
01111     public function setHeader($sHeader)
01112     {
01113         header($sHeader);
01114     }
01115 
01124     protected function _addUrlParameters($sUrl, $aParams)
01125     {
01126         $sDelimiter = ((getStr()->strpos($sUrl, '?') !== false)) ? '&' : '?';
01127         foreach ($aParams as $sName => $sVal) {
01128             $sUrl = $sUrl . $sDelimiter . $sName . '=' . $sVal;
01129             $sDelimiter = '&';
01130         }
01131 
01132         return $sUrl;
01133     }
01134 
01146     protected function _fillExplodeArray($aName, $dVat = null)
01147     {
01148         $myConfig = $this->getConfig();
01149         $oObject = new stdClass();
01150         $aPrice = explode('!P!', $aName[0]);
01151 
01152         if (($myConfig->getConfigParam('bl_perfLoadSelectLists') && $myConfig->getConfigParam('bl_perfUseSelectlistPrice') && isset($aPrice[0]) && isset($aPrice[1])) || $this->isAdmin()) {
01153 
01154             // yes, price is there
01155             $oObject->price = isset($aPrice[1]) ? $aPrice[1] : 0;
01156             $aName[0] = isset($aPrice[0]) ? $aPrice[0] : '';
01157 
01158             $iPercPos = getStr()->strpos($oObject->price, '%');
01159             if ($iPercPos !== false) {
01160                 $oObject->priceUnit = '%';
01161                 $oObject->fprice = $oObject->price;
01162                 $oObject->price = substr($oObject->price, 0, $iPercPos);
01163             } else {
01164                 $oCur = $myConfig->getActShopCurrencyObject();
01165                 $oObject->price = str_replace(',', '.', $oObject->price);
01166                 $oObject->fprice = oxRegistry::getLang()->formatCurrency($oObject->price * $oCur->rate, $oCur);
01167                 $oObject->priceUnit = 'abs';
01168             }
01169 
01170             // add price info into list
01171             if (!$this->isAdmin() && $oObject->price != 0) {
01172                 $aName[0] .= " ";
01173 
01174                 $dPrice = $this->_preparePrice($oObject->price, $dVat);
01175 
01176                 if ($oObject->price > 0) {
01177                     $aName[0] .= "+";
01178                 }
01179                 //V FS#2616
01180                 if ($dVat != null && $oObject->priceUnit == 'abs') {
01181                     $oPrice = oxNew('oxPrice');
01182                     $oPrice->setPrice($oObject->price, $dVat);
01183                     $aName[0] .= oxRegistry::getLang()->formatCurrency($dPrice * $oCur->rate, $oCur);
01184                 } else {
01185                     $aName[0] .= $oObject->fprice;
01186                 }
01187                 if ($oObject->priceUnit == 'abs') {
01188                     $aName[0] .= " " . $oCur->sign;
01189                 }
01190             }
01191         } elseif (isset($aPrice[0]) && isset($aPrice[1])) {
01192             // A. removing unused part of information
01193             $aName[0] = getStr()->preg_replace("/!P!.*/", "", $aName[0]);
01194         }
01195 
01196         $oObject->name = $aName[0];
01197         $oObject->value = $aName[1];
01198 
01199         return $oObject;
01200     }
01201 
01210     protected function _preparePrice($dPrice, $dVat)
01211     {
01212         $blCalculationModeNetto = (bool) $this->getConfig()->getConfigParam('blShowNetPrice');
01213 
01214         $oCurrency = $this->getConfig()->getActShopCurrencyObject();
01215 
01216         $blEnterNetPrice = $this->getConfig()->getConfigParam('blEnterNetPrice');
01217         if ($blCalculationModeNetto && !$blEnterNetPrice) {
01218             $dPrice = round(oxPrice::brutto2Netto($dPrice, $dVat), $oCurrency->decimal);
01219         } elseif (!$blCalculationModeNetto && $blEnterNetPrice) {
01220             $dPrice = round(oxPrice::netto2Brutto($dPrice, $dVat), $oCurrency->decimal);
01221         }
01222 
01223         return $dPrice;
01224     }
01225 
01233     public function oxMimeContentType($sFileName)
01234     {
01235         $sFileName = strtolower($sFileName);
01236         $iLastDot = strrpos($sFileName, '.');
01237 
01238         if ($iLastDot !== false) {
01239             $sType = substr($sFileName, $iLastDot + 1);
01240             switch ($sType) {
01241                 case 'gif':
01242                     $sType = 'image/gif';
01243                     break;
01244                 case 'jpeg':
01245                 case 'jpg':
01246                     $sType = 'image/jpeg';
01247                     break;
01248                 case 'png':
01249                     $sType = 'image/png';
01250                     break;
01251                 default:
01252                     $sType = false;
01253                     break;
01254             }
01255         }
01256 
01257         return $sType;
01258     }
01259 
01266     public function logger($sText, $blNewline = false)
01267     {
01268         $myConfig = $this->getConfig();
01269 
01270         if ($myConfig->getConfigParam('iDebug') == -2) {
01271             if (gettype($sText) != 'string') {
01272                 $sText = var_export($sText, true);
01273             }
01274             $sLogMsg = "----------------------------------------------\n{$sText}" . (($blNewline) ? "\n" : "") . "\n";
01275             $this->writeToLog($sLogMsg, "log.txt");
01276         }
01277 
01278     }
01279 
01287     public function strRot13($sStr)
01288     {
01289         $sFrom = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
01290         $sTo = 'nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM';
01291 
01292         return strtr($sStr, $sFrom, $sTo);
01293     }
01294 
01304     public function getCacheFilePath($sCacheName, $blPathOnly = false, $sExtension = 'txt')
01305     {
01306 
01307         $sVersionPrefix = 'pe';
01308 
01309         $sPath = realpath($this->getConfig()->getConfigParam('sCompileDir'));
01310 
01311         if (!$sPath) {
01312             return false;
01313         }
01314 
01315         return $blPathOnly ? "{$sPath}/" : "{$sPath}/ox{$sVersionPrefix}c_{$sCacheName}." . $sExtension;
01316     }
01317 
01325     public function getLangCache($sCacheName)
01326     {
01327         $aLangCache = null;
01328         $sFilePath = $this->getCacheFilePath($sCacheName);
01329         if (file_exists($sFilePath) && is_readable($sFilePath)) {
01330             include $sFilePath;
01331         }
01332 
01333         return $aLangCache;
01334     }
01335 
01344     public function setLangCache($sCacheName, $aLangCache)
01345     {
01346         $sCache = "<?php\n\$aLangCache = " . var_export($aLangCache, true) . ";\n?>";
01347         $blRes = file_put_contents($this->getCacheFilePath($sCacheName), $sCache, LOCK_EX);
01348 
01349         return $blRes;
01350     }
01351 
01359     public function checkUrlEndingSlash($sUrl)
01360     {
01361         if (!getStr()->preg_match("/\/$/", $sUrl)) {
01362             $sUrl .= '/';
01363         }
01364 
01365         return $sUrl;
01366     }
01367 
01376     public function writeToLog($sLogMessage, $sLogFileName)
01377     {
01378         $sLogDist = $this->getConfig()->getLogsDir() . $sLogFileName;
01379         $blOk = false;
01380 
01381         if (($oHandle = fopen($sLogDist, 'a')) !== false) {
01382             fwrite($oHandle, $sLogMessage);
01383             $blOk = fclose($oHandle);
01384         }
01385 
01386         return $blOk;
01387     }
01388 
01394     public function handlePageNotFoundError($sUrl = '')
01395     {
01396         $this->setHeader("HTTP/1.0 404 Not Found");
01397         if (oxRegistry::getConfig()->isUtf()) {
01398             $this->setHeader("Content-Type: text/html; charset=UTF-8");
01399         }
01400 
01401         $sReturn = "Page not found.";
01402         try {
01403             $oView = oxNew('oxUBase');
01404             $oView->init();
01405             $oView->render();
01406             $oView->setClassName('oxUBase');
01407             $oView->addTplParam('sUrl', $sUrl);
01408             if ($sRet = oxRegistry::get("oxUtilsView")->getTemplateOutput('message/err_404.tpl', $oView)) {
01409                 $sReturn = $sRet;
01410             }
01411         } catch (Exception $e) {
01412         }
01413         $this->showMessageAndExit($sReturn);
01414     }
01415 
01423     public function extractDomain($sHost)
01424     {
01425         $oStr = getStr();
01426         if (!$oStr->preg_match('/[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}/', $sHost) &&
01427             ($iLastDot = strrpos($sHost, '.')) !== false
01428         ) {
01429             $iLen = $oStr->strlen($sHost);
01430             if (($iNextDot = strrpos($sHost, '.', ($iLen - $iLastDot + 1) * -1)) !== false) {
01431                 $sHost = trim($oStr->substr($sHost, $iNextDot), '.');
01432             }
01433         }
01434 
01435         return $sHost;
01436     }
01437 }