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 
00117     public function strMan( $sVal, $sKey = null )
00118     {
00119         $oEncryptor = oxNew('oxEncryptor');
00120         $sKey = $sKey ? $sKey : $this->getConfig()->getConfigParam('sConfigKey');
00121 
00122         return $oEncryptor->encrypt($sVal, $sKey);
00123     }
00124 
00135     public function strRem( $sVal, $sKey = null )
00136     {
00137         $oDecryptor = oxNew('oxDecryptor');
00138         $sKey = $sKey ? $sKey : $this->getConfig()->getConfigParam('sConfigKey');
00139 
00140         return $oDecryptor->decrypt($sVal, $sKey);
00141     }
00142 
00150     public function getArrFldName( $sName )
00151     {
00152         return str_replace( ".", "__", $sName);
00153     }
00154 
00163     public function assignValuesFromText( $sIn, $dVat = null )
00164     {
00165         $aRet = array();
00166         $aPieces = explode( '@@', $sIn );
00167         while ( list( $sKey, $sVal ) = each( $aPieces ) ) {
00168             if ( $sVal ) {
00169                 $aName = explode( '__', $sVal );
00170                 if ( isset( $aName[0] ) && isset( $aName[1] ) ) {
00171                     $aRet[] = $this->_fillExplodeArray( $aName, $dVat );
00172                 }
00173             }
00174         }
00175         return $aRet;
00176     }
00177 
00185     public function assignValuesToText( $aIn)
00186     {
00187         $sRet = "";
00188         reset( $aIn );
00189         while (list($sKey, $sVal) = each($aIn)) {
00190             $sRet .= $sKey;
00191             $sRet .= "__";
00192             $sRet .= $sVal;
00193             $sRet .= "@@";
00194         }
00195         return $sRet;
00196     }
00197 
00205     public function currency2Float( $sValue)
00206     {
00207         $fRet = $sValue;
00208         $iPos = strrpos( $sValue, ".");
00209         if ($iPos && ((strlen($sValue)-1-$iPos) < 2+1)) {
00210             // replace decimal with ","
00211             $fRet = substr_replace( $fRet, ",", $iPos, 1);
00212         }
00213         // remove thousands
00214         $fRet = str_replace( array(" ","."), "", $fRet);
00215 
00216         $fRet = str_replace( ",", ".", $fRet);
00217         return (float) $fRet;
00218     }
00219 
00220 
00228     public function string2Float( $sValue)
00229     {
00230         $fRet = str_replace( " ", "", $sValue);
00231         $iCommaPos = strpos( $fRet, ",");
00232         $iDotPos = strpos( $fRet, ".");
00233         if (!$iDotPos xor !$iCommaPos) {
00234             if (substr_count( $fRet, ",") > 1 || substr_count( $fRet, ".") > 1) {
00235                 $fRet = str_replace( array(",","."), "", $fRet);
00236             } else {
00237                 $fRet = str_replace( ",", ".", $fRet);
00238             }
00239         } else if ( $iDotPos < $iCommaPos ) {
00240             $fRet = str_replace( ".", "", $fRet);
00241             $fRet = str_replace( ",", ".", $fRet);
00242         }
00243         // remove thousands
00244         $fRet = str_replace( array(" ",","), "", $fRet);
00245         return (float) $fRet;
00246     }
00247 
00255     public function isSearchEngine( $sClient = null )
00256     {
00257         if (is_null($this->_blIsSe)) {
00258             $this->setSearchEngine( null, $sClient );
00259         }
00260         return $this->_blIsSe;
00261     }
00262 
00271     public function setSearchEngine( $blIsSe = null, $sClient = null )
00272     {
00273         if (isset($blIsSe)) {
00274             $this->_blIsSe = $blIsSe;
00275             return;
00276         }
00277         startProfile("isSearchEngine");
00278 
00279         $myConfig = $this->getConfig();
00280         $blIsSe   = false;
00281 
00282         if ( !( $myConfig->getConfigParam( 'iDebug' ) && $this->isAdmin() ) ) {
00283             $aRobots = $myConfig->getConfigParam( 'aRobots' );
00284             $aRobots = is_array( $aRobots )?$aRobots:array();
00285 
00286             $aRobotsExcept = $myConfig->getConfigParam( 'aRobotsExcept' );
00287             $aRobotsExcept = is_array( $aRobotsExcept )?$aRobotsExcept:array();
00288 
00289             $sClient = $sClient?$sClient:strtolower( getenv( 'HTTP_USER_AGENT' ) );
00290             $blIsSe  = false;
00291             $aRobots = array_merge( $aRobots, $aRobotsExcept );
00292             foreach ( $aRobots as $sRobot ) {
00293                 if ( strpos( $sClient, $sRobot ) !== false ) {
00294                     $blIsSe = true;
00295                     break;
00296                 }
00297             }
00298         }
00299 
00300         $this->_blIsSe = $blIsSe;
00301 
00302         stopProfile("isSearchEngine");
00303     }
00304 
00313     public function isValidEmail( $sEmail )
00314     {
00315         $blValid = true;
00316         if ( $sEmail != 'admin' ) {
00317             $sEmailTpl = "/^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/i";
00318             $blValid = ( getStr()->preg_match( $sEmailTpl, $sEmail ) != 0 );
00319         }
00320 
00321         return $blValid;
00322     }
00323 
00331     public function loadAdminProfile($aInterfaceProfiles)
00332     {
00333         // improved #533
00334         // checking for available profiles list
00335         if ( is_array( $aInterfaceProfiles ) ) {
00336             //checking for previous profiles
00337             $sPrevProfile = oxRegistry::get("oxUtilsServer")->getOxCookie('oxidadminprofile');
00338             if (isset($sPrevProfile)) {
00339                 $aPrevProfile = @explode("@", trim($sPrevProfile));
00340             }
00341 
00342             //array to store profiles
00343             $aProfiles = array();
00344             foreach ( $aInterfaceProfiles as $iPos => $sProfile) {
00345                 $aProfileSettings = array($iPos, $sProfile);
00346                 $aProfiles[] = $aProfileSettings;
00347             }
00348             // setting previous used profile as active
00349             if (isset($aPrevProfile[0]) && isset($aProfiles[$aPrevProfile[0]])) {
00350                 $aProfiles[$aPrevProfile[0]][2] = 1;
00351             }
00352 
00353             oxSession::setVar("aAdminProfiles", $aProfiles);
00354             return $aProfiles;
00355         }
00356         return null;
00357     }
00358 
00367     public function fRound($sVal, $oCur = null)
00368     {
00369         startProfile('fround');
00370 
00371         //cached currency precision, this saves about 1% of execution time
00372         $iCurPrecision = null;
00373         if (! defined('OXID_PHP_UNIT')) {
00374             $iCurPrecision = $this->_iCurPrecision;
00375         }
00376 
00377         if (is_null($iCurPrecision)) {
00378             if ( !$oCur ) {
00379                 $oCur = $this->getConfig()->getActShopCurrencyObject();
00380             }
00381 
00382             $iCurPrecision = $oCur->decimal;
00383             $this->_iCurPrecision = $iCurPrecision;
00384         }
00385 
00386         // if < 5.3.x this is a workaround for #36008 bug in php - incorrect round() & number_format() result (R)
00387         static $dprez = null;
00388         if (!$dprez) {
00389             $prez = @ini_get("precision");
00390             if (!$prez || $prez > 12 ) {
00391                $prez = 12;
00392             }
00393             $dprez = pow(10, -$prez);
00394         }
00395         stopProfile('fround');
00396         return round($sVal + $dprez * ( $sVal >= 0 ? 1 : -1 ), $iCurPrecision);
00397     }
00398 
00408     public function toStaticCache( $sName, $sContent, $sKey = null )
00409     {
00410         // if it's an array then we add
00411         if ( $sKey ) {
00412             $this->_aStaticCache[$sName][$sKey] = $sContent;
00413         } else {
00414             $this->_aStaticCache[$sName] = $sContent;
00415         }
00416     }
00417 
00425     public function fromStaticCache( $sName)
00426     {
00427         if ( isset( $this->_aStaticCache[$sName])) {
00428             return $this->_aStaticCache[$sName];
00429         }
00430         return null;
00431     }
00432 
00440     public function cleanStaticCache($sCacheName = null)
00441     {
00442         if ($sCacheName) {
00443             unset($this->_aStaticCache[$sCacheName]);
00444         } else {
00445             $this->_aStaticCache = null;
00446         }
00447     }
00448 
00458     public function toPhpFileCache( $sKey, $mContents )
00459     {
00460         //only simple arrays are supported
00461         if ( is_array( $mContents ) && ( $sCachePath = $this->getCacheFilePath( $sKey, false, 'php' ) ) ) {
00462 
00463             // setting meta
00464             $this->setCacheMeta( $sKey, array( "serialize" => false, "cachepath" => $sCachePath ) );
00465 
00466             // caching..
00467             $this->toFileCache( $sKey, $mContents );
00468         }
00469     }
00470 
00478     public function fromPhpFileCache( $sKey )
00479     {
00480         // setting meta
00481         $this->setCacheMeta( $sKey, array( "include" => true, "cachepath" => $this->getCacheFilePath( $sKey, false, 'php' ) ) );
00482         return $this->fromFileCache( $sKey );
00483     }
00484 
00492     public function getCacheMeta( $sKey )
00493     {
00494         return isset( $this->_aFileCacheMeta[$sKey] ) ? $this->_aFileCacheMeta[$sKey] : false;
00495     }
00496 
00505     public function setCacheMeta( $sKey, $aMeta )
00506     {
00507         // cache meta data
00508         $this->_aFileCacheMeta[$sKey] = $aMeta;
00509     }
00510 
00520     public function toFileCache( $sKey, $mContents )
00521     {
00522         $this->_aFileCacheContents[$sKey] = $mContents;
00523         $aMeta = $this->getCacheMeta( $sKey );
00524 
00525         // looking for cache meta
00526         $sCachePath = isset( $aMeta["cachepath"] ) ? $aMeta["cachepath"] : $this->getCacheFilePath( $sKey );
00527         return ( bool ) $this->_lockFile( $sCachePath, $sKey );
00528     }
00529 
00537     public function fromFileCache( $sKey )
00538     {
00539         if ( !array_key_exists( $sKey, $this->_aFileCacheContents ) ) {
00540             $sRes = null;
00541 
00542             $aMeta = $this->getCacheMeta( $sKey );
00543             $blInclude  = isset( $aMeta["include"] ) ? $aMeta["include"] : false;
00544             $sCachePath = isset( $aMeta["cachepath"] ) ? $aMeta["cachepath"] : $this->getCacheFilePath( $sKey );
00545 
00546             // trying to lock
00547             $this->_lockFile( $sCachePath, $sKey, LOCK_SH );
00548 
00549             clearstatcache();
00550             if ( is_readable( $sCachePath ) ) {
00551                 $sRes = $blInclude ? $this->_includeFile( $sCachePath ) : $this->_readFile( $sCachePath );
00552             }
00553 
00554             // release lock
00555             $this->_releaseFile( $sKey, LOCK_SH );
00556 
00557             // caching
00558             $this->_aFileCacheContents[$sKey] = $sRes;
00559         }
00560 
00561         return $this->_aFileCacheContents[$sKey];
00562     }
00563 
00571     protected function _readFile( $sFilePath )
00572     {
00573         $sRes = file_get_contents( $sFilePath );
00574         return $sRes ? unserialize( $sRes ) : null;
00575     }
00576 
00584     protected function _includeFile( $sFilePath )
00585     {
00586         $_aCacheContents = null;
00587         include $sFilePath;
00588         return $_aCacheContents;
00589     }
00590 
00599     protected function _processCache( $sKey, $mContents )
00600     {
00601         // looking for cache meta
00602         $aCacheMeta  = $this->getCacheMeta( $sKey );
00603         $blSerialize = isset( $aCacheMeta["serialize"] ) ? $aCacheMeta["serialize"] : true;
00604 
00605         if ( $blSerialize ) {
00606             $mContents = serialize( $mContents );
00607         } else {
00608             $mContents = "<?php\n//automatically generated file\n//" . date( "Y-m-d H:i:s" ) . "\n\n\$_aCacheContents = " . var_export( $mContents, true ) . "\n?>";
00609         }
00610 
00611         return $mContents;
00612     }
00613 
00620     public function commitFileCache()
00621     {
00622         if ( count( $this->_aLockedFileHandles[LOCK_EX] ) ) {
00623             startProfile("!__SAVING CACHE__! (warning)");
00624             foreach ( $this->_aLockedFileHandles[LOCK_EX] as $sKey => $rHandle ) {
00625                 if ( $rHandle !== false && isset( $this->_aFileCacheContents[$sKey] ) ) {
00626 
00627                     // #0002931A truncate file once more before writing
00628                     ftruncate( $rHandle, 0 );
00629 
00630                     // writing cache
00631                     fwrite( $rHandle, $this->_processCache( $sKey, $this->_aFileCacheContents[$sKey] ) );
00632 
00633                     // releasing locks
00634                     $this->_releaseFile( $sKey );
00635                 }
00636             }
00637 
00638             stopProfile("!__SAVING CACHE__! (warning)");
00639 
00640             //empty buffer
00641             $this->_aFileCacheContents = array();
00642         }
00643     }
00644 
00654     protected function _lockFile( $sFilePath, $sIdent, $iLockMode = LOCK_EX )
00655     {
00656         $rHandle = isset( $this->_aLockedFileHandles[$iLockMode][$sIdent] ) ? $this->_aLockedFileHandles[$iLockMode][$sIdent] : null;
00657         if ( $rHandle === null ) {
00658 
00659             $blLocked = false;
00660             $rHandle = @fopen( $sFilePath, "a+" );
00661 
00662             if ( $rHandle !== false ) {
00663 
00664                 if ( flock( $rHandle, $iLockMode | LOCK_NB ) ) {
00665                     if ( $iLockMode === LOCK_EX ) {
00666                         // truncate file
00667                         $blLocked = ftruncate( $rHandle, 0 );
00668                     } else {
00669                         // move to a start position
00670                         $blLocked = fseek( $rHandle, 0 ) === 0;
00671                     }
00672                 }
00673 
00674                 // on failure - closing and setting false..
00675                 if ( !$blLocked ) {
00676                     fclose( $rHandle );
00677                     $rHandle = false;
00678                 }
00679             }
00680 
00681             // in case system does not support file locking
00682             if ( !$blLocked && $iLockMode === LOCK_EX ) {
00683 
00684                 // clearing on first call
00685                 if ( count( $this->_aLockedFileHandles ) == 0 ) {
00686                     clearstatcache();
00687                 }
00688 
00689                 // start a blank file to inform other processes we are dealing with it.
00690                 if (!( file_exists( $sFilePath ) && !filesize( $sFilePath ) && abs( time() - filectime( $sFilePath ) < 40 ) ) ) {
00691                     $rHandle = @fopen( $sFilePath, "w" );
00692                 }
00693             }
00694 
00695             $this->_aLockedFileHandles[$iLockMode][$sIdent] = $rHandle;
00696         }
00697 
00698         return $rHandle;
00699     }
00700 
00709     protected function _releaseFile( $sIdent, $iLockMode = LOCK_EX )
00710     {
00711         $blSuccess = true;
00712         if ( isset( $this->_aLockedFileHandles[$iLockMode][$sIdent] ) &&
00713              $this->_aLockedFileHandles[$iLockMode][$sIdent] !== false ) {
00714 
00715              // release the lock and close file
00716             $blSuccess = flock( $this->_aLockedFileHandles[$iLockMode][$sIdent], LOCK_UN ) &&
00717                          fclose( $this->_aLockedFileHandles[$iLockMode][$sIdent] );
00718             unset( $this->_aLockedFileHandles[$iLockMode][$sIdent] );
00719         }
00720 
00721         return $blSuccess;
00722     }
00723 
00731     public function oxResetFileCache()
00732     {
00733         $aFiles = glob( $this->getCacheFilePath( null, true ) . '*' );
00734         if ( is_array( $aFiles ) ) {
00735             // delete all the files, except cached tables field names
00736             $aFiles = preg_grep( $this->_sPermanentCachePattern, $aFiles, PREG_GREP_INVERT );
00737             foreach ( $aFiles as $sFile ) {
00738                 @unlink( $sFile );
00739             }
00740         }
00741     }
00742 
00750     public function resetTemplateCache($aTemplates)
00751     {
00752         $sSmartyDir = oxRegistry::get("oxUtilsView")->getSmartyDir();
00753         //$aFiles = glob( $this->getCacheFilePath( null, true ) . '*' );
00754         $aFiles = glob( $sSmartyDir . '*' );
00755 
00756         if ( is_array( $aFiles ) && is_array( $aTemplates ) && count($aTemplates) ) {
00757             // delete all template cache files
00758             foreach ($aTemplates as &$sTemplate) {
00759                 $sTemplate = preg_quote(basename(strtolower($sTemplate), '.tpl'));
00760             }
00761 
00762             $sPattern = sprintf("/%%(%s)\.tpl\.php$/i", implode('|', $aTemplates));
00763             $aFiles = preg_grep( $sPattern, $aFiles );
00764 
00765             if (is_array( $aFiles ) ) {
00766                 foreach ( $aFiles as $sFile ) {
00767                     @unlink( $sFile );
00768                 }
00769             }
00770         }
00771 
00772     }
00773 
00779     public function resetLanguageCache()
00780     {
00781         $aFiles = glob( $this->getCacheFilePath( null, true ) . '*' );
00782         if ( is_array( $aFiles ) ) {
00783             // delete all language cache files
00784             $sPattern = $this->_sLanguageCachePattern;
00785             $aFiles = preg_grep( $sPattern, $aFiles );
00786             foreach ( $aFiles as $sFile ) {
00787                 @unlink( $sFile );
00788             }
00789         }
00790     }
00791 
00797     public function resetMenuCache()
00798     {
00799         $aFiles = glob( $this->getCacheFilePath( null, true ) . '*' );
00800         if ( is_array( $aFiles ) ) {
00801             // delete all menu cache files
00802             $sPattern = $this->_sMenuCachePattern;
00803             $aFiles = preg_grep( $sPattern, $aFiles );
00804             foreach ( $aFiles as $sFile ) {
00805                 @unlink( $sFile );
00806             }
00807         }
00808     }
00809 
00819     public function getRemoteCachePath($sRemote, $sLocal)
00820     {
00821         clearstatcache();
00822         if ( file_exists( $sLocal ) && filemtime( $sLocal ) && filemtime( $sLocal ) > time() - 86400 ) {
00823             return $sLocal;
00824         }
00825         $hRemote = @fopen( $sRemote, "rb");
00826         $blSuccess = false;
00827         if ( isset( $hRemote) && $hRemote ) {
00828             $hLocal = fopen( $sLocal, "wb");
00829             stream_copy_to_stream($hRemote, $hLocal);
00830             fclose($hRemote);
00831             fclose($hLocal);
00832             $blSuccess = true;
00833         } else {
00834             // try via fsockopen
00835             $aUrl = @parse_url( $sRemote);
00836             if ( !empty( $aUrl["host"])) {
00837                 $sPath = $aUrl["path"];
00838                 if ( empty( $sPath ) ) {
00839                     $sPath = "/";
00840                 }
00841                 $sHost = $aUrl["host"];
00842 
00843                 $hSocket = @fsockopen( $sHost, 80, $iErrorNumber, $iErrStr, 5);
00844                 if ( $hSocket) {
00845                     fputs( $hSocket, "GET ".$sPath." HTTP/1.0\r\nHost: $sHost\r\n\r\n");
00846                     $headers = stream_get_line($hSocket, 4096, "\r\n\r\n");
00847                     if ( ( $hLocal = @fopen( $sLocal, "wb") ) !== false ) {
00848                         rewind($hLocal);
00849                         // does not copy all the data
00850                         // stream_copy_to_stream($hSocket, $hLocal);
00851                         fwrite ( $hLocal, stream_get_contents( $hSocket ) );
00852                         fclose( $hLocal );
00853                         fclose( $hSocket );
00854                         $blSuccess = true;
00855                     }
00856                 }
00857             }
00858         }
00859         if ( $blSuccess || file_exists( $sLocal ) ) {
00860             return $sLocal;
00861         }
00862         return false;
00863     }
00864 
00870     public function canPreview()
00871     {
00872         $blCan = null;
00873         if ( ( $sPrevId = oxConfig::getParameter( 'preview' ) ) &&
00874              ( $sAdminSid = oxRegistry::get("oxUtilsServer")->getOxCookie( 'admin_sid' ) ) ) {
00875 
00876             $sTable = getViewName( 'oxuser' );
00877             $oDb = oxDb::getDb();
00878             $sQ = "select 1 from $sTable where MD5( CONCAT( ".$oDb->quote($sAdminSid).", {$sTable}.oxid, {$sTable}.oxpassword, {$sTable}.oxrights ) ) = ".oxDb::getDb()->quote($sPrevId);
00879             $blCan = (bool) $oDb->getOne( $sQ );
00880         }
00881 
00882         return $blCan;
00883     }
00884 
00890     public function getPreviewId()
00891     {
00892         $sAdminSid = oxRegistry::get("oxUtilsServer")->getOxCookie( 'admin_sid' );
00893         if ( ( $oUser = $this->getUser() ) ) {
00894             return md5( $sAdminSid . $oUser->getId() . $oUser->oxuser__oxpassword->value . $oUser->oxuser__oxrights->value );
00895         }
00896     }
00897 
00903     public function checkAccessRights()
00904     {
00905         $myConfig  = $this->getConfig();
00906 
00907         $blIsAuth = false;
00908 
00909         $sUserID = oxSession::getVar( "auth");
00910 
00911         // deleting admin marker
00912         oxSession::setVar( "malladmin", 0);
00913         oxSession::setVar( "blIsAdmin", 0);
00914         oxSession::deleteVar( "blIsAdmin" );
00915         $myConfig->setConfigParam( 'blMallAdmin', false );
00916         //#1552T
00917         $myConfig->setConfigParam( 'blAllowInheritedEdit', false );
00918 
00919         if ( $sUserID) {
00920             // escaping
00921             $oDb = oxDb::getDb();
00922             $sRights = $oDb->getOne("select oxrights from oxuser where oxid = ".$oDb->quote($sUserID));
00923 
00924             if ( $sRights != "user") {
00925                 // malladmin ?
00926                 if ( $sRights == "malladmin") {
00927                     oxSession::setVar( "malladmin", 1);
00928                     $myConfig->setConfigParam( 'blMallAdmin', true );
00929 
00930                     //#1552T
00931                     //So far this blAllowSharedEdit is Equal to blMallAdmin but in future to be solved over rights and roles
00932                     $myConfig->setConfigParam( 'blAllowSharedEdit', true );
00933 
00934                     $sShop = oxSession::getVar( "actshop");
00935                     if ( !isset($sShop)) {
00936                         oxSession::setVar( "actshop", $myConfig->getBaseShopId());
00937                     }
00938                     $blIsAuth = true;
00939                 } else {
00940                     // Shopadmin... check if this shop is valid and exists
00941                     $sShopID = $oDb->getOne("select oxid from oxshops where oxid = " . $oDb->quote( $sRights ) );
00942                     if ( isset( $sShopID) && $sShopID) {
00943                         // success, this shop exists
00944 
00945                         oxSession::setVar( "actshop", $sRights);
00946                         oxSession::setVar( "currentadminshop", $sRights);
00947                         oxSession::setVar( "shp", $sRights);
00948 
00949                         // check if this subshop admin is evil.
00950                         if ('chshp' == oxConfig::getParameter( 'fnc' )) {
00951                             // dont allow this call
00952                             $blIsAuth = false;
00953                         } else {
00954                             $blIsAuth = true;
00955 
00956                             $aShopIdVars = array('actshop', 'shp', 'currentadminshop');
00957                             foreach ($aShopIdVars as $sShopIdVar) {
00958                                 if ($sGotShop = oxConfig::getParameter( $sShopIdVar )) {
00959                                     if ($sGotShop != $sRights) {
00960                                         $blIsAuth = false;
00961                                         break;
00962                                     }
00963                                 }
00964                             }
00965                         }
00966                     }
00967                 }
00968                 // marking user as admin
00969                 oxSession::setVar( "blIsAdmin", 1);
00970             }
00971         }
00972         return $blIsAuth;
00973     }
00974 
00984     public function seoIsActive( $blReset = false, $sShopId = null, $iActLang = null )
00985     {
00986         if ( !is_null( $this->_blSeoIsActive ) && !$blReset ) {
00987             return $this->_blSeoIsActive;
00988         }
00989 
00990         $myConfig = $this->getConfig();
00991 
00992         if ( ( $this->_blSeoIsActive = $myConfig->getConfigParam( 'blSeoMode' ) ) === null ) {
00993             $this->_blSeoIsActive = true;
00994 
00995             $aSeoModes  = $myConfig->getconfigParam( 'aSeoModes' );
00996             $sActShopId = $sShopId ? $sShopId : $myConfig->getActiveShop()->getId();
00997             $iActLang   = $iActLang ? $iActLang : (int) oxRegistry::getLang()->getBaseLanguage();
00998 
00999             // checking special config param for active shop and language
01000             if ( is_array( $aSeoModes ) && isset( $aSeoModes[$sActShopId] ) && isset( $aSeoModes[$sActShopId][$iActLang] ) ) {
01001                 $this->_blSeoIsActive = (bool) $aSeoModes[$sActShopId][$iActLang];
01002             }
01003         }
01004 
01005         return $this->_blSeoIsActive;
01006     }
01007 
01015     public function isValidAlpha( $sField )
01016     {
01017         return (boolean) getStr()->preg_match( '/^[a-zA-Z0-9_]*$/', $sField );
01018     }
01019 
01029     protected function _simpleRedirect( $sUrl, $sHeaderCode )
01030     {
01031         $oHeader = oxNew( "oxHeader" );
01032         $oHeader->setHeader( $sHeaderCode );
01033         $oHeader->setHeader( "Location: $sUrl" );
01034         $oHeader->setHeader( "Connection: close" );
01035         $oHeader->sendHeader();
01036     }
01037 
01047     public function redirect( $sUrl, $blAddRedirectParam = true, $iHeaderCode = 302 )
01048     {
01049         //preventing possible cyclic redirection
01050         //#M341 and check only if redirect parameter must be added
01051         if ( $blAddRedirectParam && oxConfig::getParameter( 'redirected' ) ) {
01052             return;
01053         }
01054 
01055         if ( $blAddRedirectParam ) {
01056             $sUrl = $this->_addUrlParameters( $sUrl, array( 'redirected' => 1 ) );
01057         }
01058 
01059         $sUrl = str_ireplace( "&amp;", "&", $sUrl );
01060 
01061         $sHeaderCode = '';
01062         switch ($iHeaderCode) {
01063             case 301:
01064                 $sHeaderCode = "HTTP/1.1 301 Moved Permanently";
01065                 break;
01066             case 302:
01067             default:
01068                 $sHeaderCode = "HTTP/1.1 302 Found";
01069         }
01070 
01071         $this->_simpleRedirect( $sUrl, $sHeaderCode );
01072 
01073         try {//may occur in case db is lost
01074             $this->getSession()->freeze();
01075         } catch( oxException $oEx ) {
01076             $oEx->debugOut();
01077             //do nothing else to make sure the redirect takes place
01078         }
01079 
01080         if ( defined( 'OXID_PHP_UNIT' ) ) {
01081             return;
01082         }
01083 
01084         $this->showMessageAndExit( '' );
01085     }
01086 
01095     public function showMessageAndExit( $sMsg )
01096     {
01097         $this->getSession()->freeze();
01098         $this->commitFileCache();
01099 
01100         if ( defined( 'OXID_PHP_UNIT' ) ) {
01101             return;
01102         }
01103 
01104 
01105         exit( $sMsg );
01106     }
01107 
01115     public function setHeader($sHeader)
01116     {
01117         header($sHeader);
01118     }
01119 
01128     protected function _addUrlParameters( $sUrl, $aParams )
01129     {
01130         $sDelimiter = ( ( getStr()->strpos( $sUrl, '?' ) !== false ) )?'&':'?';
01131         foreach ( $aParams as $sName => $sVal ) {
01132             $sUrl = $sUrl . $sDelimiter . $sName . '=' . $sVal;
01133             $sDelimiter = '&';
01134         }
01135 
01136         return $sUrl;
01137     }
01138 
01150     protected function _fillExplodeArray( $aName, $dVat = null)
01151     {
01152         $myConfig = $this->getConfig();
01153         $oObject = new stdClass();
01154         $aPrice = explode( '!P!', $aName[0]);
01155 
01156         if ( ( $myConfig->getConfigParam( 'bl_perfLoadSelectLists' ) && $myConfig->getConfigParam( 'bl_perfUseSelectlistPrice' ) && isset( $aPrice[0] ) && isset( $aPrice[1] ) ) || $this->isAdmin() ) {
01157 
01158             // yes, price is there
01159             $oObject->price = isset( $aPrice[1] ) ? $aPrice[1] : 0;
01160             $aName[0] = isset( $aPrice[0] ) ? $aPrice[0] : '';
01161 
01162             $iPercPos = getStr()->strpos( $oObject->price, '%' );
01163             if ( $iPercPos !== false ) {
01164                 $oObject->priceUnit = '%';
01165                 $oObject->fprice = $oObject->price;
01166                 $oObject->price  = substr( $oObject->price, 0, $iPercPos );
01167             } else {
01168                 $oCur = $myConfig->getActShopCurrencyObject();
01169                 $oObject->price = str_replace(',', '.', $oObject->price);
01170                 $oObject->fprice = oxRegistry::getLang()->formatCurrency( $oObject->price  * $oCur->rate, $oCur);
01171                 $oObject->priceUnit = 'abs';
01172             }
01173 
01174             // add price info into list
01175             if ( !$this->isAdmin() && $oObject->price != 0 ) {
01176                 $aName[0] .= " ";
01177 
01178                 $dPrice = $this->_preparePrice( $oObject->price, $dVat );
01179 
01180                 if ( $oObject->price > 0 ) {
01181                     $aName[0] .= "+";
01182                 }
01183                 //V FS#2616
01184                 if ( $dVat != null && $oObject->priceUnit == 'abs' ) {
01185                     $oPrice = oxNew('oxPrice');
01186                     $oPrice->setPrice($oObject->price, $dVat);
01187                     $aName[0] .= oxRegistry::getLang()->formatCurrency( $dPrice * $oCur->rate, $oCur);
01188                 } else {
01189                     $aName[0] .= $oObject->fprice;
01190                 }
01191                 if ( $oObject->priceUnit == 'abs' ) {
01192                     $aName[0] .= " ".$oCur->sign;
01193                 }
01194             }
01195         } elseif ( isset( $aPrice[0] ) && isset($aPrice[1] ) ) {
01196             // A. removing unused part of information
01197             $aName[0] = getStr()->preg_replace( "/!P!.*/", "", $aName[0] );
01198         }
01199 
01200         $oObject->name  = $aName[0];
01201         $oObject->value = $aName[1];
01202         return $oObject;
01203     }
01204 
01213     protected function _preparePrice( $dPrice, $dVat )
01214     {
01215         $blCalculationModeNetto = $this->_isPriceViewModeNetto();
01216 
01217         $oCurrency = $this->getConfig()->getActShopCurrencyObject();
01218 
01219         $blEnterNetPrice = $this->getConfig()->getConfigParam('blEnterNetPrice');
01220         if ( $blCalculationModeNetto && !$blEnterNetPrice ) {
01221             $dPrice = round( oxPrice::brutto2Netto( $dPrice, $dVat ), $oCurrency->decimal );
01222         } elseif ( !$blCalculationModeNetto && $blEnterNetPrice ) {
01223             $dPrice = round( oxPrice::netto2Brutto( $dPrice, $dVat ), $oCurrency->decimal );
01224         }
01225 
01226         return $dPrice;
01227     }
01228 
01234     protected function _isPriceViewModeNetto()
01235     {
01236         $blResult = (bool) $this->getConfig()->getConfigParam('blShowNetPrice');
01237         $oUser = $this->_getArticleUser();
01238         if ($oUser) {
01239             $blResult = $oUser->isPriceViewModeNetto();
01240         }
01241 
01242         return $blResult;
01243     }
01244 
01250     protected function _getArticleUser()
01251     {
01252         if ($this->_oUser) {
01253             return $this->_oUser;
01254         }
01255 
01256         return $this->getUser();
01257     }
01258 
01266     public function oxMimeContentType( $sFileName )
01267     {
01268         $sFileName = strtolower( $sFileName );
01269         $iLastDot  = strrpos( $sFileName, '.' );
01270 
01271         if ( $iLastDot !== false ) {
01272             $sType = substr( $sFileName, $iLastDot + 1 );
01273             switch ( $sType ) {
01274                 case 'gif':
01275                     $sType = 'image/gif';
01276                     break;
01277                 case 'jpeg':
01278                 case 'jpg':
01279                     $sType = 'image/jpeg';
01280                     break;
01281                 case 'png':
01282                     $sType = 'image/png';
01283                     break;
01284                 default:
01285                     $sType = false;
01286                     break;
01287             }
01288         }
01289         return $sType;
01290     }
01291 
01300     public function logger( $sText, $blNewline = false )
01301     {   $myConfig = $this->getConfig();
01302 
01303         if ( $myConfig->getConfigParam( 'iDebug' ) == -2) {
01304             if ( gettype( $sText ) != 'string' ) {
01305                 $sText = var_export( $sText, true);
01306             }
01307             $sLogMsg = "----------------------------------------------\n{$sText}".( ( $blNewline ) ?"\n":"" )."\n";
01308             $this->writeToLog( $sLogMsg, "log.txt" );
01309         }
01310 
01311     }
01312 
01320     protected function _stripQuotes($mInput)
01321     {
01322         return is_array($mInput) ? array_map( array( $this, '_stripQuotes' ), $mInput) : stripslashes( $mInput );
01323     }
01324 
01332     public function strRot13( $sStr )
01333     {
01334         $sFrom = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
01335         $sTo   = 'nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM';
01336 
01337         return strtr( $sStr, $sFrom, $sTo );
01338     }
01339 
01349     public function getCacheFilePath( $sCacheName, $blPathOnly = false, $sExtension = 'txt' )
01350     {
01351 
01352             $sVersionPrefix = 'pe';
01353 
01354         $sPath = realpath($this->getConfig()->getConfigParam( 'sCompileDir' ));
01355 
01356         if (!$sPath) {
01357             return false;
01358         }
01359 
01360         return $blPathOnly ? "{$sPath}/" : "{$sPath}/ox{$sVersionPrefix}c_{$sCacheName}." . $sExtension;
01361     }
01362 
01370     public function getLangCache( $sCacheName )
01371     {
01372         $aLangCache = null;
01373         $sFilePath = $this->getCacheFilePath( $sCacheName );
01374         if ( file_exists( $sFilePath ) && is_readable( $sFilePath ) ) {
01375             include $sFilePath;
01376         }
01377         return $aLangCache;
01378     }
01379 
01388     public function setLangCache( $sCacheName, $aLangCache )
01389     {
01390         $sCache = "<?php\n\$aLangCache = ".var_export( $aLangCache, true ).";\n?>";
01391         $blRes = file_put_contents($this->getCacheFilePath($sCacheName), $sCache, LOCK_EX);
01392         return $blRes;
01393     }
01394 
01402     public function checkUrlEndingSlash( $sUrl )
01403     {
01404         if ( !getStr()->preg_match("/\/$/", $sUrl) ) {
01405             $sUrl .= '/';
01406         }
01407 
01408         return $sUrl;
01409     }
01410 
01419     public function writeToLog( $sLogMessage, $sLogFileName )
01420     {
01421         $sLogDist = $this->getConfig()->getLogsDir().$sLogFileName;
01422         $blOk = false;
01423 
01424         if ( ( $oHandle = fopen( $sLogDist, 'a' ) ) !== false ) {
01425             fwrite( $oHandle, $sLogMessage );
01426             $blOk = fclose( $oHandle );
01427         }
01428 
01429         return $blOk;
01430     }
01431 
01439     public function handlePageNotFoundError($sUrl = '')
01440     {
01441         $this->setHeader("HTTP/1.0 404 Not Found");
01442         if ( oxRegistry::getConfig()->isUtf() ) {
01443             $this->setHeader("Content-Type: text/html; charset=UTF-8");
01444         }
01445 
01446         $sReturn = "Page not found.";
01447         try {
01448             $oView = oxNew('oxUBase');
01449             $oView->init();
01450             $oView->render();
01451             $oView->setClassName( 'oxUBase' );
01452             $oView->addTplParam('sUrl', $sUrl);
01453             if ($sRet = oxRegistry::get("oxUtilsView")->getTemplateOutput('message/err_404.tpl', $oView)) {
01454                 $sReturn = $sRet;
01455             }
01456         } catch (Exception $e) {
01457         }
01458         $this->showMessageAndExit( $sReturn );
01459     }
01460 
01468     public function extractDomain( $sHost )
01469     {
01470         $oStr = getStr();
01471         if ( !$oStr->preg_match( '/[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}/', $sHost ) &&
01472              ( $iLastDot = strrpos( $sHost, '.' ) ) !== false ) {
01473             $iLen = $oStr->strlen( $sHost );
01474             if ( ( $iNextDot = strrpos( $sHost, '.', ( $iLen - $iLastDot + 1 ) * - 1 ) ) !== false ) {
01475                 $sHost = trim( $oStr->substr( $sHost, $iNextDot ), '.' );
01476             }
01477         }
01478 
01479         return $sHost;
01480     }
01481 }