<?php
if (!defined('SECRET_KEY')){ header("HTTP/1.0 404 Not Found"); exit; }

###
###  Export Routine
###

class exportRecipe {

	var $_ids;
	var $_recipe;
    var $_eol = "\n";
    var $_tab = "\t";

	function exportRecipe($id){
		global $rSdb;

        $this->_ids 		= array();
		if( $id == 'all' )
		    $this->_ids		= $rSdb->fetchArr("SELECT id FROM {$rSdb->DBrecipes}");
		else
		    $this->_ids		= $rSdb->fetchArr("SELECT id FROM {$rSdb->DBrecipes} WHERE id='".esc_sql((int)$id)."'");
	}

    function export(){
        $xml = $this->recipeXML();
        if( !$xml )
			return false;

		$xml = $this->headerXML() . $xml . $this->footerXML();

		header('Pragma: public');
		header('Expires: 0');
		header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
		header('Content-Type: application/force-download');
		header('Content-Type: text/download');
		header('Content-Type: text/xml');
		header('Content-Disposition: attachment; filename="recipe-export.xml"');
		header('Content-Transfer-Encoding: binary');
		header('Content-Length: ' .(string)(strlen($xml)) );
	    ob_clean();
	    flush();
		print $xml;
    }

    function recipeXML(){
	    $xml = '';
		foreach(  $this->_ids as $id  ){

			if ( !$this->getRecipe($id->id) )
            	return false;

			$xml	.=	$this->recipeStart();
			$xml	.=	$this->head();
            $xml    .=  $this->tags();
            $xml    .=  $this->cats();
			$xml	.=	$this->ingredients();
			$xml	.=	$this->directions();
			$xml	.=	$this->notes();
			$xml	.=	$this->urls();
			$xml	.=	$this->recipeEnd();

        }
        return $xml;
	}

    function ingredients(){
		$arrI 		= explode('$%&', $this->_recipe->ingredients);
		$xml		= $this->ingredientsStart();
		foreach(  $arrI as $ing  ){

			$arrItem = explode('$$$', $ing);
			$xml	.= $this->ingredient($arrItem);

        }
		$xml		.=	$this->ingredientsEnd();
        return $xml;
	}


	function urls(){
		$arrD 		= explode('$%&', $this->_recipe->urls);
		$xml		= $this->urlsStart();

		foreach(  $arrD as $step  )
			$xml	.= $this->_tab.$this->_tab.'<ref>'.$step.'</ref>'.$this->_eol;

		$xml		.=	$this->urlsEnd();
        return $xml;
	}

    function urlsStart(){
        return  $this->_tab.'<urls>'.$this->_eol;
	}

    function urlsEnd(){
        return  $this->_tab.'</urls>'.$this->_eol;
	}

	function directions(){
		$arrD 		= explode('$%&', $this->_recipe->steps);
		$xml		= $this->directionsStart();

		foreach(  $arrD as $step  )
			$xml	.= $this->_tab.$this->_tab.'<step>'.htmlspecialchars($step).'</step>'.$this->_eol;

		$xml		.=	$this->directionsEnd();
        return $xml;
	}

	function notes(){
		$arrD 		= explode('$%&', $this->_recipe->notes);
		$xml		= $this->notesStart();

		foreach(  $arrD as $step  )
			$xml	.= $this->_tab.$this->_tab.'<note>'.htmlspecialchars($step).'</note>'.$this->_eol;

		$xml		.=	$this->notesEnd();
        return $xml;
	}

    function directionsStart(){
        return  $this->_tab.'<directions>'.$this->_eol;
	}

    function directionsEnd(){
        return  $this->_tab.'</directions>'.$this->_eol;
	}

    function notesStart(){
        return  $this->_tab.'<notes>'.$this->_eol;
	}

    function notesEnd(){
        return  $this->_tab.'</notes>'.$this->_eol;
	}

    function ingredient($i){
        return  $this->_tab.$this->_tab.'<item>'.$this->_eol.
        		$this->_tab.$this->_tab.$this->_tab.'<amount><quantity>'.$i[0].'</quantity>'.'<unit>'.$i[1].'</unit></amount>'.$this->_eol.
        		$this->_tab.$this->_tab.$this->_tab.'<product>'.$i[2].'</product>'.$this->_eol.
                $this->_tab.$this->_tab.$this->_tab.'<info>'.$i[3].'</info>'.$this->_eol.
        		$this->_tab.$this->_tab.'</item>'.$this->_eol;
	}

