<?php
/* $Id: modulemanager.php,v 1.61 2003/12/03 17:39:50 k-fish Exp $ */
$myEnv["module"] = "admin";
$myEnv['stdsmenu'] = false;
$myEnv["output"] = "html";

include("../../config.inc.php");
include(INCLUDEPATH . "container.inc.php");

// adding file revision into global array
revisionInit("\$Revision: 1.61 $", __FILE__);

// =================================================
//	              (de)activate entry
// =================================================
	 
if (isset($_GET["active"])) {
    queryRights2("root_modules_admin_modulemanager_modifygroups");

	$active = (int) $_GET["active"];
	$mod = $conn->QMagic($_GET["mod"]);
	$sql="UPDATE mgw_modules SET active = $active, lu_user=".$_SESSION["MGW"]->userid.", lu_date=". $conn->DBTimeStamp(time()). " WHERE modulename=$mod AND module_type=3";
	if(!$conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));

	// remove as def_module (use overview instead)
	$sql="UPDATE mgw_config SET value_str='overview', lu_user=".$_SESSION["MGW"]->userid.", lu_date=". $conn->DBTimeStamp(time()). " WHERE configtagname='def_module' AND value_str=".$mod;
	if(!$conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
    
	// rebuild modules array 
	$_SESSION['MGW']->modules = getInstalledModules();
}

// create CSV backup of all tables the module uses
if (isset($_GET["action"]) && $_GET["action"] == "getcsvtar"){
    queryRights2("root_modules_admin_modulemanager_deletemodules");
    $_GET['mod'] = str_replace(array(".","'","\"","\\","/"),"",$_GET['mod']);

    $data = implode("",file(ROOTPATH."/modules/".$_GET['mod']."/definition2.xml"));
    $parser = xml_parser_create();
    xml_parser_set_option($parser,XML_OPTION_CASE_FOLDING,0);
    xml_parser_set_option($parser,XML_OPTION_SKIP_WHITE,1);
    xml_parse_into_struct($parser,$data,$values,$tags);
    xml_parser_free($parser);

    include(INCLUDEPATH . "adodb/toexport.inc.php");
    $tar = new tar();
    foreach ($values as $value) {
	if (isset($value["tag"]) && $value["tag"]=='table' && isset($value["attributes"])){
	    $res = $conn->Execute('SELECT * FROM mgw_'.$value["attributes"]['name']);
	    $tar->addData('mgw_'.$value["attributes"]['name'].'.csv',rs2csv($res));
	}
    }
    $tar->__generateTar();

    header('Content-Type: application/x-tar');
    header('Content-Disposition: attachment; filename='.$_GET['mod'].'-csv-'.date('Y-m-d').'.tar');
    header('Content-Length: '.strlen($tar->tar_file));
    echo $tar->tar_file;
    exit();
}
   
// create backup of all files in data_store
if (isset($_GET["action"]) && $_GET["action"] == "getfiletar"){
    queryRights2("root_modules_admin_modulemanager_deletemodules");
    $_GET['mod'] = str_replace(array(".","'","\"","\\","/"),"",$_GET['mod']);

    $tar = new tar();
    chdir(ROOTPATH.'/data_cache');
    $mdir = opendir(ROOTPATH.'/data_cache/'.$_GET['mod']);
    while(($file = readdir($mdir)) !== false){
	if($file != '.' && $file != '..' && $file != 'index.htm' && $file != 'index.html')
	    $tar->addFile($_GET['mod'].'/'.$file);
    }
    $tar->__generateTar();

    header('Content-Type: application/x-tar');
    header('Content-Disposition: attachment; filename='.$_GET['mod'].'-files-'.date('Y-m-d').'.tar');
    header('Content-Length: '.strlen($tar->tar_file));
    echo $tar->tar_file;
    exit();
}

// =================================================
//	              delete module
// =================================================
if (isset($_GET["action"]) && $_GET["action"] == "delete"){
    queryRights2("root_modules_admin_modulemanager_deletemodules");
	
    $sql = "SELECT modulename, description, version, author, email FROM mgw_modules WHERE modulename=".$conn->QMagic($_GET["mod"]);
    if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
    $row = $res->FetchRow();
    $row['modname'] = Lang::getLanguageString($row['modulename']);

    $smarty->assign('row', $row);
    $smarty->display("modulemanager_delete.tpl");
    exit();
}

