
@textpattern_tables = (
    "textpattern",
    "txp_category",
    "txp_css",
    "txp_discuss",
    "txp_discuss_ipban",
    "txp_discuss_nonce",
    "txp_file",
    "txp_form",
    "txp_image",
    "txp_lang",
    "txp_link",
    "txp_log",
    "txp_page",
    "txp_plugin",
    "txp_prefs",
    "txp_section",
    "txp_users"
    );

# script_textpattern_desc()
sub script_textpattern_desc
{
return "Textpattern";
}

sub script_textpattern_uses
{
return ( "php" );
}

sub script_textpattern_longdesc
{
return "A free, flexible, elegant, easy-to-use content management system for all kinds of websites, even weblogs";
}

# script_textpattern_versions()
sub script_textpattern_versions
{
return ( "4.8.8" );
}

sub script_textpattern_category
{
return "Blog";
}

sub script_textpattern_php_vers
{
return ( 5 );
}

sub script_textpattern_php_modules
{
return ( "mysql" );
}

sub script_textpattern_dbs
{
return ("mysql");
}

sub script_textpattern_release
{
return 3;	# Fix download URL
}

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

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

# script_textpattern_files(&domain, version, &opts, &upgrade-info)
# Returns a list of files needed by Textpattern, each of which is a hash ref
# containing a name, filename and URL
sub script_textpattern_files
{
local ($d, $ver, $opts, $upgrade) = @_;
local @files = ( { 'name' => "source",
	   'file' => "textpattern-$ver.zip",
	   'url' => "https://textpattern.com/File+download/118/textpattern-$ver.zip" } );
return @files;
}

sub script_textpattern_commands
{
return ("unzip");
}

# script_textpattern_install(&domain, version, &opts, &files, &upgrade-info)
# Actually installs Textpattern, and returns either 1 and an informational
# message, or 0 and an error
sub script_textpattern_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 = $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);

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

local $url = &script_path_url($d, $opts);
if (!$upgrade) {
	# Make config.php writable
	local $cfile = "$opts->{'dir'}/textpattern/config.php";

	# Get the first wizard form, which should set a cookie
	local $wout;
	local $ipage = $opts->{'path'}."/textpattern/setup/index.php";
	&get_http_connection($d, $ipage, \$wout, undef, \&capture_http_headers);
	local $txp_cookie;
	if ($post_http_headers->{'set-cookie'} =~ /(PHPSESSID=[a-z0-9]+)/i) {
		$txp_cookie = $1;
		}
	else {
		return (-1, "Failed to get session cookie");
		}
	local %headers = ( 'Cookie', $txp_cookie );

	# Call the first wizard page
	local $resturl = $url;
	$resturl =~ s/^(http|https):\/\///g;
	$resturl =~ s/\/$//;
	local @params = (
		[ "duser", $dbuser ],
		[ "dpass", $dbpass ],
		[ "dhost", $dbhost ],
		[ "ddb", $dbname ],
		[ "dprefix", "" ],
		[ "siteurl", $resturl ],
		[ "step", "printConfig" ],
		);
	local $params = join("&", map { $_->[0]."=".&urlize($_->[1]) } @params);

	# Make an HTTP post to the installer page
	local ($iout, $ierror);
	&post_http_connection($d, $ipage, $params, \$iout, \$ierror, \%headers);
	if ($ierror) {
		return (-1, "Textpattern post-install configuration failed : $ierror");
		}

	# Parse out the suggested config, and paste into config.php
	if ($iout =~ /<textarea[^>]*>([\000-\377]*)<\/textarea>/i) {
		&open_tempfile_as_domain_user($d, CFILE, ">$cfile");
		&print_tempfile(CFILE, $1);
		&close_tempfile_as_domain_user($d, CFILE);
		&set_permissions_as_domain_user($d, 0750, $cfile);
		}
	else {
		return (-1, "Textpattern post-install configuration failed : $iout");
		}

	# Call the 'I did it' URL
	local @params = (
		[ "step", "getTxpLogin" ],
		);
	local $params = join("&", map { $_->[0]."=".&urlize($_->[1]) } @params);
	&post_http_connection($d, $ipage, $params, \$iout, \$ierror, \%headers);
	if ($ierror) {
		return (-1, "Textpattern config creation failed : $ierror");
		}

	# Call the admin user creation URL
	local @params = (
		[ "RealName", $d->{'owner'} ],
		[ "name", $domuser ],
		[ "pass", $dompass ],
		[ "email", $d->{'emailto_addr'} ],
		[ "theme", "classic" ],
		[ "step", "createTxp" ],
		);
	local $params = join("&", map { $_->[0]."=".&urlize($_->[1]) } @params);
	&post_http_connection($d, $ipage, $params, \$iout, \$ierror, \%headers);
	if ($ierror) {
		return (-1, "Textpattern database creation failed : $ierror");
		}
	elsif ($iout !~ /Database\s+tables\s+were\s+created/i) {
		return (-1, "Textpattern database creation failed");
		}

	# Delete the setup script
	&run_as_domain_user($d, "rm -rf ".
				 quotemeta("$opts->{'dir'}/textpattern/setup"));
	}

# Tell the user about the new install
local $adminurl = $url."textpattern/";
local $rp = $opts->{'dir'};
$rp =~ s/^$d->{'home'}\///;
return (1, "Textpattern installation complete. Go to <a target=_blank href='$adminurl'>$adminurl</a> to manage it.", "Under $rp", $url, $domuser, $dompass);
}

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

# Remove textpattern tables from the database
&cleanup_script_database($d, $opts->{'db'}, \@textpattern_tables);

# 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, "Deleted Textpattern directory and tables.");
}

# script_textpattern_latest()
# Returns a URL and regular expression or callback func to get the version
sub script_textpattern_latest
{
return ( "http://www.textpattern.com/download",
	 "textpattern-([0-9\\.]+)\\.zip" );
}

sub script_textpattern_site
{
return 'http://www.textpattern.com/';
}

sub script_textpattern_passmode
{
return 1;
}

1;

