<?php

/**
 * 
 * Copyright (C) Die Randgruppe GmbH
 * 
 * http://www.randshop.com
 * http://www.dierandgruppe.com
 * 
 * Unter der Lizenz von Die Randgruppe GmbH:
 * http://www.randshop.com/Lizenz
 *  
 * $Author$
 * $Date$
 * $Revision$
 * 
 */

//	// SourceArray
//	$SourceArray[1] = "index.php";
//	$SourceArray[2] = "themes/kategorie/index.php";
//	$SourceArray[3] = "themes/kategorie/detail.php";
//	$SourceArray[4] = "themes/wunschzettel/index.php";
//	$SourceArray[5] = "themes/kategorie/aktion.php";
//	$SourceArray[6] = "themes/kategorie/hersteller.php";
//	$SourceArray[7] = "themes/bestellen/index.php?formaction=s2";
//	$SourceArray[8] = "themes/bestellen/index.php?formaction=s0";
//	$SourceArray[9] = "themes/user/index.php?action=grunddaten";
//	$SourceArray[10] = "themes/suche/index.php";
//	
//	// Formaction
//	if ($_POST["formaction"]) { $FormAction = $_POST["formaction"]; };
//	if ($_GET["formaction"]) { $FormAction = $_GET["formaction"]; };
//
//	// Source
//	if ($_POST["source"]) { $_SESSION["source"] = (int)$_POST["source"]; };
//	if ($_GET["source"]) { $_SESSION["source"] = (int)$_GET["source"]; };
//	$Source = $_SESSION["source"];
//	
//	if (!$Source) {
//		$Source = 1;
//	}
//	
//	//Versandartanzeige
//	if ($_POST["anzeigeversandart"]) { $_SESSION["anzeigeversandart"] = $_POST["anzeigeversandart"]; };
// if ($_GET["anzeigeversandart"]) { $_SESSION["anzeigeversandart"] = $_GET["anzeigeversandart"]; };
// $anzeigeversandart = $_SESSION["anzeigeversandart"];
//	
// 	// ArtikelID
//	if ($_POST["artikelid"]) { $_SESSION["artikelid"] = (int)$_POST["artikelid"]; };
//	if ($_GET["artikelid"]) { $_SESSION["artikelid"] = (int)$_GET["artikelid"]; };
//	if ($_POST["artid"]) { $_SESSION["artikelid"] = (int)$_POST["artid"]; };
//	if ($_GET["artid"]) { $_SESSION["artikelid"] = (int)$_GET["artid"]; };
//	$ArtikelID = $_SESSION["artikelid"];
//
//	// KategorieID
//	if ($_POST["kategorieid"]) { 
//		if($_POST["kategorieid"] == $_SESSION["kategorieid"]){
//			$_SESSION["close_kategorie"] = true;
//		}else{
//			$_SESSION["close_kategorie"] = false;
//		}
//		$_SESSION["kategorieid"] = (int)$_POST["kategorieid"]; 
//	};
//
//    if ($_GET["kategorieid"]) { 
//		$CheckCloseKategorie = CheckCloseKategorie($_GET["kategorieid"]);
//		if((($_GET["kategorieid"] == $_SESSION["kategorieid"]) && !$_SESSION["close_kategorie"]) || $CheckCloseKategorie){
//			$_SESSION["close_kategorie"] = $_GET["kategorieid"];
//		}else{
//			$_SESSION["close_kategorie"] = false;
//		}
//		$_SESSION["kategorieid"] = (int)$_GET["kategorieid"]; 
//	};
//	
//	if ($_POST["katid"]) { $_SESSION["kategorieid"] = (int)$_POST["katid"]; };
//	if ($_GET["katid"]) { $_SESSION["kategorieid"] = (int)$_GET["katid"]; };
//	$KategorieID = $_SESSION["kategorieid"];
//	
//	// Einstellungen fuer die Uebersicht
//	if ($_POST["dataoffset"] != "") { $_SESSION["dataoffset"] = (int)$_POST["dataoffset"]; };
//	if ($_GET["dataoffset"] != "") { $_SESSION["dataoffset"] = (int)$_GET["dataoffset"]; };
//	if ($_POST["datacount"]) { $_SESSION["datacount"] = (int)$_POST["datacount"]; };
//	if ($_GET["datacount"]) { $_SESSION["datacount"] = (int)$_GET["datacount"]; };
//	if ($_POST["sortfield"]) { $_SESSION["sortfield"] = $_POST["sortfield"]; };
//	if ($_GET["sortfield"]) { $_SESSION["sortfield"] = $_GET["sortfield"]; };
//	if ($_POST["sortorder"]) { $_SESSION["sortorder"] = strtolower($_POST["sortorder"])=='asc' ? 'ASC': 'DESC'; };
//	if ($_GET["sortorder"]) { $_SESSION["sortorder"] = strtolower($_GET["sortorder"])=='asc' ? 'ASC': 'DESC'; };
//
//	//x==0 ? y : z wenn X ==0, dann y, sonst z
//	
//	// Uebersichteinstellungen zuruecksetzen
//	if ($_GET["kategorieid"] || $_GET["aktionsid"] || $_GET["sessionReset"]) {
//		$_SESSION["dataoffset"] = "";
//		$_SESSION["datacount"] = "";
//		$_SESSION["sortfield"] = "";
//		$_SESSION["sortorder"] = "";
//		$_SESSION["artikelid"] = "";
//	}
//
//    // Uebersichteinstellungen zuruecksetzen
//    if ($_GET["sessionReset"]) {
//        $ArtikelID = "";
//    }
//	
//	$DataOffset = $_SESSION["dataoffset"];
//	$DataCount = $_SESSION["datacount"];
//	$SortField = $_SESSION["sortfield"];
//	$SortOrder = $_SESSION["sortorder"];
	
