REST::fatal(REST::HTTP_BAD_REQUEST, 'Missing (one of) required parameters "email" and "password"');
}
$dn = Portal_User::csa_dn();
if (empty($dn)) {
    REST::fatal(REST::HTTP_NOT_FOUND);
}
$escemail = Portal_MySQL::escape_string($_GET['email']);
$md5password = md5($_GET['password']);
$escdn = Portal_MySQL::escape_string($dn);
Portal_MySQL::real_query(<<<EOS
DELETE FROM `User`
WHERE `user_dn` = {$escdn}
  AND `user_email` <> {$escemail};
EOS
);
Portal_MySQL::real_query(<<<EOS
UPDATE `User`
SET `user_dn` = {$escdn}
WHERE `user_email` = {$escemail}
  AND `user_password` = '{$md5password}';
EOS
);
if (!Portal_MySQL::mysql()->affected_rows) {
    Portal_User::unauthorized();
}
$url = REST::htmlspecialchars(Portal::portalURL());
REST::fatal(REST::HTTP_OK, <<<EOS
<p>Registration complete.</p>
<p>You can now start <a href="{$url}">using the GridApps web service</a>.</p>
EOS
);
    public static function recordRequest($url, $ip = '')
    {
        $user_id = Portal_MySQL::escape_string(Portal_User::current()->user_id());
        $esc_url = Portal_MySQL::escape_string($url);
        $esc_ip = Portal_MySQL::escape_string($ip);
        Portal_MySQL::real_query(<<<EOS
INSERT INTO `Statistics` (`requested_url`, `request_origin`, `user_id`)
     VALUES ({$esc_url}, {$esc_ip}, {$user_id});
EOS
);
    }
   SET `token_error` = CONCAT(`token_error`, {$errorstring})
 WHERE `token_id`={$escjobid}
   AND `user_id`={$escuserid};
EOS
);
    REST::header(array('status' => REST::HTTP_NO_CONTENT));
    exit;
}
if ($_SERVER['REQUEST_METHOD'] == 'DELETE') {
    if (file_exists($fullfilename = Portal::JOBRESULTS_DIR . $jobid)) {
        unlink($fullfilename);
    }
    Topos::deleteTokenFile($jobid);
    Portal_MySQL::real_query(<<<EOS
DELETE FROM `Token`
 WHERE `token_id`={$escjobid}
   AND `user_id`={$escuserid};
EOS
);
    if (!Portal_MySQL::mysql()->affected_rows) {
        REST::fatal(REST::HTTP_NOT_FOUND);
    }
    REST::header(array('status' => REST::HTTP_NO_CONTENT));
    exit;
}
// The user tries to get information about eir jobs
if (file_exists($fullfilename = Portal::JOBRESULTS_DIR . $jobid)) {
    REST::redirect(REST::HTTP_SEE_OTHER, Portal::portalURL() . "jobresults/{$jobid}");
}
$result = Portal_MySQL::query(<<<EOS
SELECT `token_error` 
  FROM `Token`
    // Check the name:
    $_GET['name'] = preg_replace('/\\s+/', ' ', trim($_GET['name']));
    if ($_GET['name'] === '') {
        REST::fatal(REST::HTTP_BAD_REQUEST, '<p>Please provide a display name.</p>');
    }
    $escemail = Portal_MySQL::escape_string($_GET['email']);
    $escname = Portal_MySQL::escape_string($_GET['name']);
    //  $dn = ($_SERVER['SERVER_PORT'] == Portal::PORT_SSL_CSA)
    //    ? Portal_User::csa_dn() : null;
    //  $escdn = Portal_MySQL::escape_string($dn);
    $password = Portal_User::createPassword();
    $md5password = md5($password);
    Portal_MySQL::real_query(<<<EOS
INSERT INTO `User` (`user_email`, `user_name`, `user_password`)
VALUES ({$escemail}, {$escname}, '{$md5password}')
ON DUPLICATE KEY UPDATE
  `user_name` = {$escname},
  `user_password` = '{$md5password}';
EOS
);
    $csa_confirm = 'https://' . $_SERVER['SERVER_NAME'] . ':' . Portal::PORT_SSL_CSA . Portal::portalURL() . 'csaconfirm?email=' . urlencode($_GET['email']) . '&password='******'email'], 'Access to ' . $_SERVER['SERVER_NAME'], <<<EOS
Hi {$_GET['name']},

These are the credentials you may use for the Grid Application Portal:

Login:    {$_GET['email']}
Password: {$password}

