oxutils.php

Go to the documentation of this file.
00001 <?php
00002 
00006 require_once getShopBasePath()."core/smarty/Smarty.class.php";
00007 
00012 class oxUtils extends oxSuperCfg
00013 {
00019     protected $_iCurPrecision = null;
00020 
00028     protected $_sPermanentCachePattern = "/c_fieldnames_|c_tbdsc_|_allfields_/";
00029 
00035     protected $_sLanguageCachePattern = "/c_langcache_/i";
00036 
00042     protected $_sMenuCachePattern = "/c_menu_/i";
00043 
00049     protected $_aLockedFileHandles = array();
00050 
00056     protected $_aFileCacheContents = array();
00057 
00063     protected $_blIsSe = null;
00064 
00072     public static function getInstance()
00073     {
00074         return oxRegistry::getUtils();
00075     }
00076 
00082     protected $_aStaticCache;
00083 
00089     protected $_blSeoIsActive = null;
00090 
00096     public function stripGpcMagicQuotes()
00097     {
00098         if (!get_magic_quotes_gpc()) {
00099             return;
00100         }
00101         $_REQUEST = self::_stripQuotes($_REQUEST);
00102         $_POST = self::_stripQuotes($_POST);
00103         $_GET = self::_stripQuotes($_GET);
00104         $_COOKIE = self::_stripQuotes($_COOKIE);
00105     }
00106 
00115     public function strMan( $sVal, $sKey = null )
00116     {
00117         $sKey = $sKey ? $sKey : $this->getConfig()->getConfigParam('sConfigKey');
00118         $sVal = "ox{$sVal}id";
00119 
00120         $sKey = str_repeat( $sKey, strlen( $sVal ) / strlen( $sKey ) + 5 );
00121         $sVal = $this->strRot13( $sVal );
00122         $sVal = $sVal ^ $sKey;
00123         $sVal = base64_encode ( $sVal );
00124         $sVal = str_replace( "=", "!", $sVal );
00125 
00126         return "ox_$sVal";
00127     }
00128 
00137     public function strRem( $sVal, $sKey = null )
00138     {
00139         $sKey = $sKey ? $sKey : $this->getConfig()->getConfigParam('sConfigKey');
00140         $sKey = str_repeat( $sKey, strlen( $sVal ) / strlen( $sKey ) + 5 );
00141 
00142         $sVal = substr( $sVal, 3 );
00143         $sVal = str_replace( '!', '=', $sVal );
00144         $sVal = base64_decode( $sVal );
00145         $sVal = $sVal ^ $sKey;
00146         $sVal = $this->strRot13( $sVal );
00147 
00148         return substr( $sVal, 2, -2 );
00149     }
00150 
00158     public function getArrFldName( $sName )
00159     {
00160         return str_replace( ".", "__", $sName);
00161     }
00162 
00171     public function assignValuesFromText( $sIn, $dVat = null )
00172     {
00173         $aRet = array();
00174         $aPieces = explode( '@@', $sIn );
00175         while ( list( $sKey, $sVal ) = each( $aPieces ) ) {
00176             if ( $sVal ) {
00177                 $aName = explode( '__', $sVal );
00178                 if ( isset( $aName[0] ) && isset( $aName[1] ) ) {
00179                     $aRet[] = $this->_fillExplodeArray( $aName, $dVat );
00180                 }
00181             }
00182         }
00183         return $aRet;
00184     }
00185 
00193     public function assignValuesToText( $aIn)
00194     {
00195         $sRet = "";
00196         reset( $aIn );
00197         while (list($sKey, $sVal) = each($aIn)) {
00198             $sRet .= $sKey;
00199             $sRet .= "__";
00200             $sRet .= $sVal;
00201             $sRet .= "@@";
00202         }
00203         return $sRet;
00204     }
00205 
00213     public function currency2Float( $sValue)
00214     {
00215         $fRet = $sValue;
00216         $iPos = strrpos( $sValue, ".");
00217         if ($iPos && ((strlen($sValue)-1-$iPos) < 2+1)) {
00218             // replace decimal with ","
00219             $fRet = substr_replace( $fRet, ",", $iPos, 1);
00220         }
00221         // remove thousands
00222         $fRet = str_replace( array(" ","."), "", $fRet);
00223 
00224         $fRet = str_replace( ",", ".", $fRet);
00225         return (float) $fRet;
00226     }
00227 
00228 
00236     public function string2Float( $sValue)
00237     {
00238         $fRet = str_replace( " ", "", $sValue);
00239         $iCommaPos = strpos( $fRet, ",");
00240         $iDotPos = strpos( $fRet, ".");
00241         if (!$iDotPos xor !$iCommaPos) {
00242             if (substr_count( $fRet, ",") > 1 || substr_count( $fRet, ".") > 1) {
00243                 $fRet = str_replace( array(",","."), "", $fRet);
00244             } else {
00245                 $fRet = str_replace( ",", ".", $fRet);
00246             }
00247         } else if ( $iDotPos < $iCommaPos ) {
00248             $fRet = str_replace( ".", "", $fRet);
00249             $fRet = str_replace( ",", ".", $fRet);
00250         }
00251         // remove thousands
00252         $fRet = str_replace( array(" ",","), "", $fRet);
00253         return (float) $fRet;
00254     }
00255 
00263     public function isSearchEngine( $sClient = null )
00264     {
00265         if (is_null($this->_blIsSe)) {
00266             $this->setSearchEngine( null, $sClient );
00267         }
00268         return $this->_blIsSe;
00269     }
00270 
00279     public function setSearchEngine( $blIsSe = null, $sClient = null )
00280     {
00281         if (isset($blIsSe)) {
00282             $this->_blIsSe = $blIsSe;
00283             return;
00284         }
00285         startProfile("isSearchEngine");
00286 
00287         $myConfig = $this->getConfig();
00288         $blIsSe   = false;
00289 
00290         if ( !( $myConfig->getConfigParam( 'iDebug' ) && $this->isAdmin() ) ) {
00291             $aRobots = $myConfig->getConfigParam( 'aRobots' );
00292             $aRobots = is_array( $aRobots )?$aRobots:array();
00293 
00294             $aRobotsExcept = $myConfig->getConfigParam( 'aRobotsExcept' );
00295             $aRobotsExcept = is_array( $aRobotsExcept )?$aRobotsExcept:array();
00296 
00297             $sClient = $sClient?$sClient:strtolower( getenv( 'HTTP_USER_AGENT' ) );
00298             $blIsSe  = false;
00299             $aRobots = array_merge( $aRobots, $aRobotsExcept );
00300             foreach ( $aRobots as $sRobot ) {
00301                 if ( strpos( $sClient, $sRobot ) !== false ) {
00302                     $blIsSe = true;
00303                     break;
00304                 }
00305             }
00306         }
00307 
00308         $this->_blIsSe = $blIsSe;
00309 
00310         stopProfile("isSearchEngine");
00311     }
00312 
00321     public function isValidEmail( $sEmail )
00322     {
00323         $blValid = true;
00324         if ( $sEmail != 'admin' ) {
00325             $sEmailTpl = "/^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/i";
00326             $blValid = ( getStr()->preg_match( $sEmailTpl, $sEmail ) != 0 );
00327         }
00328 
00329         return $blValid;
00330     }
00331 
00339     public function loadAdminProfile($aInterfaceProfiles)
00340     {
00341         // improved #533
00342         // checking for available profiles list
00343         if ( is_array( $aInterfaceProfiles ) ) {
00344             //checking for previous profiles
00345             $sPrevProfile = oxRegistry::get("oxUtilsServer")->getOxCookie('oxidadminprofile');
00346             if (isset($sPrevProfile)) {
00347                 $aPrevProfile = @explode("@", trim($sPrevProfile));
00348             }
00349 
00350             //array to store profiles
00351             $aProfiles = array();
00352             foreach ( $aInterfaceProfiles as $iPos => $sProfile) {
00353                 $aProfileSettings = array($iPos, $sProfile);
00354                 $aProfiles[] = $aProfileSettings;
00355             }
00356             // setting previous used profile as active
00357             if (isset($aPrevProfile[0]) && isset($aProfiles[$aPrevProfile[0]])) {
00358                 $aProfiles[$aPrevProfile[0]][2] = 1;
00359             }
00360 
00361             oxSession::setVar("aAdminProfiles", $aProfiles);
00362             return $aProfiles;
00363         }
00364         return null;
00365     }
00366 
00375     public function fRound($sVal, $oCur = null)
00376     {
00377         startProfile('fround');
00378 
00379         //cached currency precision, this saves about 1% of execution time
00380         $iCurPrecision = null;
00381         if (! defined('OXID_PHP_UNIT')) {
00382             $iCurPrecision = $this->_iCurPrecision;
00383         }
00384 
00385         if (is_null($iCurPrecision)) {
00386             if ( !$oCur ) {
00387                 $oCur = $this->getConfig()->getActShopCurrencyObject();
00388             }
00389 
00390             $iCurPrecision = $oCur->decimal;
00391             $this->_iCurPrecision = $iCurPrecision;
00392         }
00393 
00394         // if < 5.3.x this is a workaround for #36008 bug in php - incorrect round() & number_format() result (R)
00395         static $dprez = null;
00396         if (!$dprez) {
00397             $prez = @ini_get("precision");
00398             if (!$prez || $prez > 12 ) {
00399                $prez = 12;
00400             }
00401             $dprez = pow(10, -$prez);
00402         }
00403         stopProfile('fround');
00404         return round($sVal + $dprez * ( $sVal >= 0 ? 1 : -1 ), $iCurPrecision);
00405     }
00406 
00416     public function toStaticCache( $sName, $sContent, $sKey = null )
00417     {
00418         // if it's an array then we add
00419         if ( $sKey ) {
00420             $this->_aStaticCache[$sName][$sKey] = $sContent;
00421         } else {
00422             $this->_aStaticCache[$sName] = $sContent;
00423         }
00424     }
00425 
00433     public function fromStaticCache( $sName)
00434     {
00435         if ( isset( $this->_aStaticCache[$sName])) {
00436             return $this->_aStaticCache[$sName];
00437         }
00438         return null;
00439     }
00440 
00448     public function cleanStaticCache($sCacheName = null)
00449     {
00450         if ($sCacheName) {
00451             unset($this->_aStaticCache[$sCacheName]);
00452         } else {
00453             $this->_aStaticCache = null;
00454         }
00455     }
00456 
00466     public function toPhpFileCache( $sKey, $mContents )
00467     {
00468         //only simple arrays are supported
00469         if ( is_array( $mContents ) && ( $sCachePath = $this->getCacheFilePath( $sKey, false, 'php' ) ) ) {
00470 
00471             // setting meta
00472             $this->setCacheMeta( $sKey, array( "serialize" => false, "cachepath" => $sCachePath ) );
00473 
00474             // caching..
00475             $this->toFileCache( $sKey, $mContents );
00476         }
00477     }
00478 
00486     public function fromPhpFileCache( $sKey )
00487     {
00488         // setting meta
00489         $this->setCacheMeta( $sKey, array( "include" => true, "cachepath" => $this->getCacheFilePath( $sKey, false, 'php' ) ) );
00490         return $this->fromFileCache( $sKey );
00491     }
00492 
00500     public function getCacheMeta( $sKey )
00501     {
00502         return isset( $this->_aFileCacheMeta[$sKey] ) ? $this->_aFileCacheMeta[$sKey] : false;
00503     }
00504 
00513     public function setCacheMeta( $sKey, $aMeta )
00514     {
00515         // cache meta data
00516         $this->_aFileCacheMeta[$sKey] = $aMeta;
00517     }
00518 
00528     public function toFileCache( $sKey, $mContents )
00529     {
00530         $this->_aFileCacheContents[$sKey] = $mContents;
00531         $aMeta = $this->getCacheMeta( $sKey );
00532 
00533         // looking for cache meta
00534         $sCachePath = isset( $aMeta["cachepath"] ) ? $aMeta["cachepath"] : $this->getCacheFilePath( $sKey );
00535         return ( bool ) $this->_lockFile( $sCachePath, $sKey );
00536     }
00537 
00545     public function fromFileCache( $sKey )
00546     {
00547         if ( !array_key_exists( $sKey, $this->_aFileCacheContents ) ) {
00548             $sRes = null;
00549 
00550             $aMeta = $this->getCacheMeta( $sKey );
00551             $blInclude  = isset( $aMeta["include"] ) ? $aMeta["include"] : false;
00552             $sCachePath = isset( $aMeta["cachepath"] ) ? $aMeta["cachepath"] : $this->getCacheFilePath( $sKey );
00553 
00554             // trying to lock
00555             $this->_lockFile( $sCachePath, $sKey, LOCK_SH );
00556 
00557             clearstatcache();
00558             if ( is_readable( $sCachePath ) ) {
00559                 $sRes = $blInclude ? $this->_includeFile( $sCachePath ) : $this->_readFile( $sCachePath );
00560             }
00561 
00562             // release lock
00563             $this->_releaseFile( $sKey, LOCK_SH );
00564 
00565             // caching
00566             $this->_aFileCacheContents[$sKey] = $sRes;
00567         }
00568 
00569         return $this->_aFileCacheContents[$sKey];
00570     }
00571 
00579     protected function _readFile( $sFilePath )
00580     {
00581         $sRes = file_get_contents( $sFilePath );
00582         return $sRes ? unserialize( $sRes ) : null;
00583     }
00584 
00592     protected function _includeFile( $sFilePath )
00593     {
00594         $_aCacheContents = null;
00595         include $sFilePath;
00596         return $_aCacheContents;
00597     }
00598 
00607     protected function _processCache( $sKey, $mContents )
00608     {
00609         // looking for cache meta
00610         $aCacheMeta  = $this->getCacheMeta( $sKey );
00611         $blSerialize = isset( $aCacheMeta["serialize"] ) ? $aCacheMeta["serialize"] : true;
00612 
00613         if ( $blSerialize ) {
00614             $mContents = serialize( $mContents );
00615         } else {
00616             $mContents = "<?php\n//automatically generated file\n//" . date( "Y-m-d H:i:s" ) . "\n\n\$_aCacheContents = " . var_export( $mContents, true ) . "\n?>";
00617         }
00618 
00619         return $mContents;
00620     }
00621 
00628     public function commitFileCache()
00629     {
00630         if ( count( $this->_aLockedFileHandles[LOCK_EX] ) ) {
00631             startProfile("!__SAVING CACHE__! (warning)");
00632             foreach ( $this->_aLockedFileHandles[LOCK_EX] as $sKey => $rHandle ) {
00633                 if ( $rHandle !== false && isset( $this->_aFileCacheContents[$sKey] ) ) {
00634 
00635                     // #0002931A truncate file once more before writing
00636                     ftruncate( $rHandle, 0 );
00637 
00638                     // writing cache
00639                     fwrite( $rHandle, $this->_processCache( $sKey, $this->_aFileCacheContents[$sKey] ) );
00640 
00641                     // releasing locks
00642                     $this->_releaseFile( $sKey );
00643                 }
00644             }
00645 
00646             stopProfile("!__SAVING CACHE__! (warning)");
00647 
00648             //empty buffer
00649             $this->_aFileCacheContents = array();
00650         }
00651     }
00652 
00662     protected function _lockFile( $sFilePath, $sIdent, $iLockMode = LOCK_EX )
00663     {
00664         $rHandle = isset( $this->_aLockedFileHandles[$iLockMode][$sIdent] ) ? $this->_aLockedFileHandles[$iLockMode][$sIdent] : null;
00665         if ( $rHandle === null ) {
00666 
00667             $blLocked = false;
00668             $rHandle = @fopen( $sFilePath, "a+" );
00669 
00670             if ( $rHandle !== false ) {
00671 
00672                 if ( flock( $rHandle, $iLockMode | LOCK_NB ) ) {
00673                     if ( $iLockMode === LOCK_EX ) {
00674                         // truncate file
00675                         $blLocked = ftruncate( $rHandle, 0 );
00676                     } else {
00677                         // move to a start position
00678                         $blLocked = fseek( $rHandle, 0 ) === 0;
00679                     }
00680                 }
00681 
00682                 // on failure - closing and setting false..
00683                 if ( !$blLocked ) {
00684                     fclose( $rHandle );
00685                     $rHandle = false;
00686                 }
00687             }
00688 
00689             // in case system does not support file locking
00690             if ( !$blLocked && $iLockMode === LOCK_EX ) {
00691 
00692                 // clearing on first call
00693                 if ( count( $this->_aLockedFileHandles ) == 0 ) {
00694                     clearstatcache();
00695                 }
00696 
00697                 // start a blank file to inform other processes we are dealing with it.
00698                 if (!( file_exists( $sFilePath ) && !filesize( $sFilePath ) && abs( time() - filectime( $sFilePath ) < 40 ) ) ) {
00699                     $rHandle = @fopen( $sFilePath, "w" );
00700                 }
00701             }
00702 
00703             $this->_aLockedFileHandles[$iLockMode][$sIdent] = $rHandle;
00704         }
00705 
00706         return $rHandle;
00707     }
00708 
00717     protected function _releaseFile( $sIdent, $iLockMode = LOCK_EX )
00718     {
00719         $blSuccess = true;
00720         if ( isset( $this->_aLockedFileHandles[$iLockMode][$sIdent] ) &&
00721              $this->_aLockedFileHandles[$iLockMode][$sIdent] !== false ) {
00722 
00723              // release the lock and close file
00724             $blSuccess = flock( $this->_aLockedFileHandles[$iLockMode][$sIdent], LOCK_UN ) &&
00725                          fclose( $this->_aLockedFileHandles[$iLockMode][$sIdent] );
00726             unset( $this->_aLockedFileHandles[$iLockMode][$sIdent] );
00727         }
00728 
00729         return $blSuccess;
00730     }
00731 
00739     public function oxResetFileCache()
00740     {
00741         $aFiles = glob( $this->getCacheFilePath( null, true ) . '*' );
00742         if ( is_array( $aFiles ) ) {
00743             // delete all the files, except cached tables field names
00744             $aFiles = preg_grep( $this->_sPermanentCachePattern, $aFiles, PREG_GREP_INVERT );
00745             foreach ( $aFiles as $sFile ) {
00746                 @unlink( $sFile );
00747             }
00748         }
00749     }
00750 
00758     public function resetTemplateCache($aTemplates)
00759     {
00760         $sSmartyDir = oxRegistry::get("oxUtilsView")->getSmartyDir();
00761         //$aFiles = glob( $this->getCacheFilePath( null, true ) . '*' );
00762         $aFiles = glob( $sSmartyDir . '*' );
00763 
00764         if ( is_array( $aFiles ) && is_array( $aTemplates ) && count($aTemplates) ) {
00765             // delete all template cache files
00766             foreach ($aTemplates as &$sTemplate) {
00767                 $sTemplate = preg_quote(basename(strtolower($sTemplate), '.tpl'));
00768             }
00769 
00770             $sPattern = sprintf("/%%(%s)\.tpl\.php$/i", implode('|', $aTemplates));
00771             $aFiles = preg_grep( $sPattern, $aFiles );
00772 
00773             if (is_array( $aFiles ) ) {
00774                 foreach ( $aFiles as $sFile ) {
00775                     @unlink( $sFile );
00776                 }
00777             }
00778         }
00779 
00780     }
00781 
00787     public function resetLanguageCache()
00788     {
00789         $aFiles = glob( $this->getCacheFilePath( null, true ) . '*' );
00790         if ( is_array( $aFiles ) ) {
00791             // delete all language cache files
00792             $sPattern = $this->_sLanguageCachePattern;
00793             $aFiles = preg_grep( $sPattern, $aFiles );
00794             foreach ( $aFiles as $sFile ) {
00795                 @unlink( $sFile );
00796             }
00797         }
00798     }
00799 
00805     public function resetMenuCache()
00806     {
00807         $aFiles = glob( $this->getCacheFilePath( null, true ) . '*' );
00808         if ( is_array( $aFiles ) ) {
00809             // delete all menu cache files
00810             $sPattern = $this->_sMenuCachePattern;
00811             $aFiles = preg_grep( $sPattern, $aFiles );
00812             foreach ( $aFiles as $sFile ) {
00813                 @unlink( $sFile );
00814             }
00815         }
00816     }
00817 
00827     public function getRemoteCachePath($sRemote, $sLocal)
00828     {
00829         clearstatcache();
00830         if ( file_exists( $sLocal ) && filemtime( $sLocal ) && filemtime( $sLocal ) > time() - 86400 ) {
00831             return $sLocal;
00832         }
00833         $hRemote = @fopen( $sRemote, "rb");
00834         $blSuccess = false;
00835         if ( isset( $hRemote) && $hRemote ) {
00836             $hLocal = fopen( $sLocal, "wb");
00837             stream_copy_to_stream($hRemote, $hLocal);
00838             fclose($hRemote);
00839             fclose($hLocal);
00840             $blSuccess = true;
00841         } else {
00842             // try via fsockopen
00843             $aUrl = @parse_url( $sRemote);
00844             if ( !empty( $aUrl["host"])) {
00845                 $sPath = $aUrl["path"];
00846                 if ( empty( $sPath ) ) {
00847                     $sPath = "/";
00848                 }
00849                 $sHost = $aUrl["host"];
00850 
00851                 $hSocket = @fsockopen( $sHost, 80, $iErrorNumber, $iErrStr, 5);
00852                 if ( $hSocket) {
00853                     fputs( $hSocket, "GET ".$sPath." HTTP/1.0\r\nHost: $sHost\r\n\r\n");
00854                     $headers = stream_get_line($hSocket, 4096, "\r\n\r\n");
00855                     if ( ( $hLocal = @fopen( $sLocal, "wb") ) !== false ) {
00856                         rewind($hLocal);
00857                         // does not copy all the data
00858                         // stream_copy_to_stream($hSocket, $hLocal);
00859                         fwrite ( $hLocal, stream_get_contents( $hSocket ) );
00860                         fclose( $hLocal );
00861                         fclose( $hSocket );
00862                         $blSuccess = true;
00863                     }
00864                 }
00865             }
00866         }
00867         if ( $blSuccess || file_exists( $sLocal ) ) {
00868             return $sLocal;
00869         }
00870         return false;
00871     }
00872 
00878     public function canPreview()
00879     {
00880         $blCan = null;
00881         if ( ( $sPrevId = oxConfig::getParameter( 'preview' ) ) &&
00882              ( $sAdminSid = oxRegistry::get("oxUtilsServer")->getOxCookie( 'admin_sid' ) ) ) {
00883 
00884             $sTable = getViewName( 'oxuser' );
00885             $oDb = oxDb::getDb();
00886             $sQ = "select 1 from $sTable where MD5( CONCAT( ".$oDb->quote($sAdminSid).", {$sTable}.oxid, {$sTable}.oxpassword, {$sTable}.oxrights ) ) = ".oxDb::getDb()->quote($sPrevId);
00887             $blCan = (bool) $oDb->getOne( $sQ );
00888         }
00889 
00890         return $blCan;
00891     }
00892 
00898     public function getPreviewId()
00899     {
00900         $sAdminSid = oxRegistry::get("oxUtilsServer")->getOxCookie( 'admin_sid' );
00901         if ( ( $oUser = $this->getUser() ) ) {
00902             return md5( $sAdminSid . $oUser->getId() . $oUser->oxuser__oxpassword->value . $oUser->oxuser__oxrights->value );
00903         }
00904     }
00905 
00911     public function checkAccessRights()
00912     {
00913         $myConfig  = $this->getConfig();
00914 
00915         $blIsAuth = false;
00916 
00917         $sUserID = oxSession::getVar( "auth");
00918 
00919         // deleting admin marker
00920         oxSession::setVar( "malladmin", 0);
00921         oxSession::setVar( "blIsAdmin", 0);
00922         oxSession::deleteVar( "blIsAdmin" );
00923         $myConfig->setConfigParam( 'blMallAdmin', false );
00924         //#1552T
00925         $myConfig->setConfigParam( 'blAllowInheritedEdit', false );
00926 
00927         if ( $sUserID) {
00928             // escaping
00929             $oDb = oxDb::getDb();
00930             $sRights = $oDb->getOne("select oxrights from oxuser where oxid = ".$oDb->quote($sUserID));
00931 
00932             if ( $sRights != "user") {
00933                 // malladmin ?
00934                 if ( $sRights == "malladmin") {
00935                     oxSession::setVar( "malladmin", 1);
00936                     $myConfig->setConfigParam( 'blMallAdmin', true );
00937 
00938                     //#1552T
00939                     //So far this blAllowSharedEdit is Equal to blMallAdmin but in future to be solved over rights and roles
00940                     $myConfig->setConfigParam( 'blAllowSharedEdit', true );
00941 
00942                     $sShop = oxSession::getVar( "actshop");
00943                     if ( !isset($sShop)) {
00944                         oxSession::setVar( "actshop", $myConfig->getBaseShopId());
00945                     }
00946                     $blIsAuth = true;
00947                 } else {
00948                     // Shopadmin... check if this shop is valid and exists
00949                     $sShopID = $oDb->getOne("select oxid from oxshops where oxid = " . $oDb->quote( $sRights ) );
00950                     if ( isset( $sShopID) && $sShopID) {
00951                         // success, this shop exists
00952 
00953                         oxSession::setVar( "actshop", $sRights);
00954                         oxSession::setVar( "currentadminshop", $sRights);
00955                         oxSession::setVar( "shp", $sRights);
00956 
00957                         // check if this subshop admin is evil.
00958                         if ('chshp' == oxConfig::getParameter( 'fnc' )) {
00959                             // dont allow this call
00960                             $blIsAuth = false;
00961                         } else {
00962                             $blIsAuth = true;
00963 
00964                             $aShopIdVars = array('actshop', 'shp', 'currentadminshop');
00965                             foreach ($aShopIdVars as $sShopIdVar) {
00966                                 if ($sGotShop = oxConfig::getParameter( $sShopIdVar )) {
00967                                     if ($sGotShop != $sRights) {
00968                                         $blIsAuth = false;
00969                                         break;
00970                                     }
00971                                 }
00972                             }
00973                         }
00974                     }
00975                 }
00976                 // marking user as admin
00977                 oxSession::setVar( "blIsAdmin", 1);
00978             }
00979         }
00980         return $blIsAuth;
00981     }
00982 
00992     public function seoIsActive( $blReset = false, $sShopId = null, $iActLang = null )
00993     {
00994         if ( !is_null( $this->_blSeoIsActive ) && !$blReset ) {
00995             return $this->_blSeoIsActive;
00996         }
00997 
00998         $myConfig = $this->getConfig();
00999 
01000         if ( ( $this->_blSeoIsActive = $myConfig->getConfigParam( 'blSeoMode' ) ) === null ) {
01001             $this->_blSeoIsActive = true;
01002 
01003             $aSeoModes  = $myConfig->getconfigParam( 'aSeoModes' );
01004             $sActShopId = $sShopId ? $sShopId : $myConfig->getActiveShop()->getId();
01005             $iActLang   = $iActLang ? $iActLang : (int) oxRegistry::getLang()->getBaseLanguage();
01006 
01007             // checking special config param for active shop and language
01008             if ( is_array( $aSeoModes ) && isset( $aSeoModes[$sActShopId] ) && isset( $aSeoModes[$sActShopId][$iActLang] ) ) {
01009                 $this->_blSeoIsActive = (bool) $aSeoModes[$sActShopId][$iActLang];
01010             }
01011         }
01012 
01013         return $this->_blSeoIsActive;
01014     }
01015 
01023     public function isValidAlpha( $sField )
01024     {
01025         return (boolean) getStr()->preg_match( '/^[a-zA-Z0-9_]*$/', $sField );
01026     }
01027 
01037     protected function _simpleRedirect( $sUrl, $sHeaderCode )
01038     {
01039         header( $sHeaderCode );
01040         header( "Location: $sUrl" );
01041         header( "Connection: close" );
01042     }
01043 
01053     public function redirect( $sUrl, $blAddRedirectParam = true, $iHeaderCode = 302 )
01054     {
01055         //preventing possible cyclic redirection
01056         //#M341 and check only if redirect parameter must be added
01057         if ( $blAddRedirectParam && oxConfig::getParameter( 'redirected' ) ) {
01058             return;
01059         }
01060 
01061         if ( $blAddRedirectParam ) {
01062             $sUrl = $this->_addUrlParameters( $sUrl, array( 'redirected' => 1 ) );
01063         }
01064 
01065         $sUrl = str_ireplace( "&amp;", "&", $sUrl );
01066 
01067         $sHeaderCode = '';
01068         switch ($iHeaderCode) {
01069             case 301:
01070                 $sHeaderCode = "HTTP/1.1 301 Moved Permanently";
01071                 break;
01072             case 302:
01073             default:
01074                 $sHeaderCode = "HTTP/1.1 302 Found";
01075         }
01076 
01077         $this->_simpleRedirect( $sUrl, $sHeaderCode );
01078 
01079         try {//may occur in case db is lost
01080             $this->getSession()->freeze();
01081         } catch( oxException $oEx ) {
01082             $oEx->debugOut();
01083             //do nothing else to make sure the redirect takes place
01084         }
01085 
01086         if ( defined( 'OXID_PHP_UNIT' ) ) {
01087             return;
01088         }
01089 
01090         $this->showMessageAndExit( '' );
01091     }
01092 
01101     public function showMessageAndExit( $sMsg )
01102     {
01103         $this->getSession()->freeze();
01104         $this->commitFileCache();
01105 
01106         if ( defined( 'OXID_PHP_UNIT' ) ) {
01107             return;
01108         }
01109 
01110 
01111         exit( $sMsg );
01112     }
01113 
01121     public function setHeader($sHeader)
01122     {
01123         header($sHeader);
01124     }
01125 
01134     protected function _addUrlParameters( $sUrl, $aParams )
01135     {
01136         $sDelimiter = ( ( getStr()->strpos( $sUrl, '?' ) !== false ) )?'&':'?';
01137         foreach ( $aParams as $sName => $sVal ) {
01138             $sUrl = $sUrl . $sDelimiter . $sName . '=' . $sVal;
01139             $sDelimiter = '&';
01140         }
01141 
01142         return $sUrl;
01143     }
01144 
01156     protected function _fillExplodeArray( $aName, $dVat = null)
01157     {
01158         $myConfig = $this->getConfig();
01159         $oObject = new stdClass();
01160         $aPrice = explode( '!P!', $aName[0]);
01161 
01162         if ( ( $myConfig->getConfigParam( 'bl_perfLoadSelectLists' ) && $myConfig->getConfigParam( 'bl_perfUseSelectlistPrice' ) && isset( $aPrice[0] ) && isset( $aPrice[1] ) ) || $this->isAdmin() ) {
01163 
01164             // yes, price is there
01165             $oObject->price = isset( $aPrice[1] ) ? $aPrice[1] : 0;
01166             $aName[0] = isset( $aPrice[0] ) ? $aPrice[0] : '';
01167 
01168             $iPercPos = getStr()->strpos( $oObject->price, '%' );
01169             if ( $iPercPos !== false ) {
01170                 $oObject->priceUnit = '%';
01171                 $oObject->fprice = $oObject->price;
01172                 $oObject->price  = substr( $oObject->price, 0, $iPercPos );
01173             } else {
01174                 $oCur = $myConfig->getActShopCurrencyObject();
01175                 $oObject->price = str_replace(',', '.', $oObject->price);
01176                 $oObject->fprice = oxRegistry::getLang()->formatCurrency( $oObject->price  * $oCur->rate, $oCur);
01177                 $oObject->priceUnit = 'abs';
01178             }
01179 
01180             // add price info into list
01181             if ( !$this->isAdmin() && $oObject->price != 0 ) {
01182                 $aName[0] .= " ";
01183 
01184                 $dPrice = $this->_preparePrice( $oObject->price, $dVat );
01185 
01186                 if ( $oObject->price > 0 ) {
01187                     $aName[0] .= "+";
01188                 }
01189                 //V FS#2616
01190                 if ( $dVat != null && $oObject->priceUnit == 'abs' ) {
01191                     $oPrice = oxNew('oxPrice');
01192                     $oPrice->setPrice($oObject->price, $dVat);
01193                     $aName[0] .= oxRegistry::getLang()->formatCurrency( $dPrice * $oCur->rate, $oCur);
01194                 } else {
01195                     $aName[0] .= $oObject->fprice;
01196                 }
01197                 if ( $oObject->priceUnit == 'abs' ) {
01198                     $aName[0] .= " ".$oCur->sign;
01199                 }
01200             }
01201         } elseif ( isset( $aPrice[0] ) && isset($aPrice[1] ) ) {
01202             // A. removing unused part of information
01203             $aName[0] = getStr()->preg_replace( "/!P!.*/", "", $aName[0] );
01204         }
01205 
01206         $oObject->name  = $aName[0];
01207         $oObject->value = $aName[1];
01208         return $oObject;
01209     }
01210 
01219     protected function _preparePrice( $dPrice, $dVat )
01220     {
01221         $blCalculationModeNetto = (bool) $this->getConfig()->getConfigParam('blShowNetPrice');
01222 
01223         $blEnterNetPrice = $this->getConfig()->getConfigParam('blEnterNetPrice');
01224         if ( $blCalculationModeNetto && !$blEnterNetPrice ) {
01225             $dPrice = round( oxPrice::brutto2Netto( $dPrice, $dVat ), 2 );
01226         } elseif ( !$blCalculationModeNetto && $blEnterNetPrice ) {
01227             $dPrice = round( oxPrice::netto2Brutto( $dPrice, $dVat ), 2 );
01228         }
01229         return $dPrice;
01230     }
01238     public function oxMimeContentType( $sFileName )
01239     {
01240         $sFileName = strtolower( $sFileName );
01241         $iLastDot  = strrpos( $sFileName, '.' );
01242 
01243         if ( $iLastDot !== false ) {
01244             $sType = substr( $sFileName, $iLastDot + 1 );
01245             switch ( $sType ) {
01246                 case 'gif':
01247                     $sType = 'image/gif';
01248                     break;
01249                 case 'jpeg':
01250                 case 'jpg':
01251                     $sType = 'image/jpeg';
01252                     break;
01253                 case 'png':
01254                     $sType = 'image/png';
01255                     break;
01256                 default:
01257                     $sType = false;
01258                     break;
01259             }
01260         }
01261         return $sType;
01262     }
01263 
01272     public function logger( $sText, $blNewline = false )
01273     {   $myConfig = $this->getConfig();
01274 
01275         if ( $myConfig->getConfigParam( 'iDebug' ) == -2) {
01276             if ( gettype( $sText ) != 'string' ) {
01277                 $sText = var_export( $sText, true);
01278             }
01279             $sLogMsg = "----------------------------------------------\n{$sText}".( ( $blNewline ) ?"\n":"" )."\n";
01280             $this->writeToLog( $sLogMsg, "log.txt" );
01281         }
01282 
01283     }
01284 
01292     protected function _stripQuotes($mInput)
01293     {
01294         return is_array($mInput) ? array_map( array( $this, '_stripQuotes' ), $mInput) : stripslashes( $mInput );
01295     }
01296 
01304     public function strRot13( $sStr )
01305     {
01306         $sFrom = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
01307         $sTo   = 'nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM';
01308 
01309         return strtr( $sStr, $sFrom, $sTo );
01310     }
01311 
01321     public function getCacheFilePath( $sCacheName, $blPathOnly = false, $sExtension = 'txt' )
01322     {
01323 
01324             $sVersionPrefix = 'pe';
01325 
01326         $sPath = realpath($this->getConfig()->getConfigParam( 'sCompileDir' ));
01327 
01328         if (!$sPath) {
01329             return false;
01330         }
01331 
01332         return $blPathOnly ? "{$sPath}/" : "{$sPath}/ox{$sVersionPrefix}c_{$sCacheName}." . $sExtension;
01333     }
01334 
01342     public function getLangCache( $sCacheName )
01343     {
01344         $aLangCache = null;
01345         $sFilePath = $this->getCacheFilePath( $sCacheName );
01346         if ( file_exists( $sFilePath ) && is_readable( $sFilePath ) ) {
01347             include $sFilePath;
01348         }
01349         return $aLangCache;
01350     }
01351 
01360     public function setLangCache( $sCacheName, $aLangCache )
01361     {
01362         $sCache = "<?php\n\$aLangCache = ".var_export( $aLangCache, true ).";\n?>";
01363         $blRes = file_put_contents($this->getCacheFilePath($sCacheName), $sCache);
01364         return $blRes;
01365     }
01366 
01374     public function checkUrlEndingSlash( $sUrl )
01375     {
01376         if ( !getStr()->preg_match("/\/$/", $sUrl) ) {
01377             $sUrl .= '/';
01378         }
01379 
01380         return $sUrl;
01381     }
01382 
01391     public function writeToLog( $sLogMessage, $sLogFileName )
01392     {
01393         $sLogDist = $this->getConfig()->getLogsDir().$sLogFileName;
01394         $blOk = false;
01395 
01396         if ( ( $oHandle = fopen( $sLogDist, 'a' ) ) !== false ) {
01397             fwrite( $oHandle, $sLogMessage );
01398             $blOk = fclose( $oHandle );
01399         }
01400 
01401         return $blOk;
01402     }
01403 
01411     public function handlePageNotFoundError($sUrl = '')
01412     {
01413         $this->setHeader("HTTP/1.0 404 Not Found");
01414         if ( oxRegistry::getConfig()->isUtf() ) {
01415             $this->setHeader("Content-Type: text/html; charset=UTF-8");
01416         }
01417 
01418         $sReturn = "Page not found.";
01419         try {
01420             $oView = oxNew('oxUBase');
01421             $oView->init();
01422             $oView->render();
01423             $oView->setClassName( 'oxUBase' );
01424             $oView->addTplParam('sUrl', $sUrl);
01425             if ($sRet = oxRegistry::get("oxUtilsView")->getTemplateOutput('message/err_404.tpl', $oView)) {
01426                 $sReturn = $sRet;
01427             }
01428         } catch (Exception $e) {
01429         }
01430         $this->showMessageAndExit( $sReturn );
01431     }
01432 
01440     public function extractDomain( $sHost )
01441     {
01442         $oStr = getStr();
01443         if ( !$oStr->preg_match( '/[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}/', $sHost ) &&
01444              ( $iLastDot = strrpos( $sHost, '.' ) ) !== false ) {
01445             $iLen = $oStr->strlen( $sHost );
01446             if ( ( $iNextDot = strrpos( $sHost, '.', ( $iLen - $iLastDot + 1 ) * - 1 ) ) !== false ) {
01447                 $sHost = trim( $oStr->substr( $sHost, $iNextDot ), '.' );
01448             }
01449         }
01450 
01451         return $sHost;
01452     }
01453 }