
# script_vtigercrm_desc()
sub script_vtigercrm_desc
{
return "Vtiger CRM";
}

sub script_vtigercrm_uses
{
return ( "php" );
}

sub script_vtigercrm_longdesc
{
return "Vtiger CRM is an open-source web-based customer relationship management application";
}

# script_vtigercrm_versions()
sub script_vtigercrm_versions
{
return ( "7.5.0" );
}

sub script_vtigercrm_category
{
return "Commerce";
}

sub script_vtigercrm_php_vers
{
return ( 5 );
}

sub script_vtigercrm_php_modules
{
return ("mysql", "gd", "mbstring");
}

sub script_vtigercrm_php_optional_modules
{
return ( "imap" );
}

sub script_vtigercrm_php_fullver
{ 
local ($d, $ver, $sinfo) = @_;
return "5.4";
}

sub script_vtigercrm_dbs
{
return ("mysql");
}

# script_vtigercrm_php_vars(&domain)
# Returns an array of extra PHP variables needed for this script
sub script_vtigercrm_php_vars
{
return ( [ 'safe_mode', 'Off' ],
	 [ 'file_uploads', 'On' ],
	 [ 'register_globals', 'Off' ],
	 [ 'output_buffering', 'On' ],
	 [ 'log_errors', 'Off' ],
	 [ 'short_open_tag', 'Off' ],
	 [ 'memory_limit', '32M', '+' ],
	 [ 'max_execution_time', '600', '+' ],
	 [ 'display_errors', 'Off' ],
	 [ 'error_reporting', 'E_WARNING & ~E_NOTICE & ~E_DEPRECATED' ],
	);
}

# script_vtigercrm_params(&domain, version, &upgrade-info)
# Returns HTML for table rows for options for installing Vtiger CRM
sub script_vtigercrm_params
{
local ($d, $ver, $upgrade) = @_;
local $rv;
local $hdir = &public_html_dir($d, 1);
if ($upgrade) {
	# Options are fixed when upgrading
	local ($dbtype, $dbname) = split(/_/, $upgrade->{'opts'}->{'db'}, 2);
	$rv .= &ui_table_row("Database for Vtiger CRM tables", $dbname);
	local $dir = $upgrade->{'opts'}->{'dir'};
	$dir =~ s/^$d->{'home'}\///;
	$rv .= &ui_table_row("Install directory", $dir);
	}
else {
	# Show editable install options
	local @dbs = &domain_databases($d, [ "mysql" ]);
	$rv .= &ui_table_row("Database for Vtiger CRM tables",
		     &ui_database_select("db", undef, \@dbs, $d, "vtigercrm"));
	$rv .= &ui_table_row("Install sub-directory under <tt>$hdir</tt>",
			     &ui_opt_textbox("dir", &substitute_scriptname_template("vtigercrm", $d), 30, "At top level"));
	}
return $rv;
}