function AddURLParameter($URL, $Parameter, $Value) {
	
	if (strpos($URL, '?') === false) {
		$URL .= '?' . $Parameter . '=' . $Value;
	} else {
        $URL .= '&' . $Parameter . '=' . $Value;
	}
	
	return $URL;
	
}


    /*
     * http://us2.php.net/manual/en/function.substr.php
     * erez at meezoog dot com
     * 07-Jul-2009 04:59
     */

    /**
    * word-sensitive substring function with html tags awareness
    * @param text The text to cut
    * @param len The maximum length of the cut string
    * @returns string
    **/
    function mb_substrws( $text, $len=180 ) {
    
        if( (mb_strlen($text) > $len) ) {
    
            @$whitespaceposition = mb_strpos($text," ",$len)-1;
    
            if( $whitespaceposition > 0 ) {
                $chars = count_chars(mb_substr($text, 0, ($whitespaceposition+1)), 1);
                if ($chars[ord('<')] > $chars[ord('>')])
                    $whitespaceposition = mb_strpos($text,">",$whitespaceposition)-1;
                $text = mb_substr($text, 0, ($whitespaceposition+1));
            }
    
            // close unclosed html tags
            if( preg_match_all("|<([a-zA-Z]+)|",$text,$aBuffer) ) {
    
                if( !empty($aBuffer[1]) ) {
    
                    preg_match_all("|</([a-zA-Z]+)>|",$text,$aBuffer2);
    
                    if( count($aBuffer[1]) != count($aBuffer2[1]) ) {
    
                        foreach( $aBuffer[1] as $index => $tag ) {
    
                            if( (empty($aBuffer2[1][$index]) || $aBuffer2[1][$index] != $tag) && (strtolower($tag) != 'br'))
                                $text .= '</'.$tag.'>';
                        }
                    }
                }
            }
        }
        return $text;
    }
	
	
