
# script_piwik_desc()
sub script_piwik_desc
{
return "Matomo";
}

sub script_piwik_uses
{
return ( "php" );
}

sub script_piwik_longdesc
{
return "Matomo is an open source web analytics software. It gives interesting reports on your website visitors, your popular pages and more";
}

# script_piwik_versions()
sub script_piwik_versions
{
return ( "4.13.2" );
}

sub script_piwik_can_upgrade
{
local ($sinfo, $newver) = @_;
if ($sinfo->{'version'} < 2 && $newver >= 2) {
	return 0;
	}
return 1;
}

sub script_piwik_php_vers
{
return ( 5 );
}

sub script_piwik_php_modules
{
return ( "curl", "gd", "xml", "mbstring" );
}

sub script_piwik_php_optional_modules
{
return ( "pdo", "pdo_mysql" );
}

sub script_piwik_dbs
{
return ("mysql");
}

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

# script_piwik_php_vars(&domain)
# Returns an array of extra PHP variables needed for this script
sub script_piwik_php_vars
{
return ( [ 'memory_limit', '128M', '+' ],
         [ 'always_populate_raw_post_data', '-1' ] );
}

# script_piwik_params(&domain, version, &upgrade-info)
# Returns HTML for table rows for options for installing Matomo
sub script_piwik_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 Matomo 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 Matomo tables",
		     &ui_database_select("db", undef, \@dbs, $d, "matomo"));
	$rv .= &ui_table_row("Install sub-directory under <tt>$hdir</tt>",
			     &ui_opt_textbox("dir", &substitute_scriptname_template("matomo", $d), 30, "At top level"));
	if ($d->{'virtualmin-google-analytics'}) {
		$rv .= &ui_table_row("Use this Matomo installation for ".
				     "analytics by default?",
			&ui_yesno_radio("analytics", 1));
		}
	}
return $rv;
}

# script_piwik_parse(&domain, version, &in, &upgrade-info)
# Returns either a hash ref of parsed options, or an error string
sub script_piwik_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'}",
		 'analyics' => $in->{'analyics'}, };
	}
}

# script_piwik_check(&domain, version, &opts, &upgrade-info)
# Returns an error message if a required option is missing or invalid
sub script_piwik_check
{
local ($d, $ver, $opts, $upgrade) = @_;
$opts->{'dir'} =~ /^\// || return "Missing or invalid install directory";
$opts->{'db'} || return "Missing database";
if (-r "$opts->{'dir'}/piwik.php") {
	return "Matomo appears to be already installed in the selected directory";
	}
local ($dbtype, $dbname) = split(/_/, $opts->{'db'}, 2);
local $clash = &find_database_table($dbtype, $dbname, "(piwik|matomo)_");
$clash && return "Matomo appears to be already using the selected database (table $clash)";
return undef;
}

# script_piwik_files(&domain, version, &opts, &upgrade-info)
# Returns a list of files needed by Matomo, each of which is a hash ref
# containing a name, filename and URL
sub script_piwik_files
{
local ($d, $ver, $opts, $upgrade) = @_;
local @files = ( { 'name' => "source",
	   'file' => "matomo-$ver.zip",
	   'url' => "https://builds.matomo.org/matomo-$ver.zip" } );
return @files;
}

sub script_piwik_commands
{
return ("unzip");
}

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

# Create and get the DB
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($dbtype, $d);
local $dberr = &check_script_db_connection($dbtype, $dbname, $dbuser, $dbpass);
return (0, "Database connection failed : $dberr") if ($dberr);

# Remove obsolete files from old version
if ($upgrade) {
	&unlink_file_as_domain_user($d, "$opts->{'dir'}/piwik/plugins/CoreVisualizations/Visualizations/HtmlTable/PivotBy.php");
	}

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

