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         header( $sHeaderCode );
01054         header( "Location: $sUrl" );
01055         header( "Connection: close" );
01056     }
01057 
01067     public function redirect( $sUrl, $blAddRedirectParam = true, $iHeaderCode = 302 )
01068     {
01069         //preventing possible cyclic redirection
01070         //#M341 and check only if redirect parameter must be added
01071         if ( $blAddRedirectParam && oxConfig::getParameter( 'redirected' ) ) {
01072             return;
01073         }
01074 
01075         if ( $blAddRedirectParam ) {
01076             $sUrl = $this->_addUrlParameters( $sUrl, array( 'redirected' => 1 ) );
01077         }
01078 
01079         $sUrl = str_ireplace( "&amp;", "&", $sUrl );
01080 
01081         $sHeaderCode = '';
01082         switch ($iHeaderCode) {
01083             case 301:
01084                 $sHeaderCode = "HTTP/1.1 301 Moved Permanently";
01085                 break;
01086             case 302:
01087             default:
01088                 $sHeaderCode = "HTTP/1.1 302 Found";
01089         }
01090 
01091         $this->_simpleRedirect( $sUrl, $sHeaderCode );
01092 
01093         try {//may occur in case db is lost
01094             $this->getSession()->freeze();
01095         } catch( oxException $oEx ) {
01096             $oEx->debugOut();
01097             //do nothing else to make sure the redirect takes place
01098         }
01099 
01100         if ( defined( 'OXID_PHP_UNIT' ) ) {
01101             return;
01102         }
01103 
01104         $this->showMessageAndExit( '' );
01105     }
01106 
01115     public function showMessageAndExit( $sMsg )
01116     {
01117         $this->getSession()->freeze();
01118         $this->commitFileCache();
01119 
01120         if ( defined( 'OXID_PHP_UNIT' ) ) {
01121             return;
01122         }
01123 
01124 
01125         exit( $sMsg );
01126     }
01127 
01135     public function setHeader($sHeader)
01136     {
01137         header($sHeader);
01138     }
01139 
01148     protected function _addUrlParameters( $sUrl, $aParams )
01149     {
01150         $sDelimiter = ( ( getStr()->strpos( $sUrl, '?' ) !== false ) )?'&':'?';
01151         foreach ( $aParams as $sName => $sVal ) {
01152             $sUrl = $sUrl . $sDelimiter . $sName . '=' . $sVal;
01153             $sDelimiter = '&';
01154         }
01155 
01156         return $sUrl;
01157     }
01158 
01170     protected function _fillExplodeArray( $aName, $dVat = null)
01171     {
01172         $myConfig = $this->getConfig();
01173         $oObject = new stdClass();
01174         $aPrice = explode( '!P!', $aName[0]);
01175 
01176         if ( ( $myConfig->getConfigParam( 'bl_perfLoadSelectLists' ) && $myConfig->getConfigParam( 'bl_perfUseSelectlistPrice' ) && isset( $aPrice[0] ) && isset( $aPrice[1] ) ) || $this->isAdmin() ) {
01177 
01178             // yes, price is there
01179             $oObject->price = isset( $aPrice[1] ) ? $aPrice[1] : 0;
01180             $aName[0] = isset( $aPrice[0] ) ? $aPrice[0] : '';
01181 
01182             $iPercPos = getStr()->strpos( $oObject->price, '%' );
01183             if ( $iPercPos !== false ) {
01184                 $oObject->priceUnit = '%';
01185                 $oObject->fprice = $oObject->price;
01186                 $oObject->price  = substr( $oObject->price, 0, $iPercPos );
01187             } else {
01188                 $oCur = $myConfig->getActShopCurrencyObject();
01189                 $oObject->price = str_replace(',', '.', $oObject->price);
01190                 $oObject->fprice = oxRegistry::getLang()->formatCurrency( $oObject->price  * $oCur->rate, $oCur);
01191                 $oObject->priceUnit = 'abs';
01192             }
01193 
01194             // add price info into list
01195             if ( !$this->isAdmin() && $oObject->price != 0 ) {
01196                 $aName[0] .= " ";
01197 
01198                 $dPrice = $this->_preparePrice( $oObject->price, $dVat );
01199 
01200                 if ( $oObject->price > 0 ) {
01201                     $aName[0] .= "+";
01202                 }
01203                 //V FS#2616
01204                 if ( $dVat != null && $oObject->priceUnit == 'abs' ) {
01205                     $oPrice = oxNew('oxPrice');
01206                     $oPrice->setPrice($oObject->price, $dVat);
01207                     $aName[0] .= oxRegistry::getLang()->formatCurrency( $dPrice * $oCur->rate, $oCur);
01208                 } else {
01209                     $aName[0] .= $oObject->fprice;
01210                 }
01211                 if ( $oObject->priceUnit == 'abs' ) {
01212                     $aName[0] .= " ".$oCur->sign;
01213                 }
01214             }
01215         } elseif ( isset( $aPrice[0] ) && isset($aPrice[1] ) ) {
01216             // A. removing unused part of information
01217             $aName[0] = getStr()->preg_replace( "/!P!.*/", "", $aName[0] );
01218         }
01219 
01220         $oObject->name  = $aName[0];
01221         $oObject->value = $aName[1];
01222         return $oObject;
01223     }
01224 
01233     protected function _preparePrice( $dPrice, $dVat )
01234     {
01235         $blCalculationModeNetto = (bool) $this->getConfig()->getConfigParam('blShowNetPrice');
01236 
01237         $blEnterNetPrice = $this->getConfig()->getConfigParam('blEnterNetPrice');
01238         if ( $blCalculationModeNetto && !$blEnterNetPrice ) {
01239             $dPrice = round( oxPrice::brutto2Netto( $dPrice, $dVat ), 2 );
01240         } elseif ( !$blCalculationModeNetto && $blEnterNetPrice ) {
01241             $dPrice = round( oxPrice::netto2Brutto( $dPrice, $dVat ), 2 );
01242         }
01243         return $dPrice;
01244     }
01252     public function oxMimeContentType( $sFileName )
01253     {
01254         $sFileName = strtolower( $sFileName );
01255         $iLastDot  = strrpos( $sFileName, '.' );
01256 
01257         if ( $iLastDot !== false ) {
01258             $sType = substr( $sFileName, $iLastDot + 1 );
01259             switch ( $sType ) {
01260                 case 'gif':
01261                     $sType = 'image/gif';
01262                     break;
01263                 case 'jpeg':
01264                 case 'jpg':
01265                     $sType = 'image/jpeg';
01266                     break;
01267                 case 'png':
01268                     $sType = 'image/png';
01269                     break;
01270                 default:
01271                     $sType = false;
01272                     break;
01273             }
01274         }
01275         return $sType;
01276     }
01277 
01286     public function logger( $sText, $blNewline = false )
01287     {   $myConfig = $this->getConfig();
01288 
01289         if ( $myConfig->getConfigParam( 'iDebug' ) == -2) {
01290             if ( gettype( $sText ) != 'string' ) {
01291                 $sText = var_export( $sText, true);
01292             }
01293             $sLogMsg = "----------------------------------------------\n{$sText}".( ( $blNewline ) ?"\n":"" )."\n";
01294             $this->writeToLog( $sLogMsg, "log.txt" );
01295         }
01296 
01297     }
01298 
01306     protected function _stripQuotes($mInput)
01307     {
01308         return is_array($mInput) ? array_map( array( $this, '_stripQuotes' ), $mInput) : stripslashes( $mInput );
01309     }
01310 
01318     public function strRot13( $sStr )
01319     {
01320         $sFrom = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
01321         $sTo   = 'nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM';
01322 
01323         return strtr( $sStr, $sFrom, $sTo );
01324     }
01325 
01335     public function getCacheFilePath( $sCacheName, $blPathOnly = false, $sExtension = 'txt' )
01336     {
01337 
01338             $sVersionPrefix = 'pe';
01339 
01340         $sPath = realpath($this->getConfig()->getConfigParam( 'sCompileDir' ));
01341 
01342         if (!$sPath) {
01343             return false;
01344         }
01345 
01346         return $blPathOnly ? "{$sPath}/" : "{$sPath}/ox{$sVersionPrefix}c_{$sCacheName}." . $sExtension;
01347     }
01348 
01356     public function getLangCache( $sCacheName )
01357     {
01358         $aLangCache = null;
01359         $sFilePath = $this->getCacheFilePath( $sCacheName );
01360         if ( file_exists( $sFilePath ) && is_readable( $sFilePath ) ) {
01361             include $sFilePath;
01362         }
01363         return $aLangCache;
01364     }
01365 
01374     public function setLangCache( $sCacheName, $aLangCache )
01375     {
01376         $sCache = "<?php\n\$aLangCache = ".var_export( $aLangCache, true ).";\n?>";
01377         $blRes = file_put_contents($this->getCacheFilePath($sCacheName), $sCache, LOCK_EX);
01378         return $blRes;
01379     }
01380 
01388     public function checkUrlEndingSlash( $sUrl )
01389     {
01390         if ( !getStr()->preg_match("/\/$/", $sUrl) ) {
01391             $sUrl .= '/';
01392         }
01393 
01394         return $sUrl;
01395     }
01396 
01405     public function writeToLog( $sLogMessage, $sLogFileName )
01406     {
01407         $sLogDist = $this->getConfig()->getLogsDir().$sLogFileName;
01408         $blOk = false;
01409 
01410         if ( ( $oHandle = fopen( $sLogDist, 'a' ) ) !== false ) {
01411             fwrite( $oHandle, $sLogMessage );
01412             $blOk = fclose( $oHandle );
01413         }
01414 
01415         return $blOk;
01416     }
01417 
01425     public function handlePageNotFoundError($sUrl = '')
01426     {
01427         $this->setHeader("HTTP/1.0 404 Not Found");
01428         if ( oxRegistry::getConfig()->isUtf() ) {
01429             $this->setHeader("Content-Type: text/html; charset=UTF-8");
01430         }
01431 
01432         $sReturn = "Page not found.";
01433         try {
01434             $oView = oxNew('oxUBase');
01435             $oView->init();
01436             $oView->render();
01437             $oView->setClassName( 'oxUBase' );
01438             $oView->addTplParam('sUrl', $sUrl);
01439             if ($sRet = oxRegistry::get("oxUtilsView")->getTemplateOutput('message/err_404.tpl', $oView)) {
01440                 $sReturn = $sRet;
01441             }
01442         } catch (Exception $e) {
01443         }
01444         $this->showMessageAndExit( $sReturn );
01445     }
01446 
01454     public function extractDomain( $sHost )
01455     {
01456         $oStr = getStr();
01457         if ( !$oStr->preg_match( '/[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}/', $sHost ) &&
01458              ( $iLastDot = strrpos( $sHost, '.' ) ) !== false ) {
01459             $iLen = $oStr->strlen( $sHost );
01460             if ( ( $iNextDot = strrpos( $sHost, '.', ( $iLen - $iLastDot + 1 ) * - 1 ) ) !== false ) {
01461                 $sHost = trim( $oStr->substr( $sHost, $iNextDot ), '.' );
01462             }
01463         }
01464 
01465         return $sHost;
01466     }
01467 }