
# script_drupal_desc()
sub script_drupal_desc
{
return "Drupal";
}

sub script_drupal_uses
{
return ( "php" );
}

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

# script_drupal_versions(for-install)
sub script_drupal_versions
{
return ( "10.0.2", "9.5.2", "8.9.20", "7.94" );
}

sub script_drupal_release
{
return 3;	# Version bump down to 8.8.6
}

sub script_drupal_can_upgrade
{
local ($sinfo, $newver) = @_;
if ($newver >= 6 && $sinfo->{'version'} < 6) {
	# Cannot upgrade 5 -> 6
	return 0;
	}
elsif ($newver >= 7 && $sinfo->{'version'} < 7) {
	# Cannot upgrade 6 -> 7
	return 0;
	}
elsif ($newver >= 8 && $sinfo->{'version'} < 8) {
	# Cannot upgrade 7 -> 8
	return 0;
	}
elsif ($newver >= 9 && $sinfo->{'version'} < 9) {
	# Cannot upgrade 8 -> 9
	return 0;
	}
return 1;
}

sub script_drupal_category
{
return ("CMS", "Community", "Commerce");
}

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

sub script_drupal_php_vers
{
return ( 5 );
}

sub script_drupal_php_modules
{
return ( "mysql", "gd", "xml", "date",
         "json", "mbstring", "curl" );
}

sub script_drupal_php_optional_modules
{
return ( "tokenizer" );
}

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

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

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

# script_drupal_parse(&domain, version, &in, &upgrade-info)
# Returns either a hash ref of parsed options, or an error string
sub script_drupal_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_drupal_check(&domain, version, &opts, &upgrade-info)
# Returns an error message if a required option is missing or invalid
sub script_drupal_check
{
local ($d, $ver, $opts, $upgrade) = @_;
$opts->{'dir'} =~ /^\// || return "Missing or invalid install directory";
$opts->{'db'} || return "Missing database";
if (-r "$opts->{'dir'}/sites/default/settings.php") {
	return "Drupal appears to be already installed in the selected directory";
	}
local ($dbtype, $dbname) = split(/_/, $opts->{'db'}, 2);
local $clash = &find_database_table($dbtype, $dbname,
				    $ver >= 5.1 ? "drupal_.*" : "access");
$clash && return "Drupal appears to be already using the selected database (table $clash)";
return undef;
}

# script_drupal_files(&domain, version, &opts, &upgrade-info)
# Returns a list of files needed by Drupal, each of which is a hash ref
# containing a name, filename and URL
sub script_drupal_files
{
local ($d, $ver, $opts, $upgrade) = @_;
if ($d && &has_drupal_cli() && !$opts->{'nodrush'}) {
	# Drush does the downloads for us
	return ( );
	}
local @files = ( { 'name' => "source",
	   'file' => "drupal-$ver.tar.gz",
	   'url' => "http://ftp.drupal.org/files/projects/drupal-$ver.tar.gz" } );
return @files;
}

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

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

# Check for an un-supported upgrade
if ($upgrade) {
	my $ver_curr = int($version);
	my $ver_next =  int($upgrade->{'version'});
	if($ver_curr && $ver_next && $ver_curr != $ver_next) {
		return (0, "Unattended Drupal upgrades from version $ver_next to $ver_curr are not supported");
		}
	}

# 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);
local $cfile = &compare_versions($ver, 4.6) >= 0 ?
			"$opts->{'dir'}/sites/default/settings.php" :
			"$opts->{'dir'}/includes/conf.php";

