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 {
00019     protected $_iCurPrecision = null;
00020 
00028     protected $_sPermanentCachePattern = "/c_fieldnames_|c_tbdsc_|_allfields_/";
00029 
00035     protected $_sLanguageCachePattern = "/c_langcache_/i";
00036 
00042     protected $_sMenuCachePattern = "/c_menu_/i";
00043 
00049     protected $_aLockedFileHandles = array();
00050 
00056     protected $_aFileCacheContents = array();
00057 
00063     protected $_blIsSe = null;
00064 
00072     public static function getInstance()
00073     {
00074         return oxRegistry::getUtils();
00075     }
00076 
00082     protected $_aStaticCache;
00083 
00089     protected $_blSeoIsActive = null;
00090 
00096     public function stripGpcMagicQuotes()
00097     {
00098         if (!get_magic_quotes_gpc()) {
00099             return;
00100         }
00101         $_REQUEST = self::_stripQuotes($_REQUEST);
00102         $_POST = self::_stripQuotes($_POST);
00103         $_GET = self::_stripQuotes($_GET);
00104         $_COOKIE = self::_stripQuotes($_COOKIE);
00105     }
00106 
00117     public function strMan( $sVal, $sKey = null )
00118     {
00119         $oEncryptor = oxNew('oxEncryptor');
00120         $sKey = $sKey ? $sKey : $this->getConfig()->getConfigParam('sConfigKey');
00121 
00122         return $oEncryptor->encrypt($sVal, $sKey);
00123     }
00124 
00135     public function strRem( $sVal, $sKey = null )
00136     {
00137         $oDecryptor = oxNew('oxDecryptor');
00138         $sKey = $sKey ? $sKey : $this->getConfig()->getConfigParam('sConfigKey');
00139 
00140         return $oDecryptor->decrypt($sVal, $sKey);
00141     }
00142 
00150     public function getArrFldName( $sName )
00151     {
00152         return str_replace( ".", "__", $sName);
00153     }
00154 
00163     public function assignValuesFromText( $sIn, $dVat = null )
00164     {
00165         $aRet = array();
00166         $aPieces = explode( '@@', $sIn );
00167         while ( list( $sKey, $sVal ) = each( $aPieces ) ) {
00168             if ( $sVal ) {
00169                 $aName = explode( '__', $sVal );
00170                 if ( isset( $aName[0] ) && isset( $aName[1] ) ) {
00171                     $aRet[] = $this->_fillExplodeArray( $aName, $dVat );
00172                 }
00173             }
00174         }
00175         return $aRet;
00176     }
00177 
00185     public function assignValuesToText( $aIn)
00186     {
00187         $sRet = "";
00188         reset( $aIn );
00189         while (list($sKey, $sVal) = each($aIn)) {
00190             $sRet .= $sKey;
00191             $sRet .= "__";
00192             $sRet .= $sVal;
00193             $sRet .= "@@";
00194         }
00195         return $sRet;
00196     }
00197 
00205     public function currency2Float( $sValue)
00206     {
00207         $fRet = $sValue;
00208         $iPos = strrpos( $sValue, ".");
00209         if ($iPos && ((strlen($sValue)-1-$iPos) < 2+1)) {
00210             // replace decimal with ","
00211             $fRet = substr_replace( $fRet, ",", $iPos, 1);
00212         }
00213         // remove thousands
00214         $fRet = str_replace( array(" ","."), "", $fRet);
00215 
00216         $fRet = str_replace( ",", ".", $fRet);
00217         return (float) $fRet;
00218     }
00219 
00227     public function string2Float( $sValue)
00228     {
00229         $fRet = str_replace( " ", "", $sValue);
00230         $iCommaPos = strpos( $fRet, ",");
00231         $iDotPos = strpos( $fRet, ".");
00232         if (!$iDotPos xor !$iCommaPos) {
00233             if (substr_count( $fRet, ",") > 1 || substr_count( $fRet, ".") > 1) {
00234                 $fRet = str_replace( array(",","."), "", $fRet);
00235             } else {
00236                 $fRet = str_replace( ",", ".", $fRet);
00237             }
00238         } else if ( $iDotPos < $iCommaPos ) {
00239             $fRet = str_replace( ".", "", $fRet);
00240             $fRet = str_replace( ",", ".", $fRet);
00241         }
00242         // remove thousands
00243         $fRet = str_replace( array(" ",","), "", $fRet);
00244         return (float) $fRet;
00245     }
00246 
00254     public function isSearchEngine( $sClient = null )
00255     {
00256         if (is_null($this->_blIsSe)) {
00257             $this->setSearchEngine( null, $sClient );
00258         }
00259         return $this->_blIsSe;
00260     }
00261 
00270     public function setSearchEngine( $blIsSe = null, $sClient = null )
00271     {
00272         if (isset($blIsSe)) {
00273             $this->_blIsSe = $blIsSe;
00274             return;
00275         }
00276         startProfile("isSearchEngine");
00277 
00278         $myConfig = $this->getConfig();
00279         $blIsSe   = false;
00280 
00281         if ( !( $myConfig->getConfigParam( 'iDebug' ) && $this->isAdmin() ) ) {
00282             $aRobots = $myConfig->getConfigParam( 'aRobots' );
00283             $aRobots = is_array( $aRobots )?$aRobots:array();
00284 
00285             $aRobotsExcept = $myConfig->getConfigParam( 'aRobotsExcept' );
00286             $aRobotsExcept = is_array( $aRobotsExcept )?$aRobotsExcept:array();
00287 
00288             $sClient = $sClient?$sClient:strtolower( getenv( 'HTTP_USER_AGENT' ) );
00289             $blIsSe  = false;
00290             $aRobots = array_merge( $aRobots, $aRobotsExcept );
00291             foreach ( $aRobots as $sRobot ) {
00292                 if ( strpos( $sClient, $sRobot ) !== false ) {
00293                     $blIsSe = true;
00294                     break;
00295                 }
00296             }
00297         }
00298 
00299         $this->_blIsSe = $blIsSe;
00300 
00301         stopProfile("isSearchEngine");
00302     }
00303 
00312     public function isValidEmail( $sEmail )
00313     {
00314         $blValid = true;
00315         if ( $sEmail != 'admin' ) {
00316             $sEmailTpl = "/^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/i";
00317             $blValid = ( getStr()->preg_match( $sEmailTpl, $sEmail ) != 0 );
00318         }
00319 
00320         return $blValid;
00321     }
00322 
00330     public function loadAdminProfile($aInterfaceProfiles)
00331     {
00332         // improved #533
00333         // checking for available profiles list
00334         if ( is_array( $aInterfaceProfiles ) ) {
00335             //checking for previous profiles
00336             $sPrevProfile = oxRegistry::get("oxUtilsServer")->getOxCookie('oxidadminprofile');
00337             if (isset($sPrevProfile)) {
00338                 $aPrevProfile = @explode("@", trim($sPrevProfile));
00339             }
00340 
00341             //array to store profiles
00342             $aProfiles = array();
00343             foreach ( $aInterfaceProfiles as $iPos => $sProfile) {
00344                 $aProfileSettings = array($iPos, $sProfile);
00345                 $aProfiles[] = $aProfileSettings;
00346             }
00347             // setting previous used profile as active
00348             if (isset($aPrevProfile[0]) && isset($aProfiles[$aPrevProfile[0]])) {
00349                 $aProfiles[$aPrevProfile[0]][2] = 1;
00350             }
00351 
00352             oxSession::setVar("aAdminProfiles", $aProfiles);
00353             return $aProfiles;
00354         }
00355         return null;
00356     }
00357 
00366     public function fRound($sVal, $oCur = null)
00367     {
00368         startProfile('fround');
00369 
00370         //cached currency precision, this saves about 1% of execution time
00371         $iCurPrecision = null;
00372         if (! defined('OXID_PHP_UNIT')) {
00373             $iCurPrecision = $this->_iCurPrecision;
00374         }
00375 
00376         if (is_null($iCurPrecision)) {
00377             if ( !$oCur ) {
00378                 $oCur = $this->getConfig()->getActShopCurrencyObject();
00379             }
00380 
00381             $iCurPrecision = $oCur->decimal;
00382             $this->_iCurPrecision = $iCurPrecision;
00383         }
00384 
00385         // if < 5.3.x this is a workaround for #36008 bug in php - incorrect round() & number_format() result (R)
00386         static $dprez = null;
00387         if (!$dprez) {
00388             $prez = @ini_get("precision");
00389             if (!$prez || $prez > 12 ) {
00390                $prez = 12;
00391             }
00392             $dprez = pow(10, -$prez);
00393         }
00394         stopProfile('fround');
00395         return round($sVal + $dprez * ( $sVal >= 0 ? 1 : -1 ), $iCurPrecision);
00396     }
00397 
00407     public function toStaticCache( $sName, $sContent, $sKey = null )
00408     {
00409         // if it's an array then we add
00410         if ( $sKey ) {
00411             $this->_aStaticCache[$sName][$sKey] = $sContent;
00412         } else {
00413             $this->_aStaticCache[$sName] = $sContent;
00414         }
00415     }
00416 
00424     public function fromStaticCache( $sName)
00425     {
00426         if ( isset( $this->_aStaticCache[$sName])) {
00427             return $this->_aStaticCache[$sName];
00428         }
00429         return null;
00430     }
00431 
00439     public function cleanStaticCache($sCacheName = null)
00440     {
00441         if ($sCacheName) {
00442             unset($this->_aStaticCache[$sCacheName]);
00443         } else {
00444             $this->_aStaticCache = null;
00445         }
00446     }
00447 
00457     public function toPhpFileCache( $sKey, $mContents )
00458     {
00459         //only simple arrays are supported
00460         if ( is_array( $mContents ) && ( $sCachePath = $this->getCacheFilePath( $sKey, false, 'php' ) ) ) {
00461 
00462             // setting meta
00463             $this->setCacheMeta( $sKey, array( "serialize" => false, "cachepath" => $sCachePath ) );
00464 
00465             // caching..
00466             $this->toFileCache( $sKey, $mContents );
00467         }
00468     }
00469 
00477     public function fromPhpFileCache( $sKey )
00478     {
00479         // setting meta
00480         $this->setCacheMeta( $sKey, array( "include" => true, "cachepath" => $this->getCacheFilePath( $sKey, false, 'php' ) ) );
00481         return $this->fromFileCache( $sKey );
00482     }
00483 
00491     public function getCacheMeta( $sKey )
00492     {
00493         return isset( $this->_aFileCacheMeta[$sKey] ) ? $this->_aFileCacheMeta[$sKey] : false;
00494     }
00495 
00504     public function setCacheMeta( $sKey, $aMeta )
00505     {
00506         // cache meta data
00507         $this->_aFileCacheMeta[$sKey] = $aMeta;
00508     }
00509 
00520     public function toFileCache( $sKey, $mContents, $iTtl = 0 )
00521     {
00522         $aCacheData['content'] = $mContents;
00523         $aMeta = $this->getCacheMeta( $sKey );
00524         if ( $iTtl ) {
00525             $aCacheData['ttl'] = $iTtl;
00526             $aCacheData['timestamp'] = oxRegistry::get("oxUtilsDate")->getTime();
00527         }
00528         $this->_aFileCacheContents[$sKey] = $aCacheData;
00529 
00530         // looking for cache meta
00531         $sCachePath = isset( $aMeta["cachepath"] ) ? $aMeta["cachepath"] : $this->getCacheFilePath( $sKey );
00532         return ( bool ) $this->_lockFile( $sCachePath, $sKey );
00533     }
00534 
00542     public function fromFileCache( $sKey )
00543     {
00544         if ( !array_key_exists( $sKey, $this->_aFileCacheContents ) ) {
00545             $sRes = null;
00546 
00547             $aMeta = $this->getCacheMeta( $sKey );
00548             $blInclude  = isset( $aMeta["include"] ) ? $aMeta["include"] : false;
00549             $sCachePath = isset( $aMeta["cachepath"] ) ? $aMeta["cachepath"] : $this->getCacheFilePath( $sKey );
00550 
00551             // trying to lock
00552             $this->_lockFile( $sCachePath, $sKey, LOCK_SH );
00553 
00554             clearstatcache();
00555             if ( is_readable( $sCachePath ) ) {
00556                 $sRes = $blInclude ? $this->_includeFile( $sCachePath ) : $this->_readFile( $sCachePath );
00557             }
00558 
00559             if ( isset( $sRes['ttl'] ) && $sRes['ttl'] != 0 ) {
00560                 $iTimestamp = $sRes['timestamp'];
00561                 $iTtl = $sRes['ttl'];
00562 
00563                 $iTime = oxRegistry::get("oxUtilsDate")->getTime();
00564                 if ( $iTime > $iTimestamp + $iTtl ) {
00565                     return null;
00566                 }
00567             }
00568             // release lock
00569             $this->_releaseFile( $sKey, LOCK_SH );
00570 
00571             // caching
00572             $this->_aFileCacheContents[$sKey] = $sRes;
00573         }
00574 
00575         return $this->_aFileCacheContents[$sKey]['content'];
00576     }
00577 
00585     protected function _readFile( $sFilePath )
00586     {
00587         $sRes = file_get_contents( $sFilePath );
00588         return $sRes ? unserialize( $sRes ) : null;
00589     }
00590 
00598     protected function _includeFile( $sFilePath )
00599     {
00600         $_aCacheContents = null;
00601         include $sFilePath;
00602         return $_aCacheContents;
00603     }
00604 
00613     protected function _processCache( $sKey, $mContents )
00614     {
00615         // looking for cache meta
00616         $aCacheMeta  = $this->getCacheMeta( $sKey );
00617         $blSerialize = isset( $aCacheMeta["serialize"] ) ? $aCacheMeta["serialize"] : true;
00618 
00619         if ( $blSerialize ) {
00620             $mContents = serialize( $mContents );
00621         } else {
00622             $mContents = "<?php\n//automatically generated file\n//" . date( "Y-m-d H:i:s" ) . "\n\n\$_aCacheContents = " . var_export( $mContents, true ) . "\n?>";
00623         }
00624 
00625         return $mContents;
00626     }
00627 
00634     public function commitFileCache()
00635     {
00636         if ( count( $this->_aLockedFileHandles[LOCK_EX] ) ) {
00637             startProfile("!__SAVING CACHE__! (warning)");
00638             foreach ( $this->_aLockedFileHandles[LOCK_EX] as $sKey => $rHandle ) {
00639                 if ( $rHandle !== false && isset( $this->_aFileCacheContents[$sKey] ) ) {
00640 
00641                     // #0002931A truncate file once more before writing
00642                     ftruncate( $rHandle, 0 );
00643 
00644                     // writing cache
00645                     fwrite( $rHandle, $this->_processCache( $sKey, $this->_aFileCacheContents[$sKey] ) );
00646 
00647                     // releasing locks
00648                     $this->_releaseFile( $sKey );
00649                 }
00650             }
00651 
00652             stopProfile("!__SAVING CACHE__! (warning)");
00653 
00654             //empty buffer
00655             $this->_aFileCacheContents = array();
00656         }
00657     }
00658 
00668     protected function _lockFile( $sFilePath, $sIdent, $iLockMode = LOCK_EX )
00669     {
00670         $rHandle = isset( $this->_aLockedFileHandles[$iLockMode][$sIdent] ) ? $this->_aLockedFileHandles[$iLockMode][$sIdent] : null;
00671         if ( $rHandle === null ) {
00672 
00673             $blLocked = false;
00674             $rHandle = @fopen( $sFilePath, "a+" );
00675 
00676             if ( $rHandle !== false ) {
00677 
00678                 if ( flock( $rHandle, $iLockMode | LOCK_NB ) ) {
00679                     if ( $iLockMode === LOCK_EX ) {
00680                         // truncate file
00681                         $blLocked = ftruncate( $rHandle, 0 );
00682                     } else {
00683                         // move to a start position
00684                         $blLocked = fseek( $rHandle, 0 ) === 0;
00685                     }
00686                 }
00687 
00688                 // on failure - closing and setting false..
00689                 if ( !$blLocked ) {
00690                     fclose( $rHandle );
00691                     $rHandle = false;
00692                 }
00693             }
00694 
00695             // in case system does not support file locking
00696             if ( !$blLocked && $iLockMode === LOCK_EX ) {
00697 
00698                 // clearing on first call
00699                 if ( count( $this->_aLockedFileHandles ) == 0 ) {
00700                     clearstatcache();
00701                 }
00702 
00703                 // start a blank file to inform other processes we are dealing with it.
00704                 if (!( file_exists( $sFilePath ) && !filesize( $sFilePath ) && abs( time() - filectime( $sFilePath ) < 40 ) ) ) {
00705                     $rHandle = @fopen( $sFilePath, "w" );
00706                 }
00707             }
00708 
00709             $this->_aLockedFileHandles[$iLockMode][$sIdent] = $rHandle;
00710         }
00711 
00712         return $rHandle;
00713     }
00714 
00723     protected function _releaseFile( $sIdent, $iLockMode = LOCK_EX )
00724     {
00725         $blSuccess = true;
00726         if ( isset( $this->_aLockedFileHandles[$iLockMode][$sIdent] ) &&
00727              $this->_aLockedFileHandles[$iLockMode][$sIdent] !== false ) {
00728 
00729              // release the lock and close file
00730             $blSuccess = flock( $this->_aLockedFileHandles[$iLockMode][$sIdent], LOCK_UN ) &&
00731                          fclose( $this->_aLockedFileHandles[$iLockMode][$sIdent] );
00732             unset( $this->_aLockedFileHandles[$iLockMode][$sIdent] );
00733         }
00734 
00735         return $blSuccess;
00736     }
00737 
00745     public function oxResetFileCache()
00746     {
00747         $aFiles = glob( $this->getCacheFilePath( null, true ) . '*' );
00748         if ( is_array( $aFiles ) ) {
00749             // delete all the files, except cached tables field names
00750             $aFiles = preg_grep( $this->_sPermanentCachePattern, $aFiles, PREG_GREP_INVERT );
00751             foreach ( $aFiles as $sFile ) {
00752                 @unlink( $sFile );
00753             }
00754         }
00755     }
00756 
00764     public function resetTemplateCache($aTemplates)
00765     {
00766         $sSmartyDir = oxRegistry::get("oxUtilsView")->getSmartyDir();
00767         //$aFiles = glob( $this->getCacheFilePath( null, true ) . '*' );
00768         $aFiles = glob( $sSmartyDir . '*' );
00769 
00770         if ( is_array( $aFiles ) && is_array( $aTemplates ) && count($aTemplates) ) {
00771             // delete all template cache files
00772             foreach ($aTemplates as &$sTemplate) {
00773                 $sTemplate = preg_quote(basename(strtolower($sTemplate), '.tpl'));
00774             }
00775 
00776             $sPattern = sprintf("/%%(%s)\.tpl\.php$/i", implode('|', $aTemplates));
00777             $aFiles = preg_grep( $sPattern, $aFiles );
00778 
00779             if (is_array( $aFiles ) ) {
00780                 foreach ( $aFiles as $sFile ) {
00781                     @unlink( $sFile );
00782                 }
00783             }
00784         }
00785 
00786     }
00787 
00793     public function resetLanguageCache()
00794     {
00795         $aFiles = glob( $this->getCacheFilePath( null, true ) . '*' );
00796         if ( is_array( $aFiles ) ) {
00797             // delete all language cache files
00798             $sPattern = $this->_sLanguageCachePattern;
00799             $aFiles = preg_grep( $sPattern, $aFiles );
00800             foreach ( $aFiles as $sFile ) {
00801                 @unlink( $sFile );
00802             }
00803         }
00804     }
00805 
00811     public function resetMenuCache()
00812     {
00813         $aFiles = glob( $this->getCacheFilePath( null, true ) . '*' );
00814         if ( is_array( $aFiles ) ) {
00815             // delete all menu cache files
00816             $sPattern = $this->_sMenuCachePattern;
00817             $aFiles = preg_grep( $sPattern, $aFiles );
00818             foreach ( $aFiles as $sFile ) {
00819                 @unlink( $sFile );
00820             }
00821         }
00822     }
00823 
00833     public function getRemoteCachePath($sRemote, $sLocal)
00834     {
00835         clearstatcache();
00836         if ( file_exists( $sLocal ) && filemtime( $sLocal ) && filemtime( $sLocal ) > time() - 86400 ) {
00837             return $sLocal;
00838         }
00839         $hRemote = @fopen( $sRemote, "rb");
00840         $blSuccess = false;
00841         if ( isset( $hRemote) && $hRemote ) {
00842             $hLocal = fopen( $sLocal, "wb");
00843             stream_copy_to_stream($hRemote, $hLocal);
00844             fclose($hRemote);
00845             fclose($hLocal);
00846             $blSuccess = true;
00847         } else {
00848             // try via fsockopen
00849             $aUrl = @parse_url( $sRemote);
00850             if ( !empty( $aUrl["host"])) {
00851                 $sPath = $aUrl["path"];
00852                 if ( empty( $sPath ) ) {
00853                     $sPath = "/";
00854                 }
00855                 $sHost = $aUrl["host"];
00856 
00857                 $hSocket = @fsockopen( $sHost, 80, $iErrorNumber, $iErrStr, 5);
00858                 if ( $hSocket) {
00859                     fputs( $hSocket, "GET ".$sPath." HTTP/1.0\r\nHost: $sHost\r\n\r\n");
00860                     $headers = stream_get_line($hSocket, 4096, "\r\n\r\n");
00861                     if ( ( $hLocal = @fopen( $sLocal, "wb") ) !== false ) {
00862                         rewind($hLocal);
00863                         // does not copy all the data
00864                         // stream_copy_to_stream($hSocket, $hLocal);
00865                         fwrite ( $hLocal, stream_get_contents( $hSocket ) );
00866                         fclose( $hLocal );
00867                         fclose( $hSocket );
00868                         $blSuccess = true;
00869                     }
00870                 }
00871             }
00872         }
00873         if ( $blSuccess || file_exists( $sLocal ) ) {
00874             return $sLocal;
00875         }
00876         return false;
00877     }
00878 
00884     public function canPreview()
00885     {
00886         $blCan = null;
00887         if ( ( $sPrevId = oxConfig::getParameter( 'preview' ) ) &&
00888              ( $sAdminSid = oxRegistry::get("oxUtilsServer")->getOxCookie( 'admin_sid' ) ) ) {
00889 
00890             $sTable = getViewName( 'oxuser' );
00891             $oDb = oxDb::getDb();
00892             $sQ = "select 1 from $sTable where MD5( CONCAT( ".$oDb->quote($sAdminSid).", {$sTable}.oxid, {$sTable}.oxpassword, {$sTable}.oxrights ) ) = ".oxDb::getDb()->quote($sPrevId);
00893             $blCan = (bool) $oDb->getOne( $sQ );
00894         }
00895 
00896         return $blCan;
00897     }
00898 
00904     public function getPreviewId()
00905     {
00906         $sAdminSid = oxRegistry::get("oxUtilsServer")->getOxCookie( 'admin_sid' );
00907         if ( ( $oUser = $this->getUser() ) ) {
00908             return md5( $sAdminSid . $oUser->getId() . $oUser->oxuser__oxpassword->value . $oUser->oxuser__oxrights->value );
00909         }
00910     }
00911 
00917     public function checkAccessRights()
00918     {
00919         $myConfig  = $this->getConfig();
00920 
00921         $blIsAuth = false;
00922 
00923         $sUserID = oxSession::getVar( "auth");
00924 
00925         // deleting admin marker
00926         oxSession::setVar( "malladmin", 0);
00927         oxSession::setVar( "blIsAdmin", 0);
00928         oxSession::deleteVar( "blIsAdmin" );
00929         $myConfig->setConfigParam( 'blMallAdmin', false );
00930         //#1552T
00931         $myConfig->setConfigParam( 'blAllowInheritedEdit', false );
00932 
00933         if ( $sUserID) {
00934             // escaping
00935             $oDb = oxDb::getDb();
00936             $sRights = $oDb->getOne("select oxrights from oxuser where oxid = ".$oDb->quote($sUserID));
00937 
00938             if ( $sRights != "user") {
00939                 // malladmin ?
00940                 if ( $sRights == "malladmin") {
00941                     oxSession::setVar( "malladmin", 1);
00942                     $myConfig->setConfigParam( 'blMallAdmin', true );
00943 
00944                     //#1552T
00945                     //So far this blAllowSharedEdit is Equal to blMallAdmin but in future to be solved over rights and roles
00946                     $myConfig->setConfigParam( 'blAllowSharedEdit', true );
00947 
00948                     $sShop = oxSession::getVar( "actshop");
00949                     if ( !isset($sShop)) {
00950                         oxSession::setVar( "actshop", $myConfig->getBaseShopId());
00951                     }
00952                     $blIsAuth = true;
00953                 } else {
00954                     // Shopadmin... check if this shop is valid and exists
00955                     $sShopID = $oDb->getOne("select oxid from oxshops where oxid = " . $oDb->quote( $sRights ) );
00956                     if ( isset( $sShopID) && $sShopID) {
00957                         // success, this shop exists
00958 
00959                         oxSession::setVar( "actshop", $sRights);
00960                         oxSession::setVar( "currentadminshop", $sRights);
00961                         oxSession::setVar( "shp", $sRights);
00962 
00963                         // check if this subshop admin is evil.
00964                         if ('chshp' == oxConfig::getParameter( 'fnc' )) {
00965                             // dont allow this call
00966                             $blIsAuth = false;
00967                         } else {
00968                             $blIsAuth = true;
00969 
00970                             $aShopIdVars = array('actshop', 'shp', 'currentadminshop');
00971                             foreach ($aShopIdVars as $sShopIdVar) {
00972                                 if ($sGotShop = oxConfig::getParameter( $sShopIdVar )) {
00973                                     if ($sGotShop != $sRights) {
00974                                         $blIsAuth = false;
00975                                         break;
00976                                     }
00977                                 }
00978                             }
00979                         }
00980                     }
00981                 }
00982                 // marking user as admin
00983                 oxSession::setVar( "blIsAdmin", 1);
00984             }
00985         }
00986         return $blIsAuth;
00987     }
00988 
00998     public function seoIsActive( $blReset = false, $sShopId = null, $iActLang = null )
00999     {
01000         if ( !is_null( $this->_blSeoIsActive ) && !$blReset ) {
01001             return $this->_blSeoIsActive;
01002         }
01003 
01004         $myConfig = $this->getConfig();
01005 
01006         if ( ( $this->_blSeoIsActive = $myConfig->getConfigParam( 'blSeoMode' ) ) === null ) {
01007             $this->_blSeoIsActive = true;
01008 
01009             $aSeoModes  = $myConfig->getconfigParam( 'aSeoModes' );
01010             $sActShopId = $sShopId ? $sShopId : $myConfig->getActiveShop()->getId();
01011             $iActLang   = $iActLang ? $iActLang : (int) oxRegistry::getLang()->getBaseLanguage();
01012 
01013             // checking special config param for active shop and language
01014             if ( is_array( $aSeoModes ) && isset( $aSeoModes[$sActShopId] ) && isset( $aSeoModes[$sActShopId][$iActLang] ) ) {
01015                 $this->_blSeoIsActive = (bool) $aSeoModes[$sActShopId][$iActLang];
01016             }
01017         }
01018 
01019         return $this->_blSeoIsActive;
01020     }
01021 
01029     public function isValidAlpha( $sField )
01030     {
01031         return (boolean) getStr()->preg_match( '/^[a-zA-Z0-9_]*$/', $sField );
01032     }
01033 
01043     protected function _simpleRedirect( $sUrl, $sHeaderCode )
01044     {
01045         $oHeader = oxNew( "oxHeader" );
01046         $oHeader->setHeader( $sHeaderCode );
01047         $oHeader->setHeader( "Location: $sUrl" );
01048         $oHeader->setHeader( "Connection: close" );
01049         $oHeader->sendHeader();
01050     }
01051 
01057     public function redirectOffline($iHeaderCode = 302)
01058     {
01059         $sUrl = $this->getConfig()->getShopUrl() .'offline.html';
01060         $this->redirect($sUrl, false, $iHeaderCode);
01061     }
01062 
01072     public function redirect( $sUrl, $blAddRedirectParam = true, $iHeaderCode = 302 )
01073     {
01074         //preventing possible cyclic redirection
01075         //#M341 and check only if redirect parameter must be added
01076         if ( $blAddRedirectParam && oxConfig::getParameter( 'redirected' ) ) {
01077             return;
01078         }
01079 
01080         if ( $blAddRedirectParam ) {
01081             $sUrl = $this->_addUrlParameters( $sUrl, array( 'redirected' => 1 ) );
01082         }
01083 
01084         $sUrl = str_ireplace( "&amp;", "&", $sUrl );
01085 
01086         switch ($iHeaderCode) {
01087             case 301:
01088                 $sHeaderCode = "HTTP/1.1 301 Moved Permanently";
01089                 break;
01090             case 500:
01091                 $sHeaderCode = "HTTP/1.1 500 Internal Server Error";
01092                 break;
01093             case 302:
01094             default:
01095                 $sHeaderCode = "HTTP/1.1 302 Found";
01096         }
01097 
01098         $this->_simpleRedirect( $sUrl, $sHeaderCode );
01099 
01100         try {//may occur in case db is lost
01101             $this->getSession()->freeze();
01102         } catch( oxException $oEx ) {
01103             $oEx->debugOut();
01104             //do nothing else to make sure the redirect takes place
01105         }
01106 
01107         if ( defined( 'OXID_PHP_UNIT' ) ) {
01108             return;
01109         }
01110 
01111         $this->showMessageAndExit( '' );
01112     }
01113 
01122     public function showMessageAndExit( $sMsg )
01123     {
01124         $this->getSession()->freeze();
01125         $this->commitFileCache();
01126 
01127         if ( defined( 'OXID_PHP_UNIT' ) ) {
01128             return;
01129         }
01130 
01131 
01132         exit( $sMsg );
01133     }
01134 
01142     public function setHeader($sHeader)
01143     {
01144         header($sHeader);
01145     }
01146 
01155     protected function _addUrlParameters( $sUrl, $aParams )
01156     {
01157         $sDelimiter = ( ( getStr()->strpos( $sUrl, '?' ) !== false ) )?'&':'?';
01158         foreach ( $aParams as $sName => $sVal ) {
01159             $sUrl = $sUrl . $sDelimiter . $sName . '=' . $sVal;
01160             $sDelimiter = '&';
01161         }
01162 
01163         return $sUrl;
01164     }
01165 
01177     protected function _fillExplodeArray( $aName, $dVat = null)
01178     {
01179         $myConfig = $this->getConfig();
01180         $oObject = new stdClass();
01181         $aPrice = explode( '!P!', $aName[0]);
01182 
01183         if ( ( $myConfig->getConfigParam( 'bl_perfLoadSelectLists' ) && $myConfig->getConfigParam( 'bl_perfUseSelectlistPrice' ) && isset( $aPrice[0] ) && isset( $aPrice[1] ) ) || $this->isAdmin() ) {
01184 
01185             // yes, price is there
01186             $oObject->price = isset( $aPrice[1] ) ? $aPrice[1] : 0;
01187             $aName[0] = isset( $aPrice[0] ) ? $aPrice[0] : '';
01188 
01189             $iPercPos = getStr()->strpos( $oObject->price, '%' );
01190             if ( $iPercPos !== false ) {
01191                 $oObject->priceUnit = '%';
01192                 $oObject->fprice = $oObject->price;
01193                 $oObject->price  = substr( $oObject->price, 0, $iPercPos );
01194             } else {
01195                 $oCur = $myConfig->getActShopCurrencyObject();
01196                 $oObject->price = str_replace(',', '.', $oObject->price);
01197                 $oObject->fprice = oxRegistry::getLang()->formatCurrency( $oObject->price  * $oCur->rate, $oCur);
01198                 $oObject->priceUnit = 'abs';
01199             }
01200 
01201             // add price info into list
01202             if ( !$this->isAdmin() && $oObject->price != 0 ) {
01203                 $aName[0] .= " ";
01204 
01205                 $dPrice = $this->_preparePrice( $oObject->price, $dVat );
01206 
01207                 if ( $oObject->price > 0 ) {
01208                     $aName[0] .= "+";
01209                 }
01210                 //V FS#2616
01211                 if ( $dVat != null && $oObject->priceUnit == 'abs' ) {
01212                     $oPrice = oxNew('oxPrice');
01213                     $oPrice->setPrice($oObject->price, $dVat);
01214                     $aName[0] .= oxRegistry::getLang()->formatCurrency( $dPrice * $oCur->rate, $oCur);
01215                 } else {
01216                     $aName[0] .= $oObject->fprice;
01217                 }
01218                 if ( $oObject->priceUnit == 'abs' ) {
01219                     $aName[0] .= " ".$oCur->sign;
01220                 }
01221             }
01222         } elseif ( isset( $aPrice[0] ) && isset($aPrice[1] ) ) {
01223             // A. removing unused part of information
01224             $aName[0] = getStr()->preg_replace( "/!P!.*/", "", $aName[0] );
01225         }
01226 
01227         $oObject->name  = $aName[0];
01228         $oObject->value = $aName[1];
01229         return $oObject;
01230     }
01231 
01240     protected function _preparePrice( $dPrice, $dVat )
01241     {
01242         $blCalculationModeNetto = $this->_isPriceViewModeNetto();
01243 
01244         $oCurrency = $this->getConfig()->getActShopCurrencyObject();
01245 
01246         $blEnterNetPrice = $this->getConfig()->getConfigParam('blEnterNetPrice');
01247         if ( $blCalculationModeNetto && !$blEnterNetPrice ) {
01248             $dPrice = round( oxPrice::brutto2Netto( $dPrice, $dVat ), $oCurrency->decimal );
01249         } elseif ( !$blCalculationModeNetto && $blEnterNetPrice ) {
01250             $dPrice = round( oxPrice::netto2Brutto( $dPrice, $dVat ), $oCurrency->decimal );
01251         }
01252 
01253         return $dPrice;
01254     }
01255 
01261     protected function _isPriceViewModeNetto()
01262     {
01263         $blResult = (bool) $this->getConfig()->getConfigParam('blShowNetPrice');
01264         $oUser = $this->_getArticleUser();
01265         if ($oUser) {
01266             $blResult = $oUser->isPriceViewModeNetto();
01267         }
01268 
01269         return $blResult;
01270     }
01271 
01277     protected function _getArticleUser()
01278     {
01279         if ($this->_oUser) {
01280             return $this->_oUser;
01281         }
01282 
01283         return $this->getUser();
01284     }
01285 
01293     public function oxMimeContentType( $sFileName )
01294     {
01295         $sFileName = strtolower( $sFileName );
01296         $iLastDot  = strrpos( $sFileName, '.' );
01297 
01298         if ( $iLastDot !== false ) {
01299             $sType = substr( $sFileName, $iLastDot + 1 );
01300             switch ( $sType ) {
01301                 case 'gif':
01302                     $sType = 'image/gif';
01303                     break;
01304                 case 'jpeg':
01305                 case 'jpg':
01306                     $sType = 'image/jpeg';
01307                     break;
01308                 case 'png':
01309                     $sType = 'image/png';
01310                     break;
01311                 default:
01312                     $sType = false;
01313                     break;
01314             }
01315         }
01316         return $sType;
01317     }
01318 
01327     public function logger( $sText, $blNewline = false )
01328     {   $myConfig = $this->getConfig();
01329 
01330         if ( $myConfig->getConfigParam( 'iDebug' ) == -2) {
01331             if ( gettype( $sText ) != 'string' ) {
01332                 $sText = var_export( $sText, true);
01333             }
01334             $sLogMsg = "----------------------------------------------\n{$sText}".( ( $blNewline ) ?"\n":"" )."\n";
01335             $this->writeToLog( $sLogMsg, "log.txt" );
01336         }
01337 
01338     }
01339 
01347     protected function _stripQuotes($mInput)
01348     {
01349         return is_array($mInput) ? array_map( array( $this, '_stripQuotes' ), $mInput) : stripslashes( $mInput );
01350     }
01351 
01359     public function strRot13( $sStr )
01360     {
01361         $sFrom = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
01362         $sTo   = 'nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM';
01363 
01364         return strtr( $sStr, $sFrom, $sTo );
01365     }
01366 
01376     public function getCacheFilePath( $sCacheName, $blPathOnly = false, $sExtension = 'txt' )
01377     {
01378 
01379             $sVersionPrefix = 'pe';
01380 
01381         $sPath = realpath($this->getConfig()->getConfigParam( 'sCompileDir' ));
01382 
01383         if (!$sPath) {
01384             return false;
01385         }
01386 
01387         return $blPathOnly ? "{$sPath}/" : "{$sPath}/ox{$sVersionPrefix}c_{$sCacheName}." . $sExtension;
01388     }
01389 
01397     public function getLangCache( $sCacheName )
01398     {
01399         $aLangCache = null;
01400         $sFilePath = $this->getCacheFilePath( $sCacheName );
01401         if ( file_exists( $sFilePath ) && is_readable( $sFilePath ) ) {
01402             include $sFilePath;
01403         }
01404         return $aLangCache;
01405     }
01406 
01415     public function setLangCache( $sCacheName, $aLangCache )
01416     {
01417         $sCache = "<?php\n\$aLangCache = ".var_export( $aLangCache, true ).";\n?>";
01418         $blRes = file_put_contents($this->getCacheFilePath($sCacheName), $sCache, LOCK_EX);
01419         return $blRes;
01420     }
01421 
01429     public function checkUrlEndingSlash( $sUrl )
01430     {
01431         if ( !getStr()->preg_match("/\/$/", $sUrl) ) {
01432             $sUrl .= '/';
01433         }
01434 
01435         return $sUrl;
01436     }
01437 
01446     public function writeToLog( $sLogMessage, $sLogFileName )
01447     {
01448         $sLogDist = $this->getConfig()->getLogsDir().$sLogFileName;
01449         $blOk = false;
01450 
01451         if ( ( $oHandle = fopen( $sLogDist, 'a' ) ) !== false ) {
01452             fwrite( $oHandle, $sLogMessage );
01453             $blOk = fclose( $oHandle );
01454         }
01455 
01456         return $blOk;
01457     }
01458 
01466     public function handlePageNotFoundError($sUrl = '')
01467     {
01468         $this->setHeader("HTTP/1.0 404 Not Found");
01469         if ( oxRegistry::getConfig()->isUtf() ) {
01470             $this->setHeader("Content-Type: text/html; charset=UTF-8");
01471         }
01472 
01473         $sReturn = "Page not found.";
01474         try {
01475             $oView = oxNew('oxUBase');
01476             $oView->init();
01477             $oView->render();
01478             $oView->setClassName( 'oxUBase' );
01479             $oView->addTplParam('sUrl', $sUrl);
01480             if ($sRet = oxRegistry::get("oxUtilsView")->getTemplateOutput('message/err_404.tpl', $oView)) {
01481                 $sReturn = $sRet;
01482             }
01483         } catch (Exception $e) {
01484         }
01485         $this->showMessageAndExit( $sReturn );
01486     }
01487 
01495     public function extractDomain( $sHost )
01496     {
01497         $oStr = getStr();
01498         if ( !$oStr->preg_match( '/[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}/', $sHost ) &&
01499              ( $iLastDot = strrpos( $sHost, '.' ) ) !== false ) {
01500             $iLen = $oStr->strlen( $sHost );
01501             if ( ( $iNextDot = strrpos( $sHost, '.', ( $iLen - $iLastDot + 1 ) * - 1 ) ) !== false ) {
01502                 $sHost = trim( $oStr->substr( $sHost, $iNextDot ), '.' );
01503             }
01504         }
01505 
01506         return $sHost;
01507     }
01508 }