
# script_phpadsnew_desc()
sub script_phpadsnew_desc
{
return "Revive Adserver";
}

sub script_phpadsnew_uses
{
return ( "php" );
}

sub script_phpadsnew_longdesc
{
return "Revive Adserver is an open-source ad server, with an integrated banner management interface and tracking system for gathering statistics";
}

# script_phpadsnew_versions(installing)
sub script_phpadsnew_versions
{
return ( "5.4.1" );
}

# script_phpadsnew_release()
sub script_phpadsnew_release
{
return 2;	# To fix the root-install bug
}

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

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

sub script_phpadsnew_category
{
return "Commerce";
}

sub script_phpadsnew_php_vers
{
return ( 5 );
}

sub script_phpadsnew_php_modules
{
return ("mysql");
}

sub script_phpadsnew_perl_modules
{
return ( "Digest::MD5" );
}

sub script_phpadsnew_dbs
{
return ("mysql");
}

# script_phpadsnew_php_vars(&domain)
# Returns an array of extra PHP variables needed for this script
sub script_phpadsnew_php_vars
{
return ( [ 'register_argc_argv', 'On' ],
	 [ 'magic_quotes_runtime', 'Off' ],
	 [ 'safe_mode', 'Off' ],
	 [ 'file_uploads', 'On' ],
	 [ 'memory_limit', '128M', '+' ],
       );
}

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

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

# script_phpadsnew_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_phpadsnew_files
{
local ($d, $ver, $opts, $upgrade) = @_;
local @files = ( { 'name' => "source",
	   'file' => "revive-adserver-$ver.zip",
	   'url' => "https://download.revive-adserver.com/revive-adserver-$ver.zip" } );
return @files;
}

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

# script_phpadsnew_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_phpadsnew_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" : "pgsql";
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'}, "revive-adserver-$ver");
$err && return (0, "Failed to extract source : $err");

# Work out the URL
local $url = &script_path_url($d, $opts);
local $rp = $opts->{'dir'};
$rp =~ s/^$d->{'home'}\///;

# Make var and www directories writable
&make_file_php_writable($d, "$opts->{'dir'}/var", 0);
&make_file_php_writable($d, "$opts->{'dir'}/www/images", 1);
&set_permissions_as_domain_user($d, 0777, "$opts->{'dir'}/www/images");

if (!$upgrade) {
	# Step through the wizard
	local %cookieheader;
	local $dompath = $d->{'dom'}.
			 ($opts->{'path'} eq '/' ? '' : $opts->{'path'});
	foreach my $btn ("", "welcome", "database", "configuration") {
		# Work out params for this page
		local @params = ( [ "action", $btn ] );
		if ($btn eq "database") {
			push(@params,
				[ "_qf__install-db-form", "" ],
				[ "token", "" ],
				[ "moreFieldsShown", "" ],
				[ "dbName", $dbname ],
				[ "dbUser", $dbuser ],
				[ "dbPassword", $dbpass ],
				[ "dbType", $dbtype ],
				[ "dbHost", $dbhost ],
				[ "dbLocal", "0" ],
				[ "dbPort", 3306 ],
				[ "dbTableType", "INNODB" ],
				[ "dbTablePrefix", "rv_" ],
				[ "save", "Continue »" ],
				);
			}
		elsif ($btn eq "configuration") {
			push(@params, 
				[ "_qf__install-config-form", "" ],
				[ "token", "" ],
				[ "moreFieldsShown", "0" ],
				[ "adminName", $domuser ],
				[ "adminPassword", $dompass ],
				[ "adminPassword2", $dompass ],
				[ "adminEmail", $d->{'emailto'} ],
				[ "adminLanguage", "en" ],
				[ "prefsTimezone", "America/Los_Angeles" ],
				[ "webpathAdmin", "$dompath/www/admin" ],
				[ "webpathDelivery", "$dompath/www/delivery" ],
				[ "webpathImages", "$dompath/www/images" ],
				[ "webpathDeliverySSL", "$dompath/www/delivery" ],
				[ "webpathImagesSSL", "$dompath/www/images" ],
				[ "storeWebDir", "$opts->{'dir'}/www/images" ],
				);
			}

		# Make the call
		local $params = join("&", map { &urlize($_->[0])."=".&urlize($_->[1]) } @params);
		local $ipage = $opts->{'path'}."/www/admin/install.php";
		local ($iout, $ierror);
		local (@gotheaders, %gotheaders);
		&post_http_connection($d, $ipage, $params, \$iout, \$ierror,
				      \%cookieheader, \%gotheaders);
		if ($ierror) {
			return (-1, "Revive Adserver wizard failed : $ierror");
			}
		if ($gotheaders{'set-cookie'} =~ /(PHPSESSID|oat|ox_install_session_id)=([^ ;]+)/) {
			local ($cn, $cv) = ($1, $2);
			local @cookie = split(/;\s*/, $cookieheader{'Cookie'});
			@cookie = grep { !/^\Q$cn\E=/ } @cookie;
			if ($cv ne 'deleted') {
				push(@cookie, "$cn=$cv");
				}
			$cookieheader{'Cookie'} = join("; ", @cookie);
			}
		}

	# Setup the Cron job to run the maintenance program
	&create_script_wget_job($d, $url."maintenance/maintenance.php", 0, 0);

	# Link up the config file for the domain name
	&symlink_file_as_domain_user(
		$d, "$opts->{'dir'}/var/www.$d->{'dom'}.conf.php",
		    "$opts->{'dir'}/var/$d->{'dom'}.conf.php");
	}

return (1, $upgrade ? "Revive Adserver upgrade installed. You can complete the upgrade process at <a target=_blank href='$url'>$url</a>." : "Revive Adserver installation complete. It can be accessed at <a target=_blank href='$url'>$url</a>.", $opts->{'db'} ? "Under $rp using $dbphptype database $dbname" : "Under $rp", $url, $domuser, $dompass);
}

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

# Remove all Revive Adserver tables from the database
&cleanup_script_database($d, $opts->{'db'}, "(phpads|ox|rv)_");

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

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

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

# script_phpadsnew_latest(version)
# Returns a URL and regular expression or callback func to get the version
sub script_phpadsnew_latest
{
local ($ver) = @_;
return ( "http://www.revive-adserver.com/download/",
	 "revive-adserver-([0-9\\.]*)\\.zip" );
}

sub script_phpadsnew_site
{
return 'http://www.revive-adserver.com/';
}

sub script_phpadsnew_passmode
{
return 1;
}

1;