my @rv;
local $url = &script_path_url($d, $opts);
if (&has_drupal_cli() && !$opts->{'nodrush'}) {
	# Download the new Drupal version
	my $drush = "cd ".quotemeta($opts->{'dir'})." && yes y | ".&has_command("drush");
	my $rp = $opts->{'dir'};
	$rp =~ s/^$d->{'home'}\///;
	if ($upgrade) {
		my $out = &run_as_domain_user($d, "$drush pm-update drupal-$ver 2>&1");
		if ($?) {
			return (-1, "drush pm-update failed : $out");
			}
		@rv = (1, "Drupal upgrade complete.",
			"Under $rp using $dbphptype database $dbname", $url,
			$domuser, $dompass);
		}
	else {
		&make_dir_as_domain_user($d, $opts->{'dir'}, 0755);
		my $out = &run_as_domain_user($d, "$drush dl drupal-$ver 2>&1");
		if ($?) {
			return (-1, "drush dl failed : $out");
			}
		$out = &run_as_domain_user($d, "cd ".quotemeta($opts->{'dir'})." && mv drupal-$ver/* drupal-$ver/.??* . && rmdir drupal-$ver");
		if ($?) {
			return (-1, "Moving files failed : $out");
			}

		# Install into the selected database
		my $out = &run_as_domain_user($d, "$drush si standard --db-url=${dbphptype}://${dbuser}:${dbpass}\@${dbhost}/${dbname} --db-prefix=drupal_ --account-name=$domuser --account-pass=$dompass --account-mail=$d->{'emailto'} 2>&1");
		if ($?) {
			return (-1, "drush si failed : $out");
			}

		# Return a URL for the user
		@rv = (1, "Drupal installation complete. It can be accessed at <a target=_blank href='$url'>$url</a>.",
		       "Under $rp using $dbphptype database $dbname", $url,
		       $domuser, $dompass);
		}
	}