    function ingredientsStart(){
        return  $this->_tab.'<ingredients>'.$this->_eol;
	}

    function ingredientsEnd(){
        return  $this->_tab.'</ingredients>'.$this->_eol;
	}

    function tags(){
        return  $this->_tab.'<tags>'.$this->_recipe->tags.'</tags>'.$this->_eol;
	}

    function cats(){
        $cats	= str_replace('$%&',',',$this->_recipe->options);
        return  $this->_tab.'<cats>'.$cats.'</cats>'.$this->_eol;
	}

    function head(){
    	$yield	= explode('$$$',$this->_recipe->yield);
    	$time	= explode('$$$',$this->_recipe->cookingtime);
    	return	$this->_tab.'<head>'.$this->_eol.
        		$this->_tab.$this->_tab.'<title>'.$this->_recipe->name.'</title>'.$this->_eol.
        		$this->_tab.$this->_tab.'<description>'.htmlspecialchars($this->_recipe->description).'</description>'.$this->_eol.
        		$this->_tab.$this->_tab.'<yield><amount>'.$yield[0].'</amount><unit>'.$yield[1].'</unit><kcal>'.$yield[2].'</kcal></yield>'.$this->_eol.
        		$this->_tab.$this->_tab.'<time><active>'.$time[0].'</active><passive>'.$time[1].'</passive><overall>'.$time[2].'</overall></time>'.$this->_eol.
        		$this->_tab.$this->_tab.'<level>'.$this->_recipe->level.'</level>'.$this->_eol.
                $this->_tab.'</head>'.$this->_eol;
	}

    function recipeStart(){
    	return	$this->_tab.'<recipe>'.$this->_eol;
	}

    function recipeEnd(){
    	return	$this->_tab.'</recipe>'.$this->_eol;
	}

    function getRecipe($id){
		global $rSdb;
	    $this->_recipe = $rSdb->fetchArr("SELECT * FROM {$rSdb->DBrecipes} WHERE id='".esc_sql((int)$id)."'");

		if ( count($this->_recipe)==0 )
        	return false;

        $this->_recipe = $this->_recipe[0];
		return true;
	 }

    function headerXML(){
		return 	'<?xml version="1.0" encoding="UTF-8"?'.'>'.$this->_eol.
				'<recipeShelfml>'.$this->_eol;
    }

    function footerXML(){
		return '</recipeShelfml>';
    }
}






###
###  Import Routine
###

class importRecipe {

	var $_recipes;
	var $_recipeID;

	function importRecipe(){
        if ($_FILES) {
            foreach ($_FILES as $f) {
                $xmlstring = join( "", file( $f['tmp_name'] ) );
                $this->_recipes = $this->xml2array($xmlstring);
            }
        }
	}


    function importXML(){
    	foreach( $this->_recipes[recipeShelfml] as $r ){
			if( ! $this->insertXML($r) )
	            return false;
		}
	    return $this->_recipeID;
    }

    function importCookML(){
    	foreach( $this->_recipes[cookml] as $r ){
			if( ! $this->insertXML($r) )
	            return false;
		}
	    return $this->_recipeID;
    }


    function insertXML( $r ){
		global $rSdb;

		$y = $c = $o = $u = $s = $n = $i = '';
        $time	= gmdate('Y-m-d H:i:s', current_time('timestamp'));

		if( is_array($r[head][yield]) )
			$y = implode('$$$',$r[head][yield]);
			
		if( is_array($r[head][time]) )
			$c = implode('$$$',$r[head][time]);
			
		if( $r[cats] <> '' )
			$o = str_replace(',','$%&',$r[cats]);

		if( is_array($r[urls]) )
			$u = implode('$%&',$r[urls]);


		if( is_array( $r[directions][step] ) ){
			foreach( $r[directions][step] as $step )
				$s	.= htmlspecialchars_decode($step).'$%&';
		    $s = substr($s,0, strlen($s)-3);
		}
		else
			$s = $r[directions][step];

		if( is_array( $r[notes][note] ) ){
			foreach( $r[notes][note] as $note )
				$n	.= htmlspecialchars_decode($note).'$%&';
		    $n = substr($n,0, strlen($n)-3);
		}
		else
			$n = $r[notes][note];


   		if( is_array($r[ingredients]) ){

			if( is_array( $r[ingredients][item][amount] ) )
				$allIng = $r[ingredients];
   			else
				$allIng = $r[ingredients][item];

			foreach( $allIng as $item ){
				$i	.= $item[amount][quantity].'$$$'.$item[amount][unit].'$$$'.$item[product].'$$$'.$item[info].'$%&';
		    }
		    $i		 = substr($i,0, strlen($i)-3);
		}
		
        return $this->writeSQL($time,$r[head][title],
								htmlspecialchars_decode($r[head][description]),
								$r[tags],
								htmlspecialchars_decode($s),
								htmlspecialchars_decode($n),
								$i,$y,$c,$r[head][level],$o,$u);
	}


