
# script_mediawiki_desc()
sub script_mediawiki_desc
{
return "MediaWiki";
}

sub script_mediawiki_uses
{
return ( "php" );
}

sub script_mediawiki_longdesc
{
return "MediaWiki is a free Wiki software package, used to run WikiPedia";
}

# script_mediawiki_versions()
sub script_mediawiki_versions
{
return ( "1.39.1", "1.19.24" );
}

sub script_mediawiki_php_fullver
{ 
local ($d, $ver, $sinfo) = @_;
return &compare_versions($ver, "1.35.0") >= 0 ? "7.3.19" :
       &compare_versions($ver, "1.32.1") >= 0 ? "7.0.13" :
       &compare_versions($ver, "1.27") >= 0 ? "5.5.9" : undef;
}

sub script_mediawiki_release
{
return 3;
}

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

sub script_mediawiki_category
{
return "Wiki";
}

sub script_mediawiki_php_vers
{
return ( 5 );
}

sub script_mediawiki_php_modules
{
return ( "mysql", "xml", "dom",
         "mbstring", "json", "intl" );
}

sub script_mediawiki_php_optional_modules
{
return ( "apcu" );
}

sub script_mediawiki_php_vars
{
return ( [ 'memory_limit', '256M', '+' ] );
}

sub script_mediawiki_dbs
{
return ("mysql");
}

# script_mediawiki_params(&domain, version, &upgrade-info)
# Returns HTML for table rows for options for installing PHP-NUKE
sub script_mediawiki_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 MediaWiki tables", $dbname);
	local $dir = $upgrade->{'opts'}->{'dir'};
	$dir =~ s/^$d->{'home'}\///;
	$rv .= &ui_table_row("Install directory", $dir);
	$rv .= &ui_table_row("Wiki name", $opts->{'wiki'});
	}
else {
	# Show editable install options
	local @dbs = &domain_databases($d, [ "mysql" ]);
	$rv .= &ui_table_row("Database for MediaWiki tables",
		     &ui_database_select("db", undef, \@dbs, $d, "mediawiki"));
	$rv .= &ui_table_row("Install sub-directory under <tt>$hdir</tt>",
			     &ui_opt_textbox("dir", &substitute_scriptname_template("mediawiki", $d), 30, "At top level"));
	$rv .= &ui_table_row("Wiki name",
			     &ui_textbox("wiki", undef, 50));
	}
return $rv;
}

# script_mediawiki_parse(&domain, version, &in, &upgrade-info)
# Returns either a hash ref of parsed options, or an error string
sub script_mediawiki_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";
	$in{'wiki'} =~ /\S/ || return "Missing wiki name";
	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'}",
		 'wiki' => $in{'wiki'}, };
	}
}

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

# script_mediawiki_files(&domain, version, &opts, &upgrade-info)
# Returns a list of files needed by PHP-Nuke, each of which is a hash ref
# containing a name, filename and URL
sub script_mediawiki_files
{
local ($d, $ver, $opts, $upgrade) = @_;
local $verfirst = $ver;
$verfirst =~ s/\.\d+$//;
local @files = ( { 'name' => "source",
	   'file' => "mediawiki-$ver.tar.gz",
	   'url' => "http://releases.wikimedia.org/mediawiki/$verfirst/mediawiki-$ver.tar.gz"
	   } );
return @files;
}

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

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

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

if (!$upgrade) {
	# Make config directory world-writable
	&set_permissions_as_domain_user($d, 0777, "$opts->{'dir'}/config");
	}

# Get php executable
local $cmd = &get_php_cli_command($opts->{'phpver'});