else {
	# Extract tar file to temp dir and copy to target
	local $temp = &transname();
	local $err = &extract_script_archive($files->{'source'}, $temp, $d,
					     $opts->{'dir'}, "drupal-$ver");
	$err && return (0, "Failed to extract source : $err");
	local $cfilesrc = "$opts->{'dir'}/sites/default/default.settings.php";
	-r $cfile || -r $cfilesrc ||
		return (0, "Failed to copy source : <tt>$out</tt>.");
	&run_as_domain_user($d, "cp -p ".quotemeta($temp)."/drupal-$ver/.htaccess ".
				quotemeta($opts->{'dir'}));

	local $noslash = $url;
	$noslash =~ s/\/$//;
	if ($upgrade && &compare_versions($ver, 6.2) >= 0) {
		# Nothing to do, hopefully
		}
	elsif (&compare_versions($ver, 7.0) >= 0) {
		# Copy and modify settings.php
		if (!-r $cfile) {
			&copy_source_dest_as_domain_user($d, $cfilesrc, $cfile);
			}
		&make_file_php_writable($d, $cfile, 0, 1);

		# Set the base_url and DB spec in settings.php
		local $lref = &read_file_lines_as_domain_user($d, $cfile);
		foreach my $l (@$lref) {
			if ($l =~ /^\s*#*\s*\$databases\s*=/) {
				local $driver = $dbtype eq "mysql" ? "mysql" : "pgsql";
				$dbhost ||= "localhost";
				$l = "\$databases['default']['default'] = array('driver' => '$driver', 'database' => '$dbname', 'username' => '$dbuser', 'password' => '$dbpass', 'host' => '$dbhost', 'prefix' => 'drupal_');";
				}
			}
		&flush_file_lines_as_domain_user($d, $cfile);
		}
	elsif (&compare_versions($ver, 6.2) >= 0) {
		# Copy and modify settings.php
		if (!-r $cfile) {
			&copy_source_dest_as_domain_user($d, $cfilesrc, $cfile);
			}
		&make_file_php_writable($d, $cfile, 0, 1);

		# Set the base_url and DB spec in settings.php
		local $lref = &read_file_lines_as_domain_user($d, $cfile);
		foreach my $l (@$lref) {
			if ($l =~ /^\s*#*\s*\$base_url\s*=/) {
				$l = "\$base_url = '$noslash';";
				}
			elsif ($l =~ /^\$db_url\s*=/) {
				local $driver = $dbtype eq "mysql" ? "mysql" : "pgsql";
				$dbhost ||= "localhost";
				$l = "\$db_url = '${driver}://${dbuser}:".
					&php_quotemeta($dbpass, 1)."\@$dbhost/${dbname}';";
				}
			elsif ($l =~ /^\$db_prefix\s*=/) {
				$l = "\$db_prefix = 'drupal_';";
				}
			}
		&flush_file_lines_as_domain_user($d, $cfile);
		}
	elsif ($ver >= 5.1) {
		# Use HTTP request to setup

		# Create settings.php and make writable
		if (!-r $cfile) {
			&copy_source_dest_as_domain_user($d, $cfilesrc, $cfile);
			}
		&make_file_php_writable($d, $cfile, 0, 1);
		&make_file_php_writable($d, "$opts->{'dir'}/sites/default");

		if (&compare_versions($ver, 5.2) >= 0 && -r $cfile) {
			# Set the base_url in settings.php
			local $lref = &read_file_lines_as_domain_user($d, $cfile);
			foreach my $l (@$lref) {
				if ($l =~ /^\s*#*\s*\$base_url\s*=/) {
					$l = "\$base_url = '$noslash';";
					}
				}
			&flush_file_lines_as_domain_user($d, $cfile);
			}

		# Trigger the installation PHP script
		local @params = (
			[ "db_type", $dbtype eq "mysql" ? "mysql" : "pgsql" ],
			[ "db_path", $dbname ],
			[ "db_user", $dbuser ],
			[ "db_pass", $dbpass ],
			[ "db_host", $dbhost ],
			[ "db_port", "" ],
			[ "db_prefix", "drupal_" ],
			[ "form_id", "install_settings_form" ],
			);
		local $params = join("&", map { $_->[0]."=".&urlize($_->[1]) } @params);
		local $ipage = $opts->{'path'}."/core/install.php?profile=default";

		# Make an HTTP post to the installer page
		local ($iout, $ierror);
		&post_http_connection($d, $ipage, $params, \$iout, \$ierror);
		if ($ierror && $ierror !~ /302|404/) {
			# Redirects and 404s are OK, as sometimes we get a redirect
			# to the wrong URL
			return (-1,
				"Drupal post-install configuration failed : $ierror");
			}
		}
	else {
		# Update the config file
		local $lref = &read_file_lines_as_domain_user($d, $cfile);
		local $dburl = "$dbphptype://$dbuser:".&php_quotemeta($dbpass, 1).
			       "\@$dbhost/$dbname";
		local $pt = $d->{'web_port'} == 80 ? "" : ":$d->{'web_port'}";
		foreach $l (@$lref) {
			if ($l =~ /^\$db_url\s*=/) {
				$l = "\$db_url = '$dburl';"
				}
			if ($l =~ /^(# *)?\$base_url\s*=/) {
				local $p = $opts->{'path'} eq "/" ? "" : $opts->{'path'};
				$l = "\$base_url = 'http://$d->{'dom'}$pt$p';"
				}
			}
		&flush_file_lines_as_domain_user($d, $cfile);

		if (!$upgrade) {
			# Run the SQL setup script
			if ($dbtype eq "mysql") {
				local $sqlfile = "$opts->{'dir'}/database/database.4.1.mysql";
				&require_mysql();
				($ex, $out) = &mysql::execute_sql_file($dbname, $sqlfile, $dbuser, $dbpass);
				$ex && return (-1, "Failed to run database setup script : <tt>$out</tt>.");
				}
			elsif ($dbtype eq "postgres") {
				local $sqlfile = "$opts->{'dir'}/database/database.pgsql";
				&require_postgres();
				($ex, $out) = &postgresql::execute_sql_file($dbname, $sqlfile, $dbuser, $dbpass);
				$ex && return (-1, "Failed to run database setup script in $dbname : <tt>$out</tt>.");
				}
			}
		}

	# Return a URL for the user
	local $rp = $opts->{'dir'};
	$rp =~ s/^$d->{'home'}\///;
	local $iurl = $url."core/install.php";
	my $msg_upd = $upgrade ? 'upgrade' : 'installation';
	my $msg = $ver >= 6 && !$upgrade ?
		"Drupal initial installation finished. It can be completed at <a target=_blank href='$iurl'>$iurl</a>." :
		"Drupal $msg_upd complete. It can be accessed at <a target=_blank href='$url'>$url</a>.";
	@rv = (1, $msg,
		"Under $rp using $dbphptype database $dbname", $url);
	}

# Fix up code that generates .htaccess
local $ffile = "$opts->{'dir'}/includes/file.inc";
if (-r $ffile) {
	my $lref = &read_file_lines($ffile);
	foreach my $l (@$lref) {
		if ($l =~ /\$htaccess_lines\s*=/) {
			$l =~ s/FollowSymLinks/SymLinksifOwnerMatch/g;
			}
		$l =~ s/Options \+FollowSymLinks/Options +SymLinksifOwnerMatch/g;
		}
	&flush_file_lines($ffile);
	}

# Fix up actual .htaccess
local $hfile = "$opts->{'dir'}/.htaccess";
if (-r $hfile) {
	my $lref = &read_file_lines($hfile);
	foreach my $l (@$lref) {
		$l =~ s/Options \+FollowSymLinks/Options +SymLinksifOwnerMatch/g;
		}
	&flush_file_lines($hfile);
	}

if (&compare_versions($ver, 5.1) >= 0) {
	# Create the files sub-directory
	foreach my $dir ("$opts->{'dir'}/files",
			 "$opts->{'dir'}/sites/default/files") {
		&make_dir_as_domain_user($d, $dir, 0755);
		&make_file_php_writable($d, $dir);
		}

	# Setup the cron job
	&create_script_wget_job($d, $url."cron.php", int(rand()*60), '*', 1);
	}

# Make settings.php read-only
&make_file_php_nonwritable($d, $cfile);

return @rv;
}

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

