<?php

if (!defined('ROOTPATH')) die("This is a library.");

/* $Id: module_exec.inc.php,v 1.44 2003/11/27 15:06:29 leyeti Exp $ */
// =====================================================================================
// Moregroupware - Module automatic execution File (module_exec.inc.php.php)
// -------------------------------------------------------------------------------------
// This file is something like a startup script for an operating system.
// Some general issues like connect_database or authentication will be
// done here, each module/script will call this file autoamticly. You
// can turn off/on some commands with the $myEnv[] Flags
// -------------------------------------------------------------------------------------
// the following flags are available:
//
//	$myEnv[stdsmenu] - decides wheter to use external submenu file (default = true)
//	$myEnv[auth] - Authenticate user based on session-id (default = true)
// 	$myEnv[connectdb] - connects to database (default = true)
//	$myEnv[translate] - translate module based on module language file (default = true)
// =====================================================================================

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

// Authentication of User according his session (its not the main auth)
if(!isset($myEnv["auth"]) || $myEnv["auth"] !== false) checkLogin();

if ($myEnv["module"]!="general" and isset($_SESSION["MGW"]->userid) && $_SESSION["MGW"]->userid and $_SESSION["MGW"]->username!="admin") {
  if (!query_access_module($myEnv["module"])) {
    if (query_access_module($_SESSION["MGW"]->settings["def_module"])) {
	    redirect(ROOTURL."modules/".$_SESSION["MGW"]->settings["def_module"]."/index.php?".SID);
	} else {
	    exit("<html><head><title>Error</title><link rel='stylesheet' type='text/css' href='".ROOTURL."setup/templates/default/css/setup.css'></head><body bgcolor='#c8c9d4'><table align='center' width='500'><tr><td><br /><table border='0' cellpadding='6' cellspacing='1' bgcolor='black'><tr><td align='center' bgcolor='#ededed'style='font: 12px Arial;'><strong>ERROR</strong></td></tr><tr><td bgcolor='#ededed'style='font: 12px Arial;'><br />You have no 'read' right to the selected default module.<br /><br />Most of the time this is caused by the creation of a new group without setting rights for that group before using it. Have a <a href='".ROOTURL."docs/html/en/index.html'>look at the manual</a> for more information, or contact your administrator.</td></tr></table></td></tr></table></body></html>");
    }
  }
}

// Connect to ADOdb and return $db2 object
if(!isset($myEnv["connectdb"]) || $myEnv["connectdb"] !== false) $conn = connect_database();

// do module translation
if( !isset($myEnv["translate"]) || $myEnv["translate"] !== false) Lang::setLocaledText($_SESSION["MGW"]->spkz, $myEnv["module"]);

// send header for used charset
if(isset($_SESSION['MGW']->charset) && $_SESSION['MGW']->charset != '')
     header('Content-Type: text/html; charset='.$_SESSION['MGW']->charset);

// call standard module submenu (smenu.php) and integrate it
if(isset($_SESSION["MGW"]->modules[$myEnv["module"]]) and (!isset($myEnv["stdsmenu"]) || $myEnv["stdsmenu"] !== false)){
    if(file_exists(ROOTPATH . "/modules/" . $myEnv["module"]. "/inc/smenu.php"))
	include(ROOTPATH . "/modules/" . $myEnv["module"] . "/inc/smenu.php");
    else
	echo "<html><head><title>Error</title></head><body bgcolor='#c8c9d4'><table align='center' width='500'><tr><td><br /><table border='0' cellpadding='6' cellspacing='1' bgcolor='black'><tr><td align='center' bgcolor='#ededed'style='font: 12px Arial;'><strong>ERROR</strong></td></tr><tr><td bgcolor='#ededed'style='font: 12px Arial;'><br />Program cannot find submenu definition file (smenu.php) in the module's 'inc' folder. Please create this file or set \$myEnv['stdsmenu'] to false in your code and define it there.<br /><br />Have a <a href='docs/html/en/index.html'>look at the manual</a> for more information.</td></tr></table></td></tr></table></body></html>";
}
else $smarty->assign("sdata","");

$moduleSettings = array();

