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 isSearchEngine( $sClient = null )
00254     {
00255 
00256         if (!is_null($this->_blIsSe)) {
00257             return $this->_blIsSe;
00258         }
00259 
00260         startProfile("isSearchEngine");
00261 
00262         $myConfig = $this->getConfig();
00263         $blIsSe   = false;
00264 
00265         if ( !( $myConfig->getConfigParam( 'iDebug' ) && $this->isAdmin() ) ) {
00266 
00267             // caching
00268             $blIsSe = $myConfig->getGlobalParameter( 'blIsSearchEngine' );
00269             if ( !isset( $blIsSe ) ) {
00270 
00271                 $aRobots = $myConfig->getConfigParam( 'aRobots' );
00272                 $aRobots = is_array( $aRobots )?$aRobots:array();
00273 
00274                 $aRobotsExcept = $myConfig->getConfigParam( 'aRobotsExcept' );
00275                 $aRobotsExcept = is_array( $aRobotsExcept )?$aRobotsExcept:array();
00276 
00277                 $sClient = $sClient?$sClient:strtolower( getenv( 'HTTP_USER_AGENT' ) );
00278                 $blIsSe  = false;
00279                 $aRobots = array_merge( $aRobots, $aRobotsExcept );
00280                 foreach ( $aRobots as $sRobot ) {
00281                     if ( strpos( $sClient, $sRobot ) !== false ) {
00282                         $blIsSe = true;
00283                         break;
00284                     }
00285                 }
00286                 $myConfig->setGlobalParameter( 'blIsSearchEngine', $blIsSe );
00287             }
00288         }
00289 
00290         stopProfile("isSearchEngine");
00291 
00292         $this->_blIsSe = $blIsSe;
00293 
00294         return $blIsSe;
00295     }
00296 
00305     public function isValidEmail( $sEmail )
00306     {
00307         $blValid = true;
00308         if ( $sEmail != 'admin' ) {
00309             $sEmailTpl = "/^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/i";
00310             $blValid = ( getStr()->preg_match( $sEmailTpl, $sEmail ) != 0 );
00311         }
00312 
00313         return $blValid;
00314     }
00315 
00323     public function rebuildCache()
00324     {
00325         // not needed from 3.0 on and unused <- MK: not correct, its used for example in shop_config.php, oxbase.php
00326 
00327         //$smarty  = & oxUtils::getInstance()->getSmarty();
00328         //$smarty->clear_all_cache();
00329 
00330         if ( function_exists( "UserdefinedRebuildCache")) {
00331             UserdefinedRebuildCache();
00332         }
00333     }
00334 
00342     public function loadAdminProfile($aInterfaceProfiles)
00343     {
00344         // improved #533
00345         // checking for available profiles list
00346         $aInterfaceProfiles = $aInterfaceProfiles;
00347         if ( is_array( $aInterfaceProfiles ) ) {
00348             //checking for previous profiles
00349             $sPrevProfile = oxUtilsServer::getInstance()->getOxCookie('oxidadminprofile');
00350             if (isset($sPrevProfile)) {
00351                 $aPrevProfile = @explode("@", trim($sPrevProfile));
00352             }
00353 
00354             //array to store profiles
00355             $aProfiles = array();
00356             foreach ( $aInterfaceProfiles as $iPos => $sProfile) {
00357                 $aProfileSettings = array($iPos, $sProfile);
00358                 $aProfiles[] = $aProfileSettings;
00359             }
00360             // setting previous used profile as active
00361             if (isset($aPrevProfile[0]) && isset($aProfiles[$aPrevProfile[0]])) {
00362                 $aProfiles[$aPrevProfile[0]][2] = 1;
00363             }
00364 
00365             oxSession::setVar("aAdminProfiles", $aProfiles);
00366             return $aProfiles;
00367         }
00368         return null;
00369     }
00370 
00379     public function fRound($sVal, $oCur = null)
00380     {
00381         startProfile('fround');
00382 
00383         //cached currency precision, this saves about 1% of execution time
00384         $iCurPrecision = null;
00385         if (! defined('OXID_PHP_UNIT')) {
00386             $iCurPrecision = $this->_iCurPrecision;
00387         }
00388 
00389         if (is_null($iCurPrecision)) {
00390             if ( !$oCur ) {
00391                 $oCur = $this->getConfig()->getActShopCurrencyObject();
00392             }
00393 
00394             $iCurPrecision = $oCur->decimal;
00395             $this->_iCurPrecision = $iCurPrecision;
00396         }
00397 
00398         // this is a workaround for #36008 bug in php - incorrect round() & number_format() result (R)
00399         static $dprez = null;
00400         if (!$dprez) {
00401             $prez = @ini_get("precision");
00402             if (!$prez) {
00403                 $prez = 9;
00404             }
00405             $dprez = pow(10, -$prez);
00406         }
00407         stopProfile('fround');
00408 
00409         return round($sVal + $dprez * ( $sVal >= 0 ? 1 : -1 ), $iCurPrecision);
00410     }
00411 
00421     public function toStaticCache( $sName, $sContent, $sKey = null )
00422     {
00423         // if it's an array then we add
00424         if ( $sKey ) {
00425             $this->_aStaticCache[$sName][$sKey] = $sContent;
00426         } else {
00427             $this->_aStaticCache[$sName] = $sContent;
00428         }
00429     }
00430 
00438     public function fromStaticCache( $sName)
00439     {
00440         if ( isset( $this->_aStaticCache[$sName])) {
00441             return $this->_aStaticCache[$sName];
00442         }
00443         return null;
00444     }
00445 
00453     public function cleanStaticCache($sCacheName = null)
00454     {
00455         if ($sCacheName) {
00456             unset($this->_aStaticCache[$sCacheName]);
00457         } else {
00458             $this->_aStaticCache = null;
00459         }
00460     }
00461 
00471     public function toPhpFileCache( $sKey, $mContents )
00472     {
00473         //only simple arrays are supported
00474         if ( is_array( $mContents ) && ( $sCachePath = $this->getCacheFilePath( $sKey, false, 'php' ) ) ) {
00475 
00476             // setting meta
00477             $this->setCacheMeta( $sKey, array( "serialize" => false, "cachepath" => $sCachePath ) );
00478 
00479             // caching..
00480             $this->toFileCache( $sKey, $mContents );
00481         }
00482     }
00483 
00491     public function fromPhpFileCache( $sKey )
00492     {
00493         // setting meta
00494         $this->setCacheMeta( $sKey, array( "include" => true, "cachepath" => $this->getCacheFilePath( $sKey, false, 'php' ) ) );
00495         return $this->fromFileCache( $sKey );
00496     }
00497 
00505     public function getCacheMeta( $sKey )
00506     {
00507         return isset( $this->_aFileCacheMeta[$sKey] ) ? $this->_aFileCacheMeta[$sKey] : false;
00508     }
00509 
00518     public function setCacheMeta( $sKey, $aMeta )
00519     {
00520         // cache meta data
00521         $this->_aFileCacheMeta[$sKey] = $aMeta;
00522     }
00523 
00533     public function toFileCache( $sKey, $mContents )
00534     {
00535         $this->_aFileCacheContents[$sKey] = $mContents;
00536         $aMeta = $this->getCacheMeta( $sKey );
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             // release lock
00568             $this->_releaseFile( $sKey, LOCK_SH );
00569 
00570             // caching
00571             $this->_aFileCacheContents[$sKey] = $sRes;
00572         }
00573 
00574         return $this->_aFileCacheContents[$sKey];
00575     }
00576 
00584     protected function _readFile( $sFilePath )
00585     {
00586         $sRes = file_get_contents( $sFilePath );
00587         return $sRes ? unserialize( $sRes ) : null;
00588     }
00589 
00597     protected function _includeFile( $sFilePath )
00598     {
00599         $_aCacheContents = null;
00600         include $sFilePath;
00601         return $_aCacheContents;
00602     }
00603 
00612     protected function _processCache( $sKey, $mContents )
00613     {
00614         // looking for cache meta
00615         $aCacheMeta  = $this->getCacheMeta( $sKey );
00616         $blSerialize = isset( $aCacheMeta["serialize"] ) ? $aCacheMeta["serialize"] : true;
00617 
00618         if ( $blSerialize ) {
00619             $mContents = serialize( $mContents );
00620         } else {
00621             $mContents = "<?php\n//automatically generated file\n//" . date( "Y-m-d H:i:s" ) . "\n\n\$_aCacheContents = " . var_export( $mContents, true ) . "\n?>";
00622         }
00623 
00624         return $mContents;
00625     }
00626 
00633     public function commitFileCache()
00634     {
00635         if ( count( $this->_aLockedFileHandles[LOCK_EX] ) ) {
00636             startProfile("!__SAVING CACHE__! (warning)");
00637             foreach ( $this->_aLockedFileHandles[LOCK_EX] as $sKey => $rHandle ) {
00638                 if ( $rHandle !== false && isset( $this->_aFileCacheContents[$sKey] ) ) {
00639 
00640                     // #0002931A truncate file once more before writing
00641                     ftruncate( $rHandle, 0 );
00642 
00643                     // writing cache
00644                     fwrite( $rHandle, $this->_processCache( $sKey, $this->_aFileCacheContents[$sKey] ) );
00645 
00646                     // releasing locks
00647                     $this->_releaseFile( $sKey );
00648                 }
00649             }
00650 
00651             stopProfile("!__SAVING CACHE__! (warning)");
00652 
00653             //empty buffer
00654             $this->_aFileCacheContents = array();
00655         }
00656     }
00657 
00667     protected function _lockFile( $sFilePath, $sIdent, $iLockMode = LOCK_EX )
00668     {
00669         $rHandle = isset( $this->_aLockedFileHandles[$iLockMode][$sIdent] ) ? $this->_aLockedFileHandles[$iLockMode][$sIdent] : null;
00670         if ( $rHandle === null ) {
00671 
00672             $blLocked = false;
00673             $rHandle = @fopen( $sFilePath, "a+" );
00674 
00675             if ( $rHandle !== false ) {
00676 
00677                 if ( flock( $rHandle, $iLockMode | LOCK_NB ) ) {
00678                     if ( $iLockMode === LOCK_EX ) {
00679                         // truncate file
00680                         $blLocked = ftruncate( $rHandle, 0 );
00681                     } else {
00682                         // move to a start position
00683                         $blLocked = fseek( $rHandle, 0 ) === 0;
00684                     }
00685                 }
00686 
00687                 // on failure - closing and setting false..
00688                 if ( !$blLocked ) {
00689                     fclose( $rHandle );
00690                     $rHandle = false;
00691                 }
00692             }
00693 
00694             // in case system does not support file lockings
00695             if ( !$blLocked && $iLockMode === LOCK_EX ) {
00696 
00697                 // clearing on first call
00698                 if ( count( $this->_aLockedFileHandles ) == 0 ) {
00699                     clearstatcache();
00700                 }
00701 
00702                 // start a blank file to inform other processes we are dealing with it.
00703                 if (!( file_exists( $sFilePath ) && !filesize( $sFilePath ) && abs( time() - filectime( $sFilePath ) < 40 ) ) ) {
00704                     $rHandle = @fopen( $sFilePath, "w" );
00705                 }
00706             }
00707 
00708             $this->_aLockedFileHandles[$iLockMode][$sIdent] = $rHandle;
00709         }
00710 
00711         return $rHandle;
00712     }
00713 
00722     protected function _releaseFile( $sIdent, $iLockMode = LOCK_EX )
00723     {
00724         $blSuccess = true;
00725         if ( isset( $this->_aLockedFileHandles[$iLockMode][$sIdent] ) &&
00726              $this->_aLockedFileHandles[$iLockMode][$sIdent] !== false ) {
00727 
00728              // release the lock and close file
00729             $blSuccess = flock( $this->_aLockedFileHandles[$iLockMode][$sIdent], LOCK_UN ) &&
00730                          fclose( $this->_aLockedFileHandles[$iLockMode][$sIdent] );
00731             unset( $this->_aLockedFileHandles[$iLockMode][$sIdent] );
00732         }
00733 
00734         return $blSuccess;
00735     }
00736 
00744     public function oxResetFileCache()
00745     {
00746         $aFiles = glob( $this->getCacheFilePath( null, true ) . '*' );
00747         if ( is_array( $aFiles ) ) {
00748             // delete all the files, except cached tables fieldnames
00749             $aFiles = preg_grep( $this->_sPermanentCachePattern, $aFiles, PREG_GREP_INVERT );
00750             foreach ( $aFiles as $sFile ) {
00751                 @unlink( $sFile );
00752             }
00753         }
00754     }
00755 
00763     public function resetTemplateCache($aTemplates)
00764     {
00765         $aFiles = glob( $this->getCacheFilePath( null, true ) . '*' );
00766         if ( is_array( $aFiles ) && is_array( $aTemplates ) && count($aTemplates) ) {
00767             // delete all template cache files
00768             foreach ($aTemplates as &$sTemplate) {
00769                 $sTemplate = preg_quote(basename(strtolower($sTemplate), '.tpl'));
00770             }
00771 
00772             $sPattern = sprintf("/%%(%s)\.tpl\.php$/i", implode('|', $aTemplates));
00773             $aFiles = preg_grep( $sPattern, $aFiles );
00774             
00775             if (is_array( $aFiles ) ) {
00776                 foreach ( $aFiles as $sFile ) {
00777                     @unlink( $sFile );
00778                 }
00779             }
00780         }
00781 
00782     }
00783 
00789     public function resetLanguageCache()
00790     {
00791         $aFiles = glob( $this->getCacheFilePath( null, true ) . '*' );
00792         if ( is_array( $aFiles ) ) {
00793             // delete all language cache files
00794             $sPattern = $this->_sLanguageCachePattern;
00795             $aFiles = preg_grep( $sPattern, $aFiles );
00796             foreach ( $aFiles as $sFile ) {
00797                 @unlink( $sFile );
00798             }
00799         }
00800     }
00801 
00807     public function resetMenuCache()
00808     {
00809         $aFiles = glob( $this->getCacheFilePath( null, true ) . '*' );
00810         if ( is_array( $aFiles ) ) {
00811             // delete all menu cache files
00812             $sPattern = $this->_sMenuCachePattern;
00813             $aFiles = preg_grep( $sPattern, $aFiles );
00814             foreach ( $aFiles as $sFile ) {
00815                 @unlink( $sFile );
00816             }
00817         }
00818     }
00819 
00829     public function getRemoteCachePath($sRemote, $sLocal)
00830     {
00831         clearstatcache();
00832         if ( file_exists( $sLocal ) && filemtime( $sLocal ) && filemtime( $sLocal ) > time() - 86400 ) {
00833             return $sLocal;
00834         }
00835         $hRemote = @fopen( $sRemote, "rb");
00836         $blSuccess = false;
00837         if ( isset( $hRemote) && $hRemote ) {
00838             $hLocal = fopen( $sLocal, "wb");
00839             stream_copy_to_stream($hRemote, $hLocal);
00840             fclose($hRemote);
00841             fclose($hLocal);
00842             $blSuccess = true;
00843         } else {
00844             // try via fsockopen
00845             $aUrl = @parse_url( $sRemote);
00846             if ( !empty( $aUrl["host"])) {
00847                 $sPath = $aUrl["path"];
00848                 if ( empty( $sPath ) ) {
00849                     $sPath = "/";
00850                 }
00851                 $sHost = $aUrl["host"];
00852 
00853                 $hSocket = @fsockopen( $sHost, 80, $iErrorNumber, $iErrStr, 5);
00854                 if ( $hSocket) {
00855                     fputs( $hSocket, "GET ".$sPath." HTTP/1.0\r\nHost: $sHost\r\n\r\n");
00856                     $headers = stream_get_line($hSocket, 4096, "\r\n\r\n");
00857                     if ( ( $hLocal = @fopen( $sLocal, "wb") ) !== false ) {
00858                         rewind($hLocal);
00859                         // does not copy all the data
00860                         // stream_copy_to_stream($hSocket, $hLocal);
00861                         fwrite ( $hLocal, stream_get_contents( $hSocket ) );
00862                         fclose( $hLocal );
00863                         fclose( $hSocket );
00864                         $blSuccess = true;
00865                     }
00866                 }
00867             }
00868         }
00869         if ( $blSuccess || file_exists( $sLocal ) ) {
00870             return $sLocal;
00871         }
00872         return false;
00873     }
00874 
00880     public function canPreview()
00881     {
00882         $blCan = null;
00883         if ( ( $sPrevId = oxConfig::getParameter( 'preview' ) ) &&
00884              ( $sAdminSid = oxUtilsServer::getInstance()->getOxCookie( 'admin_sid' ) ) ) {
00885 
00886             $sTable = getViewName( 'oxuser' );
00887             $oDb = oxDb::getDb();
00888             $sQ = "select 1 from $sTable where MD5( CONCAT( ".$oDb->quote($sAdminSid).", {$sTable}.oxid, {$sTable}.oxpassword, {$sTable}.oxrights ) ) = ".oxDb::getDb()->quote($sPrevId);
00889             $blCan = (bool) $oDb->getOne( $sQ );
00890         }
00891 
00892         return $blCan;
00893     }
00894 
00900     public function getPreviewId()
00901     {
00902         $sAdminSid = oxUtilsServer::getInstance()->getOxCookie( 'admin_sid' );
00903         if ( ( $oUser = $this->getUser() ) ) {
00904             return md5( $sAdminSid . $oUser->getId() . $oUser->oxuser__oxpassword->value . $oUser->oxuser__oxrights->value );
00905         }
00906     }
00907 
00913     public function checkAccessRights()
00914     {
00915         $myConfig  = $this->getConfig();
00916 
00917         $blIsAuth = false;
00918 
00919         $sUserID = oxSession::getVar( "auth");
00920 
00921         // deleting admin marker
00922         oxSession::setVar( "malladmin", 0);
00923         oxSession::setVar( "blIsAdmin", 0);
00924         oxSession::deleteVar( "blIsAdmin" );
00925         $myConfig->setConfigParam( 'blMallAdmin', false );
00926         //#1552T
00927         $myConfig->setConfigParam( 'blAllowInheritedEdit', false );
00928 
00929         if ( $sUserID) {
00930             // escaping
00931             $oDb = oxDb::getDb();
00932             $sRights = $oDb->getOne("select oxrights from oxuser where oxid = ".$oDb->quote($sUserID));
00933 
00934             if ( $sRights != "user") {
00935                 // malladmin ?
00936                 if ( $sRights == "malladmin") {
00937                     oxSession::setVar( "malladmin", 1);
00938                     $myConfig->setConfigParam( 'blMallAdmin', true );
00939 
00940                     //#1552T
00941                     //So far this blAllowSharedEdit is Equal to blMallAdmin but in future to be solved over rights and roles
00942                     $myConfig->setConfigParam( 'blAllowSharedEdit', true );
00943 
00944                     $sShop = oxSession::getVar( "actshop");
00945                     if ( !isset($sShop)) {
00946                         oxSession::setVar( "actshop", $myConfig->getBaseShopId());
00947                     }
00948                     $blIsAuth = true;
00949                 } else {
00950                     // Shopadmin... check if this shop is valid and exists
00951                     $sShopID = $oDb->getOne("select oxid from oxshops where oxid = " . $oDb->quote( $sRights ) );
00952                     if ( isset( $sShopID) && $sShopID) {
00953                         // success, this shop exists
00954 
00955                         oxSession::setVar( "actshop", $sRights);
00956                         oxSession::setVar( "currentadminshop", $sRights);
00957                         oxSession::setVar( "shp", $sRights);
00958 
00959                         // check if this subshop admin is evil.
00960                         if ('chshp' == oxConfig::getParameter( 'fnc' )) {
00961                             // dont allow this call
00962                             $blIsAuth = false;
00963                         } else {
00964                             $blIsAuth = true;
00965 
00966                             $aShopIdVars = array('actshop', 'shp', 'currentadminshop');
00967                             foreach ($aShopIdVars as $sShopIdVar) {
00968                                 if ($sGotShop = oxConfig::getParameter( $sShopIdVar )) {
00969                                     if ($sGotShop != $sRights) {
00970                                         $blIsAuth = false;
00971                                         break;
00972                                     }
00973                                 }
00974                             }
00975                         }
00976                     }
00977                 }
00978                 // marking user as admin
00979                 oxSession::setVar( "blIsAdmin", 1);
00980             }
00981         }
00982         return $blIsAuth;
00983     }
00984 
00994     public function seoIsActive( $blReset = false, $sShopId = null, $iActLang = null )
00995     {
00996         if ( !is_null( $this->_blSeoIsActive ) && !$blReset ) {
00997             return $this->_blSeoIsActive;
00998         }
00999 
01000         $myConfig = $this->getConfig();
01001 
01002         if ( ( $this->_blSeoIsActive = $myConfig->getConfigParam( 'blSeoMode' ) ) === null ) {
01003             $this->_blSeoIsActive = true;
01004 
01005             $aSeoModes  = $myConfig->getconfigParam( 'aSeoModes' );
01006             $sActShopId = $sShopId ? $sShopId : $myConfig->getActiveShop()->getId();
01007             $iActLang   = $iActLang ? $iActLang : (int) oxLang::getInstance()->getBaseLanguage();
01008 
01009             // checking special config param for active shop and language
01010             if ( is_array( $aSeoModes ) && isset( $aSeoModes[$sActShopId] ) && isset( $aSeoModes[$sActShopId][$iActLang] ) ) {
01011                 $this->_blSeoIsActive = (bool) $aSeoModes[$sActShopId][$iActLang];
01012             }
01013         }
01014 
01015         return $this->_blSeoIsActive;
01016     }
01017 
01029     public function getShopBit( $iShopId )
01030     {
01031         return oxShopMetaData::getInstance()->getShopBit( $iShopId );
01032     }
01033 
01045     public function bitwiseAnd( $iVal1, $iVal2 )
01046     {
01047         //this works for large numbers when $sShopNr is up to (inclusive) 64
01048         $iRes = oxDb::getDb()->getOne( "select ($iVal1 & $iVal2) as bitwiseAnd" );
01049 
01050         //as php ints supports only 32 bits, we return string.
01051         return $iRes;
01052     }
01053 
01065     public function bitwiseOr( $iVal1, $iVal2 )
01066     {
01067         //this works for large numbers when $sShopNr is up to (inclusive) 64
01068         $iRes = oxDb::getDb()->getOne( "select ($iVal1 | $iVal2) as bitwiseOr" );
01069 
01070         //as php ints supports only 32 bits, we return string.
01071         return $iRes;
01072     }
01073 
01081     public function isValidAlpha( $sField )
01082     {
01083         return (boolean) getStr()->preg_match( '/^[a-zA-Z0-9_]*$/', $sField );
01084     }
01085 
01095     protected function _simpleRedirect( $sUrl, $sHeaderCode )
01096     {
01097         header( $sHeaderCode );
01098         header( "Location: $sUrl" );
01099         header( "Connection: close" );
01100     }
01101 
01115     public function redirect( $sUrl, $blAddRedirectParam = true, $iHeaderCode = 301 )
01116     {
01117         //preventing possible cyclic redirection
01118         //#M341 and check only if redirect paramater must be added
01119         if ( $blAddRedirectParam && oxConfig::getParameter( 'redirected' ) ) {
01120             return;
01121         }
01122 
01123         if ( $blAddRedirectParam ) {
01124             $sUrl = $this->_addUrlParameters( $sUrl, array( 'redirected' => 1 ) );
01125         }
01126 
01127         $sUrl = str_ireplace( "&amp;", "&", $sUrl );
01128 
01129         $sHeaderCode = '';
01130         switch ($iHeaderCode) {
01131             case 301:
01132                 $sHeaderCode = "HTTP/1.1 301 Moved Permanently";
01133                 break;
01134             case 302:
01135             default:
01136                 $sHeaderCode = "HTTP/1.1 302 Found";
01137         }
01138 
01139         $this->_simpleRedirect( $sUrl, $sHeaderCode );
01140 
01141         try {//may occur in case db is lost
01142             $this->getSession()->freeze();
01143         } catch( oxException $oEx ) {
01144             $oEx->debugOut();
01145             //do nothing else to make sure the redirect takes place
01146         }
01147 
01148         if ( defined( 'OXID_PHP_UNIT' ) ) {
01149             return;
01150         }
01151 
01152         $this->showMessageAndExit( '' );
01153     }
01154 
01162     public function showMessageAndExit( $sMsg )
01163     {
01164         $this->getSession()->freeze();
01165         $this->commitFileCache();
01166 
01167         if ( defined( 'OXID_PHP_UNIT' ) ) {
01168             return;
01169         }
01170 
01171         exit( $sMsg );
01172     }
01173 
01181     public function setHeader($sHeader)
01182     {
01183         header($sHeader);
01184     }
01185 
01194     protected function _addUrlParameters( $sUrl, $aParams )
01195     {
01196         $sDelim = ( ( getStr()->strpos( $sUrl, '?' ) !== false ) )?'&':'?';
01197         foreach ( $aParams as $sName => $sVal ) {
01198             $sUrl = $sUrl . $sDelim . $sName . '=' . $sVal;
01199             $sDelim = '&';
01200         }
01201 
01202         return $sUrl;
01203     }
01204 
01216     protected function _fillExplodeArray( $aName, $dVat = null)
01217     {
01218         $myConfig = $this->getConfig();
01219         $oObject = new oxStdClass();
01220         $aPrice = explode( '!P!', $aName[0]);
01221 
01222         if ( ( $myConfig->getConfigParam( 'bl_perfLoadSelectLists' ) && $myConfig->getConfigParam( 'bl_perfUseSelectlistPrice' ) && isset( $aPrice[0] ) && isset( $aPrice[1] ) ) || $this->isAdmin() ) {
01223 
01224             // yes, price is there
01225             $oObject->price = isset( $aPrice[1] ) ? $aPrice[1] : 0;
01226             $aName[0] = isset( $aPrice[0] ) ? $aPrice[0] : '';
01227 
01228             $iPercPos = getStr()->strpos( $oObject->price, '%' );
01229             if ( $iPercPos !== false ) {
01230                 $oObject->priceUnit = '%';
01231                 $oObject->fprice = $oObject->price;
01232                 $oObject->price  = substr( $oObject->price, 0, $iPercPos );
01233             } else {
01234                 $oCur = $myConfig->getActShopCurrencyObject();
01235                 $oObject->price = str_replace(',', '.', $oObject->price);
01236                 $oObject->fprice = oxLang::getInstance()->formatCurrency( $oObject->price  * $oCur->rate, $oCur);
01237                 $oObject->priceUnit = 'abs';
01238             }
01239 
01240             // add price info into list
01241             if ( !$this->isAdmin() && $oObject->price != 0 ) {
01242                 $aName[0] .= " ";
01243                 if ( $oObject->price > 0 ) {
01244                     $aName[0] .= "+";
01245                 }
01246                 //V FS#2616
01247                 if ( $dVat != null && $oObject->priceUnit == 'abs' ) {
01248                     $oPrice = oxNew('oxPrice');
01249                     $oPrice->setPrice($oObject->price, $dVat);
01250                     $aName[0] .= oxLang::getInstance()->formatCurrency( $oPrice->getBruttoPrice() * $oCur->rate, $oCur);
01251                 } else {
01252                     $aName[0] .= $oObject->fprice;
01253                 }
01254                 if ( $oObject->priceUnit == 'abs' ) {
01255                     $aName[0] .= " ".$oCur->sign;
01256                 }
01257             }
01258         } elseif ( isset( $aPrice[0] ) && isset($aPrice[1] ) ) {
01259             // A. removing unused part of information
01260             $aName[0] = getStr()->preg_replace( "/!P!.*/", "", $aName[0] );
01261         }
01262 
01263         $oObject->name  = $aName[0];
01264         $oObject->value = $aName[1];
01265         return $oObject;
01266     }
01267 
01275     public function oxMimeContentType( $sFileName )
01276     {
01277         $sFileName = strtolower( $sFileName );
01278         $iLastDot  = strrpos( $sFileName, '.' );
01279 
01280         if ( $iLastDot !== false ) {
01281             $sType = substr( $sFileName, $iLastDot + 1 );
01282             switch ( $sType ) {
01283                 case 'gif':
01284                     $sType = 'image/gif';
01285                     break;
01286                 case 'jpeg':
01287                 case 'jpg':
01288                     $sType = 'image/jpeg';
01289                     break;
01290                 case 'png':
01291                     $sType = 'image/png';
01292                     break;
01293                 default:
01294                     $sType = false;
01295                     break;
01296             }
01297         }
01298         return $sType;
01299     }
01300 
01309     public function logger( $sText, $blNewline = false )
01310     {   $myConfig = $this->getConfig();
01311 
01312         if ( $myConfig->getConfigParam( 'iDebug' ) == -2) {
01313             if ( gettype( $sText ) != 'string' ) {
01314                 $sText = var_export( $sText, true);
01315             }
01316             $sLogMsg = "----------------------------------------------\n{$sText}".( ( $blNewline ) ?"\n":"" )."\n";
01317             $this->writeToLog( $sLogMsg, "log.txt" );
01318         }
01319 
01320     }
01321 
01329     protected function _stripQuotes($mInput)
01330     {
01331         return is_array($mInput) ? array_map( array( $this, '_stripQuotes' ), $mInput) : stripslashes( $mInput );
01332     }
01333 
01341     public function strRot13( $sStr )
01342     {
01343         $sFrom = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
01344         $sTo   = 'nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM';
01345 
01346         return strtr( $sStr, $sFrom, $sTo );
01347     }
01348 
01358     public function getCacheFilePath( $sCacheName, $blPathOnly = false, $sExtension = 'txt' )
01359     {
01360         $sVersionPrefix = "";
01361 
01362 
01363             $sVersionPrefix = 'pe';
01364 
01365         $sPath = realpath($this->getConfig()->getConfigParam( 'sCompileDir' ));
01366 
01367         if (!$sPath) {
01368             return false;
01369         }
01370 
01371         return $blPathOnly ? "{$sPath}/" : "{$sPath}/ox{$sVersionPrefix}c_{$sCacheName}." . $sExtension;
01372     }
01373 
01381     public function getLangCache( $sCacheName )
01382     {
01383         $aLangCache = null;
01384         $sFilePath = $this->getCacheFilePath( $sCacheName );
01385         if ( file_exists( $sFilePath ) && is_readable( $sFilePath ) ) {
01386             include $sFilePath;
01387         }
01388         return $aLangCache;
01389     }
01390 
01399     public function setLangCache( $sCacheName, $aLangCache )
01400     {
01401         $sCache = "<?php\n\$aLangCache = ".var_export( $aLangCache, true ).";";
01402         $blRes = file_put_contents($this->getCacheFilePath($sCacheName), $sCache);
01403         return $blRes;
01404     }
01405 
01413     public function checkUrlEndingSlash( $sUrl )
01414     {
01415         if ( !getStr()->preg_match("/\/$/", $sUrl) ) {
01416             $sUrl .= '/';
01417         }
01418 
01419         return $sUrl;
01420     }
01421 
01430     public function writeToLog( $sLogMessage, $sLogFileName )
01431     {
01432         $sLogDist = $this->getConfig()->getLogsDir().$sLogFileName;
01433         $blOk = false;
01434 
01435         if ( ( $oHandle = fopen( $sLogDist, 'a' ) ) !== false ) {
01436             fwrite( $oHandle, $sLogMessage );
01437             $blOk = fclose( $oHandle );
01438         }
01439 
01440         return $blOk;
01441     }
01442 
01450     public function handlePageNotFoundError($sUrl = '')
01451     {
01452         $this->setHeader("HTTP/1.0 404 Not Found");
01453         if ( oxConfig::getInstance()->isUtf() ) {
01454             $this->setHeader("Content-Type: text/html; charset=UTF-8");
01455         }
01456 
01457         $sReturn = "Page not found.";
01458         try {
01459             $oView = oxNew('oxubase');
01460             $oView->init();
01461             $oView->render();
01462             $oView->addTplParam('sUrl', $sUrl);
01463             if ($sRet = oxUtilsView::getInstance()->getTemplateOutput('message/err_404.tpl', $oView)) {
01464                 $sReturn = $sRet;
01465             }
01466         } catch (Exception $e) {
01467         }
01468         $this->showMessageAndExit( $sReturn );
01469     }
01470 
01478     public function extractDomain( $sHost )
01479     {
01480         $oStr = getStr();
01481         if ( !$oStr->preg_match( '/[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}/', $sHost ) &&
01482              ( $iLastDot = strrpos( $sHost, '.' ) ) !== false ) {
01483             $iLen = $oStr->strlen( $sHost );
01484             if ( ( $iNextDot = strrpos( $sHost, '.', ( $iLen - $iLastDot + 1 ) * - 1 ) ) !== false ) {
01485                 $sHost = trim( $oStr->substr( $sHost, $iNextDot ), '.' );
01486             }
01487         }
01488 
01489         return $sHost;
01490     }
01491 }