
# script_cmsmadesimple_desc()
sub script_cmsmadesimple_desc
{
return "CMS Made Simple";
}

sub script_cmsmadesimple_uses
{
return ( "php" );
}

sub script_cmsmadesimple_longdesc
{
return "CMS Made Simple makes it easy to set up a site and then hand it over to non-techies to maintain";
}

# script_cmsmadesimple_versions()
sub script_cmsmadesimple_versions
{
return ( "2.2.16", "1.12.1" );
}

sub script_cmsmadesimple_category
{
return "CMS";
}

sub script_cmsmadesimple_php_vers
{
return ( 5 );
}

sub script_cmsmadesimple_release
{
return 2;	# Fix download URL
}

sub script_cmsmadesimple_php_modules
{
return ("mysql");
}

sub script_cmsmadesimple_dbs
{
return ("mysql");
}

sub script_cmsmadesimple_php_fullver
{
my ($d, $ver, $sinfo) = @_;
return "5.6";
}

sub script_cmsmadesimple_php_vars
{
return ( [ 'post_max_size', '10M', '+' ],
	 [ 'upload_max_filesize', '10M', '+' ],
	 [ 'memory_limit', '24M', '+' ],
	 [ 'max_execution_time', '60', '+' ],
       );
}

# script_cmsmadesimple_params(&domain, version, &upgrade-info)
# Returns HTML for table rows for options for installing CMS Made Simple
sub script_cmsmadesimple_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 CMS Made Simple 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 CMS Made Simple tables",
		     &ui_database_select("db", undef, \@dbs, $d, "cms"));
	$rv .= &ui_table_row("Install sub-directory under <tt>$hdir</tt>",
			     &ui_opt_textbox("dir", &substitute_scriptname_template("cms", $d), 30, "At top level"));
	}
return $rv;
}

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

# script_cmsmadesimple_files(&domain, version, &opts, &upgrade-info)
# Returns a list of files needed by CMS Made Simple, each of which is a hash ref
# containing a name, filename and URL
sub script_cmsmadesimple_files
{
local ($d, $ver, $opts, $upgrade) = @_;
local @files = ( { 'name' => "source",
	   'file' => $ver > 2 ? "cmsms-$ver-install.zip"
			      : "cmsmadesimple-$ver-full.tar.gz",
	   'url' => $ver > 2 ? 
		"http://s3.amazonaws.com/cmsms/downloads/14832/cmsms-$ver-install.zip" :
		"http://s3.amazonaws.com/cmsms/downloads/12800/cmsmadesimple-$ver-english.tar.gz" } );
return @files;
}

sub script_cmsmadesimple_commands
{
return ("tar", "gunzip");
}