if (isset($_SESSION["MGW"]->modules) and query_access_module("settings")) {
  foreach ($_SESSION["MGW"]->modules as $module) {
    if (($module['module_type'] == 1 || $module['active']=='1') and (query_access_module($module["modulename"]) or $module["module_type"]=="1")) { // core modules always!
      if (file_exists(ROOTPATH."/modules/".$module["modulename"]."/inc/settings.inc.php")) {
        unset($settings);
        include(ROOTPATH."/modules/".$module["modulename"]."/inc/settings.inc.php");
        if (is_array($settings[$module["modulename"]])) {
          $moduleSettings[$module["modulename"]] = array();
          $moduleSettings[$module["modulename"]]["name"] = Lang::getLanguageString($module["modulename"]);
          $moduleSettings[$module["modulename"]]["options"] = array();
          foreach ($settings[$module["modulename"]] as $optionName => $option) {
            if (in_array("admin",$option) and (isset($option["admin"]) && $option["admin"])) {
              if ($_SESSION["MGW"]->userid==1) {
                $tmp = array(trim(Lang::getLanguageString($optionName))." (".Lang::getLanguageString("admin_only").")",$optionName,true);
                array_push($moduleSettings[$module["modulename"]]["options"], $tmp);
              }
            } else {
              $tmp = array(trim(Lang::getLanguageString($optionName)),$optionName,false);
              array_push($moduleSettings[$module["modulename"]]["options"], $tmp);
            }
          }
          $settings = array();
          unset($settings);
        }
      }
    }
  }
  $output = "";
  $output2 = "";
  foreach ($moduleSettings as $curr_id=>$title) {
    $output .= "[null, '".$title["name"]."', null, null, null,";
    $output2 .= "<optgroup label=\"".$title["name"]."\">\n";
	
    foreach ($title["options"] as $subItem) {
	  $output .= "[null, '".$subItem[0]."', '".ROOTURL."modules/settings/index.php?module=".$curr_id."&option=".$subItem[1]."&".SID."', null, null],";
	  $output2 .= "<option value=\"".ROOTURL."modules/settings/index.php?module=".$curr_id."&option=".$subItem[1]."&".SID."\">".$subItem[0]."</option>\n";
	}
	$output .= "],";
	$output2 .= "</optgroup>\n";
  }
  $smarty->assign("top_moduleSettings",$output);
  $smarty->assign("top_moduleSettings2",$output2);
}

