
# script_opengoo_desc()
sub script_opengoo_desc
{
return "Feng Office";
}

sub script_opengoo_uses
{
return ( "php" );
}

sub script_opengoo_longdesc
{
return "A full-featured content management/discussion engine suitable to setup a news-driven community or portal site";
}

# script_opengoo_versions()
sub script_opengoo_versions
{
return ( "3.8.6.13" );
}

sub script_opengoo_can_upgrade
{
local ($sinfo, $newver) = @_;
if ($newver >= 2 && $sinfo->{'version'} < 2) {
	# Upgrade from 1.x to 2 isn't automatable
	return 0;
	}
return 1;
}

sub script_opengoo_php_vars
{
return ( [ 'memory_limit', '256M', '+' ], 
         [ 'register_globals', 'Off' ] );
}

sub script_opengoo_php_fullver
{
return 7.1;
}

sub script_opengoo_php_vers
{
return ( 5 );
}

sub script_opengoo_php_modules
{
return ("mysql", "gd");
}

sub script_opengoo_dbs
{
return ("mysql", "postgres");
}

# script_opengoo_params(&domain, version, &upgrade-info)
# Returns HTML for table rows for options for installing PHP-NUKE
sub script_opengoo_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 Feng Office 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", "postgres" ]);
	$rv .= &ui_table_row("Database for Feng Office tables",
		     &ui_database_select("db", undef, \@dbs, $d, "fengoffice"));
	$rv .= &ui_table_row("Install sub-directory under <tt>$hdir</tt>",
			     &ui_opt_textbox("dir", &substitute_scriptname_template("fengoffice", $d), 30, "At top level"));
	}
return $rv;
}

# script_opengoo_parse(&domain, version, &in, &upgrade-info)
# Returns either a hash ref of parsed options, or an error string
sub script_opengoo_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_opengoo_check(&domain, version, &opts, &upgrade-info)
# Returns an error message if a required option is missing or invalid
sub script_opengoo_check
{
local ($d, $ver, $opts, $upgrade) = @_;
$opts->{'dir'} =~ /^\// || return "Missing or invalid install directory";
$opts->{'db'} || return "Missing database";
if (-r "$opts->{'dir'}/config/config.php") {
	return "Feng Office appears to be already installed in the selected directory";
	}
local ($dbtype, $dbname) = split(/_/, $opts->{'db'}, 2);
local $clash = &find_database_table($dbtype, $dbname, "(og|fo)_.*");
$clash && return "Feng Office appears to be already using the selected database (table $clash)";
return undef;
}

# script_opengoo_files(&domain, version, &opts, &upgrade-info)
# Returns a list of files needed by Feng Office, each of which is a hash ref
# containing a name, filename and URL
sub script_opengoo_files
{
local ($d, $ver, $opts, $upgrade) = @_;
local @files = ( { 'name' => "source",
	   'file' => "fengoffice_${ver}.zip",
	   'url' => "https://github.com/fengoffice/fengoffice/archive/refs/tags/$ver.zip" } );
return @files;
}

sub script_opengoo_commands
{
return ("unzip");
}

# script_opengoo_install(&domain, version, &opts, &files, &upgrade-info)
# Actually installs Feng Office, and returns either 1 and an informational
# message, or 0 and an error
sub script_opengoo_install
{
local ($d, $version, $opts, $files, $upgrade) = @_;

# Get DB details
local ($out, $ex);
if ($opts->{'newdb'} && !$upgrade) {
	local $err = &create_script_database($d, $opts->{'db'});
	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);

# Copy old config file
local $oldcfile = &transname();
local $cfile = "$opts->{'dir'}/config/config.php";
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'},
			     "fengoffice-$version");
$err && return (0, "Failed to extract source : $err");

# Make needed directories writable
foreach my $dir ("public/files", "cache", "upload", "tmp") {
	&make_file_php_writable($d, "$opts->{'dir'}/$dir", 1);
	}

local $url = &script_path_url($d, $opts);
local $noslash = $url;
$noslash =~ s/\/$//;
if ($upgrade) {
	# Put back config file
	&copy_source_dest_as_domain_user($d, $oldcfile, $cfile);

	# Open the upgrade form (to get cookie)
	$opengoo_session_cookie = undef;
	local $ipage = $opts->{'path'}."/public/upgrade/";
	local ($iout, $ierror);
	&get_http_connection($d, $ipage, \$iout, \$ierror,
		       \&opengoo_cookie_callback, 0, undef, undef, undef, 0, 1);
	if ($ierror) {
		return (-1, "Failed to get PHP session cookie : $ierror");
		}
	elsif (!$opengoo_session_cookie) {
		return (-1, "Failed to get PHP session cookie");
		}
	local %headers = ( 'Cookie' => 'PHPSESSID='.$opengoo_session_cookie );

	# Submit the upgrade form
	my $ufrom = $upgrade->{'version'};
	my $uto = $version;
	$ufrom =~ s/^(\d+\.\d+)\.0$/$1/;
	$uto =~ s/^(\d+\.\d+)\.0$/$1/;
	local @params = ( [ "form_data[upgrade_from]", $ufrom ],
			  [ "form_data[upgrade_to]", $uto ],
			  [ "submited", "submited" ], );
	local $params = join("&", map { $_->[0]."=".&urlize($_->[1]) } @params);
	local ($iout, $ierror);
	&post_http_connection($d, $ipage."index.php", $params, \$iout, \$ierror,
			      \%headers);
	if ($ierror && $ierror !~ /index\.php/) {
		return (-1, "Upgrade failed : $ierror");
		}
	}
