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 
00033     protected $_sEmailTpl = "/^([-!#\$%&'*+.\/0-9=?A-Z^_`a-z{|}~\177])+@([-!#\$%&'*+\/0-9=?A-Z^_`a-z{|}~\177]+\\.)+[a-zA-Z]{2,6}\$/i";
00034 
00042     protected $_sPermanentCachePattern = "/c_fieldnames_/";
00043 
00049     protected $_aLockedFileHandles = array();
00050 
00056     protected $_aFileCacheContents = array();
00057 
00063     protected $_blIsSe = null;
00064 
00070     public static function getInstance()
00071     {
00072         // disable caching for test modules
00073         if ( defined( 'OXID_PHP_UNIT' ) ) {
00074             self::$_instance = modInstances::getMod( __CLASS__ );
00075         }
00076 
00077         if ( !(self::$_instance instanceof oxUtils) ) {
00078 
00079             self::$_instance = oxNew( 'oxUtils' );
00080 
00081             if ( defined( 'OXID_PHP_UNIT' ) ) {
00082                 modInstances::addMod( __CLASS__, self::$_instance);
00083             }
00084         }
00085         return self::$_instance;
00086     }
00087 
00093     protected $_aStaticCache;
00094 
00100     protected $_blSeoIsActive = null;
00101 
00107     public function stripGpcMagicQuotes()
00108     {
00109         if (!get_magic_quotes_gpc()) {
00110             return;
00111         }
00112         $_REQUEST = self::_stripQuotes($_REQUEST);
00113         $_POST = self::_stripQuotes($_POST);
00114         $_GET = self::_stripQuotes($_GET);
00115         $_COOKIE = self::_stripQuotes($_COOKIE);
00116     }
00117 
00126     public function strMan( $sVal, $sKey = null )
00127     {
00128         $sKey = $sKey?$sKey:'oxid123456789';
00129         $sVal = "ox{$sVal}id";
00130 
00131         $sKey = str_repeat( $sKey, strlen( $sVal ) / strlen( $sKey ) + 5 );
00132         $sVal = $this->strRot13( $sVal );
00133         $sVal = $sVal ^ $sKey;
00134         $sVal = base64_encode( $sVal );
00135         $sVal = str_replace( "=", "!", $sVal );
00136 
00137         return "ox_$sVal";
00138     }
00139 
00148     public function strRem( $sVal, $sKey = null )
00149     {
00150         $sKey = $sKey?$sKey:'oxid123456789';
00151         $sKey = str_repeat( $sKey, strlen( $sVal ) / strlen( $sKey ) + 5 );
00152 
00153         $sVal = substr( $sVal, 3 );
00154         $sVal = str_replace( '!', '=', $sVal );
00155         $sVal = base64_decode( $sVal );
00156         $sVal = $sVal ^ $sKey;
00157         $sVal = $this->strRot13( $sVal );
00158 
00159         return substr( $sVal, 2, -2 );
00160     }
00161 
00169     public function getArrFldName( $sName)
00170     {
00171         return str_replace( ".", "__", $sName);
00172     }
00173 
00182     public function assignValuesFromText( $sIn, $dVat = null)
00183     {
00184         $aRet = array();
00185         $aPieces = explode( '@@', $sIn );
00186         while ( list( $sKey, $sVal ) = each( $aPieces ) ) {
00187             if ( $sVal ) {
00188                 $aName = explode( '__', $sVal );
00189                 if ( isset( $aName[0] ) && isset( $aName[1] ) ) {
00190                     $aRet[] = $this->_fillExplodeArray( $aName, $dVat );
00191                 }
00192             }
00193         }
00194         return $aRet;
00195     }
00196 
00204     public function assignValuesToText( $aIn)
00205     {
00206         $sRet = "";
00207         reset( $aIn );
00208         while (list($sKey, $sVal) = each($aIn)) {
00209             $sRet .= $sKey;
00210             $sRet .= "__";
00211             $sRet .= $sVal;
00212             $sRet .= "@@";
00213         }
00214         return $sRet;
00215     }
00216 
00224     public function currency2Float( $sValue)
00225     {
00226         $fRet = $sValue;
00227         $iPos = strrpos( $sValue, ".");
00228         if ($iPos && ((strlen($sValue)-1-$iPos) < 2+1)) {
00229             // replace decimal with ","
00230             $fRet = substr_replace( $fRet, ",", $iPos, 1);
00231         }
00232         // remove thousands
00233         $fRet = str_replace( array(" ","."), "", $fRet);
00234 
00235         $fRet = str_replace( ",", ".", $fRet);
00236         return (float) $fRet;
00237     }
00238 
00246     public function isSearchEngine( $sClient = null )
00247     {
00248 
00249         if (!is_null($this->_blIsSe)) {
00250             return $this->_blIsSe;
00251         }
00252 
00253         startProfile("isSearchEngine");
00254 
00255         $myConfig = $this->getConfig();
00256         $blIsSe   = false;
00257 
00258         if ( !( $myConfig->getConfigParam( 'iDebug' ) && $this->isAdmin() ) ) {
00259 
00260             // caching
00261             $blIsSe = $myConfig->getGlobalParameter( 'blIsSearchEngine' );
00262             if ( !isset( $blIsSe ) ) {
00263 
00264                 $aRobots = $myConfig->getConfigParam( 'aRobots' );
00265                 $aRobots = is_array( $aRobots )?$aRobots:array();
00266 
00267                 $aRobotsExcept = $myConfig->getConfigParam( 'aRobotsExcept' );
00268                 $aRobotsExcept = is_array( $aRobotsExcept )?$aRobotsExcept:array();
00269 
00270                 $sClient = $sClient?$sClient:strtolower( getenv( 'HTTP_USER_AGENT' ) );
00271                 $blIsSe  = false;
00272                 $aRobots = array_merge( $aRobots, $aRobotsExcept );
00273                 foreach ( $aRobots as $sRobot ) {
00274                     if ( strpos( $sClient, $sRobot ) !== false ) {
00275                         $blIsSe = true;
00276                         break;
00277                     }
00278                 }
00279                 $myConfig->setGlobalParameter( 'blIsSearchEngine', $blIsSe );
00280             }
00281         }
00282 
00283         stopProfile("isSearchEngine");
00284 
00285         $this->_blIsSe = $blIsSe;
00286 
00287         return $blIsSe;
00288     }
00289 
00298     public function isValidEmail( $sEmail )
00299     {
00300         $blValid = true;
00301         if ( $sEmail != 'admin' ) {
00302             $blValid = ( getStr()->preg_match( $this->_sEmailTpl, $sEmail ) != 0 );
00303         }
00304 
00305         return $blValid;
00306     }
00307 
00313     public function rebuildCache()
00314     {
00315         // not needed from 3.0 on and unused <- MK: not correct, its used for example in shop_config.php, oxbase.php
00316 
00317         //$smarty  = & oxUtils::getInstance()->getSmarty();
00318         //$smarty->clear_all_cache();
00319 
00320         if ( function_exists( "UserdefinedRebuildCache")) {
00321             UserdefinedRebuildCache();
00322         }
00323     }
00324 
00332     public function loadAdminProfile($aInterfaceProfiles)
00333     {
00334         // improved #533
00335         // checking for available profiles list
00336         $aInterfaceProfiles = $aInterfaceProfiles;
00337         if ( is_array( $aInterfaceProfiles ) ) {
00338             //checking for previous profiles
00339             $sPrevProfile = oxUtilsServer::getInstance()->getOxCookie('oxidadminprofile');
00340             if (isset($sPrevProfile)) {
00341                 $aPrevProfile = @explode("@", trim($sPrevProfile));
00342             }
00343 
00344             //array to store profiles
00345             $aProfiles = array();
00346             foreach ( $aInterfaceProfiles as $iPos => $sProfile) {
00347                 $aProfileSettings = array($iPos, $sProfile);
00348                 $aProfiles[] = $aProfileSettings;
00349             }
00350             // setting previous used profile as active
00351             if (isset($aPrevProfile[0]) && isset($aProfiles[$aPrevProfile[0]])) {
00352                 $aProfiles[$aPrevProfile[0]][2] = 1;
00353             }
00354 
00355             oxSession::setVar("aAdminProfiles", $aProfiles);
00356             return $aProfiles;
00357         }
00358         return null;
00359     }
00360 
00369     public function fRound($sVal, $oCur = null)
00370     {
00371         startProfile('fround');
00372 
00373         //cached currency precision, this saves about 1% of execution time
00374         $iCurPrecision = null;
00375         if (! defined('OXID_PHP_UNIT')) {
00376             $iCurPrecision = $this->_iCurPrecision;
00377         }
00378 
00379         if (is_null($iCurPrecision)) {
00380             if ( !$oCur ) {
00381                 $oCur = $this->getConfig()->getActShopCurrencyObject();
00382             }
00383 
00384             $iCurPrecision = $oCur->decimal;
00385             $this->_iCurPrecision = $iCurPrecision;
00386         }
00387 
00388         // this is a workaround for #36008 bug in php - incorrect round() & number_format() result (R)
00389         static $dprez = null;
00390         if (!$dprez) {
00391             $prez = @ini_get("precision");
00392             if (!$prez) {
00393                 $prez = 9;
00394             }
00395             $dprez = pow(10, -$prez);
00396         }
00397         stopProfile('fround');
00398 
00399         return round($sVal + $dprez * ( $sVal >= 0 ? 1 : -1 ), $iCurPrecision);
00400     }
00401 
00411     public function toStaticCache( $sName, $sContent, $sKey = null )
00412     {
00413         // if it's an array then we add
00414         if ( $sKey ) {
00415             $this->_aStaticCache[$sName][$sKey] = $sContent;
00416         } else {
00417             $this->_aStaticCache[$sName] = $sContent;
00418         }
00419     }
00420 
00428     public function fromStaticCache( $sName)
00429     {
00430         if ( isset( $this->_aStaticCache[$sName])) {
00431             return $this->_aStaticCache[$sName];
00432         }
00433         return null;
00434     }
00435 
00443     public function cleanStaticCache($sCacheName = null)
00444     {
00445         if ($sCacheName) {
00446             unset($this->_aStaticCache[$sCacheName]);
00447         } else {
00448             $this->_aStaticCache = null;
00449         }
00450     }
00451 
00461     public function toPhpFileCache( $sKey, $mContents )
00462     {
00463         //only simple arrays are supported
00464         if ( is_array( $mContents ) && ( $sCachePath = $this->getCacheFilePath( $sKey, false, 'php' ) ) ) {
00465 
00466             // setting meta
00467             $this->setCacheMeta( $sKey, array( "serialize" => false, "cachepath" => $sCachePath ) );
00468 
00469             // caching..
00470             $this->toFileCache( $sKey, $mContents );
00471         }
00472     }
00473 
00481     public function fromPhpFileCache( $sKey )
00482     {
00483         // setting meta
00484         $this->setCacheMeta( $sKey, array( "include" => true, "cachepath" => $this->getCacheFilePath( $sKey, false, 'php' ) ) );
00485         return $this->fromFileCache( $sKey );
00486     }
00487 
00495     public function getCacheMeta( $sKey )
00496     {
00497         return isset( $this->_aFileCacheMeta[$sKey] ) ? $this->_aFileCacheMeta[$sKey] : false;
00498     }
00499 
00508     public function setCacheMeta( $sKey, $aMeta )
00509     {
00510         // cache meta data
00511         $this->_aFileCacheMeta[$sKey] = $aMeta;
00512     }
00513 
00523     public function toFileCache( $sKey, $mContents )
00524     {
00525         $this->_aFileCacheContents[$sKey] = $mContents;
00526         $aMeta = $this->getCacheMeta( $sKey );
00527 
00528         // looking for cache meta
00529         $sCachePath = isset( $aMeta["cachepath"] ) ? $aMeta["cachepath"] : $this->getCacheFilePath( $sKey );
00530         return ( bool ) $this->_lockFile( $sCachePath, $sKey );
00531     }
00532 
00540     public function fromFileCache( $sKey )
00541     {
00542         if ( !array_key_exists( $sKey, $this->_aFileCacheContents ) ) {
00543             $sRes = null;
00544 
00545             $aMeta = $this->getCacheMeta( $sKey );
00546             $blInclude  = isset( $aMeta["include"] ) ? $aMeta["include"] : false;
00547             $sCachePath = isset( $aMeta["cachepath"] ) ? $aMeta["cachepath"] : $this->getCacheFilePath( $sKey );
00548 
00549             // trying to lock
00550             $this->_lockFile( $sCachePath, $sKey, LOCK_SH );
00551 
00552             clearstatcache();
00553             if ( is_readable( $sCachePath ) ) {
00554                 $sRes = $blInclude ? $this->_includeFile( $sCachePath ) : $this->_readFile( $sCachePath );
00555             }
00556 
00557             // release lock
00558             $this->_releaseFile( $sKey, LOCK_SH );
00559 
00560             // caching
00561             $this->_aFileCacheContents[$sKey] = $sRes;
00562         }
00563 
00564         return $this->_aFileCacheContents[$sKey];
00565     }
00566 
00574     protected function _readFile( $sFilePath )
00575     {
00576         $sRes = file_get_contents( $sFilePath );
00577         return $sRes ? unserialize( $sRes ) : null;
00578     }
00579 
00587     protected function _includeFile( $sFilePath )
00588     {
00589         $_aCacheContents = null;
00590         include $sFilePath;
00591         return $_aCacheContents;
00592     }
00593 
00602     protected function _processCache( $sKey, $mContents )
00603     {
00604         // looking for cache meta
00605         $aCacheMeta  = $this->getCacheMeta( $sKey );
00606         $blSerialize = isset( $aCacheMeta["serialize"] ) ? $aCacheMeta["serialize"] : true;
00607 
00608         if ( $blSerialize ) {
00609             $mContents = serialize( $mContents );
00610         } else {
00611             $mContents = "<?php\n//automatically generated file\n//" . date( "Y-m-d H:i:s" ) . "\n\n\$_aCacheContents = " . var_export( $mContents, true ) . "\n?>";
00612         }
00613 
00614         return $mContents;
00615     }
00616 
00623     public function commitFileCache()
00624     {
00625         if ( count( $this->_aLockedFileHandles[LOCK_EX] ) ) {
00626             startProfile("!__SAVING CACHE__! (warning)");
00627             foreach ( $this->_aLockedFileHandles[LOCK_EX] as $sKey => $rHandle ) {
00628                 if ( $rHandle !== false && isset( $this->_aFileCacheContents[$sKey] ) ) {
00629 
00630                     // #0002931A truncate file once more before writing
00631                     ftruncate( $rHandle, 0 );
00632 
00633                     // writing cache
00634                     fwrite( $rHandle, $this->_processCache( $sKey, $this->_aFileCacheContents[$sKey] ) );
00635 
00636                     // releasing locks
00637                     $this->_releaseFile( $sKey );
00638                 }
00639             }
00640 
00641             stopProfile("!__SAVING CACHE__! (warning)");
00642 
00643             //empty buffer
00644             $this->_aFileCacheContents = array();
00645         }
00646     }
00647 
00657     protected function _lockFile( $sFilePath, $sIdent, $iLockMode = LOCK_EX )
00658     {
00659         $rHandle = isset( $this->_aLockedFileHandles[$iLockMode][$sIdent] ) ? $this->_aLockedFileHandles[$iLockMode][$sIdent] : null;
00660         if ( $rHandle === null ) {
00661 
00662             $blLocked = false;
00663             $rHandle = @fopen( $sFilePath, "a+" );
00664 
00665             if ( $rHandle !== false ) {
00666 
00667                 if ( flock( $rHandle, $iLockMode | LOCK_NB ) ) {
00668                     if ( $iLockMode === LOCK_EX ) {
00669                         // truncate file
00670                         $blLocked = ftruncate( $rHandle, 0 );
00671                     } else {
00672                         // move to a start position
00673                         $blLocked = fseek( $rHandle, 0 ) === 0;
00674                     }
00675                 }
00676 
00677                 // on failure - closing and setting false..
00678                 if ( !$blLocked ) {
00679                     fclose( $rHandle );
00680                     $rHandle = false;
00681                 }
00682             }
00683 
00684             // in case system does not support file lockings
00685             if ( !$blLocked && $iLockMode === LOCK_EX ) {
00686 
00687                 // clearing on first call
00688                 if ( count( $this->_aLockedFileHandles ) == 0 ) {
00689                     clearstatcache();
00690                 }
00691 
00692                 // start a blank file to inform other processes we are dealing with it.
00693                 if (!( file_exists( $sFilePath ) && !filesize( $sFilePath ) && abs( time() - filectime( $sFilePath ) < 40 ) ) ) {
00694                     $rHandle = @fopen( $sFilePath, "w" );
00695                 }
00696             }
00697 
00698             $this->_aLockedFileHandles[$iLockMode][$sIdent] = $rHandle;
00699         }
00700 
00701         return $rHandle;
00702     }
00703 
00712     protected function _releaseFile( $sIdent, $iLockMode = LOCK_EX )
00713     {
00714         $blSuccess = true;
00715         if ( isset( $this->_aLockedFileHandles[$iLockMode][$sIdent] ) &&
00716              $this->_aLockedFileHandles[$iLockMode][$sIdent] !== false ) {
00717 
00718              // release the lock and close file
00719             $blSuccess = flock( $this->_aLockedFileHandles[$iLockMode][$sIdent], LOCK_UN ) &&
00720                          fclose( $this->_aLockedFileHandles[$iLockMode][$sIdent] );
00721             unset( $this->_aLockedFileHandles[$iLockMode][$sIdent] );
00722         }
00723 
00724         return $blSuccess;
00725     }
00726 
00734     public function oxResetFileCache()
00735     {
00736         $aPathes = glob( $this->getCacheFilePath( null, true ) . '*' );
00737         if ( is_array( $aPathes ) ) {
00738             // delete all the files, except cached tables fieldnames
00739             $aPathes = preg_grep( $this->_sPermanentCachePattern, $aPathes, PREG_GREP_INVERT );
00740             foreach ( $aPathes as $sFilename ) {
00741                 @unlink( $sFilename );
00742             }
00743         }
00744     }
00745 
00755     public function getRemoteCachePath($sRemote, $sLocal)
00756     {
00757         clearstatcache();
00758         if ( file_exists( $sLocal ) && filemtime( $sLocal ) && filemtime( $sLocal ) > time() - 86400 ) {
00759             return $sLocal;
00760         }
00761         $hRemote = @fopen( $sRemote, "rb");
00762         $blSuccess = false;
00763         if ( isset( $hRemote) && $hRemote ) {
00764             $hLocal = fopen( $sLocal, "wb");
00765             stream_copy_to_stream($hRemote, $hLocal);
00766             fclose($hRemote);
00767             fclose($hLocal);
00768             $blSuccess = true;
00769         } else {
00770             // try via fsockopen
00771             $aUrl = @parse_url( $sRemote);
00772             if ( !empty( $aUrl["host"])) {
00773                 $sPath = $aUrl["path"];
00774                 if ( empty( $sPath ) ) {
00775                     $sPath = "/";
00776                 }
00777                 $sHost = $aUrl["host"];
00778 
00779                 $hSocket = @fsockopen( $sHost, 80, $iErrorNumber, $iErrStr, 5);
00780                 if ( $hSocket) {
00781                     fputs( $hSocket, "GET ".$sPath." HTTP/1.0\r\nHost: $sHost\r\n\r\n");
00782                     $headers = stream_get_line($hSocket, 4096, "\r\n\r\n");
00783                     if ( ( $hLocal = @fopen( $sLocal, "wb") ) !== false ) {
00784                         rewind($hLocal);
00785                         // does not copy all the data
00786                         // stream_copy_to_stream($hSocket, $hLocal);
00787                         fwrite ( $hLocal, stream_get_contents( $hSocket ) );
00788                         fclose( $hLocal );
00789                         fclose( $hSocket );
00790                         $blSuccess = true;
00791                     }
00792                 }
00793             }
00794         }
00795         if ( $blSuccess || file_exists( $sLocal ) ) {
00796             return $sLocal;
00797         }
00798         return false;
00799     }
00800 
00806     public function canPreview()
00807     {
00808         $blCan = null;
00809         if ( ( $sPrevId = oxConfig::getParameter( 'preview' ) ) &&
00810              ( $sAdminSid = oxUtilsServer::getInstance()->getOxCookie( 'admin_sid' ) ) ) {
00811 
00812             $sTable = getViewName( 'oxuser' );
00813             $sQ = "select 1 from $sTable where MD5( CONCAT( ?, {$sTable}.oxid, {$sTable}.oxpassword, {$sTable}.oxrights ) ) = ?";
00814             $blCan = (bool) oxDb::getDb()->getOne( $sQ, array( $sAdminSid, $sPrevId ) );
00815         }
00816 
00817         return $blCan;
00818     }
00819 
00825     public function getPreviewId()
00826     {
00827         $sAdminSid = oxUtilsServer::getInstance()->getOxCookie( 'admin_sid' );
00828         if ( ( $oUser = $this->getUser() ) ) {
00829             return md5( $sAdminSid . $oUser->getId() . $oUser->oxuser__oxpassword->value . $oUser->oxuser__oxrights->value );
00830         }
00831     }
00832 
00838     public function checkAccessRights()
00839     {
00840         $myConfig  = $this->getConfig();
00841 
00842         $blIsAuth = false;
00843 
00844         $sUserID = oxSession::getVar( "auth");
00845 
00846         // deleting admin marker
00847         oxSession::setVar( "malladmin", 0);
00848         oxSession::setVar( "blIsAdmin", 0);
00849         oxSession::deleteVar( "blIsAdmin" );
00850         $myConfig->setConfigParam( 'blMallAdmin', false );
00851         //#1552T
00852         $myConfig->setConfigParam( 'blAllowInheritedEdit', false );
00853 
00854         if ( $sUserID) {
00855             // escaping
00856             $oDb = oxDb::getDb();
00857             $sRights = $oDb->getOne("select oxrights from oxuser where oxid = ".$oDb->quote($sUserID));
00858 
00859             if ( $sRights != "user") {
00860                 // malladmin ?
00861                 if ( $sRights == "malladmin") {
00862                     oxSession::setVar( "malladmin", 1);
00863                     $myConfig->setConfigParam( 'blMallAdmin', true );
00864 
00865                     //#1552T
00866                     //So far this blAllowSharedEdit is Equal to blMallAdmin but in future to be solved over rights and roles
00867                     $myConfig->setConfigParam( 'blAllowSharedEdit', true );
00868 
00869                     $sShop = oxSession::getVar( "actshop");
00870                     if ( !isset($sShop)) {
00871                         oxSession::setVar( "actshop", $myConfig->getBaseShopId());
00872                     }
00873                     $blIsAuth = true;
00874                 } else {
00875                     // Shopadmin... check if this shop is valid and exists
00876                     $sShopID = $oDb->getOne("select oxid from oxshops where oxid = " . $oDb->quote( $sRights ) );
00877                     if ( isset( $sShopID) && $sShopID) {
00878                         // success, this shop exists
00879 
00880                         oxSession::setVar( "actshop", $sRights);
00881                         oxSession::setVar( "currentadminshop", $sRights);
00882                         oxSession::setVar( "shp", $sRights);
00883 
00884                         // check if this subshop admin is evil.
00885                         if ('chshp' == oxConfig::getParameter( 'fnc' )) {
00886                             // dont allow this call
00887                             $blIsAuth = false;
00888                         } else {
00889                             $blIsAuth = true;
00890 
00891                             $aShopIdVars = array('actshop', 'shp', 'currentadminshop');
00892                             foreach ($aShopIdVars as $sShopIdVar) {
00893                                 if ($sGotShop = oxConfig::getParameter( $sShopIdVar )) {
00894                                     if ($sGotShop != $sRights) {
00895                                         $blIsAuth = false;
00896                                         break;
00897                                     }
00898                                 }
00899                             }
00900                         }
00901                     }
00902                 }
00903                 // marking user as admin
00904                 oxSession::setVar( "blIsAdmin", 1);
00905             }
00906         }
00907         return $blIsAuth;
00908     }
00909 
00919     public function seoIsActive( $blReset = false, $sShopId = null, $iActLang = null )
00920     {
00921         if ( !is_null( $this->_blSeoIsActive ) && !$blReset ) {
00922             return $this->_blSeoIsActive;
00923         }
00924 
00925         $myConfig = $this->getConfig();
00926 
00927         if ( ( $this->_blSeoIsActive = $myConfig->getConfigParam( 'blSeoMode' ) ) === null ) {
00928             $this->_blSeoIsActive = true;
00929 
00930             $aSeoModes  = $myConfig->getconfigParam( 'aSeoModes' );
00931             $sActShopId = $sShopId ? $sShopId : $myConfig->getActiveShop()->getId();
00932             $iActLang   = $iActLang ? $iActLang : (int) oxLang::getInstance()->getBaseLanguage();
00933 
00934             // checking special config param for active shop and language
00935             if ( is_array( $aSeoModes ) && isset( $aSeoModes[$sActShopId] ) && isset( $aSeoModes[$sActShopId][$iActLang] ) ) {
00936                 $this->_blSeoIsActive = (bool) $aSeoModes[$sActShopId][$iActLang];
00937             }
00938         }
00939 
00940         return $this->_blSeoIsActive;
00941     }
00942 
00952     public function getShopBit( $iShopId )
00953     {
00954         $iShopId = (int) $iShopId;
00955         //this works for large numbers when $sShopNr is up to (inclusive) 64
00956         $iRes = oxDb::getDb()->getOne( "select 1 << ( $iShopId - 1 ) as shopbit" );
00957 
00958         //as php ints supports only 32 bits, we return string.
00959         return $iRes;
00960     }
00961 
00971     public function bitwiseAnd( $iVal1, $iVal2 )
00972     {
00973         //this works for large numbers when $sShopNr is up to (inclusive) 64
00974         $iRes = oxDb::getDb()->getOne( "select ($iVal1 & $iVal2) as bitwiseAnd" );
00975 
00976         //as php ints supports only 32 bits, we return string.
00977         return $iRes;
00978     }
00979 
00989     public function bitwiseOr( $iVal1, $iVal2 )
00990     {
00991         //this works for large numbers when $sShopNr is up to (inclusive) 64
00992         $iRes = oxDb::getDb()->getOne( "select ($iVal1 | $iVal2) as bitwiseOr" );
00993 
00994         //as php ints supports only 32 bits, we return string.
00995         return $iRes;
00996     }
00997 
01005     public function isValidAlpha( $sField )
01006     {
01007         return (boolean) getStr()->preg_match( '/^[a-zA-Z0-9_]*$/', $sField );
01008     }
01009 
01019     protected function _simpleRedirect( $sUrl, $sHeaderCode )
01020     {
01021         header( $sHeaderCode );
01022         header( "Location: $sUrl" );
01023         header( "Connection: close" );
01024     }
01025 
01039     public function redirect( $sUrl, $blAddRedirectParam = true, $iHeaderCode = 301 )
01040     {
01041         //preventing possible cyclic redirection
01042         //#M341 and check only if redirect paramater must be added
01043         if ( $blAddRedirectParam && oxConfig::getParameter( 'redirected' ) ) {
01044             return;
01045         }
01046 
01047         if ( $blAddRedirectParam ) {
01048             $sUrl = $this->_addUrlParameters( $sUrl, array( 'redirected' => 1 ) );
01049         }
01050 
01051         $sUrl = str_ireplace( "&amp;", "&", $sUrl );
01052 
01053         $sHeaderCode = '';
01054         switch ($iHeaderCode) {
01055             case 301:
01056                 $sHeaderCode = "HTTP/1.1 301 Moved Permanently";
01057                 break;
01058             case 302:
01059             default:
01060                 $sHeaderCode = "HTTP/1.1 302 Found";
01061         }
01062 
01063         $this->_simpleRedirect( $sUrl, $sHeaderCode );
01064 
01065         try {//may occur in case db is lost
01066             $this->getSession()->freeze();
01067         } catch( oxException $oEx ) {
01068             $oEx->debugOut();
01069             //do nothing else to make sure the redirect takes place
01070         }
01071 
01072         if ( defined( 'OXID_PHP_UNIT' ) ) {
01073             return;
01074         }
01075 
01076         $this->showMessageAndExit( '' );
01077     }
01078 
01086     public function showMessageAndExit( $sMsg )
01087     {
01088         $this->getSession()->freeze();
01089         $this->commitFileCache();
01090 
01091         if ( defined( 'OXID_PHP_UNIT' ) ) {
01092             return;
01093         }
01094 
01095         exit( $sMsg );
01096     }
01097 
01105     public function setHeader($sHeader)
01106     {
01107         header($sHeader);
01108     }
01109 
01118     protected function _addUrlParameters( $sUrl, $aParams )
01119     {
01120         $sDelim = ( ( getStr()->strpos( $sUrl, '?' ) !== false ) )?'&':'?';
01121         foreach ( $aParams as $sName => $sVal ) {
01122             $sUrl = $sUrl . $sDelim . $sName . '=' . $sVal;
01123             $sDelim = '&';
01124         }
01125 
01126         return $sUrl;
01127     }
01128 
01140     protected function _fillExplodeArray( $aName, $dVat = null)
01141     {
01142         $myConfig = $this->getConfig();
01143         $oObject = new oxStdClass();
01144         $aPrice = explode( '!P!', $aName[0]);
01145 
01146         if ( ( $myConfig->getConfigParam( 'bl_perfLoadSelectLists' ) && $myConfig->getConfigParam( 'bl_perfUseSelectlistPrice' ) && isset( $aPrice[0] ) && isset( $aPrice[1] ) ) || $this->isAdmin() ) {
01147 
01148             // yes, price is there
01149             $oObject->price = isset( $aPrice[1] ) ? $aPrice[1] : 0;
01150             $aName[0] = isset( $aPrice[0] ) ? $aPrice[0] : '';
01151 
01152             $iPercPos = getStr()->strpos( $oObject->price, '%' );
01153             if ( $iPercPos !== false ) {
01154                 $oObject->priceUnit = '%';
01155                 $oObject->fprice = $oObject->price;
01156                 $oObject->price  = substr( $oObject->price, 0, $iPercPos );
01157             } else {
01158                 $oCur = $myConfig->getActShopCurrencyObject();
01159                 $oObject->price = str_replace(',', '.', $oObject->price);
01160                 $oObject->fprice = oxLang::getInstance()->formatCurrency( $oObject->price  * $oCur->rate, $oCur);
01161                 $oObject->priceUnit = 'abs';
01162             }
01163 
01164             // add price info into list
01165             if ( !$this->isAdmin() && $oObject->price != 0 ) {
01166                 $aName[0] .= " ";
01167                 if ( $oObject->price > 0 ) {
01168                     $aName[0] .= "+";
01169                 }
01170                 //V FS#2616
01171                 if ( $dVat != null && $oObject->priceUnit == 'abs' ) {
01172                     $oPrice = oxNew('oxPrice');
01173                     $oPrice->setPrice($oObject->price, $dVat);
01174                     $aName[0] .= oxLang::getInstance()->formatCurrency( $oPrice->getBruttoPrice() * $oCur->rate, $oCur);
01175                 } else {
01176                     $aName[0] .= $oObject->fprice;
01177                 }
01178                 if ( $oObject->priceUnit == 'abs' ) {
01179                     $aName[0] .= " ".$oCur->sign;
01180                 }
01181             }
01182         } elseif ( isset( $aPrice[0] ) && isset($aPrice[1] ) ) {
01183             // A. removing unused part of information
01184             $aName[0] = getStr()->preg_replace( "/!P!.*/", "", $aName[0] );
01185         }
01186 
01187         $oObject->name  = $aName[0];
01188         $oObject->value = $aName[1];
01189         return $oObject;
01190     }
01191 
01199     public function oxMimeContentType( $sFileName )
01200     {
01201         $sFileName = strtolower( $sFileName );
01202         $iLastDot  = strrpos( $sFileName, '.' );
01203 
01204         if ( $iLastDot !== false ) {
01205             $sType = substr( $sFileName, $iLastDot + 1 );
01206             switch ( $sType ) {
01207                 case 'gif':
01208                     $sType = 'image/gif';
01209                     break;
01210                 case 'jpeg':
01211                 case 'jpg':
01212                     $sType = 'image/jpeg';
01213                     break;
01214                 case 'png':
01215                     $sType = 'image/png';
01216                     break;
01217                 default:
01218                     $sType = false;
01219                     break;
01220             }
01221         }
01222         return $sType;
01223     }
01224 
01233     public function logger( $sText, $blNewline = false )
01234     {   $myConfig = $this->getConfig();
01235 
01236         if ( $myConfig->getConfigParam( 'iDebug' ) == -2) {
01237             if ( gettype( $sText ) != 'string' ) {
01238                 $sText = var_export( $sText, true);
01239             }
01240             $sLogMsg = "----------------------------------------------\n{$sText}".( ( $blNewline ) ?"\n":"" )."\n";
01241             $this->writeToLog( $sLogMsg, "log.txt" );
01242         }
01243 
01244     }
01245 
01253     protected function _stripQuotes($mInput)
01254     {
01255         return is_array($mInput) ? array_map( array( $this, '_stripQuotes' ), $mInput) : stripslashes( $mInput );
01256     }
01257 
01265     public function strRot13( $sStr )
01266     {
01267         $sFrom = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
01268         $sTo   = 'nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM';
01269 
01270         return strtr( $sStr, $sFrom, $sTo );
01271     }
01272 
01282     public function getCacheFilePath( $sCacheName, $blPathOnly = false, $sExtension = 'txt' )
01283     {
01284         $sVersionPrefix = "";
01285 
01286 
01287             $sVersionPrefix = 'pe';
01288 
01289         $sPath = realpath($this->getConfig()->getConfigParam( 'sCompileDir' ));
01290 
01291         if (!$sPath) {
01292             return false;
01293         }
01294 
01295         return $blPathOnly ? "{$sPath}/" : "{$sPath}/ox{$sVersionPrefix}c_{$sCacheName}." . $sExtension;
01296     }
01297 
01305     public function getLangCache( $sCacheName )
01306     {
01307         $aLangCache = null;
01308         $sFilePath = $this->getCacheFilePath( $sCacheName );
01309         if ( file_exists( $sFilePath ) && is_readable( $sFilePath ) ) {
01310             include $sFilePath;
01311         }
01312         return $aLangCache;
01313     }
01314 
01323     public function setLangCache( $sCacheName, $aLangCache )
01324     {
01325         $sCache = "<?php\n\$aLangCache = ".var_export( $aLangCache, true ).";";
01326         $blRes = file_put_contents($this->getCacheFilePath($sCacheName), $sCache);
01327         return $blRes;
01328     }
01329 
01337     public function checkUrlEndingSlash( $sUrl )
01338     {
01339         if ( !getStr()->preg_match("/\/$/", $sUrl) ) {
01340             $sUrl .= '/';
01341         }
01342 
01343         return $sUrl;
01344     }
01345 
01354     public function writeToLog( $sLogMessage, $sLogFileName )
01355     {
01356         $sLogDist = $this->getConfig()->getLogsDir().$sLogFileName;
01357         $blOk = false;
01358 
01359         if ( ( $oHandle = fopen( $sLogDist, 'a' ) ) !== false ) {
01360             fwrite( $oHandle, $sLogMessage );
01361             $blOk = fclose( $oHandle );
01362         }
01363 
01364         return $blOk;
01365     }
01366 
01374     public function handlePageNotFoundError($sUrl = '')
01375     {
01376         $this->setHeader("HTTP/1.0 404 Not Found");
01377         if ( oxConfig::getInstance()->isUtf() ) {
01378             $this->setHeader("Content-Type: text/html; charset=UTF-8");
01379         }
01380 
01381         $sReturn = "Page not found.";
01382         try {
01383             $oView = oxNew('oxubase');
01384             $oView->init();
01385             $oView->render();
01386             $oView->addTplParam('sUrl', $sUrl);
01387             if ($sRet = oxUtilsView::getInstance()->getTemplateOutput('message/err_404.tpl', $oView)) {
01388                 $sReturn = $sRet;
01389             }
01390         } catch (Exception $e) {
01391         }
01392         $this->showMessageAndExit( $sReturn );
01393     }
01394 
01402     public function extractDomain( $sHost )
01403     {
01404         $oStr = getStr();
01405         if ( !$oStr->preg_match( '/[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}/', $sHost ) &&
01406              ( $iLastDot = strrpos( $sHost, '.' ) ) !== false ) {
01407             $iLen = $oStr->strlen( $sHost );
01408             if ( ( $iNextDot = strrpos( $sHost, '.', ( $iLen - $iLastDot + 1 ) * - 1 ) ) !== false ) {
01409                 $sHost = trim( $oStr->substr( $sHost, $iNextDot ), '.' );
01410             }
01411         }
01412 
01413         return $sHost;
01414     }
01415 }