# script_cmsmadesimple_install(&domain, version, &opts, &files, &upgrade-info)
# Actually installs CMS Made Simple, and returns either 1 and an informational
# message, or 0 and an error
sub script_cmsmadesimple_install
{
local ($d, $version, $opts, $files, $upgrade, $domuser, $dompass) = @_;
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 = &mysql_user($d);
local $dbpass = &mysql_pass($d);
local $dbhost = &get_database_host("mysql", $d);
local $dberr = &check_script_db_connection($dbtype, $dbname, $dbuser, $dbpass);
return (0, "Database connection failed : $dberr") if ($dberr);

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

# Make important directories writable
&make_file_php_writable($d, "$opts->{'dir'}/tmp");
&make_file_php_writable($d, "$opts->{'dir'}/uploads");
&make_file_php_writable($d, "$opts->{'dir'}/modules");
if (!-r $cfile) {
	&open_tempfile_as_domain_user($d, TOUCH, ">$cfile", 0, 1);
	&close_tempfile_as_domain_user($d, TOUCH);
	&make_file_php_writable($d, $cfile, 0, 1);
	}

# Work out URL paths
local $url = &script_path_url($d, $opts);
local $rp = $opts->{'dir'};
$rp =~ s/^$d->{'home'}\///;

if ($upgrade) {
	# Put back the config file
	&copy_source_dest_as_domain_user($d, $oldcfile, $cfile);

	local $upgradeurl = $url."install/upgrade.php";
	return (1, "CMS Made Simple upgrade complete. Go to <a target=_blank href='$upgradeurl'>$upgradeurl</a> to complete the upgrade process.", "Under $rp using $dbphptype database $dbname", $url, $domuser, $dompass);
	}
elsif ($ver < 2) {
	# Make an HTTP request to get the cookie
	local ($iout, $ierror, $cms_cookie);
	&get_http_connection($d, "$opts->{'path'}/install/", \$iout, \$ierror,
			     \&capture_http_headers);
	if ($ierror) {
		return (-1, "CMS Made Easy first page failed : $ierror");
		}
	if ($post_http_headers->{'set-cookie'} =~ /(PHPSESSID=[a-z0-9]+)/i) {
		$cms_cookie = $1;
		}
	else {
		return (-1, "Failed to get session cookie");
		}
	local %headers = ( 'Cookie', $cms_cookie );

	# Call DB setup page
	local @params = (
		[ "umask", "022" ],
		[ "page", 6 ],
		[ "default_cms_lang", "en_US" ],
		[ "adminusername", $domuser ],
		[ "adminemail", $d->{'emailto_addr'} ],
		[ "adminpassword", $dompass ],
		[ "adminpasswordagain", $dompass ],
		[ "email_accountinfo", 1 ],
		[ "sitename", "$d->{'owner'} CMS" ],
		[ "dbms", "mysql" ],
		[ "host", $dbhost ],
		[ "database", $dbname ],
		[ "username", $dbuser ],
		[ "password", $dbpass ],
		[ "db_port", "" ],
		[ "prefix", "cms_" ],
		[ "createtables", 1 ],
		[ "createextra", 1 ],
		);
	local $params = join("&", map { $_->[0]."=".&urlize($_->[1]) } @params);
	local $ipage = $opts->{'path'}."/install/index.php";
	local ($iout, $ierror);
	&post_http_connection($d, $ipage, $params, \$iout, \$ierror, \%headers);
	if ($ierror) {
		return (-1, "CMS Made Easy database setup failed : $ierror");
		}
	elsif ($iout !~ /Creating\s+additional_users\s+table/i) {
		return (-1, "CMS Made Easy database setup failed");
		}

	# Call config creation page
	@params = grep { $_->[0] ne 'page' } @params;
	local $noslash = $opts->{'dir'};
	$noslash =~ s/\/$//;
	push(@params, [ 'page', 7 ],
		      [ 'docroot', "http://www.$d->{'dom'}$opts->{'path'}" ],
		      [ 'docpath', $noslash ],
		      [ 'querystr', 'page' ],
		      [ 'frontendlang', 'en_US' ],
		      [ 'default_encoding', 'utf-8' ],
		      );
	local $params = join("&", map { $_->[0]."=".&urlize($_->[1]) } @params);
	local $ipage = $opts->{'path'}."/install/index.php";
	local ($iout, $ierror);
	&post_http_connection($d, $ipage, $params, \$iout, \$ierror, \%headers);
	if ($ierror) {
		return (-1, "CMS Made Easy configuration failed : $ierror");
		}
	elsif ($iout !~ /Congratulations/i) {
		return (-1, "CMS Made Easy configuration failed");
		}

	local $adminurl = $url."admin/";
	return (1, "CMS Made Simple installation complete. It can be managed at <a target=_blank href='$adminurl'>$adminurl</a> .", "Under $rp using $dbphptype database $dbname", $url, $domuser, $dompass);
	}
else {
	# For newer versions, tell the user to perform the install
	local $adminurl = $url."cmsms-${ver}-install.php";
	return (1, "Initial CMS Made Simple installation complete. Please complete the installation process at <a target=_blank href='$adminurl'>$adminurl</a> .", "Under $rp using $dbphptype database $dbname", $url);
	}

}

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

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

# Remove all cmsmadesimple_ tables from the database
&cleanup_script_database($d, $opts->{'db'}, "cms_");

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

return (1, "CMS Made Simple directory and tables deleted.");
}

sub script_cmsmadesimple_db_conn_desc
{
my $db_conn_desc = 
    { 'config.php' =>
        {
           'dbpass' =>
           {
               'func'        => 'php_quotemeta',
               'func_params' => 1,
               'replace'     => [ '\$config\[[\'"]db_password[\'"]\]\s*=' =>
                                  '$config[\'db_password\'] = \'$$sdbpass\';' ],
           },
           'dbuser' =>
           {
               'replace'     => [ '\$config\[[\'"]db_username[\'"]\]\s*=' =>
                                  '$config[\'db_username\'] = \'$$sdbuser\';' ],
           },
        }
    };
return $db_conn_desc;
}

# script_cmsmadesimple_latest(version)
# Returns a URL and regular expression or callback func to get the version
sub script_cmsmadesimple_latest
{
local ($ver) = @_;
if ($ver < 2) {
	return ( );
	}
return ( "http://www.cmsmadesimple.org/downloads",
	 "Download\\s+([0-9\\.]+)<" );
}

sub script_cmsmadesimple_site
{
return 'http://www.cmsmadesimple.org/';
}

sub script_cmsmadesimple_passmode
{
local ($d, $ver) = @_;
return $ver < 2 ? 1 : 0;
}

1;