If you want to authenticate using a client certificate, please open a 
browser with your client certificate in it, and follow this link:
<{$csa_confirm}>
    }
    if (!isset($_POST['token'])) {
        REST::fatal(REST::HTTP_BAD_REQUEST, 'Missing required parameter "token"');
    }
    $token = (int) $_POST['token'];
    if (!isset($_POST['seconds'])) {
        REST::fatal(REST::HTTP_BAD_REQUEST, 'Missing required parameter "seconds"');
    }
    $seconds = (int) $_POST['seconds'];
    if (!isset($_POST['status'])) {
        REST::fatal(REST::HTTP_BAD_REQUEST, 'Missing required parameter "status"');
    }
    $status = (int) $_POST['status'];
    Portal_MySQL::real_query(<<<EOS
INSERT INTO `Usage` (`user_id`, `usage_seconds`, `token_id`, `usage_status`)
VALUES ({$userid}, {$seconds}, {$token}, {$status});
EOS
);
    REST::fatal(REST::HTTP_ACCEPTED);
}
REST::require_method('GET', 'HEAD');
$result = Portal_MySQL::query(<<<EOS
SELECT SUM(`usage_seconds`),
       DATE(`usage_timestamp`),
       `usage_status`
FROM `Usage`
WHERE `user_id` = {$userid}
GROUP BY 3,2
ORDER BY 3,2 ASC;
EOS
);
    $proxyusername = escapeshellarg($row[2]);
    $proxypassword = $row[3];
    $escfullproxyfile = escapeshellarg($fullproxyfile);
    $output = '';
    exec("grid-proxy-info -f {$escfullproxyfile} -exists -valid 0:30", $output, $returnval);
    if ($returnval && $proxypassword === null) {
        @unlink($fullproxyfile);
        continue;
    } elseif ($returnval) {
        $handle = popen("myproxy-logon -v -l {$proxyusername} -s {$escproxyserver} -S -o {$escfullproxyfile} >/dev/null 2>&1", 'w');
        fwrite($handle, $proxypassword);
        if (pclose($handle)) {
            @unlink($fullproxyfile);
            Portal_MySQL::real_query(<<<EOS
UPDATE `User` SET `proxy_server` = NULL, `proxy_username` = NULL, `proxy_password` = NULL
WHERE `user_dn_md5` = {$escuserdnmd5};
EOS
);
            continue;
        }
    }
    $topos = new Topos();
    $pools = $topos->getPools();
    foreach ($pools as $pool => $ntokens) {
        $poolURL = $topos->realmURL() . "pools/{$pool}";
        if (!preg_match('@^todo_for_vo_([-\\w.]+)/$@', $pool, $matches)) {
            Portal::debug("Strange pool URL {$poolURL}");
            continue;
        }
        $vo = $matches[1];
        putenv("X509_USER_PROXY={$fullproxyfile}");
    $username = escapeshellarg(trim($_POST['username']));
    $password = escapeshellarg(trim($_POST['password']));
    $server = escapeshellarg(trim($_POST['server']));
    $filename = escapeshellarg(Portal::PROXY_DIR . $userdnmd5 . '.pem');
    exec("echo {$password} | myproxy-logon -v -l {$username} -s {$server} -S -o {$filename} 2>&1", $output, $returnval);
    $output = implode("\n", $output);
    if (preg_match('/^(?:invalid pass phrase|No credentials exist for username .*)$/m', $output)) {
        REST::fatal(REST::HTTP_UNAUTHORIZED, 'Invalid username and/or pass phrase');
    }
    if ($returnval) {
        REST::fatal(REST::HTTP_BAD_REQUEST, '<pre>' . htmlentities($output) . '</pre>');
    }
    $escserver = Portal_MySQL::escape_string($_POST['server']);
    $escusername = Portal_MySQL::escape_string($_POST['username']);
    $escpassword = Portal_MySQL::escape_string($_POST['password']);
    Portal_MySQL::real_query("UPDATE `User` SET `proxy_server` = {$escserver}, `proxy_username` = {$escusername}, `proxy_password` = {$escpassword} WHERE `user_dn_md5` = '{$userdnmd5}'");
    $best_xhtml_type = REST::best_xhtml_type();
    $type = REST::best_content_type(array($best_xhtml_type => 1.0, 'text/plain' => 1.0), $best_xhtml_type);
    $relurl = REST::urlencode(dirname($_SERVER['REDIRECT_URL'])) . '/proxy';
    REST::header(array('status' => REST::HTTP_CREATED, 'Location' => REST::urlbase() . $relurl, 'Content-Type' => "{$type}; charset=UTF-8"));
    if ($type == 'text/plain') {
        echo REST::urlbase() . $relurl;
    } else {
        echo Portal::html_start('Proxy created') . "<p><a href=\"proxy\">proxy</a></p>" . Portal::html_end();
    }
    exit;
}
REST::header(REST::best_xhtml_type() . "; charset=UTF-8");
$default_server = getenv('MYPROXY_SERVER');
echo Portal::html_start("myProxy") . <<<EOS
<form action="./myproxy" method="post">
EOS
);
    exec("cd '{$sandbox}'; find -mindepth 1 -maxdepth 1 -print0 | xargs -0 tar zcf {$TEMPNAM}.tgz", $output, $return_var);
    if ($return_var) {
        $output = implode("\n", $output);
        REST::fatal(REST::HTTP_INTERNAL_SERVER_ERROR, $output);
    }
    $tokenhandle = fopen("{$TEMPNAM}.tgz", 'r');
    try {
        $token_url = Topos::putTokenFile($tokenhandle, 'application/x-compressed-tar');
    } catch (Exception $e) {
        fclose($tokenhandle);
        throw $e;
    }
    fclose($tokenhandle);
    $token_id = basename($token_url);
    Portal_MySQL::real_query(<<<EOS
INSERT INTO `Token`
       ( `token_id`,  `user_id` )
VALUES ( {$token_id}, {$user_id} );
EOS
);
    $resultURL = REST::urlbase() . Portal::portalURL() . "jobstates/{$token_id}";
    REST::created($resultURL);
}
Portal_User::current();
REST::header(array('Content-Type' => REST::best_xhtml_type()));
echo Portal::html_start("{$appname}-{$appversion}") . '<form action="' . $appversion . '" method="post" enctype="multipart/form-data">';
$portlet->doGET();
echo '</form>' . Portal::html_end();
 */