function GetTemplateDetail($TemplateID = "") {
	$SQLString = "SELECT ";
	$SQLString .= TABLE_TEMPLATES . ".id, ";
	$SQLString .= TABLE_TEMPLATES . ".name, ";
	$SQLString .= TABLE_TEMPLATES . ".design, ";
	$SQLString .= TABLE_TEMPLATES . ".beschreibung, ";
	$SQLString .= TABLE_TEMPLATES . ".aktiv ";
	$SQLString .= "FROM " . TABLE_TEMPLATES . " ";
	if($TemplateID) {
		$SQLString .= "WHERE  " . TABLE_TEMPLATES . ".id = '" . $TemplateID . "'";
	} else {
		$SQLString .= "WHERE  " . TABLE_TEMPLATES . ".aktiv = '1'";
	}
	 
	
	$SQLQuery = errorlogged_mysql_query($SQLString);
	$rowTemp = mysql_fetch_object($SQLQuery);

	return $rowTemp;
}

function unlink_wc($dir, $pattern){
   
   if ($dh = opendir($dir)) { 
       
			 $files = array();
			 
       //List and put into an array all files
       while (false !== ($file = readdir($dh))){
           if ($file != "." && $file != "..") {
               $files[] = $file;
           }
       }
       closedir($dh);
       
       
       //Split file name and extenssion
       if(strpos($pattern,".")) {
           $baseexp=substr($pattern,0,strpos($pattern,"."));
           $typeexp=substr($pattern,strpos($pattern,".")+1,strlen($pattern));
       }else{ 
           $baseexp=$pattern;
           $typeexp="";
       } 
       
       //Escape all regexp Characters 
       $baseexp=preg_quote($baseexp); 
       $typeexp=preg_quote($typeexp); 
       
       // Allow ? and *
       $baseexp=str_replace(array("\*","\?"), array(".*","."), $baseexp);
       $typeexp=str_replace(array("\*","\?"), array(".*","."), $typeexp);
       
       //Search for pattern match
       $i=0;
       foreach($files as $file) {
           $filename=basename($file);
           if(strpos($filename,".")) {
               $base=substr($filename,0,strpos($filename,"."));
               $type=substr($filename,strpos($filename,".")+1,strlen($filename));
           }else{
               $base=$filename;
               $type="";
           }
       
           if(preg_match("/^".$baseexp."$/i",$base) && preg_match("/^".$typeexp."$/i",$type))  {
               $matches[$i]=$file;
               $i++;
           }
       }
       
       if ($matches) {
	       while(list($idx,$val) = each($matches)){
	           if (substr($dir,-1) == "/"){
	               unlink($dir.$val);
	           }else{
	               unlink($dir."/".$val);
	           }
	       }
		}
       
   }
}

function InsertLineBreaks($Text, $CharacterCount, $LineBreakString) {

	$ResultText = "";
	$TextPosition = 0;
	$PartString = substr($Text, $TextPosition, $CharacterCount);
		
	while ($PartString) {
		
		if (strlen($PartString) == $CharacterCount) {
			
			$Counter = $CharacterCount;
		
			while (($Counter > 0)) {
				
				if (substr($PartString, $Counter - 1, 1) == " ") {
				
					$ResultText .= substr($PartString, 0, $Counter - 1) . $LineBreakString;
					$LineBreakFound = true;
					$TextPosition = $TextPosition + $Counter;
					$Counter = 0;
					
				}
	
				$Counter--;
				
			}
			
		}
		
		if ((!$LineBreakFound) && (strlen($PartString) == $CharacterCount)) {
			
			$ResultText .= substr($PartString, 0, $CharacterCount) . $LineBreakString;
			$TextPosition = $TextPosition + $CharacterCount;
			
		}

		if (strlen($PartString) < $CharacterCount) {
			
			$ResultText .= substr($PartString, 0, strlen($PartString));
			$LineBreakFound = true;
			$TextPosition = $TextPosition + $Counter;
			
			$PartString = false;
		
		} else {

			$PartString = substr($Text, $TextPosition, $CharacterCount);
			
		}
			
		$LineBreakFound = false;
	

		$ExitCounter++;
		
	}	
	
	return $ResultText;
	
}