if (isset($_POST["action"]) && $_POST["action"] == "delete" && isset($_POST['confirmation_yes'])){
    queryRights2("root_modules_admin_modulemanager_deletemodules");
    $_POST['mod'] = str_replace(array(".","'","\"","\\","/"),"",$_POST['mod']);

    // remove data_cache and data_store
    recDel(ROOTPATH.'/data_cache/'.$_POST['mod']);
    @rmdir(ROOTPATH.'/data_cache/'.$_POST['mod']);
    recDel(ROOTPATH.'/data_store/'.$_POST['mod']);
    @rmdir(ROOTPATH.'/data_store/'.$_POST['mod']);

    // delete rights entries
    $sql = "DELETE FROM mgw_rights WHERE modulename=".$conn->QMagic($_POST["mod"]);
    if(!$conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
    $sql = "DELETE FROM mgw_rights2 WHERE id_string LIKE ".$conn->QMagic('root_modules_'.$_POST["mod"].'%');
    if(!$conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));

    // delete config entries
    $sql = "SELECT configtagname FROM mgw_configtags WHERE modulename=".$conn->QMagic($_POST["mod"]);
    if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
    while ($row = $res->FetchRow()) {
	  if (isset($row["configtagname"]) and $row["configtagname"]!="") {
        $sql = "DELETE FROM mgw_config WHERE mgw_config.configtagname=".$conn->QMagic($row["configtagname"]);
    if(!$conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
	  }
    }
	
    $sql = "DELETE FROM mgw_configtags WHERE modulename=".$conn->QMagic($_POST["mod"]);
    if(!$conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));

    // delete all tables
    $data = implode("",file(ROOTPATH."/modules/".$_POST['mod']."/definition2.xml"));
    $parser = xml_parser_create();
    xml_parser_set_option($parser,XML_OPTION_CASE_FOLDING,0);
    xml_parser_set_option($parser,XML_OPTION_SKIP_WHITE,1);
    xml_parse_into_struct($parser,$data,$values,$tags);
    xml_parser_free($parser);

    $dict = NewDataDictionary($conn);
    foreach ($values as $value) {
	if (isset($value["tag"]) && $value["tag"]=='table' && isset($value["attributes"])){
	    $sql = $dict->DropTableSQL('mgw_'.$value["attributes"]['name']);
	    $conn->Execute($sql[0]);
	}
    }

    // delete entry from mgw_modules
    $sql = "DELETE FROM mgw_modules WHERE modulename=".$conn->QMagic($_POST["mod"])." AND module_type=3";
    if(!$conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));

    // remove as def_module (use overview instead)
    $sql="UPDATE mgw_config SET value_str='overview', lu_user=".$_SESSION["MGW"]->userid.", lu_date=". $conn->DBTimeStamp(time()). " WHERE configtagname='def_module' AND value_str=".$conn->QMagic($_POST["mod"]);
    if(!$conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
    
    // rebuild modules array 
    $_SESSION['MGW']->modules = getInstalledModules();
	
	// redirect to module manager (for menu refresh)
	redirect(ROOTURL."modules/admin/modulemanager.php?".SID);
}

// =================================================
//	              List View
// =================================================
queryRights2("root_modules_admin_modulemanager_listmodules");

$icons = getIconStrings();

$sql = "SELECT module_type,modulename,version,author,email,description,active,secure FROM mgw_modules ORDER BY modulename";
if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));

