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         $oHeader = oxNew( "oxHeader" );
01040         $oHeader->setHeader( $sHeaderCode );
01041         $oHeader->setHeader( "Location: $sUrl" );
01042         $oHeader->setHeader( "Connection: close" );
01043         $oHeader->sendHeader();
01044     }
01045 
01055     public function redirect( $sUrl, $blAddRedirectParam = true, $iHeaderCode = 302 )
01056     {
01057         //preventing possible cyclic redirection
01058         //#M341 and check only if redirect parameter must be added
01059         if ( $blAddRedirectParam && oxConfig::getParameter( 'redirected' ) ) {
01060             return;
01061         }
01062 
01063         if ( $blAddRedirectParam ) {
01064             $sUrl = $this->_addUrlParameters( $sUrl, array( 'redirected' => 1 ) );
01065         }
01066 
01067         $sUrl = str_ireplace( "&amp;", "&", $sUrl );
01068 
01069         $sHeaderCode = '';
01070         switch ($iHeaderCode) {
01071             case 301:
01072                 $sHeaderCode = "HTTP/1.1 301 Moved Permanently";
01073                 break;
01074             case 302:
01075             default:
01076                 $sHeaderCode = "HTTP/1.1 302 Found";
01077         }
01078 
01079         $this->_simpleRedirect( $sUrl, $sHeaderCode );
01080 
01081         try {//may occur in case db is lost
01082             $this->getSession()->freeze();
01083         } catch( oxException $oEx ) {
01084             $oEx->debugOut();
01085             //do nothing else to make sure the redirect takes place
01086         }
01087 
01088         if ( defined( 'OXID_PHP_UNIT' ) ) {
01089             return;
01090         }
01091 
01092         $this->showMessageAndExit( '' );
01093     }
01094 
01103     public function showMessageAndExit( $sMsg )
01104     {
01105         $this->getSession()->freeze();
01106         $this->commitFileCache();
01107 
01108         if ( defined( 'OXID_PHP_UNIT' ) ) {
01109             return;
01110         }
01111 
01112 
01113         exit( $sMsg );
01114     }
01115 
01123     public function setHeader($sHeader)
01124     {
01125         header($sHeader);
01126     }
01127 
01136     protected function _addUrlParameters( $sUrl, $aParams )
01137     {
01138         $sDelimiter = ( ( getStr()->strpos( $sUrl, '?' ) !== false ) )?'&':'?';
01139         foreach ( $aParams as $sName => $sVal ) {
01140             $sUrl = $sUrl . $sDelimiter . $sName . '=' . $sVal;
01141             $sDelimiter = '&';
01142         }
01143 
01144         return $sUrl;
01145     }
01146 
01158     protected function _fillExplodeArray( $aName, $dVat = null)
01159     {
01160         $myConfig = $this->getConfig();
01161         $oObject = new stdClass();
01162         $aPrice = explode( '!P!', $aName[0]);
01163 
01164         if ( ( $myConfig->getConfigParam( 'bl_perfLoadSelectLists' ) && $myConfig->getConfigParam( 'bl_perfUseSelectlistPrice' ) && isset( $aPrice[0] ) && isset( $aPrice[1] ) ) || $this->isAdmin() ) {
01165 
01166             // yes, price is there
01167             $oObject->price = isset( $aPrice[1] ) ? $aPrice[1] : 0;
01168             $aName[0] = isset( $aPrice[0] ) ? $aPrice[0] : '';
01169 
01170             $iPercPos = getStr()->strpos( $oObject->price, '%' );
01171             if ( $iPercPos !== false ) {
01172                 $oObject->priceUnit = '%';
01173                 $oObject->fprice = $oObject->price;
01174                 $oObject->price  = substr( $oObject->price, 0, $iPercPos );
01175             } else {
01176                 $oCur = $myConfig->getActShopCurrencyObject();
01177                 $oObject->price = str_replace(',', '.', $oObject->price);
01178                 $oObject->fprice = oxRegistry::getLang()->formatCurrency( $oObject->price  * $oCur->rate, $oCur);
01179                 $oObject->priceUnit = 'abs';
01180             }
01181 
01182             // add price info into list
01183             if ( !$this->isAdmin() && $oObject->price != 0 ) {
01184                 $aName[0] .= " ";
01185 
01186                 $dPrice = $this->_preparePrice( $oObject->price, $dVat );
01187 
01188                 if ( $oObject->price > 0 ) {
01189                     $aName[0] .= "+";
01190                 }
01191                 //V FS#2616
01192                 if ( $dVat != null && $oObject->priceUnit == 'abs' ) {
01193                     $oPrice = oxNew('oxPrice');
01194                     $oPrice->setPrice($oObject->price, $dVat);
01195                     $aName[0] .= oxRegistry::getLang()->formatCurrency( $dPrice * $oCur->rate, $oCur);
01196                 } else {
01197                     $aName[0] .= $oObject->fprice;
01198                 }
01199                 if ( $oObject->priceUnit == 'abs' ) {
01200                     $aName[0] .= " ".$oCur->sign;
01201                 }
01202             }
01203         } elseif ( isset( $aPrice[0] ) && isset($aPrice[1] ) ) {
01204             // A. removing unused part of information
01205             $aName[0] = getStr()->preg_replace( "/!P!.*/", "", $aName[0] );
01206         }
01207 
01208         $oObject->name  = $aName[0];
01209         $oObject->value = $aName[1];
01210         return $oObject;
01211     }
01212 
01221     protected function _preparePrice( $dPrice, $dVat )
01222     {
01223         $blCalculationModeNetto = (bool) $this->getConfig()->getConfigParam('blShowNetPrice');
01224 
01225         $oCurrency = $this->getConfig()->getActShopCurrencyObject();
01226 
01227         $blEnterNetPrice = $this->getConfig()->getConfigParam('blEnterNetPrice');
01228         if ( $blCalculationModeNetto && !$blEnterNetPrice ) {
01229             $dPrice = round( oxPrice::brutto2Netto( $dPrice, $dVat ), $oCurrency->decimal );
01230         } elseif ( !$blCalculationModeNetto && $blEnterNetPrice ) {
01231             $dPrice = round( oxPrice::netto2Brutto( $dPrice, $dVat ), $oCurrency->decimal );
01232         }
01233         return $dPrice;
01234     }
01242     public function oxMimeContentType( $sFileName )
01243     {
01244         $sFileName = strtolower( $sFileName );
01245         $iLastDot  = strrpos( $sFileName, '.' );
01246 
01247         if ( $iLastDot !== false ) {
01248             $sType = substr( $sFileName, $iLastDot + 1 );
01249             switch ( $sType ) {
01250                 case 'gif':
01251                     $sType = 'image/gif';
01252                     break;
01253                 case 'jpeg':
01254                 case 'jpg':
01255                     $sType = 'image/jpeg';
01256                     break;
01257                 case 'png':
01258                     $sType = 'image/png';
01259                     break;
01260                 default:
01261                     $sType = false;
01262                     break;
01263             }
01264         }
01265         return $sType;
01266     }
01267 
01276     public function logger( $sText, $blNewline = false )
01277     {   $myConfig = $this->getConfig();
01278 
01279         if ( $myConfig->getConfigParam( 'iDebug' ) == -2) {
01280             if ( gettype( $sText ) != 'string' ) {
01281                 $sText = var_export( $sText, true);
01282             }
01283             $sLogMsg = "----------------------------------------------\n{$sText}".( ( $blNewline ) ?"\n":"" )."\n";
01284             $this->writeToLog( $sLogMsg, "log.txt" );
01285         }
01286 
01287     }
01288 
01296     protected function _stripQuotes($mInput)
01297     {
01298         return is_array($mInput) ? array_map( array( $this, '_stripQuotes' ), $mInput) : stripslashes( $mInput );
01299     }
01300 
01308     public function strRot13( $sStr )
01309     {
01310         $sFrom = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
01311         $sTo   = 'nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM';
01312 
01313         return strtr( $sStr, $sFrom, $sTo );
01314     }
01315 
01325     public function getCacheFilePath( $sCacheName, $blPathOnly = false, $sExtension = 'txt' )
01326     {
01327 
01328             $sVersionPrefix = 'pe';
01329 
01330         $sPath = realpath($this->getConfig()->getConfigParam( 'sCompileDir' ));
01331 
01332         if (!$sPath) {
01333             return false;
01334         }
01335 
01336         return $blPathOnly ? "{$sPath}/" : "{$sPath}/ox{$sVersionPrefix}c_{$sCacheName}." . $sExtension;
01337     }
01338 
01346     public function getLangCache( $sCacheName )
01347     {
01348         $aLangCache = null;
01349         $sFilePath = $this->getCacheFilePath( $sCacheName );
01350         if ( file_exists( $sFilePath ) && is_readable( $sFilePath ) ) {
01351             include $sFilePath;
01352         }
01353         return $aLangCache;
01354     }
01355 
01364     public function setLangCache( $sCacheName, $aLangCache )
01365     {
01366         $sCache = "<?php\n\$aLangCache = ".var_export( $aLangCache, true ).";\n?>";
01367         $blRes = file_put_contents($this->getCacheFilePath($sCacheName), $sCache, LOCK_EX);
01368         return $blRes;
01369     }
01370 
01378     public function checkUrlEndingSlash( $sUrl )
01379     {
01380         if ( !getStr()->preg_match("/\/$/", $sUrl) ) {
01381             $sUrl .= '/';
01382         }
01383 
01384         return $sUrl;
01385     }
01386 
01395     public function writeToLog( $sLogMessage, $sLogFileName )
01396     {
01397         $sLogDist = $this->getConfig()->getLogsDir().$sLogFileName;
01398         $blOk = false;
01399 
01400         if ( ( $oHandle = fopen( $sLogDist, 'a' ) ) !== false ) {
01401             fwrite( $oHandle, $sLogMessage );
01402             $blOk = fclose( $oHandle );
01403         }
01404 
01405         return $blOk;
01406     }
01407 
01415     public function handlePageNotFoundError($sUrl = '')
01416     {
01417         $this->setHeader("HTTP/1.0 404 Not Found");
01418         if ( oxRegistry::getConfig()->isUtf() ) {
01419             $this->setHeader("Content-Type: text/html; charset=UTF-8");
01420         }
01421 
01422         $sReturn = "Page not found.";
01423         try {
01424             $oView = oxNew('oxUBase');
01425             $oView->init();
01426             $oView->render();
01427             $oView->setClassName( 'oxUBase' );
01428             $oView->addTplParam('sUrl', $sUrl);
01429             if ($sRet = oxRegistry::get("oxUtilsView")->getTemplateOutput('message/err_404.tpl', $oView)) {
01430                 $sReturn = $sRet;
01431             }
01432         } catch (Exception $e) {
01433         }
01434         $this->showMessageAndExit( $sReturn );
01435     }
01436 
01444     public function extractDomain( $sHost )
01445     {
01446         $oStr = getStr();
01447         if ( !$oStr->preg_match( '/[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}/', $sHost ) &&
01448              ( $iLastDot = strrpos( $sHost, '.' ) ) !== false ) {
01449             $iLen = $oStr->strlen( $sHost );
01450             if ( ( $iNextDot = strrpos( $sHost, '.', ( $iLen - $iLastDot + 1 ) * - 1 ) ) !== false ) {
01451                 $sHost = trim( $oStr->substr( $sHost, $iNextDot ), '.' );
01452             }
01453         }
01454 
01455         return $sHost;
01456     }
01457 }