
# script_moodle_desc()
sub script_moodle_desc
{
return "Moodle";
}

sub script_moodle_uses
{
return ( "php" );
}

# script_moodle_longdesc()
sub script_moodle_longdesc
{
return "Moodle is a course management system (CMS) to help educators create effective online learning communities";
}

# script_moodle_versions()
sub script_moodle_versions
{
return ( "4.1.1", "3.11.11", "2.9.9" );
}

sub script_moodle_abandoned
{
local ($ver) = @_;
return $ver < 2.4 ? 1 : 0;
}

sub script_moodle_release
{
return 1;
}

sub script_moodle_category
{
return "CMS";
}

sub script_moodle_php_vers
{
return ( 5 );
}

sub script_moodle_php_modules
{
local ($d, $ver, $phpver, $opts) = @_;
local ($dbtype, $dbname) = split(/_/, $opts->{'db'}, 2);
my @deps = $dbtype eq "mysql" ? ("mysql") : ("pgsql");
push(@deps, ("curl", "zip", "intl", "xmlrpc", "soap", "mbstring", "gd"));
return @deps;
}

sub script_moodle_php_optional_modules
{
return ( "sodium", "exif" );
}

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

sub script_moodle_php_fullver
{
local ($d, $ver, $sinfo) = @_;
return &compare_versions($ver, 3) >= 0 ? 7.3 : 5.4;
}

# script_moodle_php_vars(&domain)
# Returns an array of extra PHP variables needed for this script
sub script_moodle_php_vars
{
return ( [ 'max_execution_time', '300', '+' ],
         [ 'memory_limit', '512M', '+' ],
         [ 'max_input_time', '-1' ],
         [ 'max_input_vars', '5000', '+' ] );
}

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

# script_moodle_parse(&domain, version, &in, &upgrade-info)
# Returns either a hash ref of parsed options, or an error string
sub script_moodle_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_moodle_check(&domain, version, &opts, &upgrade-info)
# Returns an error message if a required option is missing or invalid
sub script_moodle_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 "Moodle appears to be already installed in the selected directory";
	}
local ($dbtype, $dbname) = split(/_/, $opts->{'db'}, 2);
local $clash = &find_database_table($dbtype, $dbname, "mdl_.*");
$clash && return "Moodle appears to be already using the selected database (table $clash)";
return undef;
}

# script_moodle_files(&domain, version, &opts, &upgrade-info)
# Returns a list of files needed by moodle, each of which is a hash ref
# containing a name, filename and URL
sub script_moodle_files
{
local ($d, $ver, $opts, $upgrade) = @_;
local $stver = $ver;
$stver =~ s/^(\d+)\.(\d+).*/$1$2/;
if ($stver =~ /^4/) {
	my $stver4 = $ver;
	$stver4 =~ s/(\.)/0/;
	$stver = $stver4;
	}
local $latest;
if ($ver =~ /^(2\.[6-9]+)/) {
	$latest = "-$1";
	}
else {
	$latest = "-${ver}";
	}
local @files = ( { 'name' => "source",
	   'file' => "moodle-$ver.zip",
	   'url' => "https://download.moodle.org/stable${stver}/moodle${latest}.zip" } );
return @files;
}

sub script_moodle_commands
{
return ("unzip", "wget");
}

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

# Check for an un-supported upgrade
if ($upgrade && $version >= 1.9 && $upgrade->{'version'} < 1.7) {
	return (0, "Moodle cannot be upgraded from versions below 1.7 to version 1.9 directly. You must upgrade to 1.7 first, convert your database to Unicode, then upgrade to 1.9");
	}

# Check DB connection
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);
if ($ver >= 2.0 && $dbtype eq "mysql") {
	$dbtype = "mysqli";
	}
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);

# Extract tar file to temp dir and copy to target
local $temp = &transname();
local $err = &extract_script_archive($files->{'source'}, $temp, $d,
                                     $opts->{'dir'}, "moodle");
$err && return (0, "Failed to extract source : $err");
local $cfile = "$opts->{'dir'}/config.php";
if (!-r $cfile) {
	local $cdef = "$opts->{'dir'}/config-dist.php";
	&run_as_domain_user($d, "cp ".quotemeta($cdef)." ".quotemeta($cfile),);
	}

my $d_nginx = &domain_has_website($d) eq 'virtualmin-nginx';
my $d_ssl = domain_has_ssl($d);

# Update database details in config.php
local $url = &script_path_url($d, $opts);
local $lref = &read_file_lines_as_domain_user($d, $cfile);
local $l;
local ($myver, $variant) = &get_dom_remote_mysql_version($d);
$dbtype = 'mariadb' if ($variant eq 'mariadb');

