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     private static $_instance = null;
00020 
00026     protected $_iCurPrecision = null;
00027 
00035     protected $_sPermanentCachePattern = "/c_fieldnames_/";
00036 
00042     protected $_sLanguageCachePattern = "/c_langcache_/i";
00043 
00049     protected $_sMenuCachePattern = "/c_menu_/i";
00050 
00056     protected $_aLockedFileHandles = array();
00057 
00063     protected $_aFileCacheContents = array();
00064 
00070     protected $_blIsSe = null;
00071 
00077     public static function getInstance()
00078     {
00079         // disable caching for test modules
00080         if ( defined( 'OXID_PHP_UNIT' ) ) {
00081             self::$_instance = modInstances::getMod( __CLASS__ );
00082         }
00083 
00084         if ( !(self::$_instance instanceof oxUtils) ) {
00085 
00086             self::$_instance = oxNew( 'oxUtils' );
00087 
00088             if ( defined( 'OXID_PHP_UNIT' ) ) {
00089                 modInstances::addMod( __CLASS__, self::$_instance);
00090             }
00091         }
00092         return self::$_instance;
00093     }
00094 
00100     protected $_aStaticCache;
00101 
00107     protected $_blSeoIsActive = null;
00108 
00114     public function stripGpcMagicQuotes()
00115     {
00116         if (!get_magic_quotes_gpc()) {
00117             return;
00118         }
00119         $_REQUEST = self::_stripQuotes($_REQUEST);
00120         $_POST = self::_stripQuotes($_POST);
00121         $_GET = self::_stripQuotes($_GET);
00122         $_COOKIE = self::_stripQuotes($_COOKIE);
00123     }
00124 
00133     public function strMan( $sVal, $sKey = null )
00134     {
00135         $sKey = $sKey ? $sKey : $this->getConfig()->getConfigParam('sConfigKey');
00136         $sVal = "ox{$sVal}id";
00137 
00138         $sKey = str_repeat( $sKey, strlen( $sVal ) / strlen( $sKey ) + 5 );
00139         $sVal = $this->strRot13( $sVal );
00140         $sVal = $sVal ^ $sKey;
00141         $sVal = base64_encode ( $sVal );
00142         $sVal = str_replace( "=", "!", $sVal );
00143 
00144         return "ox_$sVal";
00145     }
00146 
00155     public function strRem( $sVal, $sKey = null )
00156     {
00157         $sKey = $sKey ? $sKey : $this->getConfig()->getConfigParam('sConfigKey');
00158         $sKey = str_repeat( $sKey, strlen( $sVal ) / strlen( $sKey ) + 5 );
00159 
00160         $sVal = substr( $sVal, 3 );
00161         $sVal = str_replace( '!', '=', $sVal );
00162         $sVal = base64_decode( $sVal );
00163         $sVal = $sVal ^ $sKey;
00164         $sVal = $this->strRot13( $sVal );
00165 
00166         return substr( $sVal, 2, -2 );
00167     }
00168 
00176     public function getArrFldName( $sName)
00177     {
00178         return str_replace( ".", "__", $sName);
00179     }
00180 
00189     public function assignValuesFromText( $sIn, $dVat = null)
00190     {
00191         $aRet = array();
00192         $aPieces = explode( '@@', $sIn );
00193         while ( list( $sKey, $sVal ) = each( $aPieces ) ) {
00194             if ( $sVal ) {
00195                 $aName = explode( '__', $sVal );
00196                 if ( isset( $aName[0] ) && isset( $aName[1] ) ) {
00197                     $aRet[] = $this->_fillExplodeArray( $aName, $dVat );
00198                 }
00199             }
00200         }
00201         return $aRet;
00202     }
00203 
00211     public function assignValuesToText( $aIn)
00212     {
00213         $sRet = "";
00214         reset( $aIn );
00215         while (list($sKey, $sVal) = each($aIn)) {
00216             $sRet .= $sKey;
00217             $sRet .= "__";
00218             $sRet .= $sVal;
00219             $sRet .= "@@";
00220         }
00221         return $sRet;
00222     }
00223 
00231     public function currency2Float( $sValue)
00232     {
00233         $fRet = $sValue;
00234         $iPos = strrpos( $sValue, ".");
00235         if ($iPos && ((strlen($sValue)-1-$iPos) < 2+1)) {
00236             // replace decimal with ","
00237             $fRet = substr_replace( $fRet, ",", $iPos, 1);
00238         }
00239         // remove thousands
00240         $fRet = str_replace( array(" ","."), "", $fRet);
00241 
00242         $fRet = str_replace( ",", ".", $fRet);
00243         return (float) $fRet;
00244     }
00245 
00253     public function string2Float( $sValue)
00254     {
00255         $fRet = str_replace( " ", "", $sValue);
00256         $iCommaPos = strpos( $fRet, ",");
00257         $iDotPos = strpos( $fRet, ".");
00258         if (!$iDotPos xor !$iCommaPos) {
00259             if (substr_count( $fRet, ",") > 1 || substr_count( $fRet, ".") > 1) {
00260                 $fRet = str_replace( array(",","."), "", $fRet);
00261             } else {
00262                 $fRet = str_replace( ",", ".", $fRet);
00263             }
00264         } else if ( $iDotPos < $iCommaPos ) {
00265             $fRet = str_replace( ".", "", $fRet);
00266             $fRet = str_replace( ",", ".", $fRet);
00267         }
00268         // remove thousands
00269         $fRet = str_replace( array(" ",","), "", $fRet);
00270         return (float) $fRet;
00271     }
00272 
00280     public function isSearchEngine( $sClient = null )
00281     {
00282 
00283         if (!is_null($this->_blIsSe)) {
00284             return $this->_blIsSe;
00285         }
00286 
00287         startProfile("isSearchEngine");
00288 
00289         $myConfig = $this->getConfig();
00290         $blIsSe   = false;
00291 
00292         if ( !( $myConfig->getConfigParam( 'iDebug' ) && $this->isAdmin() ) ) {
00293 
00294             // caching
00295             $blIsSe = $myConfig->getGlobalParameter( 'blIsSearchEngine' );
00296             if ( !isset( $blIsSe ) ) {
00297 
00298                 $aRobots = $myConfig->getConfigParam( 'aRobots' );
00299                 $aRobots = is_array( $aRobots )?$aRobots:array();
00300 
00301                 $aRobotsExcept = $myConfig->getConfigParam( 'aRobotsExcept' );
00302                 $aRobotsExcept = is_array( $aRobotsExcept )?$aRobotsExcept:array();
00303 
00304                 $sClient = $sClient?$sClient:strtolower( getenv( 'HTTP_USER_AGENT' ) );
00305                 $blIsSe  = false;
00306                 $aRobots = array_merge( $aRobots, $aRobotsExcept );
00307                 foreach ( $aRobots as $sRobot ) {
00308                     if ( strpos( $sClient, $sRobot ) !== false ) {
00309                         $blIsSe = true;
00310                         break;
00311                     }
00312                 }
00313                 $myConfig->setGlobalParameter( 'blIsSearchEngine', $blIsSe );
00314             }
00315         }
00316 
00317         stopProfile("isSearchEngine");
00318 
00319         $this->_blIsSe = $blIsSe;
00320 
00321         return $blIsSe;
00322     }
00323 
00332     public function isValidEmail( $sEmail )
00333     {
00334         $blValid = true;
00335         if ( $sEmail != 'admin' ) {
00336             $sEmailTpl = "/^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/i";
00337             $blValid = ( getStr()->preg_match( $sEmailTpl, $sEmail ) != 0 );
00338         }
00339 
00340         return $blValid;
00341     }
00342 
00350     public function rebuildCache()
00351     {
00352         // not needed from 3.0 on and unused <- MK: not correct, its used for example in shop_config.php, oxbase.php
00353 
00354         //$smarty  = & oxUtils::getInstance()->getSmarty();
00355         //$smarty->clear_all_cache();
00356 
00357         if ( function_exists( "UserdefinedRebuildCache")) {
00358             UserdefinedRebuildCache();
00359         }
00360     }
00361 
00369     public function loadAdminProfile($aInterfaceProfiles)
00370     {
00371         // improved #533
00372         // checking for available profiles list
00373         $aInterfaceProfiles = $aInterfaceProfiles;
00374         if ( is_array( $aInterfaceProfiles ) ) {
00375             //checking for previous profiles
00376             $sPrevProfile = oxUtilsServer::getInstance()->getOxCookie('oxidadminprofile');
00377             if (isset($sPrevProfile)) {
00378                 $aPrevProfile = @explode("@", trim($sPrevProfile));
00379             }
00380 
00381             //array to store profiles
00382             $aProfiles = array();
00383             foreach ( $aInterfaceProfiles as $iPos => $sProfile) {
00384                 $aProfileSettings = array($iPos, $sProfile);
00385                 $aProfiles[] = $aProfileSettings;
00386             }
00387             // setting previous used profile as active
00388             if (isset($aPrevProfile[0]) && isset($aProfiles[$aPrevProfile[0]])) {
00389                 $aProfiles[$aPrevProfile[0]][2] = 1;
00390             }
00391 
00392             oxSession::setVar("aAdminProfiles", $aProfiles);
00393             return $aProfiles;
00394         }
00395         return null;
00396     }
00397 
00406     public function fRound($sVal, $oCur = null)
00407     {
00408         startProfile('fround');
00409 
00410         //cached currency precision, this saves about 1% of execution time
00411         $iCurPrecision = null;
00412         if (! defined('OXID_PHP_UNIT')) {
00413             $iCurPrecision = $this->_iCurPrecision;
00414         }
00415 
00416         if (is_null($iCurPrecision)) {
00417             if ( !$oCur ) {
00418                 $oCur = $this->getConfig()->getActShopCurrencyObject();
00419             }
00420 
00421             $iCurPrecision = $oCur->decimal;
00422             $this->_iCurPrecision = $iCurPrecision;
00423         }
00424 
00425         // this is a workaround for #36008 bug in php - incorrect round() & number_format() result (R)
00426         static $dprez = null;
00427         if (!$dprez) {
00428             $prez = @ini_get("precision");
00429             if (!$prez) {
00430                 $prez = 9;
00431             }
00432             $dprez = pow(10, -$prez);
00433         }
00434         stopProfile('fround');
00435 
00436         return round($sVal + $dprez * ( $sVal >= 0 ? 1 : -1 ), $iCurPrecision);
00437     }
00438 
00448     public function toStaticCache( $sName, $sContent, $sKey = null )
00449     {
00450         // if it's an array then we add
00451         if ( $sKey ) {
00452             $this->_aStaticCache[$sName][$sKey] = $sContent;
00453         } else {
00454             $this->_aStaticCache[$sName] = $sContent;
00455         }
00456     }
00457 
00465     public function fromStaticCache( $sName)
00466     {
00467         if ( isset( $this->_aStaticCache[$sName])) {
00468             return $this->_aStaticCache[$sName];
00469         }
00470         return null;
00471     }
00472 
00480     public function cleanStaticCache($sCacheName = null)
00481     {
00482         if ($sCacheName) {
00483             unset($this->_aStaticCache[$sCacheName]);
00484         } else {
00485             $this->_aStaticCache = null;
00486         }
00487     }
00488 
00498     public function toPhpFileCache( $sKey, $mContents )
00499     {
00500         //only simple arrays are supported
00501         if ( is_array( $mContents ) && ( $sCachePath = $this->getCacheFilePath( $sKey, false, 'php' ) ) ) {
00502 
00503             // setting meta
00504             $this->setCacheMeta( $sKey, array( "serialize" => false, "cachepath" => $sCachePath ) );
00505 
00506             // caching..
00507             $this->toFileCache( $sKey, $mContents );
00508         }
00509     }
00510 
00518     public function fromPhpFileCache( $sKey )
00519     {
00520         // setting meta
00521         $this->setCacheMeta( $sKey, array( "include" => true, "cachepath" => $this->getCacheFilePath( $sKey, false, 'php' ) ) );
00522         return $this->fromFileCache( $sKey );
00523     }
00524 
00532     public function getCacheMeta( $sKey )
00533     {
00534         return isset( $this->_aFileCacheMeta[$sKey] ) ? $this->_aFileCacheMeta[$sKey] : false;
00535     }
00536 
00545     public function setCacheMeta( $sKey, $aMeta )
00546     {
00547         // cache meta data
00548         $this->_aFileCacheMeta[$sKey] = $aMeta;
00549     }
00550 
00560     public function toFileCache( $sKey, $mContents )
00561     {
00562         $this->_aFileCacheContents[$sKey] = $mContents;
00563         $aMeta = $this->getCacheMeta( $sKey );
00564 
00565         // looking for cache meta
00566         $sCachePath = isset( $aMeta["cachepath"] ) ? $aMeta["cachepath"] : $this->getCacheFilePath( $sKey );
00567         return ( bool ) $this->_lockFile( $sCachePath, $sKey );
00568     }
00569 
00577     public function fromFileCache( $sKey )
00578     {
00579         if ( !array_key_exists( $sKey, $this->_aFileCacheContents ) ) {
00580             $sRes = null;
00581 
00582             $aMeta = $this->getCacheMeta( $sKey );
00583             $blInclude  = isset( $aMeta["include"] ) ? $aMeta["include"] : false;
00584             $sCachePath = isset( $aMeta["cachepath"] ) ? $aMeta["cachepath"] : $this->getCacheFilePath( $sKey );
00585 
00586             // trying to lock
00587             $this->_lockFile( $sCachePath, $sKey, LOCK_SH );
00588 
00589             clearstatcache();
00590             if ( is_readable( $sCachePath ) ) {
00591                 $sRes = $blInclude ? $this->_includeFile( $sCachePath ) : $this->_readFile( $sCachePath );
00592             }
00593 
00594             // release lock
00595             $this->_releaseFile( $sKey, LOCK_SH );
00596 
00597             // caching
00598             $this->_aFileCacheContents[$sKey] = $sRes;
00599         }
00600 
00601         return $this->_aFileCacheContents[$sKey];
00602     }
00603 
00611     protected function _readFile( $sFilePath )
00612     {
00613         $sRes = file_get_contents( $sFilePath );
00614         return $sRes ? unserialize( $sRes ) : null;
00615     }
00616 
00624     protected function _includeFile( $sFilePath )
00625     {
00626         $_aCacheContents = null;
00627         include $sFilePath;
00628         return $_aCacheContents;
00629     }
00630 
00639     protected function _processCache( $sKey, $mContents )
00640     {
00641         // looking for cache meta
00642         $aCacheMeta  = $this->getCacheMeta( $sKey );
00643         $blSerialize = isset( $aCacheMeta["serialize"] ) ? $aCacheMeta["serialize"] : true;
00644 
00645         if ( $blSerialize ) {
00646             $mContents = serialize( $mContents );
00647         } else {
00648             $mContents = "<?php\n//automatically generated file\n//" . date( "Y-m-d H:i:s" ) . "\n\n\$_aCacheContents = " . var_export( $mContents, true ) . "\n?>";
00649         }
00650 
00651         return $mContents;
00652     }
00653 
00660     public function commitFileCache()
00661     {
00662         if ( count( $this->_aLockedFileHandles[LOCK_EX] ) ) {
00663             startProfile("!__SAVING CACHE__! (warning)");
00664             foreach ( $this->_aLockedFileHandles[LOCK_EX] as $sKey => $rHandle ) {
00665                 if ( $rHandle !== false && isset( $this->_aFileCacheContents[$sKey] ) ) {
00666 
00667                     // #0002931A truncate file once more before writing
00668                     ftruncate( $rHandle, 0 );
00669 
00670                     // writing cache
00671                     fwrite( $rHandle, $this->_processCache( $sKey, $this->_aFileCacheContents[$sKey] ) );
00672 
00673                     // releasing locks
00674                     $this->_releaseFile( $sKey );
00675                 }
00676             }
00677 
00678             stopProfile("!__SAVING CACHE__! (warning)");
00679 
00680             //empty buffer
00681             $this->_aFileCacheContents = array();
00682         }
00683     }
00684 
00694     protected function _lockFile( $sFilePath, $sIdent, $iLockMode = LOCK_EX )
00695     {
00696         $rHandle = isset( $this->_aLockedFileHandles[$iLockMode][$sIdent] ) ? $this->_aLockedFileHandles[$iLockMode][$sIdent] : null;
00697         if ( $rHandle === null ) {
00698 
00699             $blLocked = false;
00700             $rHandle = @fopen( $sFilePath, "a+" );
00701 
00702             if ( $rHandle !== false ) {
00703 
00704                 if ( flock( $rHandle, $iLockMode | LOCK_NB ) ) {
00705                     if ( $iLockMode === LOCK_EX ) {
00706                         // truncate file
00707                         $blLocked = ftruncate( $rHandle, 0 );
00708                     } else {
00709                         // move to a start position
00710                         $blLocked = fseek( $rHandle, 0 ) === 0;
00711                     }
00712                 }
00713 
00714                 // on failure - closing and setting false..
00715                 if ( !$blLocked ) {
00716                     fclose( $rHandle );
00717                     $rHandle = false;
00718                 }
00719             }
00720 
00721             // in case system does not support file lockings
00722             if ( !$blLocked && $iLockMode === LOCK_EX ) {
00723 
00724                 // clearing on first call
00725                 if ( count( $this->_aLockedFileHandles ) == 0 ) {
00726                     clearstatcache();
00727                 }
00728 
00729                 // start a blank file to inform other processes we are dealing with it.
00730                 if (!( file_exists( $sFilePath ) && !filesize( $sFilePath ) && abs( time() - filectime( $sFilePath ) < 40 ) ) ) {
00731                     $rHandle = @fopen( $sFilePath, "w" );
00732                 }
00733             }
00734 
00735             $this->_aLockedFileHandles[$iLockMode][$sIdent] = $rHandle;
00736         }
00737 
00738         return $rHandle;
00739     }
00740 
00749     protected function _releaseFile( $sIdent, $iLockMode = LOCK_EX )
00750     {
00751         $blSuccess = true;
00752         if ( isset( $this->_aLockedFileHandles[$iLockMode][$sIdent] ) &&
00753              $this->_aLockedFileHandles[$iLockMode][$sIdent] !== false ) {
00754 
00755              // release the lock and close file
00756             $blSuccess = flock( $this->_aLockedFileHandles[$iLockMode][$sIdent], LOCK_UN ) &&
00757                          fclose( $this->_aLockedFileHandles[$iLockMode][$sIdent] );
00758             unset( $this->_aLockedFileHandles[$iLockMode][$sIdent] );
00759         }
00760 
00761         return $blSuccess;
00762     }
00763 
00771     public function oxResetFileCache()
00772     {
00773         $aFiles = glob( $this->getCacheFilePath( null, true ) . '*' );
00774         if ( is_array( $aFiles ) ) {
00775             // delete all the files, except cached tables fieldnames
00776             $aFiles = preg_grep( $this->_sPermanentCachePattern, $aFiles, PREG_GREP_INVERT );
00777             foreach ( $aFiles as $sFile ) {
00778                 @unlink( $sFile );
00779             }
00780         }
00781     }
00782 
00790     public function resetTemplateCache($aTemplates)
00791     {
00792         $aFiles = glob( $this->getCacheFilePath( null, true ) . '*' );
00793         if ( is_array( $aFiles ) && is_array( $aTemplates ) && count($aTemplates) ) {
00794             // delete all template cache files
00795             foreach ($aTemplates as &$sTemplate) {
00796                 $sTemplate = preg_quote(basename(strtolower($sTemplate), '.tpl'));
00797             }
00798 
00799             $sPattern = sprintf("/%%(%s)\.tpl\.php$/i", implode('|', $aTemplates));
00800             $aFiles = preg_grep( $sPattern, $aFiles );
00801             
00802             if (is_array( $aFiles ) ) {
00803                 foreach ( $aFiles as $sFile ) {
00804                     @unlink( $sFile );
00805                 }
00806             }
00807         }
00808 
00809     }
00810 
00816     public function resetLanguageCache()
00817     {
00818         $aFiles = glob( $this->getCacheFilePath( null, true ) . '*' );
00819         if ( is_array( $aFiles ) ) {
00820             // delete all language cache files
00821             $sPattern = $this->_sLanguageCachePattern;
00822             $aFiles = preg_grep( $sPattern, $aFiles );
00823             foreach ( $aFiles as $sFile ) {
00824                 @unlink( $sFile );
00825             }
00826         }
00827     }
00828 
00834     public function resetMenuCache()
00835     {
00836         $aFiles = glob( $this->getCacheFilePath( null, true ) . '*' );
00837         if ( is_array( $aFiles ) ) {
00838             // delete all menu cache files
00839             $sPattern = $this->_sMenuCachePattern;
00840             $aFiles = preg_grep( $sPattern, $aFiles );
00841             foreach ( $aFiles as $sFile ) {
00842                 @unlink( $sFile );
00843             }
00844         }
00845     }
00846 
00856     public function getRemoteCachePath($sRemote, $sLocal)
00857     {
00858         clearstatcache();
00859         if ( file_exists( $sLocal ) && filemtime( $sLocal ) && filemtime( $sLocal ) > time() - 86400 ) {
00860             return $sLocal;
00861         }
00862         $hRemote = @fopen( $sRemote, "rb");
00863         $blSuccess = false;
00864         if ( isset( $hRemote) && $hRemote ) {
00865             $hLocal = fopen( $sLocal, "wb");
00866             stream_copy_to_stream($hRemote, $hLocal);
00867             fclose($hRemote);
00868             fclose($hLocal);
00869             $blSuccess = true;
00870         } else {
00871             // try via fsockopen
00872             $aUrl = @parse_url( $sRemote);
00873             if ( !empty( $aUrl["host"])) {
00874                 $sPath = $aUrl["path"];
00875                 if ( empty( $sPath ) ) {
00876                     $sPath = "/";
00877                 }
00878                 $sHost = $aUrl["host"];
00879 
00880                 $hSocket = @fsockopen( $sHost, 80, $iErrorNumber, $iErrStr, 5);
00881                 if ( $hSocket) {
00882                     fputs( $hSocket, "GET ".$sPath." HTTP/1.0\r\nHost: $sHost\r\n\r\n");
00883                     $headers = stream_get_line($hSocket, 4096, "\r\n\r\n");
00884                     if ( ( $hLocal = @fopen( $sLocal, "wb") ) !== false ) {
00885                         rewind($hLocal);
00886                         // does not copy all the data
00887                         // stream_copy_to_stream($hSocket, $hLocal);
00888                         fwrite ( $hLocal, stream_get_contents( $hSocket ) );
00889                         fclose( $hLocal );
00890                         fclose( $hSocket );
00891                         $blSuccess = true;
00892                     }
00893                 }
00894             }
00895         }
00896         if ( $blSuccess || file_exists( $sLocal ) ) {
00897             return $sLocal;
00898         }
00899         return false;
00900     }
00901 
00907     public function canPreview()
00908     {
00909         $blCan = null;
00910         if ( ( $sPrevId = oxConfig::getParameter( 'preview' ) ) &&
00911              ( $sAdminSid = oxUtilsServer::getInstance()->getOxCookie( 'admin_sid' ) ) ) {
00912 
00913             $sTable = getViewName( 'oxuser' );
00914             $oDb = oxDb::getDb();
00915             $sQ = "select 1 from $sTable where MD5( CONCAT( ".$oDb->quote($sAdminSid).", {$sTable}.oxid, {$sTable}.oxpassword, {$sTable}.oxrights ) ) = ".oxDb::getDb()->quote($sPrevId);
00916             $blCan = (bool) $oDb->getOne( $sQ );
00917         }
00918 
00919         return $blCan;
00920     }
00921 
00927     public function getPreviewId()
00928     {
00929         $sAdminSid = oxUtilsServer::getInstance()->getOxCookie( 'admin_sid' );
00930         if ( ( $oUser = $this->getUser() ) ) {
00931             return md5( $sAdminSid . $oUser->getId() . $oUser->oxuser__oxpassword->value . $oUser->oxuser__oxrights->value );
00932         }
00933     }
00934 
00940     public function checkAccessRights()
00941     {
00942         $myConfig  = $this->getConfig();
00943 
00944         $blIsAuth = false;
00945 
00946         $sUserID = oxSession::getVar( "auth");
00947 
00948         // deleting admin marker
00949         oxSession::setVar( "malladmin", 0);
00950         oxSession::setVar( "blIsAdmin", 0);
00951         oxSession::deleteVar( "blIsAdmin" );
00952         $myConfig->setConfigParam( 'blMallAdmin', false );
00953         //#1552T
00954         $myConfig->setConfigParam( 'blAllowInheritedEdit', false );
00955 
00956         if ( $sUserID) {
00957             // escaping
00958             $oDb = oxDb::getDb();
00959             $sRights = $oDb->getOne("select oxrights from oxuser where oxid = ".$oDb->quote($sUserID));
00960 
00961             if ( $sRights != "user") {
00962                 // malladmin ?
00963                 if ( $sRights == "malladmin") {
00964                     oxSession::setVar( "malladmin", 1);
00965                     $myConfig->setConfigParam( 'blMallAdmin', true );
00966 
00967                     //#1552T
00968                     //So far this blAllowSharedEdit is Equal to blMallAdmin but in future to be solved over rights and roles
00969                     $myConfig->setConfigParam( 'blAllowSharedEdit', true );
00970 
00971                     $sShop = oxSession::getVar( "actshop");
00972                     if ( !isset($sShop)) {
00973                         oxSession::setVar( "actshop", $myConfig->getBaseShopId());
00974                     }
00975                     $blIsAuth = true;
00976                 } else {
00977                     // Shopadmin... check if this shop is valid and exists
00978                     $sShopID = $oDb->getOne("select oxid from oxshops where oxid = " . $oDb->quote( $sRights ) );
00979                     if ( isset( $sShopID) && $sShopID) {
00980                         // success, this shop exists
00981 
00982                         oxSession::setVar( "actshop", $sRights);
00983                         oxSession::setVar( "currentadminshop", $sRights);
00984                         oxSession::setVar( "shp", $sRights);
00985 
00986                         // check if this subshop admin is evil.
00987                         if ('chshp' == oxConfig::getParameter( 'fnc' )) {
00988                             // dont allow this call
00989                             $blIsAuth = false;
00990                         } else {
00991                             $blIsAuth = true;
00992 
00993                             $aShopIdVars = array('actshop', 'shp', 'currentadminshop');
00994                             foreach ($aShopIdVars as $sShopIdVar) {
00995                                 if ($sGotShop = oxConfig::getParameter( $sShopIdVar )) {
00996                                     if ($sGotShop != $sRights) {
00997                                         $blIsAuth = false;
00998                                         break;
00999                                     }
01000                                 }
01001                             }
01002                         }
01003                     }
01004                 }
01005                 // marking user as admin
01006                 oxSession::setVar( "blIsAdmin", 1);
01007             }
01008         }
01009         return $blIsAuth;
01010     }
01011 
01021     public function seoIsActive( $blReset = false, $sShopId = null, $iActLang = null )
01022     {
01023         if ( !is_null( $this->_blSeoIsActive ) && !$blReset ) {
01024             return $this->_blSeoIsActive;
01025         }
01026 
01027         $myConfig = $this->getConfig();
01028 
01029         if ( ( $this->_blSeoIsActive = $myConfig->getConfigParam( 'blSeoMode' ) ) === null ) {
01030             $this->_blSeoIsActive = true;
01031 
01032             $aSeoModes  = $myConfig->getconfigParam( 'aSeoModes' );
01033             $sActShopId = $sShopId ? $sShopId : $myConfig->getActiveShop()->getId();
01034             $iActLang   = $iActLang ? $iActLang : (int) oxLang::getInstance()->getBaseLanguage();
01035 
01036             // checking special config param for active shop and language
01037             if ( is_array( $aSeoModes ) && isset( $aSeoModes[$sActShopId] ) && isset( $aSeoModes[$sActShopId][$iActLang] ) ) {
01038                 $this->_blSeoIsActive = (bool) $aSeoModes[$sActShopId][$iActLang];
01039             }
01040         }
01041 
01042         return $this->_blSeoIsActive;
01043     }
01044 
01056     public function getShopBit( $iShopId )
01057     {
01058         return oxShopMetaData::getInstance()->getShopBit( $iShopId );
01059     }
01060 
01072     public function bitwiseAnd( $iVal1, $iVal2 )
01073     {
01074         //this works for large numbers when $sShopNr is up to (inclusive) 64
01075         $iRes = oxDb::getDb()->getOne( "select ($iVal1 & $iVal2) as bitwiseAnd" );
01076 
01077         //as php ints supports only 32 bits, we return string.
01078         return $iRes;
01079     }
01080 
01092     public function bitwiseOr( $iVal1, $iVal2 )
01093     {
01094         //this works for large numbers when $sShopNr is up to (inclusive) 64
01095         $iRes = oxDb::getDb()->getOne( "select ($iVal1 | $iVal2) as bitwiseOr" );
01096 
01097         //as php ints supports only 32 bits, we return string.
01098         return $iRes;
01099     }
01100 
01108     public function isValidAlpha( $sField )
01109     {
01110         return (boolean) getStr()->preg_match( '/^[a-zA-Z0-9_]*$/', $sField );
01111     }
01112 
01122     protected function _simpleRedirect( $sUrl, $sHeaderCode )
01123     {
01124         header( $sHeaderCode );
01125         header( "Location: $sUrl" );
01126         header( "Connection: close" );
01127     }
01128 
01142     public function redirect( $sUrl, $blAddRedirectParam = true, $iHeaderCode = 301 )
01143     {
01144         //preventing possible cyclic redirection
01145         //#M341 and check only if redirect paramater must be added
01146         if ( $blAddRedirectParam && oxConfig::getParameter( 'redirected' ) ) {
01147             return;
01148         }
01149 
01150         if ( $blAddRedirectParam ) {
01151             $sUrl = $this->_addUrlParameters( $sUrl, array( 'redirected' => 1 ) );
01152         }
01153 
01154         $sUrl = str_ireplace( "&amp;", "&", $sUrl );
01155 
01156         $sHeaderCode = '';
01157         switch ($iHeaderCode) {
01158             case 301:
01159                 $sHeaderCode = "HTTP/1.1 301 Moved Permanently";
01160                 break;
01161             case 302:
01162             default:
01163                 $sHeaderCode = "HTTP/1.1 302 Found";
01164         }
01165 
01166         $this->_simpleRedirect( $sUrl, $sHeaderCode );
01167 
01168         try {//may occur in case db is lost
01169             $this->getSession()->freeze();
01170         } catch( oxException $oEx ) {
01171             $oEx->debugOut();
01172             //do nothing else to make sure the redirect takes place
01173         }
01174 
01175         if ( defined( 'OXID_PHP_UNIT' ) ) {
01176             return;
01177         }
01178 
01179         $this->showMessageAndExit( '' );
01180     }
01181 
01189     public function showMessageAndExit( $sMsg )
01190     {
01191         $this->getSession()->freeze();
01192         $this->commitFileCache();
01193 
01194         if ( defined( 'OXID_PHP_UNIT' ) ) {
01195             return;
01196         }
01197 
01198         exit( $sMsg );
01199     }
01200 
01208     public function setHeader($sHeader)
01209     {
01210         header($sHeader);
01211     }
01212 
01221     protected function _addUrlParameters( $sUrl, $aParams )
01222     {
01223         $sDelim = ( ( getStr()->strpos( $sUrl, '?' ) !== false ) )?'&':'?';
01224         foreach ( $aParams as $sName => $sVal ) {
01225             $sUrl = $sUrl . $sDelim . $sName . '=' . $sVal;
01226             $sDelim = '&';
01227         }
01228 
01229         return $sUrl;
01230     }
01231 
01243     protected function _fillExplodeArray( $aName, $dVat = null)
01244     {
01245         $myConfig = $this->getConfig();
01246         $oObject = new oxStdClass();
01247         $aPrice = explode( '!P!', $aName[0]);
01248 
01249         if ( ( $myConfig->getConfigParam( 'bl_perfLoadSelectLists' ) && $myConfig->getConfigParam( 'bl_perfUseSelectlistPrice' ) && isset( $aPrice[0] ) && isset( $aPrice[1] ) ) || $this->isAdmin() ) {
01250 
01251             // yes, price is there
01252             $oObject->price = isset( $aPrice[1] ) ? $aPrice[1] : 0;
01253             $aName[0] = isset( $aPrice[0] ) ? $aPrice[0] : '';
01254 
01255             $iPercPos = getStr()->strpos( $oObject->price, '%' );
01256             if ( $iPercPos !== false ) {
01257                 $oObject->priceUnit = '%';
01258                 $oObject->fprice = $oObject->price;
01259                 $oObject->price  = substr( $oObject->price, 0, $iPercPos );
01260             } else {
01261                 $oCur = $myConfig->getActShopCurrencyObject();
01262                 $oObject->price = str_replace(',', '.', $oObject->price);
01263                 $oObject->fprice = oxLang::getInstance()->formatCurrency( $oObject->price  * $oCur->rate, $oCur);
01264                 $oObject->priceUnit = 'abs';
01265             }
01266 
01267             // add price info into list
01268             if ( !$this->isAdmin() && $oObject->price != 0 ) {
01269                 $aName[0] .= " ";
01270                 if ( $oObject->price > 0 ) {
01271                     $aName[0] .= "+";
01272                 }
01273                 //V FS#2616
01274                 if ( $dVat != null && $oObject->priceUnit == 'abs' ) {
01275                     $oPrice = oxNew('oxPrice');
01276                     $oPrice->setPrice($oObject->price, $dVat);
01277                     $aName[0] .= oxLang::getInstance()->formatCurrency( $oPrice->getBruttoPrice() * $oCur->rate, $oCur);
01278                 } else {
01279                     $aName[0] .= $oObject->fprice;
01280                 }
01281                 if ( $oObject->priceUnit == 'abs' ) {
01282                     $aName[0] .= " ".$oCur->sign;
01283                 }
01284             }
01285         } elseif ( isset( $aPrice[0] ) && isset($aPrice[1] ) ) {
01286             // A. removing unused part of information
01287             $aName[0] = getStr()->preg_replace( "/!P!.*/", "", $aName[0] );
01288         }
01289 
01290         $oObject->name  = $aName[0];
01291         $oObject->value = $aName[1];
01292         return $oObject;
01293     }
01294 
01302     public function oxMimeContentType( $sFileName )
01303     {
01304         $sFileName = strtolower( $sFileName );
01305         $iLastDot  = strrpos( $sFileName, '.' );
01306 
01307         if ( $iLastDot !== false ) {
01308             $sType = substr( $sFileName, $iLastDot + 1 );
01309             switch ( $sType ) {
01310                 case 'gif':
01311                     $sType = 'image/gif';
01312                     break;
01313                 case 'jpeg':
01314                 case 'jpg':
01315                     $sType = 'image/jpeg';
01316                     break;
01317                 case 'png':
01318                     $sType = 'image/png';
01319                     break;
01320                 default:
01321                     $sType = false;
01322                     break;
01323             }
01324         }
01325         return $sType;
01326     }
01327 
01336     public function logger( $sText, $blNewline = false )
01337     {   $myConfig = $this->getConfig();
01338 
01339         if ( $myConfig->getConfigParam( 'iDebug' ) == -2) {
01340             if ( gettype( $sText ) != 'string' ) {
01341                 $sText = var_export( $sText, true);
01342             }
01343             $sLogMsg = "----------------------------------------------\n{$sText}".( ( $blNewline ) ?"\n":"" )."\n";
01344             $this->writeToLog( $sLogMsg, "log.txt" );
01345         }
01346 
01347     }
01348 
01356     protected function _stripQuotes($mInput)
01357     {
01358         return is_array($mInput) ? array_map( array( $this, '_stripQuotes' ), $mInput) : stripslashes( $mInput );
01359     }
01360 
01368     public function strRot13( $sStr )
01369     {
01370         $sFrom = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
01371         $sTo   = 'nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM';
01372 
01373         return strtr( $sStr, $sFrom, $sTo );
01374     }
01375 
01385     public function getCacheFilePath( $sCacheName, $blPathOnly = false, $sExtension = 'txt' )
01386     {
01387         $sVersionPrefix = "";
01388 
01389 
01390             $sVersionPrefix = 'pe';
01391 
01392         $sPath = realpath($this->getConfig()->getConfigParam( 'sCompileDir' ));
01393 
01394         if (!$sPath) {
01395             return false;
01396         }
01397 
01398         return $blPathOnly ? "{$sPath}/" : "{$sPath}/ox{$sVersionPrefix}c_{$sCacheName}." . $sExtension;
01399     }
01400 
01408     public function getLangCache( $sCacheName )
01409     {
01410         $aLangCache = null;
01411         $sFilePath = $this->getCacheFilePath( $sCacheName );
01412         if ( file_exists( $sFilePath ) && is_readable( $sFilePath ) ) {
01413             include $sFilePath;
01414         }
01415         return $aLangCache;
01416     }
01417 
01426     public function setLangCache( $sCacheName, $aLangCache )
01427     {
01428         $sCache = "<?php\n\$aLangCache = ".var_export( $aLangCache, true ).";\n?>";
01429         $blRes = file_put_contents($this->getCacheFilePath($sCacheName), $sCache);
01430         return $blRes;
01431     }
01432 
01440     public function checkUrlEndingSlash( $sUrl )
01441     {
01442         if ( !getStr()->preg_match("/\/$/", $sUrl) ) {
01443             $sUrl .= '/';
01444         }
01445 
01446         return $sUrl;
01447     }
01448 
01457     public function writeToLog( $sLogMessage, $sLogFileName )
01458     {
01459         $sLogDist = $this->getConfig()->getLogsDir().$sLogFileName;
01460         $blOk = false;
01461 
01462         if ( ( $oHandle = fopen( $sLogDist, 'a' ) ) !== false ) {
01463             fwrite( $oHandle, $sLogMessage );
01464             $blOk = fclose( $oHandle );
01465         }
01466 
01467         return $blOk;
01468     }
01469 
01477     public function handlePageNotFoundError($sUrl = '')
01478     {
01479         $this->setHeader("HTTP/1.0 404 Not Found");
01480         if ( oxConfig::getInstance()->isUtf() ) {
01481             $this->setHeader("Content-Type: text/html; charset=UTF-8");
01482         }
01483 
01484         $sReturn = "Page not found.";
01485         try {
01486             $oView = oxNew('oxubase');
01487             $oView->init();
01488             $oView->render();
01489             $oView->addTplParam('sUrl', $sUrl);
01490             if ($sRet = oxUtilsView::getInstance()->getTemplateOutput('message/err_404.tpl', $oView)) {
01491                 $sReturn = $sRet;
01492             }
01493         } catch (Exception $e) {
01494         }
01495         $this->showMessageAndExit( $sReturn );
01496     }
01497 
01505     public function extractDomain( $sHost )
01506     {
01507         $oStr = getStr();
01508         if ( !$oStr->preg_match( '/[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}/', $sHost ) &&
01509              ( $iLastDot = strrpos( $sHost, '.' ) ) !== false ) {
01510             $iLen = $oStr->strlen( $sHost );
01511             if ( ( $iNextDot = strrpos( $sHost, '.', ( $iLen - $iLastDot + 1 ) * - 1 ) ) !== false ) {
01512                 $sHost = trim( $oStr->substr( $sHost, $iNextDot ), '.' );
01513             }
01514         }
01515 
01516         return $sHost;
01517     }
01518 }