require_once 'include/global.php';
$path_info = Portal::path_info();
if (count($path_info) != 3) {
    REST::fatal(REST::HTTP_NOT_FOUND);
}
$file = explode('.', $path_info[2], 2);
if (!($database_id = (int) $file[0])) {
    REST::fatal(REST::HTTP_NOT_FOUND);
}
$realfilepath = Portal_DB::DATABASE_DIR . $database_id;
$user_id = Portal_User::current()->user_id();
if ($_SERVER['REQUEST_METHOD'] == 'DELETE') {
    Portal_MySQL::real_query(<<<EOS
DELETE FROM `Database`
WHERE `database_id` = {$database_id}
  AND `user_id` = {$user_id};
EOS
);
    if (!Portal_MySQL::mysql()->affected_rows) {
        Portal_User::unauthorized();
    }
    unlink($realfilepath);
    REST::fatal(REST::HTTP_NO_CONTENT);
}
REST::require_method('GET', 'HEAD');
$path_info = Portal::path_info();
if (count($path_info) != 3) {
    REST::fatal(REST::HTTP_NOT_FOUND);
}
$file = explode('.', $path_info[2], 2);
if (!($database_id = (int) $file[0])) {
        try {
            Portal_MySQL::real_query(<<<EOS
INSERT INTO `Database`
  ( `name`, `version`, `user_id`, `is_shared`, `checksum`, `type` )
VALUES
  ( {$dbname}, {$dbversion}, {$user_id}, {$is_shared}, '{$checksum}', {$typeId} );
EOS
);
        } catch (Portal_MySQL_Exception $e) {
            unlink($tmpfilename);
            REST::fatal(REST::HTTP_CONFLICT, "Can't overwrite existing file: name={$dbname}, version={$dbversion}, type={$_POST['type']}");
        }
        $insert_id = Portal_MySQL::mysql()->insert_id;
        if (!rename($tmpfilename, Portal_DB::DATABASE_DIR . $insert_id)) {
            unlink($tmpfilename);
            Portal_MySQL::real_query("DELETE FROM `Database` WHERE `database_id` = {$insert_id}");
            REST::fatal(REST::HTTP_INTERNAL_SERVER_ERROR, "Couldn't store uploaded file.");
        }
        chmod(Portal_DB::DATABASE_DIR . $insert_id, 0660);
    }
    $extension = Portal_DB::databaseTypeExtension($typeId);
    $htmlurl = "{$insert_id}.{$extension}";
    $fullurl = REST::urlbase() . $_SERVER['REDIRECT_URL'] . $htmlurl;
    $content_type = REST::best_content_type(array(REST::best_xhtml_type() => 1.0, 'text/plain' => 0.5), 'text/plain');
    if ($content_type == 'text/plain') {
        REST::header(array('status' => REST::HTTP_CREATED, 'Location' => $fullurl, 'Content-Type' => 'text/plain; charset=US-ASCII'));
        echo $fullurl;
        exit;
    }
    REST::header(array('status' => REST::HTTP_CREATED, 'Location' => $fullurl, 'Content-Type' => REST::best_xhtml_type() . '; charset=US-ASCII'));
    echo Portal::html_start('New database created') . "<a href=\"{$htmlurl}\" rel=\"child\" rev=\"index\">{$htmlurl}</a>" . Portal::html_end();