local $url = &script_path_url($d, $opts);
my $longpass = $dompass;
if (!$upgrade) {
	# Make config directory writable
	&make_file_php_writable($d, "$opts->{'dir'}/config");
	local $path = $opts->{'path'};
	$path .= "/" if ($path !~ /\/$/);
	
	my $d_ssl = domain_has_ssl($d);
	my $protocol = ($d_ssl ? 'https' : 'http');

	# Call first page of install wizard, to get the cookie
	local ($iout, $ierr);
	&get_http_connection(
		       $d, $path, \$iout, \$ierr, \&piwik_cookie_callback,
		       0, undef, undef, undef, 0, 1);
	$ierr && return (-1, "Initial install page failed : $ierr");
	#$piwik_session_cookie ||
	#    return (-1, "Failed to get session cookie from initial page");

	# Call config verification page
	local $cheaders = { 'Cookie' => $piwik_session_cookie };
	local ($iout, $ierr);
	&get_http_connection(
		       $d, $path."?action=systemCheck", \$iout, \$ierr,
		       undef, 0, undef, undef, 0, 0, 1, $cheaders);
	if ($ierr) {
		return (-1, "System check page failed : $ierr");
		}
	elsif ($iout !~ /databaseSetup/) {
		return (-1, "System check failed - ".
			    "some dependencies may be missing");
		}

	# Get the DB setup form
	&get_http_connection($d, $path."?action=databaseSetup&module=Installation&clientProtocol=$protocol", \$iout, \$ierr,
			     undef, 0, undef, undef, 0, 0, 1, $cheaders);

	# Submit the DB setup form
	local @params = (
		[ "type", 'InnoDB' ],
		[ "host", $dbhost ],
		[ "username", $dbuser ],
		[ "password", $dbpass ],
		[ "dbname", $dbname ],
		[ "tables_prefix", "matomo_" ],
		[ "adapter", "PDO\\MYSQL" ],
		[ "submit", "Go!" ],
		);
	local $params = join("&", map { $_->[0]."=".&urlize($_->[1]) } @params);
	local $ipage = $path."?action=databaseSetup&module=Installation&clientProtocol=$protocol";
	local ($iout, $ierr, %gotheaders);
	&post_http_connection($d, $ipage, $params, \$iout, \$ierr, $cheaders,
			      \%gotheaders);
	if ($ierr) {
		if ($ierr !~ /tablesCreation|databaseCheck/) {
			return (-1, "Database setup failed : $ierr");
			}
		}
	elsif ($iout !~ /Tables\s+created/i) {
		return (-1, "Database setup failed");
		}

	# Call table creation page
	local ($iout, $ierr);
	&get_http_connection($d,
			     $path."?action=tablesCreation&module=Installation&deleteTables=1&clientProtocol=$protocol",
			     \$iout, \$ierr,
			     undef, 0, undef, undef, 0, 0, 1, $cheaders);
	if ($ierr) {
		return (-1, "Failed to create tables : $ierr");
		}

	# Call user creation form
	if (length($longpass) < 6) {
		# Matomo requires a 6-character password!
		$longpass .= "123456";
		}
	local @params = (
		[ "login", $domuser ],
		[ "password", $longpass ],
		[ "password_bis", $longpass ],
		[ "email", $d->{'emailto_addr'} ],
		);
	local $params = join("&", map { $_->[0]."=".&urlize($_->[1]) } @params);
	local $ipage = $path."?action=setupSuperUser&module=Installation&clientProtocol=$protocol";
	local ($iout, $ierr);
	&post_http_connection($d, $ipage, $params, \$iout, \$ierr, $cheaders);
	if ($ierr) {
		if ($ierr !~ /firstWebsiteSetup/) {
			return (-1, "Administrator setup failed : $ierr");
			}
		}
	elsif ($iout !~ /General\s+Setup\s+configured|Setup\s+a\s+website|Super\s+User\s+created|Superuser\s+created/i) {
		return (-1, "Administrator setup failed");
		}

	# Call initial website form
	local @params = (
		[ "siteName", $d->{'owner'} || 'Analyst' ],
		[ "url", ($d_ssl ? 'https' : 'http') . "://$d->{'dom'}" ],
		[ "timezone", "UTC" ],
		[ "ecommerce", "0" ],
		[ "submit", "Next" ],
		);
	local $params = join("&", map { $_->[0]."=".&urlize($_->[1]) } @params);
	local $ipage = $path."?action=firstWebsiteSetup&module=Installation&clientProtocol=$protocol";
	local ($iout, $ierr);
	&post_http_connection($d, $ipage, $params, \$iout, \$ierr, $cheaders);
	if ($ierr) {
		if ($ierr !~ /trackingCode/) {
			return (-1, "First website setup failed : $ierr");
			}
		}
	elsif ($iout !~ /created\s+successfully|website\s+created/i) {
		return (-1, "First website setup failed");
		}

	# Call JS display
	local ($iout, $ierr);
	&get_http_connection($d, $path."?action=trackingCode&module=Installation&clientProtocol=$protocol",
			     \$iout, \$ierr,
			     undef, 0, undef, undef, 0, 0, 1, $cheaders);
	if ($ierr) {
		return (-1, "Failed to get Javascript : $ierr");
		}

	# Call finished page
	local ($iout, $ierr);
	&get_http_connection($d, $path."?action=finished&module=Installation&clientProtocol=$protocol",
			     \$iout, \$ierr,
			     undef, 0, undef, undef, 0, 0, 1, $cheaders);
	if ($ierr) {
		return (-1, "Failed to finish install : $ierr");
		}

	# Submit the finished page form
	local @params = (
		[ "do_not_track", 1 ],
		[ "anonymise_ip", 1 ],
		[ "submit", "Next" ],
		);
	local $params = join("&", map { $_->[0]."=".&urlize($_->[1]) } @params);
	local $ipage = $path."?action=finished&module=Installation&clientProtocol=$protocol";
	local ($iout, $ierr);
	&post_http_connection($d, $ipage, $params, \$iout, \$ierr, $cheaders);

	# Update database tables
	local $ipage = $path."?updateCorePlugins=1&module=CoreUpdater";
	local ($iout, $ierr);
	&post_http_connection($d, $ipage, undef, \$iout, \$ierr, $cheaders);

	# Configure analytics module to use this piwik URL
	if ($opts->{'analytics'} && $d->{'virtualmin-google-analytics'}) {
		&foreign_require("virtualmin-google-analytics",
				 "virtualmin-google-analytics-lib.pl");
		if (defined(
		     &virtualmin_google_analytics::save_piwik_default_url)) {
			&virtualmin_google_analytics::save_piwik_default_url(
				$d, $url);
			}
		}
	}

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

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