    function insertCookML( $r ){
		global $rSdb;
        return false;
	}

	function writeSQL($t,$ti,$d,$ta,$s,$n,$i,$y,$c,$l,$o,$u) {
	    global $rSdb;
	    $sql 	=  "INSERT INTO {$rSdb->DBrecipes} (  date_added, ".
											" name, ".
											" description, ".
											" tags, ".
											" tips, ".
											" steps, ".
											" notes, ".
											" ingredients, ".
											" yield, ".
											" cookingtime, ".
											" level, ".
											" servewith, ".
											" rating, ".
											" options, ".
											" cooked, ".
											" urls) ".
											" VALUES ( ".
											"'".addslashes($t)."', ".
											"'".addslashes($ti)."', ".
											"'".addslashes($d)."', ".
											"'".addslashes($ta)."', ".
											"'', ".
											"'".addslashes($s)."', ".
											"'".addslashes($n)."', ".
											"'".addslashes($i)."', ".
											"'".addslashes($y)."', ".
											"'".addslashes($c)."', ".
											"'".addslashes($l)."', ".
											"'', ".
											"'5', ".
											"'".addslashes($o)."', ".
											"'', ".
											"'".addslashes($u)."');";

	    $r 		= $rSdb->fetch( $sql );

		if( $r ){
	        $this->_recipeID = $rSdb->fetchRow("SELECT LAST_INSERT_ID() AS number FROM {$rSdb->DBrecipes};");
	        $this->_recipeID = ($this->_recipeID->number=='')?'1':$this->_recipeID->number;
        	return true;
		}else
        	return false;
	}


	function xml2array($s) {
	    if ( $Atmp1=explode('>',$s,2) )
	        $this->xml2array_sub($A,$Atmp1[1]);
	    return $A;
	}

    function xml2array_sub(&$A,$s) {
	    global $error_msg;

	    for ($c=0; ereg('<([^<>/ ]*)( [^<>]*)?/>(.*)',$s,$Atmp1) or ereg('<([^<>/ ]*)( [^<>]*)?>(.*)',$s,$Atmp1) and $Atmp2=explode('</'.$Atmp1[1].'>',$Atmp1[3],2); ++$c) {
	        $E		= array();
	        $tag	= $Atmp1[1];

		    if ($Atmp1[2]) {
	            $Atmp3	= explode(' ',substr($Atmp1[2],1));
	            foreach ($Atmp3 as $d) {
		            $Atmp4	   		= explode('=',$d,2);
		            $Atmp4[1]		= ereg_replace('^"(.*)"$','\1',$Atmp4[1]);
	    	        $E[$Atmp4[0]]	= $Atmp4[1];
	        	}
	    	}

	        if ($Atmp2) {
	            if (!$this->xml2array_sub($E,$Atmp2[0])) {
	                $E	= $Atmp2[0];
	            }
	            $s		= $Atmp2[1];
	            $Atmp2	= false;
	        }
	        else {
	            $s	= $Atmp1[3];
	        }

	        if ($A[$tag]) {
	            if (!is_array($A[$tag]) or !$A[$tag][0]) {
	                $Atag		= $A[$tag];
	                unset($A[$tag]);
	                $A[$tag][]	= $Atag;
	            }

	            if ($E) {
	            $A[$tag][]	= $E;
	            }
	        }
	        else {
	            if ($E) {
	                $A[$tag]	= $E;
	                if ($tag=='$ErrorMsg') $error_msg=$E;
	            }
	        }
	    }
	    return $c;
     }
}

?>