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_|c_tbdsc_|_allfields_/";
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 
00079     public static function getInstance()
00080     {
00081         return oxRegistry::getUtils();
00082     }
00083 
00089     protected $_aStaticCache;
00090 
00096     protected $_blSeoIsActive = null;
00097 
00103     public function stripGpcMagicQuotes()
00104     {
00105         if (!get_magic_quotes_gpc()) {
00106             return;
00107         }
00108         $_REQUEST = self::_stripQuotes($_REQUEST);
00109         $_POST = self::_stripQuotes($_POST);
00110         $_GET = self::_stripQuotes($_GET);
00111         $_COOKIE = self::_stripQuotes($_COOKIE);
00112     }
00113 
00122     public function strMan( $sVal, $sKey = null )
00123     {
00124         $sKey = $sKey ? $sKey : $this->getConfig()->getConfigParam('sConfigKey');
00125         $sVal = "ox{$sVal}id";
00126 
00127         $sKey = str_repeat( $sKey, strlen( $sVal ) / strlen( $sKey ) + 5 );
00128         $sVal = $this->strRot13( $sVal );
00129         $sVal = $sVal ^ $sKey;
00130         $sVal = base64_encode ( $sVal );
00131         $sVal = str_replace( "=", "!", $sVal );
00132 
00133         return "ox_$sVal";
00134     }
00135 
00144     public function strRem( $sVal, $sKey = null )
00145     {
00146         $sKey = $sKey ? $sKey : $this->getConfig()->getConfigParam('sConfigKey');
00147         $sKey = str_repeat( $sKey, strlen( $sVal ) / strlen( $sKey ) + 5 );
00148 
00149         $sVal = substr( $sVal, 3 );
00150         $sVal = str_replace( '!', '=', $sVal );
00151         $sVal = base64_decode( $sVal );
00152         $sVal = $sVal ^ $sKey;
00153         $sVal = $this->strRot13( $sVal );
00154 
00155         return substr( $sVal, 2, -2 );
00156     }
00157 
00165     public function getArrFldName( $sName)
00166     {
00167         return str_replace( ".", "__", $sName);
00168     }
00169 
00178     public function assignValuesFromText( $sIn, $dVat = null)
00179     {
00180         $aRet = array();
00181         $aPieces = explode( '@@', $sIn );
00182         while ( list( $sKey, $sVal ) = each( $aPieces ) ) {
00183             if ( $sVal ) {
00184                 $aName = explode( '__', $sVal );
00185                 if ( isset( $aName[0] ) && isset( $aName[1] ) ) {
00186                     $aRet[] = $this->_fillExplodeArray( $aName, $dVat );
00187                 }
00188             }
00189         }
00190         return $aRet;
00191     }
00192 
00200     public function assignValuesToText( $aIn)
00201     {
00202         $sRet = "";
00203         reset( $aIn );
00204         while (list($sKey, $sVal) = each($aIn)) {
00205             $sRet .= $sKey;
00206             $sRet .= "__";
00207             $sRet .= $sVal;
00208             $sRet .= "@@";
00209         }
00210         return $sRet;
00211     }
00212 
00220     public function currency2Float( $sValue)
00221     {
00222         $fRet = $sValue;
00223         $iPos = strrpos( $sValue, ".");
00224         if ($iPos && ((strlen($sValue)-1-$iPos) < 2+1)) {
00225             // replace decimal with ","
00226             $fRet = substr_replace( $fRet, ",", $iPos, 1);
00227         }
00228         // remove thousands
00229         $fRet = str_replace( array(" ","."), "", $fRet);
00230 
00231         $fRet = str_replace( ",", ".", $fRet);
00232         return (float) $fRet;
00233     }
00234 
00235 
00243     public function string2Float( $sValue)
00244     {
00245         $fRet = str_replace( " ", "", $sValue);
00246         $iCommaPos = strpos( $fRet, ",");
00247         $iDotPos = strpos( $fRet, ".");
00248         if (!$iDotPos xor !$iCommaPos) {
00249             if (substr_count( $fRet, ",") > 1 || substr_count( $fRet, ".") > 1) {
00250                 $fRet = str_replace( array(",","."), "", $fRet);
00251             } else {
00252                 $fRet = str_replace( ",", ".", $fRet);
00253             }
00254         } else if ( $iDotPos < $iCommaPos ) {
00255             $fRet = str_replace( ".", "", $fRet);
00256             $fRet = str_replace( ",", ".", $fRet);
00257         }
00258         // remove thousands
00259         $fRet = str_replace( array(" ",","), "", $fRet);
00260         return (float) $fRet;
00261     }
00262 
00270     public function isSearchEngine( $sClient = null )
00271     {
00272         if (is_null($this->_blIsSe)) {
00273             $this->setSearchEngine( null, $sClient );
00274         }
00275         return $this->_blIsSe;
00276     }
00277 
00286     public function setSearchEngine( $blIsSe = null, $sClient = null )
00287     {
00288         if (isset($blIsSe)) {
00289             $this->_blIsSe = $blIsSe;
00290             return;
00291         }
00292         startProfile("isSearchEngine");
00293 
00294         $myConfig = $this->getConfig();
00295         $blIsSe   = false;
00296 
00297         if ( !( $myConfig->getConfigParam( 'iDebug' ) && $this->isAdmin() ) ) {
00298             $aRobots = $myConfig->getConfigParam( 'aRobots' );
00299             $aRobots = is_array( $aRobots )?$aRobots:array();
00300 
00301             $aRobotsExcept = $myConfig->getConfigParam( 'aRobotsExcept' );
00302             $aRobotsExcept = is_array( $aRobotsExcept )?$aRobotsExcept:array();
00303 
00304             $sClient = $sClient?$sClient:strtolower( getenv( 'HTTP_USER_AGENT' ) );
00305             $blIsSe  = false;
00306             $aRobots = array_merge( $aRobots, $aRobotsExcept );
00307             foreach ( $aRobots as $sRobot ) {
00308                 if ( strpos( $sClient, $sRobot ) !== false ) {
00309                     $blIsSe = true;
00310                     break;
00311                 }
00312             }
00313         }
00314 
00315         $this->_blIsSe = $blIsSe;
00316 
00317         stopProfile("isSearchEngine");
00318     }
00319 
00328     public function isValidEmail( $sEmail )
00329     {
00330         $blValid = true;
00331         if ( $sEmail != 'admin' ) {
00332             $sEmailTpl = "/^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/i";
00333             $blValid = ( getStr()->preg_match( $sEmailTpl, $sEmail ) != 0 );
00334         }
00335 
00336         return $blValid;
00337     }
00338 
00346     public function loadAdminProfile($aInterfaceProfiles)
00347     {
00348         // improved #533
00349         // checking for available profiles list
00350         if ( is_array( $aInterfaceProfiles ) ) {
00351             //checking for previous profiles
00352             $sPrevProfile = oxRegistry::get("oxUtilsServer")->getOxCookie('oxidadminprofile');
00353             if (isset($sPrevProfile)) {
00354                 $aPrevProfile = @explode("@", trim($sPrevProfile));
00355             }
00356 
00357             //array to store profiles
00358             $aProfiles = array();
00359             foreach ( $aInterfaceProfiles as $iPos => $sProfile) {
00360                 $aProfileSettings = array($iPos, $sProfile);
00361                 $aProfiles[] = $aProfileSettings;
00362             }
00363             // setting previous used profile as active
00364             if (isset($aPrevProfile[0]) && isset($aProfiles[$aPrevProfile[0]])) {
00365                 $aProfiles[$aPrevProfile[0]][2] = 1;
00366             }
00367 
00368             oxSession::setVar("aAdminProfiles", $aProfiles);
00369             return $aProfiles;
00370         }
00371         return null;
00372     }
00373 
00382     public function fRound($sVal, $oCur = null)
00383     {
00384         startProfile('fround');
00385 
00386         //cached currency precision, this saves about 1% of execution time
00387         $iCurPrecision = null;
00388         if (! defined('OXID_PHP_UNIT')) {
00389             $iCurPrecision = $this->_iCurPrecision;
00390         }
00391 
00392         if (is_null($iCurPrecision)) {
00393             if ( !$oCur ) {
00394                 $oCur = $this->getConfig()->getActShopCurrencyObject();
00395             }
00396 
00397             $iCurPrecision = $oCur->decimal;
00398             $this->_iCurPrecision = $iCurPrecision;
00399         }
00400 
00401         // if < 5.3.x this is a workaround for #36008 bug in php - incorrect round() & number_format() result (R)
00402         static $dprez = null;
00403         if (!$dprez) {
00404             $prez = @ini_get("precision");
00405             if (!$prez || $prez > 12 ) {
00406                $prez = 12;
00407             }
00408             $dprez = pow(10, -$prez);
00409         }
00410         stopProfile('fround');
00411         return round($sVal + $dprez * ( $sVal >= 0 ? 1 : -1 ), $iCurPrecision);
00412     }
00413 
00423     public function toStaticCache( $sName, $sContent, $sKey = null )
00424     {
00425         // if it's an array then we add
00426         if ( $sKey ) {
00427             $this->_aStaticCache[$sName][$sKey] = $sContent;
00428         } else {
00429             $this->_aStaticCache[$sName] = $sContent;
00430         }
00431     }
00432 
00440     public function fromStaticCache( $sName)
00441     {
00442         if ( isset( $this->_aStaticCache[$sName])) {
00443             return $this->_aStaticCache[$sName];
00444         }
00445         return null;
00446     }
00447 
00455     public function cleanStaticCache($sCacheName = null)
00456     {
00457         if ($sCacheName) {
00458             unset($this->_aStaticCache[$sCacheName]);
00459         } else {
00460             $this->_aStaticCache = null;
00461         }
00462     }
00463 
00473     public function toPhpFileCache( $sKey, $mContents )
00474     {
00475         //only simple arrays are supported
00476         if ( is_array( $mContents ) && ( $sCachePath = $this->getCacheFilePath( $sKey, false, 'php' ) ) ) {
00477 
00478             // setting meta
00479             $this->setCacheMeta( $sKey, array( "serialize" => false, "cachepath" => $sCachePath ) );
00480 
00481             // caching..
00482             $this->toFileCache( $sKey, $mContents );
00483         }
00484     }
00485 
00493     public function fromPhpFileCache( $sKey )
00494     {
00495         // setting meta
00496         $this->setCacheMeta( $sKey, array( "include" => true, "cachepath" => $this->getCacheFilePath( $sKey, false, 'php' ) ) );
00497         return $this->fromFileCache( $sKey );
00498     }
00499 
00507     public function getCacheMeta( $sKey )
00508     {
00509         return isset( $this->_aFileCacheMeta[$sKey] ) ? $this->_aFileCacheMeta[$sKey] : false;
00510     }
00511 
00520     public function setCacheMeta( $sKey, $aMeta )
00521     {
00522         // cache meta data
00523         $this->_aFileCacheMeta[$sKey] = $aMeta;
00524     }
00525 
00535     public function toFileCache( $sKey, $mContents )
00536     {
00537         $this->_aFileCacheContents[$sKey] = $mContents;
00538         $aMeta = $this->getCacheMeta( $sKey );
00539 
00540         // looking for cache meta
00541         $sCachePath = isset( $aMeta["cachepath"] ) ? $aMeta["cachepath"] : $this->getCacheFilePath( $sKey );
00542         return ( bool ) $this->_lockFile( $sCachePath, $sKey );
00543     }
00544 
00552     public function fromFileCache( $sKey )
00553     {
00554         if ( !array_key_exists( $sKey, $this->_aFileCacheContents ) ) {
00555             $sRes = null;
00556 
00557             $aMeta = $this->getCacheMeta( $sKey );
00558             $blInclude  = isset( $aMeta["include"] ) ? $aMeta["include"] : false;
00559             $sCachePath = isset( $aMeta["cachepath"] ) ? $aMeta["cachepath"] : $this->getCacheFilePath( $sKey );
00560 
00561             // trying to lock
00562             $this->_lockFile( $sCachePath, $sKey, LOCK_SH );
00563 
00564             clearstatcache();
00565             if ( is_readable( $sCachePath ) ) {
00566                 $sRes = $blInclude ? $this->_includeFile( $sCachePath ) : $this->_readFile( $sCachePath );
00567             }
00568 
00569             // release lock
00570             $this->_releaseFile( $sKey, LOCK_SH );
00571 
00572             // caching
00573             $this->_aFileCacheContents[$sKey] = $sRes;
00574         }
00575 
00576         return $this->_aFileCacheContents[$sKey];
00577     }
00578 
00586     protected function _readFile( $sFilePath )
00587     {
00588         $sRes = file_get_contents( $sFilePath );
00589         return $sRes ? unserialize( $sRes ) : null;
00590     }
00591 
00599     protected function _includeFile( $sFilePath )
00600     {
00601         $_aCacheContents = null;
00602         include $sFilePath;
00603         return $_aCacheContents;
00604     }
00605 
00614     protected function _processCache( $sKey, $mContents )
00615     {
00616         // looking for cache meta
00617         $aCacheMeta  = $this->getCacheMeta( $sKey );
00618         $blSerialize = isset( $aCacheMeta["serialize"] ) ? $aCacheMeta["serialize"] : true;
00619 
00620         if ( $blSerialize ) {
00621             $mContents = serialize( $mContents );
00622         } else {
00623             $mContents = "<?php\n//automatically generated file\n//" . date( "Y-m-d H:i:s" ) . "\n\n\$_aCacheContents = " . var_export( $mContents, true ) . "\n?>";
00624         }
00625 
00626         return $mContents;
00627     }
00628 
00635     public function commitFileCache()
00636     {
00637         if ( count( $this->_aLockedFileHandles[LOCK_EX] ) ) {
00638             startProfile("!__SAVING CACHE__! (warning)");
00639             foreach ( $this->_aLockedFileHandles[LOCK_EX] as $sKey => $rHandle ) {
00640                 if ( $rHandle !== false && isset( $this->_aFileCacheContents[$sKey] ) ) {
00641 
00642                     // #0002931A truncate file once more before writing
00643                     ftruncate( $rHandle, 0 );
00644 
00645                     // writing cache
00646                     fwrite( $rHandle, $this->_processCache( $sKey, $this->_aFileCacheContents[$sKey] ) );
00647 
00648                     // releasing locks
00649                     $this->_releaseFile( $sKey );
00650                 }
00651             }
00652 
00653             stopProfile("!__SAVING CACHE__! (warning)");
00654 
00655             //empty buffer
00656             $this->_aFileCacheContents = array();
00657         }
00658     }
00659 
00669     protected function _lockFile( $sFilePath, $sIdent, $iLockMode = LOCK_EX )
00670     {
00671         $rHandle = isset( $this->_aLockedFileHandles[$iLockMode][$sIdent] ) ? $this->_aLockedFileHandles[$iLockMode][$sIdent] : null;
00672         if ( $rHandle === null ) {
00673 
00674             $blLocked = false;
00675             $rHandle = @fopen( $sFilePath, "a+" );
00676 
00677             if ( $rHandle !== false ) {
00678 
00679                 if ( flock( $rHandle, $iLockMode | LOCK_NB ) ) {
00680                     if ( $iLockMode === LOCK_EX ) {
00681                         // truncate file
00682                         $blLocked = ftruncate( $rHandle, 0 );
00683                     } else {
00684                         // move to a start position
00685                         $blLocked = fseek( $rHandle, 0 ) === 0;
00686                     }
00687                 }
00688 
00689                 // on failure - closing and setting false..
00690                 if ( !$blLocked ) {
00691                     fclose( $rHandle );
00692                     $rHandle = false;
00693                 }
00694             }
00695 
00696             // in case system does not support file lockings
00697             if ( !$blLocked && $iLockMode === LOCK_EX ) {
00698 
00699                 // clearing on first call
00700                 if ( count( $this->_aLockedFileHandles ) == 0 ) {
00701                     clearstatcache();
00702                 }
00703 
00704                 // start a blank file to inform other processes we are dealing with it.
00705                 if (!( file_exists( $sFilePath ) && !filesize( $sFilePath ) && abs( time() - filectime( $sFilePath ) < 40 ) ) ) {
00706                     $rHandle = @fopen( $sFilePath, "w" );
00707                 }
00708             }
00709 
00710             $this->_aLockedFileHandles[$iLockMode][$sIdent] = $rHandle;
00711         }
00712 
00713         return $rHandle;
00714     }
00715 
00724     protected function _releaseFile( $sIdent, $iLockMode = LOCK_EX )
00725     {
00726         $blSuccess = true;
00727         if ( isset( $this->_aLockedFileHandles[$iLockMode][$sIdent] ) &&
00728              $this->_aLockedFileHandles[$iLockMode][$sIdent] !== false ) {
00729 
00730              // release the lock and close file
00731             $blSuccess = flock( $this->_aLockedFileHandles[$iLockMode][$sIdent], LOCK_UN ) &&
00732                          fclose( $this->_aLockedFileHandles[$iLockMode][$sIdent] );
00733             unset( $this->_aLockedFileHandles[$iLockMode][$sIdent] );
00734         }
00735 
00736         return $blSuccess;
00737     }
00738 
00746     public function oxResetFileCache()
00747     {
00748         $aFiles = glob( $this->getCacheFilePath( null, true ) . '*' );
00749         if ( is_array( $aFiles ) ) {
00750             // delete all the files, except cached tables fieldnames
00751             $aFiles = preg_grep( $this->_sPermanentCachePattern, $aFiles, PREG_GREP_INVERT );
00752             foreach ( $aFiles as $sFile ) {
00753                 @unlink( $sFile );
00754             }
00755         }
00756     }
00757 
00765     public function resetTemplateCache($aTemplates)
00766     {
00767         $sSmartyDir = oxRegistry::get("oxUtilsView")->getSmartyDir();
00768         //$aFiles = glob( $this->getCacheFilePath( null, true ) . '*' );
00769         $aFiles = glob( $sSmartyDir . '*' );
00770 
00771         if ( is_array( $aFiles ) && is_array( $aTemplates ) && count($aTemplates) ) {
00772             // delete all template cache files
00773             foreach ($aTemplates as &$sTemplate) {
00774                 $sTemplate = preg_quote(basename(strtolower($sTemplate), '.tpl'));
00775             }
00776 
00777             $sPattern = sprintf("/%%(%s)\.tpl\.php$/i", implode('|', $aTemplates));
00778             $aFiles = preg_grep( $sPattern, $aFiles );
00779 
00780             if (is_array( $aFiles ) ) {
00781                 foreach ( $aFiles as $sFile ) {
00782                     @unlink( $sFile );
00783                 }
00784             }
00785         }
00786 
00787     }
00788 
00794     public function resetLanguageCache()
00795     {
00796         $aFiles = glob( $this->getCacheFilePath( null, true ) . '*' );
00797         if ( is_array( $aFiles ) ) {
00798             // delete all language cache files
00799             $sPattern = $this->_sLanguageCachePattern;
00800             $aFiles = preg_grep( $sPattern, $aFiles );
00801             foreach ( $aFiles as $sFile ) {
00802                 @unlink( $sFile );
00803             }
00804         }
00805     }
00806 
00812     public function resetMenuCache()
00813     {
00814         $aFiles = glob( $this->getCacheFilePath( null, true ) . '*' );
00815         if ( is_array( $aFiles ) ) {
00816             // delete all menu cache files
00817             $sPattern = $this->_sMenuCachePattern;
00818             $aFiles = preg_grep( $sPattern, $aFiles );
00819             foreach ( $aFiles as $sFile ) {
00820                 @unlink( $sFile );
00821             }
00822         }
00823     }
00824 
00834     public function getRemoteCachePath($sRemote, $sLocal)
00835     {
00836         clearstatcache();
00837         if ( file_exists( $sLocal ) && filemtime( $sLocal ) && filemtime( $sLocal ) > time() - 86400 ) {
00838             return $sLocal;
00839         }
00840         $hRemote = @fopen( $sRemote, "rb");
00841         $blSuccess = false;
00842         if ( isset( $hRemote) && $hRemote ) {
00843             $hLocal = fopen( $sLocal, "wb");
00844             stream_copy_to_stream($hRemote, $hLocal);
00845             fclose($hRemote);
00846             fclose($hLocal);
00847             $blSuccess = true;
00848         } else {
00849             // try via fsockopen
00850             $aUrl = @parse_url( $sRemote);
00851             if ( !empty( $aUrl["host"])) {
00852                 $sPath = $aUrl["path"];
00853                 if ( empty( $sPath ) ) {
00854                     $sPath = "/";
00855                 }
00856                 $sHost = $aUrl["host"];
00857 
00858                 $hSocket = @fsockopen( $sHost, 80, $iErrorNumber, $iErrStr, 5);
00859                 if ( $hSocket) {
00860                     fputs( $hSocket, "GET ".$sPath." HTTP/1.0\r\nHost: $sHost\r\n\r\n");
00861                     $headers = stream_get_line($hSocket, 4096, "\r\n\r\n");
00862                     if ( ( $hLocal = @fopen( $sLocal, "wb") ) !== false ) {
00863                         rewind($hLocal);
00864                         // does not copy all the data
00865                         // stream_copy_to_stream($hSocket, $hLocal);
00866                         fwrite ( $hLocal, stream_get_contents( $hSocket ) );
00867                         fclose( $hLocal );
00868                         fclose( $hSocket );
00869                         $blSuccess = true;
00870                     }
00871                 }
00872             }
00873         }
00874         if ( $blSuccess || file_exists( $sLocal ) ) {
00875             return $sLocal;
00876         }
00877         return false;
00878     }
00879 
00885     public function canPreview()
00886     {
00887         $blCan = null;
00888         if ( ( $sPrevId = oxConfig::getParameter( 'preview' ) ) &&
00889              ( $sAdminSid = oxRegistry::get("oxUtilsServer")->getOxCookie( 'admin_sid' ) ) ) {
00890 
00891             $sTable = getViewName( 'oxuser' );
00892             $oDb = oxDb::getDb();
00893             $sQ = "select 1 from $sTable where MD5( CONCAT( ".$oDb->quote($sAdminSid).", {$sTable}.oxid, {$sTable}.oxpassword, {$sTable}.oxrights ) ) = ".oxDb::getDb()->quote($sPrevId);
00894             $blCan = (bool) $oDb->getOne( $sQ );
00895         }
00896 
00897         return $blCan;
00898     }
00899 
00905     public function getPreviewId()
00906     {
00907         $sAdminSid = oxRegistry::get("oxUtilsServer")->getOxCookie( 'admin_sid' );
00908         if ( ( $oUser = $this->getUser() ) ) {
00909             return md5( $sAdminSid . $oUser->getId() . $oUser->oxuser__oxpassword->value . $oUser->oxuser__oxrights->value );
00910         }
00911     }
00912 
00918     public function checkAccessRights()
00919     {
00920         $myConfig  = $this->getConfig();
00921 
00922         $blIsAuth = false;
00923 
00924         $sUserID = oxSession::getVar( "auth");
00925 
00926         // deleting admin marker
00927         oxSession::setVar( "malladmin", 0);
00928         oxSession::setVar( "blIsAdmin", 0);
00929         oxSession::deleteVar( "blIsAdmin" );
00930         $myConfig->setConfigParam( 'blMallAdmin', false );
00931         //#1552T
00932         $myConfig->setConfigParam( 'blAllowInheritedEdit', false );
00933 
00934         if ( $sUserID) {
00935             // escaping
00936             $oDb = oxDb::getDb();
00937             $sRights = $oDb->getOne("select oxrights from oxuser where oxid = ".$oDb->quote($sUserID));
00938 
00939             if ( $sRights != "user") {
00940                 // malladmin ?
00941                 if ( $sRights == "malladmin") {
00942                     oxSession::setVar( "malladmin", 1);
00943                     $myConfig->setConfigParam( 'blMallAdmin', true );
00944 
00945                     //#1552T
00946                     //So far this blAllowSharedEdit is Equal to blMallAdmin but in future to be solved over rights and roles
00947                     $myConfig->setConfigParam( 'blAllowSharedEdit', true );
00948 
00949                     $sShop = oxSession::getVar( "actshop");
00950                     if ( !isset($sShop)) {
00951                         oxSession::setVar( "actshop", $myConfig->getBaseShopId());
00952                     }
00953                     $blIsAuth = true;
00954                 } else {
00955                     // Shopadmin... check if this shop is valid and exists
00956                     $sShopID = $oDb->getOne("select oxid from oxshops where oxid = " . $oDb->quote( $sRights ) );
00957                     if ( isset( $sShopID) && $sShopID) {
00958                         // success, this shop exists
00959 
00960                         oxSession::setVar( "actshop", $sRights);
00961                         oxSession::setVar( "currentadminshop", $sRights);
00962                         oxSession::setVar( "shp", $sRights);
00963 
00964                         // check if this subshop admin is evil.
00965                         if ('chshp' == oxConfig::getParameter( 'fnc' )) {
00966                             // dont allow this call
00967                             $blIsAuth = false;
00968                         } else {
00969                             $blIsAuth = true;
00970 
00971                             $aShopIdVars = array('actshop', 'shp', 'currentadminshop');
00972                             foreach ($aShopIdVars as $sShopIdVar) {
00973                                 if ($sGotShop = oxConfig::getParameter( $sShopIdVar )) {
00974                                     if ($sGotShop != $sRights) {
00975                                         $blIsAuth = false;
00976                                         break;
00977                                     }
00978                                 }
00979                             }
00980                         }
00981                     }
00982                 }
00983                 // marking user as admin
00984                 oxSession::setVar( "blIsAdmin", 1);
00985             }
00986         }
00987         return $blIsAuth;
00988     }
00989 
00999     public function seoIsActive( $blReset = false, $sShopId = null, $iActLang = null )
01000     {
01001         if ( !is_null( $this->_blSeoIsActive ) && !$blReset ) {
01002             return $this->_blSeoIsActive;
01003         }
01004 
01005         $myConfig = $this->getConfig();
01006 
01007         if ( ( $this->_blSeoIsActive = $myConfig->getConfigParam( 'blSeoMode' ) ) === null ) {
01008             $this->_blSeoIsActive = true;
01009 
01010             $aSeoModes  = $myConfig->getconfigParam( 'aSeoModes' );
01011             $sActShopId = $sShopId ? $sShopId : $myConfig->getActiveShop()->getId();
01012             $iActLang   = $iActLang ? $iActLang : (int) oxRegistry::getLang()->getBaseLanguage();
01013 
01014             // checking special config param for active shop and language
01015             if ( is_array( $aSeoModes ) && isset( $aSeoModes[$sActShopId] ) && isset( $aSeoModes[$sActShopId][$iActLang] ) ) {
01016                 $this->_blSeoIsActive = (bool) $aSeoModes[$sActShopId][$iActLang];
01017             }
01018         }
01019 
01020         return $this->_blSeoIsActive;
01021     }
01022 
01030     public function isValidAlpha( $sField )
01031     {
01032         return (boolean) getStr()->preg_match( '/^[a-zA-Z0-9_]*$/', $sField );
01033     }
01034 
01044     protected function _simpleRedirect( $sUrl, $sHeaderCode )
01045     {
01046         header( $sHeaderCode );
01047         header( "Location: $sUrl" );
01048         header( "Connection: close" );
01049     }
01050 
01064     public function redirect( $sUrl, $blAddRedirectParam = true, $iHeaderCode = 301 )
01065     {
01066         //preventing possible cyclic redirection
01067         //#M341 and check only if redirect paramater must be added
01068         if ( $blAddRedirectParam && oxConfig::getParameter( 'redirected' ) ) {
01069             return;
01070         }
01071 
01072         if ( $blAddRedirectParam ) {
01073             $sUrl = $this->_addUrlParameters( $sUrl, array( 'redirected' => 1 ) );
01074         }
01075 
01076         $sUrl = str_ireplace( "&amp;", "&", $sUrl );
01077 
01078         $sHeaderCode = '';
01079         switch ($iHeaderCode) {
01080             case 301:
01081                 $sHeaderCode = "HTTP/1.1 301 Moved Permanently";
01082                 break;
01083             case 302:
01084             default:
01085                 $sHeaderCode = "HTTP/1.1 302 Found";
01086         }
01087 
01088         $this->_simpleRedirect( $sUrl, $sHeaderCode );
01089 
01090         try {//may occur in case db is lost
01091             $this->getSession()->freeze();
01092         } catch( oxException $oEx ) {
01093             $oEx->debugOut();
01094             //do nothing else to make sure the redirect takes place
01095         }
01096 
01097         if ( defined( 'OXID_PHP_UNIT' ) ) {
01098             return;
01099         }
01100 
01101         $this->showMessageAndExit( '' );
01102     }
01103 
01112     public function showMessageAndExit( $sMsg )
01113     {
01114         $this->getSession()->freeze();
01115         $this->commitFileCache();
01116 
01117         if ( defined( 'OXID_PHP_UNIT' ) ) {
01118             return;
01119         }
01120 
01121 
01122         exit( $sMsg );
01123     }
01124 
01132     public function setHeader($sHeader)
01133     {
01134         header($sHeader);
01135     }
01136 
01145     protected function _addUrlParameters( $sUrl, $aParams )
01146     {
01147         $sDelim = ( ( getStr()->strpos( $sUrl, '?' ) !== false ) )?'&':'?';
01148         foreach ( $aParams as $sName => $sVal ) {
01149             $sUrl = $sUrl . $sDelim . $sName . '=' . $sVal;
01150             $sDelim = '&';
01151         }
01152 
01153         return $sUrl;
01154     }
01155 
01167     protected function _fillExplodeArray( $aName, $dVat = null)
01168     {
01169         $myConfig = $this->getConfig();
01170         $oObject = new stdClass();
01171         $aPrice = explode( '!P!', $aName[0]);
01172 
01173         if ( ( $myConfig->getConfigParam( 'bl_perfLoadSelectLists' ) && $myConfig->getConfigParam( 'bl_perfUseSelectlistPrice' ) && isset( $aPrice[0] ) && isset( $aPrice[1] ) ) || $this->isAdmin() ) {
01174 
01175             // yes, price is there
01176             $oObject->price = isset( $aPrice[1] ) ? $aPrice[1] : 0;
01177             $aName[0] = isset( $aPrice[0] ) ? $aPrice[0] : '';
01178 
01179             $iPercPos = getStr()->strpos( $oObject->price, '%' );
01180             if ( $iPercPos !== false ) {
01181                 $oObject->priceUnit = '%';
01182                 $oObject->fprice = $oObject->price;
01183                 $oObject->price  = substr( $oObject->price, 0, $iPercPos );
01184             } else {
01185                 $oCur = $myConfig->getActShopCurrencyObject();
01186                 $oObject->price = str_replace(',', '.', $oObject->price);
01187                 $oObject->fprice = oxRegistry::getLang()->formatCurrency( $oObject->price  * $oCur->rate, $oCur);
01188                 $oObject->priceUnit = 'abs';
01189             }
01190 
01191             // add price info into list
01192             if ( !$this->isAdmin() && $oObject->price != 0 ) {
01193                 $aName[0] .= " ";
01194                 if ( $oObject->price > 0 ) {
01195                     $aName[0] .= "+";
01196                 }
01197                 //V FS#2616
01198                 if ( $dVat != null && $oObject->priceUnit == 'abs' ) {
01199                     $oPrice = oxNew('oxPrice');
01200                     $oPrice->setPrice($oObject->price, $dVat);
01201                     $aName[0] .= oxRegistry::getLang()->formatCurrency( $oPrice->getBruttoPrice() * $oCur->rate, $oCur);
01202                 } else {
01203                     $aName[0] .= $oObject->fprice;
01204                 }
01205                 if ( $oObject->priceUnit == 'abs' ) {
01206                     $aName[0] .= " ".$oCur->sign;
01207                 }
01208             }
01209         } elseif ( isset( $aPrice[0] ) && isset($aPrice[1] ) ) {
01210             // A. removing unused part of information
01211             $aName[0] = getStr()->preg_replace( "/!P!.*/", "", $aName[0] );
01212         }
01213 
01214         $oObject->name  = $aName[0];
01215         $oObject->value = $aName[1];
01216         return $oObject;
01217     }
01218 
01226     public function oxMimeContentType( $sFileName )
01227     {
01228         $sFileName = strtolower( $sFileName );
01229         $iLastDot  = strrpos( $sFileName, '.' );
01230 
01231         if ( $iLastDot !== false ) {
01232             $sType = substr( $sFileName, $iLastDot + 1 );
01233             switch ( $sType ) {
01234                 case 'gif':
01235                     $sType = 'image/gif';
01236                     break;
01237                 case 'jpeg':
01238                 case 'jpg':
01239                     $sType = 'image/jpeg';
01240                     break;
01241                 case 'png':
01242                     $sType = 'image/png';
01243                     break;
01244                 default:
01245                     $sType = false;
01246                     break;
01247             }
01248         }
01249         return $sType;
01250     }
01251 
01260     public function logger( $sText, $blNewline = false )
01261     {   $myConfig = $this->getConfig();
01262 
01263         if ( $myConfig->getConfigParam( 'iDebug' ) == -2) {
01264             if ( gettype( $sText ) != 'string' ) {
01265                 $sText = var_export( $sText, true);
01266             }
01267             $sLogMsg = "----------------------------------------------\n{$sText}".( ( $blNewline ) ?"\n":"" )."\n";
01268             $this->writeToLog( $sLogMsg, "log.txt" );
01269         }
01270 
01271     }
01272 
01280     protected function _stripQuotes($mInput)
01281     {
01282         return is_array($mInput) ? array_map( array( $this, '_stripQuotes' ), $mInput) : stripslashes( $mInput );
01283     }
01284 
01292     public function strRot13( $sStr )
01293     {
01294         $sFrom = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
01295         $sTo   = 'nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM';
01296 
01297         return strtr( $sStr, $sFrom, $sTo );
01298     }
01299 
01309     public function getCacheFilePath( $sCacheName, $blPathOnly = false, $sExtension = 'txt' )
01310     {
01311 
01312             $sVersionPrefix = 'pe';
01313 
01314         $sPath = realpath($this->getConfig()->getConfigParam( 'sCompileDir' ));
01315 
01316         if (!$sPath) {
01317             return false;
01318         }
01319 
01320         return $blPathOnly ? "{$sPath}/" : "{$sPath}/ox{$sVersionPrefix}c_{$sCacheName}." . $sExtension;
01321     }
01322 
01330     public function getLangCache( $sCacheName )
01331     {
01332         $aLangCache = null;
01333         $sFilePath = $this->getCacheFilePath( $sCacheName );
01334         if ( file_exists( $sFilePath ) && is_readable( $sFilePath ) ) {
01335             include $sFilePath;
01336         }
01337         return $aLangCache;
01338     }
01339 
01348     public function setLangCache( $sCacheName, $aLangCache )
01349     {
01350         $sCache = "<?php\n\$aLangCache = ".var_export( $aLangCache, true ).";\n?>";
01351         $blRes = file_put_contents($this->getCacheFilePath($sCacheName), $sCache);
01352         return $blRes;
01353     }
01354 
01362     public function checkUrlEndingSlash( $sUrl )
01363     {
01364         if ( !getStr()->preg_match("/\/$/", $sUrl) ) {
01365             $sUrl .= '/';
01366         }
01367 
01368         return $sUrl;
01369     }
01370 
01379     public function writeToLog( $sLogMessage, $sLogFileName )
01380     {
01381         $sLogDist = $this->getConfig()->getLogsDir().$sLogFileName;
01382         $blOk = false;
01383 
01384         if ( ( $oHandle = fopen( $sLogDist, 'a' ) ) !== false ) {
01385             fwrite( $oHandle, $sLogMessage );
01386             $blOk = fclose( $oHandle );
01387         }
01388 
01389         return $blOk;
01390     }
01391 
01399     public function handlePageNotFoundError($sUrl = '')
01400     {
01401         $this->setHeader("HTTP/1.0 404 Not Found");
01402         if ( oxRegistry::getConfig()->isUtf() ) {
01403             $this->setHeader("Content-Type: text/html; charset=UTF-8");
01404         }
01405 
01406         $sReturn = "Page not found.";
01407         try {
01408             $oView = oxNew('oxubase');
01409             $oView->init();
01410             $oView->render();
01411             $oView->setClassName( 'oxubase' );
01412             $oView->addTplParam('sUrl', $sUrl);
01413             if ($sRet = oxRegistry::get("oxUtilsView")->getTemplateOutput('message/err_404.tpl', $oView)) {
01414                 $sReturn = $sRet;
01415             }
01416         } catch (Exception $e) {
01417         }
01418         $this->showMessageAndExit( $sReturn );
01419     }
01420 
01428     public function extractDomain( $sHost )
01429     {
01430         $oStr = getStr();
01431         if ( !$oStr->preg_match( '/[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}/', $sHost ) &&
01432              ( $iLastDot = strrpos( $sHost, '.' ) ) !== false ) {
01433             $iLen = $oStr->strlen( $sHost );
01434             if ( ( $iNextDot = strrpos( $sHost, '.', ( $iLen - $iLastDot + 1 ) * - 1 ) ) !== false ) {
01435                 $sHost = trim( $oStr->substr( $sHost, $iNextDot ), '.' );
01436             }
01437         }
01438 
01439         return $sHost;
01440     }
01441 }