$modules = array();
while($row = $res->FetchRow()){
	$modules[$row["modulename"]] = "";

	// create Action URLs
	if($row['module_type']>2){
	    $row["urls"] = "<a href=\"modulemanager.php?action=delete&mod=". $row["modulename"] ."&".SID."\" onclick=\"return check_delete()\" class=\"delete\">". $icons["delete"] . "</a>";
	    $row["active"] = ($row["active"] == 1 ? '<a href="modulemanager.php?mod='.$row["modulename"].'&amp;active=0&amp;'.SID.'">'.Lang::getLanguageString("yes").'</a>' : '<a href="modulemanager.php?mod='.$row["modulename"].'&amp;active=1&amp;'.SID.'">'.Lang::getLanguageString("no").'</a>');
	}
	else{
	    $row["urls"] = '';
	    $row["active"] = ($row["active"] == 1 ? Lang::getLanguageString("yes") : Lang::getLanguageString("no"));
	}

	if (isset($_GET["upgrade"])) {
	  @set_time_limit(0);
	
	  $return = "";
	  $server = "http://www.moregroupware.org/packages/";
      if ($fp = @fopen($server.$row["modulename"]."/definition2.xml", 'rb')) {
		while (!feof($fp)) {
    	  $return .= fread($fp, 1024);
    	}
    	fclose($fp);
	
		if ($return!="") {
		  $data = $return;
		  $data = substr($data,strpos($data,"<mgw>"));
		  $parser = xml_parser_create();
		  xml_parser_set_option($parser,XML_OPTION_CASE_FOLDING,0);
		  xml_parser_set_option($parser,XML_OPTION_SKIP_WHITE,1);
		  xml_parse_into_struct($parser,$data,$values,$tags);
		  xml_parser_free($parser);

		  $data = array();
		  foreach ($values as $value) {
		    if (isset($value["tag"]) and isset($value["value"])) $data[$value["tag"]] = $value["value"];
		  }

		  if (is_array($data) and isset($data["name"]) and isset($data["version"]) and $data["name"]==$row["modulename"] and (int)str_replace(".","",$row["version"])<(int)str_replace(".","",$data["version"])) {
	    	$row["urls"] .= '&nbsp;<font style="color: #008000"><b>'.Lang::getLanguageString("update_available").'</b></font>';
		  }
		}
      } else {
	    $row["urls"] .= '&nbsp;<font class="delete">'.Lang::getLanguageString("error").'</font>';
	  }
	}
	
    if ($_SESSION["MGW"]->modules[$row["modulename"]]["version_mtime"] != filemtime(ROOTPATH."/modules/".$row["modulename"]."/definition2.xml")) {
	  $row["urls"] .= '&nbsp;<a class="delete" href="'.ROOTURL.'/modules/'.$row["modulename"].'/'.($row["base"]!=""?$row["base"]:"index.php").'?'.SID.'">'.Lang::getLanguageString("update").'</a>';
	}

	$row["modulename"] = Lang::getLanguageString($row["modulename"]);

	if ($row["secure"]) $smarty->append("td",$row);
	  else $smarty->append("td4",$row);
}	


$attaches = array();
$handle=opendir(ROOTPATH."/modules/");
while ($file = readdir($handle)) {
  $xml_def = ROOTPATH."/modules/".$file."/definition2.xml";
  if ($file!="." and $file!=".." and $file!="CVS" and is_dir(ROOTPATH."/modules/".$file) and file_exists($xml_def)) {

    if (!isset($modules[$file])) {
		$data = get_definition_data_from_xml(ROOTPATH."/modules/".$file."/definition2.xml");

		$row = array();
		$space = "&nbsp;&nbsp;";
		$row["modulename"] = Lang::getLanguageString($file);
		$row["version"] = $data["version"][0];
		$row["version_mtime"] = filemtime($xml_def);
		$row["date"] = $data["date"][0];
		$row["author"] = isset($data["author"])?$data["author"][0]:"";
		$row["email"] = isset($data["email"])?$data["email"][0]:"";
		$row["description"] = $data["description"][0];
		$row["compatibility"] = $data["compatibility"][0];
		$row["dependencies"] = "";
		$row["module_type"] = $data["module_type"][0];
		$row["active"] = Lang::getLanguageString("no");
		$row["base"] = isset($data["base"][0])?$data["base"][0]:"";
		$row["noicon"] = isset($data["noicon"][0])?$data["noicon"][0]:"";
		$installlink = "<a href=\"".ROOTURL."modules/". $file ."/".($row["base"]!=""?$row["base"]:"index.php")."?&".SID."\" class=\"delete\">". Lang::getLanguageString("install") . "</a>";
		$row["urls"] = $installlink;
		if (isset($data["secure"][0]) and $data["secure"][0]=="true") $smarty->append("td2",$row);
		  else $smarty->append("td3",$row);
	}
  }
}
closedir($handle);

		
$smarty->display("modulemanager_list.tpl");
?>