# script_vtigercrm_parse(&domain, version, &in, &upgrade-info)
# Returns either a hash ref of parsed options, or an error string
sub script_vtigercrm_parse
{
local ($d, $ver, $in, $upgrade) = @_;
if ($upgrade) {
	# Options are always the same
	return $upgrade->{'opts'};
	}
else {
	local $hdir = &public_html_dir($d, 0);
	$in{'dir_def'} || $in{'dir'} =~ /\S/ && $in{'dir'} !~ /\.\./ ||
		return "Missing or invalid installation directory";
	local $dir = $in{'dir_def'} ? $hdir : "$hdir/$in{'dir'}";
	local ($newdb) = ($in->{'db'} =~ s/^\*//);
	return { 'db' => $in->{'db'},
		 'newdb' => $newdb,
	         'dir' => $dir,
		 'path' => $in{'dir_def'} ? "/" : "/$in{'dir'}", };
	}
}

# script_vtigercrm_check(&domain, version, &opts, &upgrade-info)
# Returns an error message if a required option is missing or invalid
sub script_vtigercrm_check
{
local ($d, $ver, $opts, $upgrade) = @_;
$opts->{'dir'} =~ /^\// || return "Missing or invalid install directory";
$opts->{'db'} || return "Missing database";
if (-r "$opts->{'dir'}/config.inc.php") {
	return "Vtiger CRM appears to be already installed in the selected directory";
	}
local ($dbtype, $dbname) = split(/_/, $opts->{'db'}, 2);
local $clash = &find_database_table($dbtype, $dbname, 'vtiger_.*');
$clash && return "Vtiger CRM appears to be already using the selected database (table $clash)";
return undef;
}

# script_vtigercrm_files(&domain, version, &opts, &upgrade-info)
# Returns a list of files needed by Vtiger CRM, each of which is a hash ref
# containing a name, filename and URL
sub script_vtigercrm_files
{
local ($d, $ver, $opts, $upgrade) = @_;
local @files = ( { 'name' => "source",
	   'file' => "vtigercrm-$ver.tar.gz",
	   'url' => "http://prdownloads.sourceforge.net/vtigercrm/".
		    ($ver >= 6 ? "vtigercrm$ver.tar.gz"
			       : "vtigercrm-$ver.tar.gz") } );
return @files;
}

sub script_vtigercrm_commands
{
return ("tar", "gunzip", "wget");
}

# script_vtigercrm_install(&domain, version, &opts, &files, &upgrade-info,
# 			   domuser, dompass)
# Actually installs Vtiger CRM, and returns either 1 and an informational
# message, or 0 and an error
sub script_vtigercrm_install
{
local ($d, $version, $opts, $files, $upgrade, $domuser, $dompass) = @_;
local ($out, $ex);
if ($opts->{'newdb'} && !$upgrade) {
	local $err = &create_script_database($d, $opts->{'db'},
					     { 'charset' => 'utf8' });
	return (0, "Database creation failed : $err") if ($err);
	}
local ($dbtype, $dbname) = split(/_/, $opts->{'db'}, 2);
local $dbuser = $dbtype eq "mysql" ? &mysql_user($d) : &postgres_user($d);
local $dbpass = $dbtype eq "mysql" ? &mysql_pass($d) : &postgres_pass($d, 1);
local $dbphptype = $dbtype eq "mysql" ? "mysql" : "psql";
local $dbhost = &get_database_host($dbtype, $d);
local $dberr = &check_script_db_connection($dbtype, $dbname, $dbuser, $dbpass);
return (0, "Database connection failed : $dberr") if ($dberr);

# Preserve old config file
local $cfile = "$opts->{'dir'}/config.inc.php";
local $oldcfile = &transname();
if ($upgrade) {
	&copy_source_dest($cfile, $oldcfile);
	}

# Extract tar file to temp dir and copy to target
local $temp = &transname();
local $err = &extract_script_archive($files->{'source'}, $temp, $d,
                                     $opts->{'dir'},
				     $ver >= 6 && $ver < 6.2 ? "vtigerCRM"
							     : "vtigercrm");
$err && return (0, "Failed to extract source : $err");

# Make files and sub-directories writable
foreach my $sd ("config.inc.php", "cache", "test/wordtemplatedownload",
	        "storage", "install", "install.php", "test/product",
		"test/user", "test/contact", "test/logo",
		"modules/Emails/templates", "user_privileges",
		"Smarty/templates_c", "tabdata.php", "parent_tabdata.php",
		"Smarty/cache", "logs", "modules/Webmails/tmp/",
		"modules", "cron/modules", "test/vtlib", "test/vtlib/HTML",
	        "backup", "Smarty/templates/modules") {
	&make_file_php_writable($d, "$opts->{'dir'}/$sd");
	}

local $url = &script_path_url($d, $opts);
local $noslash = $url;
$noslash =~ s/\/$//;
if ($upgrade) {
	# Put back original config file
	&copy_source_dest_as_domain_user($d, $oldcfile, $cfile);
	}
else {
	# Make config.php writable, for version 5.1+ install
	&make_file_php_writable($d, $cfile);

	# Setup the Cron job
	&create_script_wget_job($d, $url."SendReminder.php", '*', '*');
	}

# Tell the user about the new install
local $rp = $opts->{'dir'};
$rp =~ s/^$d->{'home'}\///;
local $installurl = $ver >= 6 ? $url : $url."install.php";
return (1, "Initial Vtiger CRM installation complete. Go to <a target=_blank href='$installurl'>$installurl</a> to complete the process.<br>For filling database credentials use for host <tt>$dbhost</tt>, for name <tt>$dbname</tt>, for user <tt>$dbuser</tt> and for password use <tt>$dbpass</tt>.", "Under $rp using $dbtype database $dbname", $url);
}

# script_vtigercrm_uninstall(&domain, version, &opts)
# Un-installs a Vtiger CRM installation, by removing it's files
# Returns 1 on success and a message, or 0 on failure and an error
sub script_vtigercrm_uninstall
{
local ($d, $version, $opts) = @_;

# Remove vtigercrm tables from the database
local $tries = 0;
while(1) {
	local $err = &cleanup_script_database($d, $opts->{'db'},
					      '(vtiger_|com_vtiger_)');
	last if (!$err);
	if ($tries++ > 1000) {
		return (0, "Failed to delete all vTigerCRM tables ".
			   "after 1000 attempts : $err");
		}
	}

# Remove the contents of the target directory
local $derr = &delete_script_install_directory($d, $opts);
return (0, $derr) if ($derr);

# Take out the DB
if ($opts->{'newdb'}) {
	&delete_script_database($d, $opts->{'db'});
	}

# Find and remove the Cron job
&delete_script_wget_job($d, $sinfo->{'url'}."SendReminder.php");

return (1, "Deleted Vtiger CRM directory and tables.");
}

sub script_vtigercrm_stop
{
local ($d, $sinfo) = @_;
&delete_script_wget_job($d, $sinfo->{'url'}."SendReminder.php");
}

# script_vtigercrm_check_latest(version)
sub script_vtigercrm_check_latest
{
local ($ver) = @_;
local @vers = &osdn_package_versions("vtigercrm",
				     "vtigercrm-?([0-9\\.]+)\\.tar\\.gz");
if ($ver < 5.1) {
	@vers = grep { $_ < 5.1 } @vers;
	}
return "Failed to find versions" if (!@vers);
return $ver eq $vers[0] ? undef : $vers[0];
}

sub script_vtigercrm_site
{
return 'http://www.vtigercrm.com/';
}

sub script_sugarcrm_passmode
{
local ($d, $version) = @_;
return 0;
}

1;