# Clear database
if ($opts->{'newdb'}) {
	# Remove all tables from the database
	&cleanup_script_database($d, $opts->{'db'}, '(.*)');
	# Remove database
    &delete_script_database($d, $opts->{'db'});
    }
else {
	# Remove only default matomo_ tables from the database
	&cleanup_script_database($d, $opts->{'db'}, "(piwik|matomo)_");
	}

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

# script_piwik_latest(version)
# Returns a URL and regular expression or callback func to get the version
sub script_piwik_latest
{
local ($ver) = @_;
if ($ver >= 3) {
	return ( 'https://matomo.org/download/',
		 'Download\\s+Matomo\\s+([0-9\\.]+)' );
	}
return ( );	# Old versions aren't offered anymore
}

sub script_piwik_site
{
return 'http://matomo.org/';
}

sub script_piwik_passmode
{
# Minimum password 6 chars length
return (1, 6, '\s*(\S\s*){6,}');
}

sub piwik_cookie_callback
{
foreach my $h (@headers, @WebminCore::headers) {
	if (lc($h->[0]) eq 'set-cookie' &&
	    $h->[1] =~ /((PHPSESSID|MATOMO_SESSID)=([^ ;]+))/) {
		$piwik_session_cookie = $1;
		}
	}
}

1;