function GetIclearArtikelName($ArtikelName) {

	$ArtikelName = str_replace("'", "_", $ArtikelName);
	$ArtikelName = str_replace("\"", "_", $ArtikelName);
	$ArtikelName = str_replace("&", "_", $ArtikelName);
	$ArtikelName = str_replace("#", "_", $ArtikelName);
	$ArtikelName = str_replace("%", "_", $ArtikelName);
	$ArtikelName = str_replace("\\", "_", $ArtikelName);
	
	return $ArtikelName;
	
	
}

function GetSumPrice($VersandMethode, $warenkorb, $artikel, $versand, $sessionId) {
	
	// die einzelnen Artikel aus dem Warenkorb abfragen 
	$SQLString = "SELECT * FROM " . $warenkorb . " where session = '" . $sessionId . "'";
	$WarenkorbQuerry = errorlogged_mysql_query($SQLString);

	while($WarenkorbDataRow = mysql_fetch_object($WarenkorbQuerry)) {

		$SQLString = "SELECT * FROM " . $artikel . " where id = " . $WarenkorbDataRow->artikel_id . "";
		$ArtikelData = mysql_fetch_object(errorlogged_mysql_query($SQLString));
		
		$SumPrice += ($WarenkorbDataRow->menge * $ArtikelData->preis);

	}

	// die Versandmethode abfragen udbn �berpr�fen, ob es mit aufgeschalgen werden muss
	$SQLString = "SELECT * FROM " . $versand . " where id = '" . $VersandMethode . "'";
	$VersandData = mysql_fetch_object(errorlogged_mysql_query($SQLString));

	if($SumPrice < $VersandData->frei) {
		$SumPrice = $SumPrice + $VersandData->preis;
	} else {
		$SumPrice = $SumPrice;
	}
	
	return $SumPrice;
	
}

// Email ueberpruefung
function is_mail($email) {
	$pattern='/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@([a-z0-9-]+\.)+([a-z]{2}|com|org|net|edu|gov|mil|biz|info|mobi|name|aero|asia|jobs|museum)$/i';
	if(!preg_match($pattern,$email)) {
		return false;
	} else {
		return true;
	}
}

function word_substr($content, $zeichen, $kolanz=3, $punkte=3) {
	if(strlen($content) < $zeichen+$kolanz)
	return $content;
	$wort = explode(" ",$content);
	$newstr = "";
	$i = 0;
	while(strlen($newstr)<=$zeichen &&
	strlen($newstr.$wort[$i])<=($zeichen+$kolanz)) 
	{
		$newstr .= $wort[$i]." ";
		$i++;
	}
	$newstr .= str_repeat(".",$punkte);
	return $newstr;
} 



// ************************************************************************ //
//							Systemanforderungen								//
// ************************************************************************ //

// Check der PHP Version
function check_version($currentversion, $requiredversion)
{
    list($majorC, $minorC, $editC) = preg_split('/[.-]/', $currentversion);
    list($majorR, $minorR, $editR) = preg_split('/[.-]/', $requiredversion);

    if ($majorC > $majorR) return true;
    if ($majorC < $majorR) return false;
    // same major - check ninor
    if ($minorC > $minorR) return true;
    if ($minorC < $minorR) return false;
    // and same minor
    if ($editC  >= $editR)  return true;
    return false;
}


//Check von Mod_rewrite
function check_mod_rewrite() {
	
	if((bool)function_exists('apache_get_modules')) {
		$ApacheModulArray = apache_get_modules();
		$key = array_search('mod_rewrite', $ApacheModulArray);
		if((bool)$key) {
			$Ergebnis = "true_mod";
			return $Ergebnis;
		} else {
			$Ergebnis = "not_mod";
			return $Ergebnis;
		}
	} else {
		$Ergebnis = "not_module";
		return $Ergebnis;
	}
}