local $url = &script_path_url($d, $opts);
local $nopathurl = $url;
$nopathurl =~ s/\Q$opts->{'path'}\E\/?$//;
local $noslashpath = $opts->{'path'};
$noslashpath =~ s/\/$//;
if (!$upgrade) {
	# Run the install PHP script
	$cmd .= " maintenance/install.php";
	$cmd .= " --server ".quotemeta($nopathurl);
	$cmd .= " --scriptpath ".(quotemeta($noslashpath) || "''");
	$cmd .= " --dbuser ".quotemeta($dbuser);
	$cmd .= " --dbpass ".quotemeta($dbpass);
	$cmd .= " --dbname ".quotemeta($dbname);
	$cmd .= " --dbserver ".quotemeta($dbhost);
	$cmd .= " --dbprefix=mw_";
	$cmd .= " --pass ".quotemeta($dompass);
	$cmd .= " ".quotemeta($opts->{'wiki'});
	$cmd .= " ".quotemeta($domuser);
	local $phpver = $opts->{'phpver'} || 5;
	if (-d "$d->{'home'}/etc/php$phpver") {
		$cmd = "PHPRC=$d->{'home'}/etc/php$phpver $cmd";
		}

	# Run it as the domain owner
	&clean_environment();
	local $out = &run_as_domain_user($d,
		"cd ".quotemeta($opts->{'dir'})." && ".$cmd." 2>&1");
	&reset_environment();
	if ($? || !-r $cfile) {
		return (-1, "Installation script failed : <pre>".
			    &html_escape($out)."</pre>");
		}

	# Fix LocalSettings.php
	local $lref = &read_file_lines_as_domain_user($d, $cfile);
	foreach my $l (@$lref) {
		if ($l =~ /^\s*\$wgServer\s*=/) {
			$l = "\$wgServer = \"$nopathurl\";";
			}
		elsif ($l =~ /^\s*\$(wgEmergencyContact|wgPasswordSender)\s*=/){
			$l = "\$${1} = \"$d->{'emailto_addr'}\";";
			}
		}
	&flush_file_lines_as_domain_user($d, $cfile);
	}
else {
	# Create AdminSettings.php if missing
	local $asfile = "$opts->{'dir'}/AdminSettings.php";
	local $assrc = "$opts->{'dir'}/AdminSettings.sample";
	if (!-r $asfile) {
		&copy_source_dest_as_domain_user($d, $assrc, $asfile);
		local $lref = &read_file_lines_as_domain_user($d, $asfile);
		foreach my $l (@$lref) {
			if ($l =~ /^\s*\$wgDBadminuser\s*=/) {
				$l = "\$wgDBadminuser = '$dbuser';";
				}
			if ($l =~ /^\s*\$wgDBadminpassword\s*=/) {
				$l = "\$wgDBadminpassword = '".
				     &php_quotemeta($dbpass, 1)."';";
				}
			}
		&flush_file_lines_as_domain_user($d, $asfile);
		}

	# Run composed to update deps, if installed
	if (&has_command("composer")) {
		my $ccmd = &has_command("composer")." update --no-dev";
		&clean_environment();
		local $out = &run_as_domain_user($d, 
			"cd $opts->{'dir'} && $ccmd 2>&1");
		&reset_environment();
		}

	# Call the update command
	if ($ver >= 1.32) {
		$cmd .= " update.php";
		}
	else {
		$cmd .= " update.php --aconf ".quotemeta($asfile);
		}
	&clean_environment();
	local $out = &run_as_domain_user($d, 
		"cd $opts->{'dir'}/maintenance && $cmd 2>&1");
	&reset_environment();
	if ($? || $out =~ /No\s+superuser\s+credentials/i) {
		return (-1, "MediaWiki update command failed : $out");
		}
	}

local $rp = $opts->{'dir'};
$rp =~ s/^$d->{'home'}\///;
return (1, "MediaWiki installation complete. It can be accessed at <a target=_blank href='$url'>$url</a>.", "Under $rp using $dbtype database $dbname", $url, $domuser, $dompass);
}

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

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

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

if ($opts->{'db'}) {
	# Take out the DB
	if ($opts->{'newdb'}) {
		&delete_script_database($d, $opts->{'db'});
		}
	return (1, "MediaWiki directory and database deleted.");
	}
else {
	return (1, "MediaWiki directory deleted. Any database tables must be deleted manually.");
	}
}

# script_mediawiki_latest(version)
# Returns a URL and regular expression or callback func to get the version
sub script_mediawiki_latest
{
local ($ver) = @_;
if ($ver =~ /^1\.19/) {
	return ( "http://download.wikimedia.org/mediawiki/1.19/",
		 "mediawiki-(1\\.19\\.[0-9\\.]+).tar.gz" );
	}
else {
	return ( "http://www.mediawiki.org/wiki/Download",
		 "mediawiki-([0-9\\.]+).tar.gz" );
	}
}

sub script_mediawiki_site
{
return 'http://www.mediawiki.org/';
}

sub script_mediawiki_passmode
{
# Minimum 10 chars of alphanumeric string (unicode)
return (1, 10, '^(?=.*[\p{L}])(?=.*\d)[\p{L}\d]{10,}$');
}

1;