foreach $l (@$lref) {
    if ($l =~ /^\$CFG->dbtype\s*=/) {
		$l = "\$CFG->dbtype = \'$dbtype\';";
		}
    if ($l =~ /^\$CFG->dbhost\s*=/) {
		$l = "\$CFG->dbhost = \'$dbhost\';";
		}
	if ($l =~ /^\$CFG->dbuser\s*=/) {
		$l = "\$CFG->dbuser = \'$dbuser\';";
		}
	if ($l =~ /^\$CFG->dbpass\s*=/) {
		$l = "\$CFG->dbpass = \'".&php_quotemeta($dbpass, 1)."\';";
		}
    if ($l =~ /^\$CFG->prefix\s*=/) {
		$l = "\$CFG->prefix = \'mdl_\';";
		}
    if ($l =~ /^\$CFG->dbname\s*=/) {
		$l = "\$CFG->dbname = \'$dbname\';";
		}
    if ($l =~ /^\$CFG->dbpersist\s*=/) {
		$l = "\$CFG->dbpersist = \'false\';";
		}
	if ($l =~ /^\$CFG->wwwroot\s*=/) {
		local $noslash = $url;
		$noslash =~ s/\/$//;
		$l = "\$CFG->wwwroot = \'$noslash\';";
		}
	if ($l =~ /^\$CFG->dirroot\s*=/) {
		local $noslashd = "$opts->{'dir'}/";
		$noslashd =~ s/\/$//;
		$l = "\$CFG->dirroot = \'$noslashd\';";
		}
	if ($l =~ /^\$CFG->dataroot\s*=/) {
		local $noslashdd = "$d->{'home'}/moodledata/";
		$noslashdd =~ s/\/$//;
		$l = "\$CFG->dataroot = \'$noslashdd\';";
		}
	if ($l =~ /^\/\/\s*\$CFG->sslproxy\s*=/) {
		if ($d_ssl) {
			$l = "\$CFG->sslproxy = \'true\';";
			}
		}
	}
&flush_file_lines_as_domain_user($d, $cfile);

if (!$upgrade) {
    # Setup cron job to run the maintenance program
    &create_script_wget_job($d, $url."admin/cron.php", 0, 0);

    # Fix Nginx webserver directives for Moodle to work
    if ($d_nginx) {
        # Find server to edit directives in
        my $server = virtualmin_nginx::find_domain_server($d);
        if ($server) {
            my $location = virtualmin_nginx::find_location($server, ('\\.php(/|$)'));
            
            # Continue only, if default Virtualmin location value exists
            if ($location) {
                # Lock configs
                virtualmin_nginx::lock_all_config_files();
                
                # Remove `try_files` directive from location
                virtualmin_nginx::save_directive($location, "try_files", []);

                # Write and unlock configs
                virtualmin_nginx::flush_config_file_lines();
                virtualmin_nginx::unlock_all_config_files();
                virtualmin_nginx::apply_nginx();
                }
            }
        }
    }

# Make moodle data directory under home as recondmended by install text.
local $mdataroot = "$d->{'home'}/moodledata";
$mdataroot =~ s/\/$//;
&make_dir_as_domain_user($d, $mdataroot, 0775);
&make_file_php_writable($d, $mdataroot);

# Return a URL for the user
local $rp = $opts->{'dir'};
$rp =~ s/^$d->{'home'}\///;
return (1, "Moodle basic installation finished. To complete the installation process,
browse to <a target=_blank href='$url'>$url</a>.", "Under $rp", $url); 
}

# script_moodle_uninstall(&domain, version, &opts)
# Un-installs a moodle installation, by deleting the directory.
# Returns 1 on success and a message, or 0 on failure and an error
sub script_moodle_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);

# To remove the data directory under home.
local $mdataroot = "$d->{'home'}/moodledata";
$mdataroot =~ s/\/$//;
$out = &run_as_domain_user($d, "rm -rf ".quotemeta($mdataroot)."/* ");
$out = &run_as_domain_user($d, "rm -rf ".quotemeta($mdataroot)."/.htaccess");
$out = &run_as_domain_user($d, "rmdir ".quotemeta($mdataroot));

# Remove all mdl_ tables from the database
&cleanup_script_database($d, $opts->{'db'}, "(mdl|adodb)_");

# 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'}."admin/cron.php");

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

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

sub script_moodle_latest
{
local ($ver) = @_;
if ($ver < 3) {
	return ( "https://download.moodle.org/releases/legacy/",
		 "Moodle\\s+(2\\.[0-9\\.]+)" );
	}
elsif ($ver == 3) {
	return ( "https://download.moodle.org/releases/supported/",
		 "Moodle\\s+(3\\.[0-9\\.]+)" );
	}
else {
	return ( "https://download.moodle.org/releases/latest/",
		 "Moodle\\s+(4\\.[0-9\\.]+)" );
	}
}

sub script_moodle_site
{
return 'http://moodle.org/';
}

1;