if (isset($_SESSION["MGW"]->modules) && !(isset($_GET['view']) && $_GET['view']=='logout')) {
  $buffer = "";
  
  if (isset($_SESSION["MGW"]->modules["general"]) and $_SESSION["MGW"]->modules["general"]["version_mtime"] != filemtime(ROOTPATH."/modules/general/definition2.xml")) {
    $myEnv["module"] = "general";
  }
  if (isset($_SESSION["MGW"]->modules) and !isset($_SESSION["MGW"]->modules["general"])) $myEnv["module"] = "general";

  $install = false;
  if (!isset($_SESSION["MGW"]->modules[$myEnv["module"]])) {
    $_SESSION["MGW"]->modules[$myEnv["module"]] = array(
      "active" => 1,
      "modulename" => $myEnv["module"],
      "folder" => $myEnv["module"],
      "name" => $myEnv["module"],
      "version" => "0",
      "version_mtime" => 0,
      "date" => date("Y-m-d"),
      "author" => "",
      "email" => "",
      "description" => "",
      "base" => "",
      "compatibility" => "",
      "dependancies" => "",
      "module_type" => 3,
      "noicon" => "",
      "lu_user" => 1,
      "lu_date" => 0
	);
  }

  $module = $_SESSION["MGW"]->modules[$myEnv["module"]];

  if ($module["version"]=="0" and $myEnv["module"]!="general") $install = true;

  if (file_exists(ROOTPATH."/modules/".$module["modulename"]."/definition2.xml") and (((isset($module["base"]) and $module["base"]!="" and basename($_SERVER["PHP_SELF"])==$module["base"]) or basename($_SERVER["PHP_SELF"])=="index.php" or basename($_SERVER["PHP_SELF"])=="index2.php") or $module["modulename"]=="admin")) {
    if ($module["version_mtime"] != filemtime(ROOTPATH."/modules/".$module["modulename"]."/definition2.xml")) {
	  $buffer .= "Found changes in \"/modules/".$module["modulename"]."/definition2.xml\" ...\n";
		    
	  if ($_SESSION["MGW"]->username!="admin") die("Please log in as admin.");
		    
	  $buffer .= "Parsing new definition2.xml ...\n";
	  $data = get_definition_data_from_xml(ROOTPATH."/modules/".$module["modulename"]."/definition2.xml");
		    
	  $buffer .= "Checking dependencies ...\n";
  	  include_once(INCLUDEPATH . "version.inc.php");
	  
	  if (isset($data["compatibility"][0]) and isset($gwversion) and (int)str_replace(".","",$gwversion) < (int)str_replace(".","",$data["compatibility"][0])) {
	    $smarty->assign("errorheader","Installation / Update");
	    $smarty->assign("permerror",$buffer."\nYou need at least more.groupware '".$data["compatibility"][0]."' to run this module.\n\n\n");
	    $smarty->assign("permlink","<a href='../admin/modulemanager.php?".SID."'>Go back</a> to module manager.");
	    $smarty->display($appconf["gentemplates"] ."/perm_errors.tpl");
	    die;
	  }
		    
	  if (isset($data["dependancy"])) {
	    foreach ($data["dependancy"] as $needed_module) {
		  if (!isset($_SESSION["MGW"]->modules[$needed_module])) {
		    $smarty->assign("errorheader","Installation / Update");
		    $smarty->assign("permerror",$buffer."\nIn order to run this module you need to have the module '".$needed_module."' installed.\n\n");
	    	$smarty->assign("permlink","<a href='../admin/modulemanager.php?".SID."'>Go back</a> to module manager.");
		    $smarty->display($appconf["gentemplates"] ."/perm_errors.tpl");
			die;
		  }
		}
	  }

	  include_once(ROOTPATH."/include/adodb/adodb-xmlschema.inc.php");

	  $old_version = (int)str_replace(".","",$module["version"]);
	  $new_version = (int)str_replace(".","",$data["version"][0]);
	  $mgw_version = (int)str_replace(".","",$appconf['mgw_version_number']);

	  if (!$install and file_exists(ROOTPATH."/modules/".$module["modulename"]."/setup/update_pre.php")) {
	    $buffer .= "Executing custom update_pre.php (\$old_version=".$old_version.",\$new_version=".$new_version.",\$mgw_version=".$mgw_version.")...\n";
		include ROOTPATH."/modules/".$module["modulename"]."/setup/update_pre.php";
      }
			
	  execute_xml_schema(ROOTPATH."/modules/".$module["modulename"]."/definition2.xml",$module["modulename"],$appconf['dbvendor'],!$install);
		  
	  if (!$install and file_exists(ROOTPATH."/modules/".$module["modulename"]."/setup/update_post.php")) {
	    $buffer .= "Executing custom update_post.php (\$old_version=".$old_version.",\$new_version=".$new_version.",\$mgw_version=".$mgw_version.")...\n";
		include ROOTPATH."/modules/".$module["modulename"]."/setup/update_post.php";
	  }
	  
	  if ($install) {
	    if (file_exists(ROOTPATH."/modules/".$module["modulename"]."/setup/install.sql")) {
	      $buffer .= "Executing custom install.sql (\$new_version=".$new_version.",\$mgw_version=".$mgw_version.")...\n";

          $sqlfile = @file(ROOTPATH."/modules/".$module["modulename"]."/setup/install.sql");
                    	
          $sqlbuffer = "";
          for($o=0;$o<count($sqlfile);$o++) {
			if(substr(trim($sqlfile[$o]),0,1) != '#' and strlen(trim($sqlfile[$o]))>0) $sqlbuffer .= $sqlfile[$o];
          }
          $sql_array = explode(";",$sqlbuffer);
          unset($sqlbuffer);
          for($i=0;$i<count($sql_array);$i++) {
            if(strlen(trim($sql_array[$i])) > 0) {
			  if(!$res = $conn->Execute($sql_array[$i])) {
			    $buffer .= "\nSQL FAILED: ".$sql_array[$i]."\n".$conn->ErrorMsg()."\n\n";
			  }
			}
          }
	    }	  

	    if (file_exists(ROOTPATH."/modules/".$module["modulename"]."/setup/install.php")) {
	      $buffer .= "Executing custom install.php (\$new_version=".$new_version.",\$mgw_version=".$mgw_version.")...\n";
		  include ROOTPATH."/modules/".$module["modulename"]."/setup/install.php";
	    }	  
	  }

	  $buffer .= "Updating modules table ...\n";

	  if ($install) {
		$sql = "INSERT INTO mgw_modules (secure,modulename, version, version_mtime, date, author, email, description, noicon, base, compatibility, dependancies, module_type, active, lu_user, lu_date) VALUES (".((isset($data["secure"]) and $data["secure"][0]=="true")?1:0).",".$conn->QMagic($module["modulename"]).",".$conn->QMagic($data["version"][0]).",".(int)filemtime(ROOTPATH."/modules/".$module["modulename"]."/definition2.xml").",".$conn->QMagic(isset($data["date"])?$data["date"][0]:"").",".$conn->QMagic(isset($data["author"])?$data["author"][0]:"").",".$conn->QMagic(isset($data["email"])?$data["email"][0]:"").",".$conn->QMagic(isset($data["description"])?$data["description"][0]:"").",".$conn->QMagic(isset($data["noicon"])?$data["noicon"][0]:"").",".$conn->QMagic(isset($data["base"])?$data["base"][0]:"").",".$conn->QMagic(isset($data["compatibility"])?$data["compatibility"][0]:"").",".$conn->QMagic(isset($data["dependancy"])?implode($data["dependancy"],","):"").",".(int)$data["module_type"][0].",'1', '1', ".$conn->DBTimeStamp(time()).")";
        if(!$conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));

		$modules_rights = array("calendar","contact","forum","news","notes","projects","tts");
		
		if (in_array($module["modulename"],$modules_rights)) {
		  $sql = "INSERT INTO mgw_rights (modulename, user_group_id, _read, _write, _delete,_delete_others, _modify, _modify_others, _module_level,lu_user, lu_date) VALUES (".$conn->QMagic($module["modulename"]).", '50000', '1', '1', '1', '1','1', '1', '9', '1', ".$conn->DBTimeStamp(time()).")";
          if(!$conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
		
		  $sql = "INSERT INTO mgw_rights (modulename, user_group_id, _read, _write, _delete,_delete_others, _modify, _modify_others, _module_level,lu_user, lu_date) VALUES (".$conn->QMagic($module["modulename"]).", '50001', '1', '1', '1', '1','1', '1', '3', '1', ".$conn->DBTimeStamp(time()).")";
          if(!$conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
        }      
		
		if (file_exists(ROOTPATH."/modules/".$module["modulename"]."/inc/rights.inc.php")) {
		  $rights = array();
		  $give_all_rights_at_install = false;
		  include ROOTPATH."/modules/".$module["modulename"]."/inc/rights.inc.php";
		  if ($give_all_rights_at_install and count($rights)>0) {
		    $buffer .= "\nSetting default rights to groups: Admin & Default\n";
			set_default_rights("root_modules_".$module["modulename"]."_",$rights);
		  }
		}
	  }
		    
	  $sql = "SELECT * FROM mgw_modules WHERE modulename=".$conn->QMagic($module["modulename"]);
      if(!$res = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
      $row = $res->FetchRow();

	  if (!isset($row["modulename"])) {
		$sql = "INSERT INTO mgw_modules (modulename,version,version_mtime,date,description,noicon,base,lu_date) VALUES (".$conn->QMagic($module["modulename"]).",'','','','','','',NOW())";
        if(!$conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
	  }
      $sql="UPDATE mgw_modules SET secure=".((isset($data["secure"]) and $data["secure"][0]=="true")?1:0).",version=".$conn->QMagic($data["version"][0]).",version_mtime=".(int)filemtime(ROOTPATH."/modules/".$module["modulename"]."/definition2.xml").",date=".$conn->QMagic(isset($data["date"])?$data["date"][0]:"").",author=".$conn->QMagic(isset($data["author"])?$data["author"][0]:"").",email=".$conn->QMagic(isset($data["email"])?$data["email"][0]:"").",description=".$conn->QMagic(isset($data["description"])?$data["description"][0]:"").",noicon=".$conn->QMagic(isset($data["noicon"])?$data["noicon"][0]:"").",base=".$conn->QMagic(isset($data["base"])?$data["base"][0]:"").",compatibility=".$conn->QMagic(isset($data["compatibility"])?$data["compatibility"][0]:"").",dependancies=".$conn->QMagic(isset($data["dependancy"])?implode($data["dependancy"],","):"").",module_type=".(int)$data["module_type"][0]." WHERE modulename=".$conn->QMagic($module["modulename"]);
      if(!$conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
		
	  $_SESSION["MGW"]->modules[$myEnv["module"]]["version_mtime"] = filemtime(ROOTPATH."/modules/".$module["modulename"]."/definition2.xml");
	  $_SESSION["MGW"]->modules[$myEnv["module"]]["version"] = $data["version"][0];
		  
	  if ($module["modulename"]=="general") {
	    if (file_exists(ROOTPATH."/modules/".$module["modulename"]."/setup/install.php")) {
	      $buffer .= "Executing custom install.php (\$new_version=".$new_version.",\$mgw_version=".$mgw_version.")...\n";
		  include ROOTPATH."/modules/".$module["modulename"]."/setup/install.php";
	    }	  
	    $buffer .= "\nSetup was executed. [".$module["modulename"]."]\n\n";
		$link = "<a href='".ROOTURL."index.php?".SID."'>Please Login again</a>.";
		$_SESSION = array();
 	    session_destroy();	
	  } else {
	    $buffer .= "\nSetup was executed. [".$module["modulename"]."]\n\n";
	    $link = "<a href='".ROOTURL."modules/admin/modulemanager.php?".SID."'>Go back</a> to module manager.";
	  }
	  
	  // refresh data about user modules settings:
	  // (avoid bug when admin has just install the module and then go in this module
	  getUserSettings();
	  
	  $smarty->assign("errorheader","Installation / Update");
	  $smarty->assign("permerror",$buffer);
	  $smarty->assign("permlink",$link);
	  $smarty->display($appconf["gentemplates"] ."/perm_errors.tpl");
	  exit;
	}
  }
}
?>