# Remove drupal tables from the database
local ($dbtype, $dbname) = split(/_/, $opts->{'db'}, 2);
local $l;
if ($dbtype eq "mysql") {
	# Delete from MySQL
	&require_mysql();
	if (&compare_versions($version, 5.1) >= 0) {
		# Just delete all drupal_ tables
		&cleanup_script_database($d, $opts->{'db'}, "drupal_");
		}
	else {
		# Use original SQL file to find table names
		local $sqlfile = "$opts->{'dir'}/database/database.4.1.mysql";
		local $lref = &read_file_lines($sqlfile);
		local @tables;
		foreach $l (@$lref) {
			if ($l =~ /^\s*create\s+table\s+(\S+)/i) {
				push(@tables, $1);
				}
			}
		&cleanup_script_database($d, $opts->{'db'}, \@tables);
		}
	}
elsif ($dbtype eq "postgres") {
	# Delete from PostgreSQL
	if (&compare_versions($version, 5.1) >= 0) {
		# Just delete all drupal_ tables
		&cleanup_script_database($d, $opts->{'db'}, "drupal_");
		}
	else {
		# Use original SQL file to find table names
		local $sqlfile = "$opts->{'dir'}/database/database.pgsql";
		local $lref = &read_file_lines($sqlfile);
		local @tables;
		foreach my $l (@$lref) {
			if ($l =~ /^\s*create\s+table\s+(\S+)/i) {
				push(@tables, $1);
				}
			}
		&cleanup_script_database($d, $opts->{'db'}, \@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'});
	}

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

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

sub script_drupal_db_conn_desc
{
my $db_conn_desc = 
    { 'sites/default/settings.php' =>
        {
           'dbpass' =>
           {
               'func'        => 'php_quotemeta',
               'func_params' => 1,
               'replace'     => [ '[\'"]password[\'"]\s*=>\s*[\'"].*?[,\'"]+' =>
                                  '\'password\' => \'$$sdbpass\',' ],
               'after'       => 1,
           },
           'dbuser' =>
           {
               'replace'     => [ '[\'"]username[\'"]\s*=>\s*[\'"].*?[,\'"]+' =>
                                  '\'username\' => \'$$sdbuser\',' ],
               'after'       => 1,
           },
        }
    };
return $db_conn_desc;
}

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

# script_drupal_latest(version)
# Returns a URL and regular expression or callback func to get the version
sub script_drupal_latest
{
local ($ver) = @_;
if ($ver < 7) {
	return ( );
	}
my $pfx = $ver >= 10 ? 10 :
	  $ver >= 9 ? 9 :
	  $ver >= 8 ? 8 :
	  $ver >= 7 ? 7 : 6;
return ( "https://www.drupal.org/project/drupal/releases?version=$pfx",
	 "drupal ($pfx\\.[0-9\.]+)<" );
}

sub script_drupal_site
{
return 'http://drupal.org/';
}

sub script_drupal_passmode
{
return &has_drupal_cli() ? 1 : 0;
}

sub has_drupal_cli
{
return &has_command("drush");
}

1;

