<?php
function get_rec_info($fields, $vals) {
	$res="";
	for ($i=0; $i<count($fields); $i++) 
		$res.=($res ? ", " : "").$fields[$i]."=".shorter(str_replace("\n", "", stripcslashes($vals[$fields[$i]])), 50);
	return $res;
}
Class Import {
	var $res;
	var $error_list;
	var $fields;
	var $log;

	function Import($filename="", $delimiter=";") {
		$this->error_list=array(
			-1	=> "File not found",
		);

		$this->res=array(
			"filename"	=> $filename,
			"delimiter"	=> $delimiter,
			"error_code"	=> -1,
			"size"		=> 1000,
		);

		$this->log="";

		$fields=array();
		if ($this->res["filename"]) $this->get_fields();
	}

	function add_log($text="") {
		$this->log.="- $text\n";
	}

	function get_fields() {
		if (is_file($this->res["filename"])) {
			$this->res["size"]=filesize($this->res["filename"]);
			$this->res["error_code"]=0;
			$this->res["f"]=fopen($this->res["filename"], "r");
			$this->fields=fgetcsv($this->res["f"], $this->res["size"], $this->res["delimiter"]);
		} else $this->res["error_code"]=-1;
	}

	function get_rec() {
		$res=array();
		if (!$this->res["error_code"]) {
			if ($data=fgetcsv($this->res["f"], $this->res["size"], $this->res["delimiter"])) {
				for ($i=0; $i<count($this->fields); $i++) {
					if ($this->fields[$i]=="code2") $res[$this->fields[$i]]=check_code2($data[$i]);
					elseif ($this->fields[$i]=="description") $res[$this->fields[$i]]=check_string($data[$i]);
					else $res[$this->fields[$i]]=check_string($data[$i], 1);
				}
			} else $res="";
		}
		return $res;
	}

	function to_table($table="", $id="") {
		global $db, $info;
		$fields=implode(", ", $db->get_fields($table));
		$count=0;
		$count_ok=0;
		while ($r=$this->get_rec()) {
			$count++;
			$try=1;
			if (!isset($r[$id]) or !$r[$id]) {
				$try=0;
				$this->add_log("Запись #$count не импортирована: не указано значение $id");
			} elseif ($id and is_val($table, "where $id='".$r[$id]."'")) {
				$try=0;
				$this->add_log("Запись #$count уже существует: ".get_rec_info($this->fields, $r));
			}
			if ($try) {
				$r["c_id"]=($r["c_id"] ? $r["c_id"] : $info["category_id"]);
				$sql=get_sql_insert($table, $fields, $r);
				if ($db->execute($sql)) {
					$sql="update $table set code2='".$r["code2"]."' where code2='".$r["code"]."'";
					$db->execute($sql);
					$count_ok++;
				} else $this->add_log("Ошибка при добавлении записи #$count : ".get_rec_info($this->fields, $r));
			}
		}		
		$this->add_log("Импортировано записей: $count_ok из $count.");
	}
}
?>