<?php
	/**************************************************************************\
	* Simple Groupware 0.700                                                   *
	* http://www.simple-groupware.de                                           *
	* Copyright (C) 2002-2011 by Thomas Bley                                   *
	* ------------------------------------------------------------------------ *
	*  This program is free software; you can redistribute it and/or           *
	*  modify it under the terms of the GNU General Public License Version 2   *
	*  as published by the Free Software Foundation; only version 2            *
	*  of the License, no later version.                                       *
	*                                                                          *
	*  This program is distributed in the hope that it will be useful,         *
	*  but WITHOUT ANY WARRANTY; without even the implied warranty of          *
	*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the            *
	*  GNU General Public License for more details.                            *
	*                                                                          *
	*  You should have received a copy of the GNU General Public License       *
	*  Version 2 along with this program; if not, write to the Free Software   *
	*  Foundation, Inc., 59 Temple Place - Suite 330, Boston,                  *
	*  MA  02111-1307, USA.                                                    *
	\**************************************************************************/

class import {

private static function _url() {
  return "http".(sys_https()?"s":"")."://".$_SERVER["HTTP_HOST"].dirname($_SERVER["SCRIPT_NAME"])."/";
}

static function sss_editor($t) {
  $data = self::_build_data($t,true);
  $output = "
	sgs_folder = \"".self::_sss_quote($t["folder"])."\";
	sgs_view = '".$t["view"]."';
	cols = ".count($data).";
	rows = 20;
	dbCells = [
  ";
  if (count($data)>0) {
	$row = -1;
	$col = 0;
    foreach ($data as $field) {
	  $output .= "[".$col.",".$row.",\"".trim(self::_sss_quote($field[1]))."\",\"white-space:nowrap;\",\"".trim(self::_sss_quote($field[0]))."\"], // ".chr($row+65).($col+1)."\n";
	  $output .= "[".$col.",".($row+1).",\"".trim(self::_sss_quote($field[2]))."\",\"\",\"\"],\n";
	  $col++;
    }
    $output .= "\n";
  }
  $output .= "];";
  echo self::_sss_editor($output);
}

private static function _build_data($t) {
  $data = array();
  foreach ($t["fields"] as $akey=>$value) {
	if (isset($value["HIDDENIN"][$t["view"]]) or isset($value["HIDDENIN"]["all"])) continue;
	$data[$akey] = array($value["NAME"],$value["DISPLAYNAME"],$value["SIMPLE_DEFAULT"]);
  }
  return $data;
}

private static function _sss_editor($output) {
  $output = '  
	<html>
	<head>
	  <base href="'.self::_url().'ext/lib/simple_spreadsheet/"/>
	  <title>Simple Spreadsheet {t}Import{/t}</title>
	  <link media="all" href="styles.css" rel="stylesheet" type="text/css" />
      <script src="translations/{t}en{/t}.js" type="text/javascript"></script>
	  <script src="spreadsheet.js" type="text/javascript"></script>
	  <script src="json.js" type="text/javascript"></script>
	  <script>
		function _sgsError(result) {
		  var str = "";
		  for (key in result) {
			for (var i2=0; i2<result[key].length; i2++) {
			  str += result[key][i2][0] + ": " + result[key][i2][1] + "\n";
			}
		  }
		  return str;
		}
		function save() {
		  var datas = [];
		  var errors = [];
		  for (var i=0; i<sys.cells.length; i++) {
			if (sys.cells[i]) {
			  var data = {};
			  var id = -1;
			  data.folder = sgs_folder;
			  for (var i2=0; i2<sys.cells[-1].length; i2++) {
				var key = "";
				if (sys.cells[-1] && sys.cells[-1][i2]) {
				  if (sys.cells[-1][i2][2]) key = sys.cells[-1][i2][2]; else key = sys.cells[-1][i2][0];
				}
				if (key) {
				  data[key] = showCell(i,i2).replace(/\\\n/g,"\n");
				  // if (key=="id" && data[key]) id = data[key];
				}
			  }
			  var result = ajax_sync("asset_validate", [sgs_folder, sgs_view, data, id]);
			  if (JSON.stringify(result)!="[]") {
				errors.push("{t}Error{/t}: {t}line{/t} " + (i+1) + "\n\n" + _sgsError(result));
			  } else {
				datas.push(data);
		  } } }
		  if (errors.length>0) {
			alert("{t}validation failed{/t}:\n\n"+errors.join("\n\n"));
			return;
		  }
		  errors = [];
		  for (var i=0; i<datas.length; i++) {
			var result = ajax_sync("asset_insert", [sgs_folder, sgs_view, datas[i]]);
			if (typeof(result)!="number" && typeof(result)!="string") {
			  errors.push("{t}Error{/t}: {t}line{/t} " + (i+1) + "\n\n" + _sgsError(result));
			}
		  }
		  if (errors.length>0) alert(errors.join("\n\n")); else document.location="../../../index.php";
		}
	  </script>
	</head>
	<body>
	  <div id="data" class="data"></div>
	  <div id="source" align="center">
	  <script>
		document.write(trans("Simple Spreadsheet code / CSV data / Tab separated values (copy/paste from Excel):"));
	  </script>
	  <br><textarea id="code" wrap="off">'.modify::htmlquote($output).'</textarea><br>
	  <script>
		var out = \'<table class="default_table" style="width:50%;">\';
		out += \'<tr><td colspan="3"><input type="button" value="\'+trans("Load")+\'" onclick="load(getObj(\\\'code\\\').value);" style="width:100%;"></td></tr>\';
		out += \'<tr><td>&nbsp;</td></tr>\';
		out += \'<tr><td>\'+trans("Url:")+\'</td>\';
		out += \'<td style="width:100%;"><input type="Text" id="code_url" value="" style="width:100%;"></td>\';
		out += \'<td><input type="button" value="\'+trans("Load")+\'" onclick="loadSheetFromUrl(getObj(\\\'code_url\\\').value);"></td>\';
		out += \'</tr></table>\';
		document.write(out);
		var init_data=getObj("code").value;
		load(init_data);
	  </script>
	</div>
	</body>
	</html>  
  ';
  if (DEBUG) $output = sys_remove_trans($output);
  echo $output;
}

private static function _sss_quote($str) {
  return str_replace(array("\"","\r\n","\n"),array("\"\""," "," "),$str);
}

public static function syncml_add_update($module,$username,$lastsync) {
  $tfolder = $GLOBALS["t"]["folder"];
  $table_source = "fnbl_simple_".$module."_imp";
  $table_dest = "simple_".$module;

  $count_insert = 0;
  $count_update = 0;
  $rows = db_select($table_source,"*",array("userid=@username@","lastmodified > @lastmodified@"),"","",array("username"=>$username,"lastmodified"=>$lastsync));
  if (is_array($rows) and count($rows)>0) {
	foreach ($rows as $row) {
	  if ($row["status"]=="D") { // delete
		import::syncml_deleteitem($row["syncid"]);
		continue;
	  }
	  unset($row["userid"]);
	  unset($row["status"]);
	  if ($table_dest=="simple_contacts" and empty($row["contactid"])) continue;
	  if ($table_dest=="simple_tasks") {
	    if (empty($row["begin"]) and empty($row["ending"])) continue;
		if (empty($row["begin"])) $row["begin"] = $row["ending"];
	  }
	  $exists = db_select_value($table_dest,"id","syncid=@id@",array("id"=>$row["syncid"]));
	  if (!empty($exists)) $id = $exists; else $id = 0;
	  if ($id!=0) { // update
		$row["history"] = sprintf("{t}Item edited (%s) by %s at %s{/t} (sync)\n","@fields@",$_SESSION["username"],sys_date("{t}m/d/y g:i:s a{/t}"));
	    $cdata = "";
		$data = $row;
		$cfields = array();
		$data_old = db_select_first($table_dest,"*","id=@id@","",array("id"=>$id));
		if (is_array($data_old) and !empty($data_old["id"])) {
	      if ($row["lastmodified"]==$data_old["lastmodified"]) continue;
		  foreach ($data as $key=>$val) {
			if (isset($data_old[$key]) and $key!="history") {
			  if ($data_old[$key]!=$val) {
			    if (trim($val)!="") $cdata .= $key.": ".$val."\n";
			    $cfields[] = $key;
			  } else unset($data[$key]);
		} } }
	    if (count($data)<3) continue;
		$data["history"] = str_replace("@fields@",implode(", ",$cfields),$data["history"]).$cdata."\n";
		
		if (DEBUG) print_r($data);
		$error_sql = db_update($table_dest,$data,array("id=@id@"),array("id"=>$id));
		$count_update++;
	  } else { // new
	    $id = sql_genID($table_dest)*100+$_SESSION["serverid"];
		$row["id"] = $id;
		$row["folder"] = $tfolder;
		$row["dsize"] = 0;
		$row["history"] = sprintf("{t}Item created by %s at %s{/t} (sync)\n",$_SESSION["username"],sys_date("{t}m/d/y g:i:s a{/t}"));
		if (DEBUG) print_r($row);
		$error_sql = db_insert($table_dest,$row);
		$count_insert++;
      }
	  if ($error_sql=="") {
	    if ($module=="calendar") trigger::calcappointment($id,$row,array(),false);
	    if ($module=="contacts") trigger::createeditcontact($id,$row,array(),false);
	    if ($module=="tasks") trigger::createedittask($id,$row,array(),false);
		
		db_search_update($table_dest,$id,$GLOBALS["table"]["fields"]);
		if ($count_insert>0) sys_log_stat("new_records",$count_insert);
		if ($count_update>0) sys_log_stat("changed_records",$count_update);
  } } }
  db_update_treesize($table_dest,$tfolder);
  return "";
}

public static function syncml_deleteitem($id) {
  $t = $GLOBALS["t"];
  $tname = $t["title"];
  $tfolder = $t["folder"];
  $where = array("folder=@folder@");
  if ($id[0]=="_") $where[] = "id=@id@"; else $where[] = "syncid=@id@";
  $row_id = db_select_value($tname,"id",$where,array("id"=>trim($id,"_"),"folder"=>$tfolder));
  if (!empty($row_id)) {
	$trash = db_select_value("simple_sys_tree","id","anchor=@anchor@",array("anchor"=>"trash"));
	if (empty($trash)) {
	  sys_add_notification("{t}Error{/t}: {t}Trash folder not found.{/t}");
	  return;
	}
	$id = folders::create(sys_date("{t}m/d/Y{/t}"),"blank","",$trash,true);
	$id2 = folders::create($t["att"]["MODULENAME"],str_replace("simple_","",$tname),"",$id,true);
	$data = array("folder"=>$id2,"history"=>sprintf("{t}Item deleted by %s at %s{/t}\n",$_SESSION["username"],sys_date("{t}m/d/y g:i:s a{/t}")));
	db_update($tname,$data,array("id=@id@"),array("id"=>$row_id));
	db_update_treesize($tname,$tfolder);
	db_search_delete($tname,$row_id,$tfolder);
    sys_log_stat("deleted_records",1);
  }
}

}