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 
00115     public function strMan( $sVal, $sKey = null )
00116     {
00117         $sKey = $sKey ? $sKey : $this->getConfig()->getConfigParam('sConfigKey');
00118         $sVal = "ox{$sVal}id";
00119 
00120         $sKey = str_repeat( $sKey, strlen( $sVal ) / strlen( $sKey ) + 5 );
00121         $sVal = $this->strRot13( $sVal );
00122         $sVal = $sVal ^ $sKey;
00123         $sVal = base64_encode ( $sVal );
00124         $sVal = str_replace( "=", "!", $sVal );
00125 
00126         return "ox_$sVal";
00127     }
00128 
00137     public function strRem( $sVal, $sKey = null )
00138     {
00139         $sKey = $sKey ? $sKey : $this->getConfig()->getConfigParam('sConfigKey');
00140         $sKey = str_repeat( $sKey, strlen( $sVal ) / strlen( $sKey ) + 5 );
00141 
00142         $sVal = substr( $sVal, 3 );
00143         $sVal = str_replace( '!', '=', $sVal );
00144         $sVal = base64_decode( $sVal );
00145         $sVal = $sVal ^ $sKey;
00146         $sVal = $this->strRot13( $sVal );
00147 
00148         return substr( $sVal, 2, -2 );
00149     }
00150 
00158     public function getArrFldName( $sName )
00159     {
00160         return str_replace( ".", "__", $sName);
00161     }
00162 
00171     public function assignValuesFromText( $sIn, $dVat = null )
00172     {
00173         $aRet = array();
00174         $aPieces = explode( '@@', $sIn );
00175         while ( list( $sKey, $sVal ) = each( $aPieces ) ) {
00176             if ( $sVal ) {
00177                 $aName = explode( '__', $sVal );
00178                 if ( isset( $aName[0] ) && isset( $aName[1] ) ) {
00179                     $aRet[] = $this->_fillExplodeArray( $aName, $dVat );
00180                 }
00181             }
00182         }
00183         return $aRet;
00184     }
00185 
00193     public function assignValuesToText( $aIn)
00194     {
00195         $sRet = "";
00196         reset( $aIn );
00197         while (list($sKey, $sVal) = each($aIn)) {
00198             $sRet .= $sKey;
00199             $sRet .= "__";
00200             $sRet .= $sVal;
00201             $sRet .= "@@";
00202         }
00203         return $sRet;
00204     }
00205 
00213     public function currency2Float( $sValue)
00214     {
00215         $fRet = $sValue;
00216         $iPos = strrpos( $sValue, ".");
00217         if ($iPos && ((strlen($sValue)-1-$iPos) < 2+1)) {
00218             // replace decimal with ","
00219             $fRet = substr_replace( $fRet, ",", $iPos, 1);
00220         }
00221         // remove thousands
00222         $fRet = str_replace( array(" ","."), "", $fRet);
00223 
00224         $fRet = str_replace( ",", ".", $fRet);
00225         return (float) $fRet;
00226     }
00227 
00235     public function string2Float( $sValue)
00236     {
00237         $fRet = str_replace( " ", "", $sValue);
00238         $iCommaPos = strpos( $fRet, ",");
00239         $iDotPos = strpos( $fRet, ".");
00240         if (!$iDotPos xor !$iCommaPos) {
00241             if (substr_count( $fRet, ",") > 1 || substr_count( $fRet, ".") > 1) {
00242                 $fRet = str_replace( array(",","."), "", $fRet);
00243             } else {
00244                 $fRet = str_replace( ",", ".", $fRet);
00245             }
00246         } else if ( $iDotPos < $iCommaPos ) {
00247             $fRet = str_replace( ".", "", $fRet);
00248             $fRet = str_replace( ",", ".", $fRet);
00249         }
00250         // remove thousands
00251         $fRet = str_replace( array(" ",","), "", $fRet);
00252         return (float) $fRet;
00253     }
00254 
00262     public function isSearchEngine( $sClient = null )
00263     {
00264         if (is_null($this->_blIsSe)) {
00265             $this->setSearchEngine( null, $sClient );
00266         }
00267         return $this->_blIsSe;
00268     }
00269 
00278     public function setSearchEngine( $blIsSe = null, $sClient = null )
00279     {
00280         if (isset($blIsSe)) {
00281             $this->_blIsSe = $blIsSe;
00282             return;
00283         }
00284         startProfile("isSearchEngine");
00285 
00286         $myConfig = $this->getConfig();
00287         $blIsSe   = false;
00288 
00289         if ( !( $myConfig->getConfigParam( 'iDebug' ) && $this->isAdmin() ) ) {
00290             $aRobots = $myConfig->getConfigParam( 'aRobots' );
00291             $aRobots = is_array( $aRobots )?$aRobots:array();
00292 
00293             $aRobotsExcept = $myConfig->getConfigParam( 'aRobotsExcept' );
00294             $aRobotsExcept = is_array( $aRobotsExcept )?$aRobotsExcept:array();
00295 
00296             $sClient = $sClient?$sClient:strtolower( getenv( 'HTTP_USER_AGENT' ) );
00297             $blIsSe  = false;
00298             $aRobots = array_merge( $aRobots, $aRobotsExcept );
00299             foreach ( $aRobots as $sRobot ) {
00300                 if ( strpos( $sClient, $sRobot ) !== false ) {
00301                     $blIsSe = true;
00302                     break;
00303                 }
00304             }
00305         }
00306 
00307         $this->_blIsSe = $blIsSe;
00308 
00309         stopProfile("isSearchEngine");
00310     }
00311 
00320     public function isValidEmail( $sEmail )
00321     {
00322         $blValid = true;
00323         if ( $sEmail != 'admin' ) {
00324             $sEmailTpl = "/^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/i";
00325             $blValid = ( getStr()->preg_match( $sEmailTpl, $sEmail ) != 0 );
00326         }
00327 
00328         return $blValid;
00329     }
00330 
00338     public function loadAdminProfile($aInterfaceProfiles)
00339     {
00340         // improved #533
00341         // checking for available profiles list
00342         if ( is_array( $aInterfaceProfiles ) ) {
00343             //checking for previous profiles
00344             $sPrevProfile = oxRegistry::get("oxUtilsServer")->getOxCookie('oxidadminprofile');
00345             if (isset($sPrevProfile)) {
00346                 $aPrevProfile = @explode("@", trim($sPrevProfile));
00347             }
00348 
00349             //array to store profiles
00350             $aProfiles = array();
00351             foreach ( $aInterfaceProfiles as $iPos => $sProfile) {
00352                 $aProfileSettings = array($iPos, $sProfile);
00353                 $aProfiles[] = $aProfileSettings;
00354             }
00355             // setting previous used profile as active
00356             if (isset($aPrevProfile[0]) && isset($aProfiles[$aPrevProfile[0]])) {
00357                 $aProfiles[$aPrevProfile[0]][2] = 1;
00358             }
00359 
00360             oxSession::setVar("aAdminProfiles", $aProfiles);
00361             return $aProfiles;
00362         }
00363         return null;
00364     }
00365 
00374     public function fRound($sVal, $oCur = null)
00375     {
00376         startProfile('fround');
00377 
00378         //cached currency precision, this saves about 1% of execution time
00379         $iCurPrecision = null;
00380         if (! defined('OXID_PHP_UNIT')) {
00381             $iCurPrecision = $this->_iCurPrecision;
00382         }
00383 
00384         if (is_null($iCurPrecision)) {
00385             if ( !$oCur ) {
00386                 $oCur = $this->getConfig()->getActShopCurrencyObject();
00387             }
00388 
00389             $iCurPrecision = $oCur->decimal;
00390             $this->_iCurPrecision = $iCurPrecision;
00391         }
00392 
00393         // if < 5.3.x this is a workaround for #36008 bug in php - incorrect round() & number_format() result (R)
00394         static $dprez = null;
00395         if (!$dprez) {
00396             $prez = @ini_get("precision");
00397             if (!$prez || $prez > 12 ) {
00398                $prez = 12;
00399             }
00400             $dprez = pow(10, -$prez);
00401         }
00402         stopProfile('fround');
00403         return round($sVal + $dprez * ( $sVal >= 0 ? 1 : -1 ), $iCurPrecision);
00404     }
00405 
00415     public function toStaticCache( $sName, $sContent, $sKey = null )
00416     {
00417         // if it's an array then we add
00418         if ( $sKey ) {
00419             $this->_aStaticCache[$sName][$sKey] = $sContent;
00420         } else {
00421             $this->_aStaticCache[$sName] = $sContent;
00422         }
00423     }
00424 
00432     public function fromStaticCache( $sName)
00433     {
00434         if ( isset( $this->_aStaticCache[$sName])) {
00435             return $this->_aStaticCache[$sName];
00436         }
00437         return null;
00438     }
00439 
00447     public function cleanStaticCache($sCacheName = null)
00448     {
00449         if ($sCacheName) {
00450             unset($this->_aStaticCache[$sCacheName]);
00451         } else {
00452             $this->_aStaticCache = null;
00453         }
00454     }
00455 
00465     public function toPhpFileCache( $sKey, $mContents )
00466     {
00467         //only simple arrays are supported
00468         if ( is_array( $mContents ) && ( $sCachePath = $this->getCacheFilePath( $sKey, false, 'php' ) ) ) {
00469 
00470             // setting meta
00471             $this->setCacheMeta( $sKey, array( "serialize" => false, "cachepath" => $sCachePath ) );
00472 
00473             // caching..
00474             $this->toFileCache( $sKey, $mContents );
00475         }
00476     }
00477 
00485     public function fromPhpFileCache( $sKey )
00486     {
00487         // setting meta
00488         $this->setCacheMeta( $sKey, array( "include" => true, "cachepath" => $this->getCacheFilePath( $sKey, false, 'php' ) ) );
00489         return $this->fromFileCache( $sKey );
00490     }
00491 
00499     public function getCacheMeta( $sKey )
00500     {
00501         return isset( $this->_aFileCacheMeta[$sKey] ) ? $this->_aFileCacheMeta[$sKey] : false;
00502     }
00503 
00512     public function setCacheMeta( $sKey, $aMeta )
00513     {
00514         // cache meta data
00515         $this->_aFileCacheMeta[$sKey] = $aMeta;
00516     }
00517 
00528     public function toFileCache( $sKey, $mContents, $iTtl = 0 )
00529     {
00530         $aCacheData['content'] = $mContents;
00531         $aMeta = $this->getCacheMeta( $sKey );
00532         if ( $iTtl ) {
00533             $aCacheData['ttl'] = $iTtl;
00534             $aCacheData['timestamp'] = oxRegistry::get("oxUtilsDate")->getTime();
00535         }
00536         $this->_aFileCacheContents[$sKey] = $aCacheData;
00537 
00538         // looking for cache meta
00539         $sCachePath = isset( $aMeta["cachepath"] ) ? $aMeta["cachepath"] : $this->getCacheFilePath( $sKey );
00540         return ( bool ) $this->_lockFile( $sCachePath, $sKey );
00541     }
00542 
00550     public function fromFileCache( $sKey )
00551     {
00552         if ( !array_key_exists( $sKey, $this->_aFileCacheContents ) ) {
00553             $sRes = null;
00554 
00555             $aMeta = $this->getCacheMeta( $sKey );
00556             $blInclude  = isset( $aMeta["include"] ) ? $aMeta["include"] : false;
00557             $sCachePath = isset( $aMeta["cachepath"] ) ? $aMeta["cachepath"] : $this->getCacheFilePath( $sKey );
00558 
00559             // trying to lock
00560             $this->_lockFile( $sCachePath, $sKey, LOCK_SH );
00561 
00562             clearstatcache();
00563             if ( is_readable( $sCachePath ) ) {
00564                 $sRes = $blInclude ? $this->_includeFile( $sCachePath ) : $this->_readFile( $sCachePath );
00565             }
00566 
00567             if ( isset( $sRes['ttl'] ) && $sRes['ttl'] != 0 ) {
00568                 $iTimestamp = $sRes['timestamp'];
00569                 $iTtl = $sRes['ttl'];
00570 
00571                 $iTime = oxRegistry::get("oxUtilsDate")->getTime();
00572                 if ( $iTime > $iTimestamp + $iTtl ) {
00573                     return null;
00574                 }
00575             }
00576             // release lock
00577             $this->_releaseFile( $sKey, LOCK_SH );
00578 
00579             // caching
00580             $this->_aFileCacheContents[$sKey] = $sRes;
00581         }
00582 
00583         return $this->_aFileCacheContents[$sKey]['content'];
00584     }
00585 
00593     protected function _readFile( $sFilePath )
00594     {
00595         $sRes = file_get_contents( $sFilePath );
00596         return $sRes ? unserialize( $sRes ) : null;
00597     }
00598 
00606     protected function _includeFile( $sFilePath )
00607     {
00608         $_aCacheContents = null;
00609         include $sFilePath;
00610         return $_aCacheContents;
00611     }
00612 
00621     protected function _processCache( $sKey, $mContents )
00622     {
00623         // looking for cache meta
00624         $aCacheMeta  = $this->getCacheMeta( $sKey );
00625         $blSerialize = isset( $aCacheMeta["serialize"] ) ? $aCacheMeta["serialize"] : true;
00626 
00627         if ( $blSerialize ) {
00628             $mContents = serialize( $mContents );
00629         } else {
00630             $mContents = "<?php\n//automatically generated file\n//" . date( "Y-m-d H:i:s" ) . "\n\n\$_aCacheContents = " . var_export( $mContents, true ) . "\n?>";
00631         }
00632 
00633         return $mContents;
00634     }
00635 
00642     public function commitFileCache()
00643     {
00644         if ( count( $this->_aLockedFileHandles[LOCK_EX] ) ) {
00645             startProfile("!__SAVING CACHE__! (warning)");
00646             foreach ( $this->_aLockedFileHandles[LOCK_EX] as $sKey => $rHandle ) {
00647                 if ( $rHandle !== false && isset( $this->_aFileCacheContents[$sKey] ) ) {
00648 
00649                     // #0002931A truncate file once more before writing
00650                     ftruncate( $rHandle, 0 );
00651 
00652                     // writing cache
00653                     fwrite( $rHandle, $this->_processCache( $sKey, $this->_aFileCacheContents[$sKey] ) );
00654 
00655                     // releasing locks
00656                     $this->_releaseFile( $sKey );
00657                 }
00658             }
00659 
00660             stopProfile("!__SAVING CACHE__! (warning)");
00661 
00662             //empty buffer
00663             $this->_aFileCacheContents = array();
00664         }
00665     }
00666 
00676     protected function _lockFile( $sFilePath, $sIdent, $iLockMode = LOCK_EX )
00677     {
00678         $rHandle = isset( $this->_aLockedFileHandles[$iLockMode][$sIdent] ) ? $this->_aLockedFileHandles[$iLockMode][$sIdent] : null;
00679         if ( $rHandle === null ) {
00680 
00681             $blLocked = false;
00682             $rHandle = @fopen( $sFilePath, "a+" );
00683 
00684             if ( $rHandle !== false ) {
00685 
00686                 if ( flock( $rHandle, $iLockMode | LOCK_NB ) ) {
00687                     if ( $iLockMode === LOCK_EX ) {
00688                         // truncate file
00689                         $blLocked = ftruncate( $rHandle, 0 );
00690                     } else {
00691                         // move to a start position
00692                         $blLocked = fseek( $rHandle, 0 ) === 0;
00693                     }
00694                 }
00695 
00696                 // on failure - closing and setting false..
00697                 if ( !$blLocked ) {
00698                     fclose( $rHandle );
00699                     $rHandle = false;
00700                 }
00701             }
00702 
00703             // in case system does not support file locking
00704             if ( !$blLocked && $iLockMode === LOCK_EX ) {
00705 
00706                 // clearing on first call
00707                 if ( count( $this->_aLockedFileHandles ) == 0 ) {
00708                     clearstatcache();
00709                 }
00710 
00711                 // start a blank file to inform other processes we are dealing with it.
00712                 if (!( file_exists( $sFilePath ) && !filesize( $sFilePath ) && abs( time() - filectime( $sFilePath ) < 40 ) ) ) {
00713                     $rHandle = @fopen( $sFilePath, "w" );
00714                 }
00715             }
00716 
00717             $this->_aLockedFileHandles[$iLockMode][$sIdent] = $rHandle;
00718         }
00719 
00720         return $rHandle;
00721     }
00722 
00731     protected function _releaseFile( $sIdent, $iLockMode = LOCK_EX )
00732     {
00733         $blSuccess = true;
00734         if ( isset( $this->_aLockedFileHandles[$iLockMode][$sIdent] ) &&
00735              $this->_aLockedFileHandles[$iLockMode][$sIdent] !== false ) {
00736 
00737              // release the lock and close file
00738             $blSuccess = flock( $this->_aLockedFileHandles[$iLockMode][$sIdent], LOCK_UN ) &&
00739                          fclose( $this->_aLockedFileHandles[$iLockMode][$sIdent] );
00740             unset( $this->_aLockedFileHandles[$iLockMode][$sIdent] );
00741         }
00742 
00743         return $blSuccess;
00744     }
00745 
00753     public function oxResetFileCache()
00754     {
00755         $aFiles = glob( $this->getCacheFilePath( null, true ) . '*' );
00756         if ( is_array( $aFiles ) ) {
00757             // delete all the files, except cached tables field names
00758             $aFiles = preg_grep( $this->_sPermanentCachePattern, $aFiles, PREG_GREP_INVERT );
00759             foreach ( $aFiles as $sFile ) {
00760                 @unlink( $sFile );
00761             }
00762         }
00763     }
00764 
00772     public function resetTemplateCache($aTemplates)
00773     {
00774         $sSmartyDir = oxRegistry::get("oxUtilsView")->getSmartyDir();
00775         //$aFiles = glob( $this->getCacheFilePath( null, true ) . '*' );
00776         $aFiles = glob( $sSmartyDir . '*' );
00777 
00778         if ( is_array( $aFiles ) && is_array( $aTemplates ) && count($aTemplates) ) {
00779             // delete all template cache files
00780             foreach ($aTemplates as &$sTemplate) {
00781                 $sTemplate = preg_quote(basename(strtolower($sTemplate), '.tpl'));
00782             }
00783 
00784             $sPattern = sprintf("/%%(%s)\.tpl\.php$/i", implode('|', $aTemplates));
00785             $aFiles = preg_grep( $sPattern, $aFiles );
00786 
00787             if (is_array( $aFiles ) ) {
00788                 foreach ( $aFiles as $sFile ) {
00789                     @unlink( $sFile );
00790                 }
00791             }
00792         }
00793 
00794     }
00795 
00801     public function resetLanguageCache()
00802     {
00803         $aFiles = glob( $this->getCacheFilePath( null, true ) . '*' );
00804         if ( is_array( $aFiles ) ) {
00805             // delete all language cache files
00806             $sPattern = $this->_sLanguageCachePattern;
00807             $aFiles = preg_grep( $sPattern, $aFiles );
00808             foreach ( $aFiles as $sFile ) {
00809                 @unlink( $sFile );
00810             }
00811         }
00812     }
00813 
00819     public function resetMenuCache()
00820     {
00821         $aFiles = glob( $this->getCacheFilePath( null, true ) . '*' );
00822         if ( is_array( $aFiles ) ) {
00823             // delete all menu cache files
00824             $sPattern = $this->_sMenuCachePattern;
00825             $aFiles = preg_grep( $sPattern, $aFiles );
00826             foreach ( $aFiles as $sFile ) {
00827                 @unlink( $sFile );
00828             }
00829         }
00830     }
00831 
00841     public function getRemoteCachePath($sRemote, $sLocal)
00842     {
00843         clearstatcache();
00844         if ( file_exists( $sLocal ) && filemtime( $sLocal ) && filemtime( $sLocal ) > time() - 86400 ) {
00845             return $sLocal;
00846         }
00847         $hRemote = @fopen( $sRemote, "rb");
00848         $blSuccess = false;
00849         if ( isset( $hRemote) && $hRemote ) {
00850             $hLocal = fopen( $sLocal, "wb");
00851             stream_copy_to_stream($hRemote, $hLocal);
00852             fclose($hRemote);
00853             fclose($hLocal);
00854             $blSuccess = true;
00855         } else {
00856             // try via fsockopen
00857             $aUrl = @parse_url( $sRemote);
00858             if ( !empty( $aUrl["host"])) {
00859                 $sPath = $aUrl["path"];
00860                 if ( empty( $sPath ) ) {
00861                     $sPath = "/";
00862                 }
00863                 $sHost = $aUrl["host"];
00864 
00865                 $hSocket = @fsockopen( $sHost, 80, $iErrorNumber, $iErrStr, 5);
00866                 if ( $hSocket) {
00867                     fputs( $hSocket, "GET ".$sPath." HTTP/1.0\r\nHost: $sHost\r\n\r\n");
00868                     $headers = stream_get_line($hSocket, 4096, "\r\n\r\n");
00869                     if ( ( $hLocal = @fopen( $sLocal, "wb") ) !== false ) {
00870                         rewind($hLocal);
00871                         // does not copy all the data
00872                         // stream_copy_to_stream($hSocket, $hLocal);
00873                         fwrite ( $hLocal, stream_get_contents( $hSocket ) );
00874                         fclose( $hLocal );
00875                         fclose( $hSocket );
00876                         $blSuccess = true;
00877                     }
00878                 }
00879             }
00880         }
00881         if ( $blSuccess || file_exists( $sLocal ) ) {
00882             return $sLocal;
00883         }
00884         return false;
00885     }
00886 
00892     public function canPreview()
00893     {
00894         $blCan = null;
00895         if ( ( $sPrevId = oxConfig::getParameter( 'preview' ) ) &&
00896              ( $sAdminSid = oxRegistry::get("oxUtilsServer")->getOxCookie( 'admin_sid' ) ) ) {
00897 
00898             $sTable = getViewName( 'oxuser' );
00899             $oDb = oxDb::getDb();
00900             $sQ = "select 1 from $sTable where MD5( CONCAT( ".$oDb->quote($sAdminSid).", {$sTable}.oxid, {$sTable}.oxpassword, {$sTable}.oxrights ) ) = ".oxDb::getDb()->quote($sPrevId);
00901             $blCan = (bool) $oDb->getOne( $sQ );
00902         }
00903 
00904         return $blCan;
00905     }
00906 
00912     public function getPreviewId()
00913     {
00914         $sAdminSid = oxRegistry::get("oxUtilsServer")->getOxCookie( 'admin_sid' );
00915         if ( ( $oUser = $this->getUser() ) ) {
00916             return md5( $sAdminSid . $oUser->getId() . $oUser->oxuser__oxpassword->value . $oUser->oxuser__oxrights->value );
00917         }
00918     }
00919 
00925     public function checkAccessRights()
00926     {
00927         $myConfig  = $this->getConfig();
00928 
00929         $blIsAuth = false;
00930 
00931         $sUserID = oxSession::getVar( "auth");
00932 
00933         // deleting admin marker
00934         oxSession::setVar( "malladmin", 0);
00935         oxSession::setVar( "blIsAdmin", 0);
00936         oxSession::deleteVar( "blIsAdmin" );
00937         $myConfig->setConfigParam( 'blMallAdmin', false );
00938         //#1552T
00939         $myConfig->setConfigParam( 'blAllowInheritedEdit', false );
00940 
00941         if ( $sUserID) {
00942             // escaping
00943             $oDb = oxDb::getDb();
00944             $sRights = $oDb->getOne("select oxrights from oxuser where oxid = ".$oDb->quote($sUserID));
00945 
00946             if ( $sRights != "user") {
00947                 // malladmin ?
00948                 if ( $sRights == "malladmin") {
00949                     oxSession::setVar( "malladmin", 1);
00950                     $myConfig->setConfigParam( 'blMallAdmin', true );
00951 
00952                     //#1552T
00953                     //So far this blAllowSharedEdit is Equal to blMallAdmin but in future to be solved over rights and roles
00954                     $myConfig->setConfigParam( 'blAllowSharedEdit', true );
00955 
00956                     $sShop = oxSession::getVar( "actshop");
00957                     if ( !isset($sShop)) {
00958                         oxSession::setVar( "actshop", $myConfig->getBaseShopId());
00959                     }
00960                     $blIsAuth = true;
00961                 } else {
00962                     // Shopadmin... check if this shop is valid and exists
00963                     $sShopID = $oDb->getOne("select oxid from oxshops where oxid = " . $oDb->quote( $sRights ) );
00964                     if ( isset( $sShopID) && $sShopID) {
00965                         // success, this shop exists
00966 
00967                         oxSession::setVar( "actshop", $sRights);
00968                         oxSession::setVar( "currentadminshop", $sRights);
00969                         oxSession::setVar( "shp", $sRights);
00970 
00971                         // check if this subshop admin is evil.
00972                         if ('chshp' == oxConfig::getParameter( 'fnc' )) {
00973                             // dont allow this call
00974                             $blIsAuth = false;
00975                         } else {
00976                             $blIsAuth = true;
00977 
00978                             $aShopIdVars = array('actshop', 'shp', 'currentadminshop');
00979                             foreach ($aShopIdVars as $sShopIdVar) {
00980                                 if ($sGotShop = oxConfig::getParameter( $sShopIdVar )) {
00981                                     if ($sGotShop != $sRights) {
00982                                         $blIsAuth = false;
00983                                         break;
00984                                     }
00985                                 }
00986                             }
00987                         }
00988                     }
00989                 }
00990                 // marking user as admin
00991                 oxSession::setVar( "blIsAdmin", 1);
00992             }
00993         }
00994         return $blIsAuth;
00995     }
00996 
01006     public function seoIsActive( $blReset = false, $sShopId = null, $iActLang = null )
01007     {
01008         if ( !is_null( $this->_blSeoIsActive ) && !$blReset ) {
01009             return $this->_blSeoIsActive;
01010         }
01011 
01012         $myConfig = $this->getConfig();
01013 
01014         if ( ( $this->_blSeoIsActive = $myConfig->getConfigParam( 'blSeoMode' ) ) === null ) {
01015             $this->_blSeoIsActive = true;
01016 
01017             $aSeoModes  = $myConfig->getconfigParam( 'aSeoModes' );
01018             $sActShopId = $sShopId ? $sShopId : $myConfig->getActiveShop()->getId();
01019             $iActLang   = $iActLang ? $iActLang : (int) oxRegistry::getLang()->getBaseLanguage();
01020 
01021             // checking special config param for active shop and language
01022             if ( is_array( $aSeoModes ) && isset( $aSeoModes[$sActShopId] ) && isset( $aSeoModes[$sActShopId][$iActLang] ) ) {
01023                 $this->_blSeoIsActive = (bool) $aSeoModes[$sActShopId][$iActLang];
01024             }
01025         }
01026 
01027         return $this->_blSeoIsActive;
01028     }
01029 
01037     public function isValidAlpha( $sField )
01038     {
01039         return (boolean) getStr()->preg_match( '/^[a-zA-Z0-9_]*$/', $sField );
01040     }
01041 
01051     protected function _simpleRedirect( $sUrl, $sHeaderCode )
01052     {
01053         $oHeader = oxNew( "oxHeader" );
01054         $oHeader->setHeader( $sHeaderCode );
01055         $oHeader->setHeader( "Location: $sUrl" );
01056         $oHeader->setHeader( "Connection: close" );
01057         $oHeader->sendHeader();
01058     }
01059 
01065     public function redirectOffline($iHeaderCode = 302)
01066     {
01067         $sUrl = $this->getConfig()->getShopUrl() .'offline.html';
01068         $this->redirect($sUrl, false, $iHeaderCode);
01069     }
01070 
01080     public function redirect( $sUrl, $blAddRedirectParam = true, $iHeaderCode = 302 )
01081     {
01082         //preventing possible cyclic redirection
01083         //#M341 and check only if redirect parameter must be added
01084         if ( $blAddRedirectParam && oxConfig::getParameter( 'redirected' ) ) {
01085             return;
01086         }
01087 
01088         if ( $blAddRedirectParam ) {
01089             $sUrl = $this->_addUrlParameters( $sUrl, array( 'redirected' => 1 ) );
01090         }
01091 
01092         $sUrl = str_ireplace( "&amp;", "&", $sUrl );
01093 
01094         switch ($iHeaderCode) {
01095             case 301:
01096                 $sHeaderCode = "HTTP/1.1 301 Moved Permanently";
01097                 break;
01098             case 500:
01099                 $sHeaderCode = "HTTP/1.1 500 Internal Server Error";
01100                 break;
01101             case 302:
01102             default:
01103                 $sHeaderCode = "HTTP/1.1 302 Found";
01104         }
01105 
01106         $this->_simpleRedirect( $sUrl, $sHeaderCode );
01107 
01108         try {//may occur in case db is lost
01109             $this->getSession()->freeze();
01110         } catch( oxException $oEx ) {
01111             $oEx->debugOut();
01112             //do nothing else to make sure the redirect takes place
01113         }
01114 
01115         if ( defined( 'OXID_PHP_UNIT' ) ) {
01116             return;
01117         }
01118 
01119         $this->showMessageAndExit( '' );
01120     }
01121 
01130     public function showMessageAndExit( $sMsg )
01131     {
01132         $this->getSession()->freeze();
01133         $this->commitFileCache();
01134 
01135         if ( defined( 'OXID_PHP_UNIT' ) ) {
01136             return;
01137         }
01138 
01139 
01140         exit( $sMsg );
01141     }
01142 
01150     public function setHeader($sHeader)
01151     {
01152         header($sHeader);
01153     }
01154 
01163     protected function _addUrlParameters( $sUrl, $aParams )
01164     {
01165         $sDelimiter = ( ( getStr()->strpos( $sUrl, '?' ) !== false ) )?'&':'?';
01166         foreach ( $aParams as $sName => $sVal ) {
01167             $sUrl = $sUrl . $sDelimiter . $sName . '=' . $sVal;
01168             $sDelimiter = '&';
01169         }
01170 
01171         return $sUrl;
01172     }
01173 
01185     protected function _fillExplodeArray( $aName, $dVat = null)
01186     {
01187         $myConfig = $this->getConfig();
01188         $oObject = new stdClass();
01189         $aPrice = explode( '!P!', $aName[0]);
01190 
01191         if ( ( $myConfig->getConfigParam( 'bl_perfLoadSelectLists' ) && $myConfig->getConfigParam( 'bl_perfUseSelectlistPrice' ) && isset( $aPrice[0] ) && isset( $aPrice[1] ) ) || $this->isAdmin() ) {
01192 
01193             // yes, price is there
01194             $oObject->price = isset( $aPrice[1] ) ? $aPrice[1] : 0;
01195             $aName[0] = isset( $aPrice[0] ) ? $aPrice[0] : '';
01196 
01197             $iPercPos = getStr()->strpos( $oObject->price, '%' );
01198             if ( $iPercPos !== false ) {
01199                 $oObject->priceUnit = '%';
01200                 $oObject->fprice = $oObject->price;
01201                 $oObject->price  = substr( $oObject->price, 0, $iPercPos );
01202             } else {
01203                 $oCur = $myConfig->getActShopCurrencyObject();
01204                 $oObject->price = str_replace(',', '.', $oObject->price);
01205                 $oObject->fprice = oxRegistry::getLang()->formatCurrency( $oObject->price  * $oCur->rate, $oCur);
01206                 $oObject->priceUnit = 'abs';
01207             }
01208 
01209             // add price info into list
01210             if ( !$this->isAdmin() && $oObject->price != 0 ) {
01211                 $aName[0] .= " ";
01212 
01213                 $dPrice = $this->_preparePrice( $oObject->price, $dVat );
01214 
01215                 if ( $oObject->price > 0 ) {
01216                     $aName[0] .= "+";
01217                 }
01218                 //V FS#2616
01219                 if ( $dVat != null && $oObject->priceUnit == 'abs' ) {
01220                     $oPrice = oxNew('oxPrice');
01221                     $oPrice->setPrice($oObject->price, $dVat);
01222                     $aName[0] .= oxRegistry::getLang()->formatCurrency( $dPrice * $oCur->rate, $oCur);
01223                 } else {
01224                     $aName[0] .= $oObject->fprice;
01225                 }
01226                 if ( $oObject->priceUnit == 'abs' ) {
01227                     $aName[0] .= " ".$oCur->sign;
01228                 }
01229             }
01230         } elseif ( isset( $aPrice[0] ) && isset($aPrice[1] ) ) {
01231             // A. removing unused part of information
01232             $aName[0] = getStr()->preg_replace( "/!P!.*/", "", $aName[0] );
01233         }
01234 
01235         $oObject->name  = $aName[0];
01236         $oObject->value = $aName[1];
01237         return $oObject;
01238     }
01239 
01248     protected function _preparePrice( $dPrice, $dVat )
01249     {
01250         $blCalculationModeNetto = (bool) $this->getConfig()->getConfigParam('blShowNetPrice');
01251 
01252         $oCurrency = $this->getConfig()->getActShopCurrencyObject();
01253 
01254         $blEnterNetPrice = $this->getConfig()->getConfigParam('blEnterNetPrice');
01255         if ( $blCalculationModeNetto && !$blEnterNetPrice ) {
01256             $dPrice = round( oxPrice::brutto2Netto( $dPrice, $dVat ), $oCurrency->decimal );
01257         } elseif ( !$blCalculationModeNetto && $blEnterNetPrice ) {
01258             $dPrice = round( oxPrice::netto2Brutto( $dPrice, $dVat ), $oCurrency->decimal );
01259         }
01260         return $dPrice;
01261     }
01269     public function oxMimeContentType( $sFileName )
01270     {
01271         $sFileName = strtolower( $sFileName );
01272         $iLastDot  = strrpos( $sFileName, '.' );
01273 
01274         if ( $iLastDot !== false ) {
01275             $sType = substr( $sFileName, $iLastDot + 1 );
01276             switch ( $sType ) {
01277                 case 'gif':
01278                     $sType = 'image/gif';
01279                     break;
01280                 case 'jpeg':
01281                 case 'jpg':
01282                     $sType = 'image/jpeg';
01283                     break;
01284                 case 'png':
01285                     $sType = 'image/png';
01286                     break;
01287                 default:
01288                     $sType = false;
01289                     break;
01290             }
01291         }
01292         return $sType;
01293     }
01294 
01303     public function logger( $sText, $blNewline = false )
01304     {   $myConfig = $this->getConfig();
01305 
01306         if ( $myConfig->getConfigParam( 'iDebug' ) == -2) {
01307             if ( gettype( $sText ) != 'string' ) {
01308                 $sText = var_export( $sText, true);
01309             }
01310             $sLogMsg = "----------------------------------------------\n{$sText}".( ( $blNewline ) ?"\n":"" )."\n";
01311             $this->writeToLog( $sLogMsg, "log.txt" );
01312         }
01313 
01314     }
01315 
01323     protected function _stripQuotes($mInput)
01324     {
01325         return is_array($mInput) ? array_map( array( $this, '_stripQuotes' ), $mInput) : stripslashes( $mInput );
01326     }
01327 
01335     public function strRot13( $sStr )
01336     {
01337         $sFrom = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
01338         $sTo   = 'nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM';
01339 
01340         return strtr( $sStr, $sFrom, $sTo );
01341     }
01342 
01352     public function getCacheFilePath( $sCacheName, $blPathOnly = false, $sExtension = 'txt' )
01353     {
01354 
01355             $sVersionPrefix = 'pe';
01356 
01357         $sPath = realpath($this->getConfig()->getConfigParam( 'sCompileDir' ));
01358 
01359         if (!$sPath) {
01360             return false;
01361         }
01362 
01363         return $blPathOnly ? "{$sPath}/" : "{$sPath}/ox{$sVersionPrefix}c_{$sCacheName}." . $sExtension;
01364     }
01365 
01373     public function getLangCache( $sCacheName )
01374     {
01375         $aLangCache = null;
01376         $sFilePath = $this->getCacheFilePath( $sCacheName );
01377         if ( file_exists( $sFilePath ) && is_readable( $sFilePath ) ) {
01378             include $sFilePath;
01379         }
01380         return $aLangCache;
01381     }
01382 
01391     public function setLangCache( $sCacheName, $aLangCache )
01392     {
01393         $sCache = "<?php\n\$aLangCache = ".var_export( $aLangCache, true ).";\n?>";
01394         $blRes = file_put_contents($this->getCacheFilePath($sCacheName), $sCache, LOCK_EX);
01395         return $blRes;
01396     }
01397 
01405     public function checkUrlEndingSlash( $sUrl )
01406     {
01407         if ( !getStr()->preg_match("/\/$/", $sUrl) ) {
01408             $sUrl .= '/';
01409         }
01410 
01411         return $sUrl;
01412     }
01413 
01422     public function writeToLog( $sLogMessage, $sLogFileName )
01423     {
01424         $sLogDist = $this->getConfig()->getLogsDir().$sLogFileName;
01425         $blOk = false;
01426 
01427         if ( ( $oHandle = fopen( $sLogDist, 'a' ) ) !== false ) {
01428             fwrite( $oHandle, $sLogMessage );
01429             $blOk = fclose( $oHandle );
01430         }
01431 
01432         return $blOk;
01433     }
01434 
01442     public function handlePageNotFoundError($sUrl = '')
01443     {
01444         $this->setHeader("HTTP/1.0 404 Not Found");
01445         if ( oxRegistry::getConfig()->isUtf() ) {
01446             $this->setHeader("Content-Type: text/html; charset=UTF-8");
01447         }
01448 
01449         $sReturn = "Page not found.";
01450         try {
01451             $oView = oxNew('oxUBase');
01452             $oView->init();
01453             $oView->render();
01454             $oView->setClassName( 'oxUBase' );
01455             $oView->addTplParam('sUrl', $sUrl);
01456             if ($sRet = oxRegistry::get("oxUtilsView")->getTemplateOutput('message/err_404.tpl', $oView)) {
01457                 $sReturn = $sRet;
01458             }
01459         } catch (Exception $e) {
01460         }
01461         $this->showMessageAndExit( $sReturn );
01462     }
01463 
01471     public function extractDomain( $sHost )
01472     {
01473         $oStr = getStr();
01474         if ( !$oStr->preg_match( '/[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}/', $sHost ) &&
01475              ( $iLastDot = strrpos( $sHost, '.' ) ) !== false ) {
01476             $iLen = $oStr->strlen( $sHost );
01477             if ( ( $iNextDot = strrpos( $sHost, '.', ( $iLen - $iLastDot + 1 ) * - 1 ) ) !== false ) {
01478                 $sHost = trim( $oStr->substr( $sHost, $iNextDot ), '.' );
01479             }
01480         }
01481 
01482         return $sHost;
01483     }
01484 }