else {
	# Call wizard page 1 (to get cookie)
	$opengoo_session_cookie = undef;
	local $ipage = $opts->{'path'}."/public/install/index.php";
	local ($iout, $ierror);
	&get_http_connection($d, $ipage, \$iout, \$ierror,
		       \&opengoo_cookie_callback, 0, undef, undef, undef, 0, 1);
	if ($ierror) {
		return (-1, "Failed to get PHP session cookie : $ierror");
		}
	elsif (!$opengoo_session_cookie) {
		return (-1, "Failed to get PHP session cookie");
		}

	# Call wizard page 2 (confirm configs)
	local @params = ( [ "submited", "submited" ] );
	local $params = join("&", map { $_->[0]."=".&urlize($_->[1]) } @params);
	local ($iout, $ierror);
	&post_http_connection($d, $ipage."?step=2", $params, \$iout, \$ierror);
	if ($ierror && $ierror !~ /index.php\?step=3/) {
		return (-1, "Environment check failed : $ierror");
		}
	elsif ($iout =~ /Error:\s*([^<\n])*/i) {
		return (-1, "Environment check failed : $1");
		}
	local %headers = ( 'Cookie' => 'PHPSESSID='.$opengoo_session_cookie );

	# Call page 3 (DB setup)
	local @params = ( [ "config_form[database_type]", "mysqli" ],
		 	  [ "config_form[database_host]", $dbhost ],
			  [ "config_form[database_user]", $dbuser ],
			  [ "config_form[database_pass]", $dbpass ],
			  [ "config_form[database_name]", $dbname ],
			  [ "config_form[database_prefix]", "fo_" ],
			  [ "config_form[absolute_url]", $noslash ],
			  [ "config_form[database_engine]", "InnoDB" ],
			  [ "config_form[plugins][]", "core_dimensions" ],
			  [ "config_form[plugins][]", "workspaces" ],
			  [ "config_form[plugins][]", "mail" ],
			  [ "submited", "submited" ] );
	local $params = join("&", map { $_->[0]."=".&urlize($_->[1]) } @params);
	local ($iout, $ierror);
	&post_http_connection($d, $ipage."?step=3", $params, \$iout, \$ierror,
			      \%headers);
	if ($ierror && $ierror !~ /index.php\?step=4/) {
		return (-1, "System settings failed : $ierror");
		}
	elsif ($iout !~ /established\s+successfully/i) {
		return (-1, "System settings failed");
		}

	# Call page 4 to complete process
	local ($iout, $ierror);
	&get_http_connection($d, $ipage."?step=4", \$iout, \$ierror, undef, 0,
		       undef, undef, 0, 0, 1, \%headers);
	if ($ierror) {
		return (-1, "Final configuration failed : $ierror");
		}
	if ($iout !~ /established\s+successfully|Complete\s+the\s+installation/i) {
		return (-1, "Final configuration failed");
		}
	}

# Return a URL for the user
local $rp = $opts->{'dir'};
$rp =~ s/^$d->{'home'}\///;
local $iurl = $url."install.php";
return (1, "Feng Office installation complete. It can be accessed at <a target=_blank href='$url'>$url</a>.",
	"Under $rp using $dbphptype database $dbname", $url);
}

# script_opengoo_uninstall(&domain, version, &opts)
# Un-installs a Feng Office installation, by deleting the directory and database.
# Returns 1 on success and a message, or 0 on failure and an error
sub script_opengoo_uninstall
{
local ($d, $version, $opts) = @_;

# Remove opengoo tables from the database
&cleanup_script_database($d, $opts->{'db'}, "(og|fo)_");

# 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'});
	}

return (1, "Feng Office directory and tables deleted.");
}

sub script_opengoo_db_conn_desc
{
my $db_conn_desc = 
    { 'config/config.php' =>
        {
           'dbpass' => 
           {
               'replace' => [ 'define\(\s*[\'"]DB_PASS[\'"],' =>
                              'define(\'DB_PASS\', \'$$sdbpass\');' ],
               'func' => 'php_quotemeta',
               'func_params' => 1,
           },
           'dbuser' => 
           {
               'replace' => [ 'define\(\s*[\'"]DB_USER[\'"],' => "define('DB_USER', '\$\$sdbuser');" ],
           },
        }
    };
return $db_conn_desc;
}

# script_opengoo_latest(version)
# Checks if some version is the latest for this project, and if not returns
# a newer one. Otherwise returns undef.
sub script_opengoo_latest
{
my ($ver) = @_;
return ( "https://github.com/fengoffice/fengoffice/tags", 
         '>\s*([0-9]+\\.[0-9\\.]+)\s*<' );
}

sub script_opengoo_site
{
return 'http://www.fengoffice.com/';
}

sub opengoo_cookie_callback
{
if ($header{'set-cookie'} =~ /PHPSESSID=([^ ;]+)/ ||
    $WebminCore::header{'set-cookie'} =~ /PHPSESSID=([^ ;]+)/) {
	$opengoo_session_cookie = $1;
	}
}

1;

