public function doPOST($sandbox, &$bashcode, &$database)
    {
        $name = $_POST['name'];
        if (empty($name)) {
            REST::fatal(REST::HTTP_BAD_REQUEST, 'Missing required parameter "name"');
        }
        file_put_contents($sandbox . 'name.txt', $name);
        $bashcode = <<<EOS
\${APPDIR}greeter \$(< "\${INDIR}name.txt" )
EOS;
    }
SELECT DISTINCT `handle`
FROM `handles`
WHERE `type` = ? AND `data` {$p_mode} ?
EOS
);
$statement->bind_param('ss', $key, $value);
foreach ($parampairs as $parampair) {
    list($key, $value) = $parampair;
    if ($p_mode == 'LIKE') {
        preg_match_all('/([^~]|~.|~)/s', $value, $matches);
        $value = implode(preg_replace(array('/%/', '/_/', '/^\\*/', '/^~(.+)/s'), array('\\%', '\\_', '%', '$1'), $matches[0]));
    }
    if (!$statement->execute()) {
        switch (CP_MySQL::mysql()->errno) {
            case 1139:
                REST::fatal(REST::HTTP_BAD_REQUEST, CP_MySQL::mysql()->error);
                break;
            default:
                throw new CP_MySQL_Exception(CP_MySQL::mysql()->error, CP_MySQL::mysql()->errno);
        }
    }
    $r_handle = null;
    $statement->bind_result($r_handle);
    $r_handles = array();
    while ($statement->fetch()) {
        $r_handles[$r_handle] = 1;
    }
    if ($handles === null) {
        $handles = $r_handles;
    } else {
        $handles = array_intersect_key($handles, $r_handles);
require_once 'include/global.php';
$userdnmd5 = md5(Portal::user_dn());
$proxy = Portal::PROXY_DIR . $userdnmd5 . '.pem';
$escproxy = str_replace("'", "\\'", $proxy);
if ($_SERVER['REQUEST_METHOD'] == 'PUT') {
    $input = REST::inputhandle();
    $output = fopen($proxy, 'w');
    while (!feof($input)) {
        if (($block = fread($input, 8192)) === false) {
            REST::fatal(REST::HTTP_INTERNAL_SERVER_ERROR, 'Error while reading PUT data');
        }
        fwrite($output, $block);
    }
    fclose($output);
    fclose($input);
    REST::header(array('status' => REST::HTTP_NO_CONTENT));
    exit;
}
REST::require_method('GET', 'HEAD');
if (file_exists($proxy)) {
    REST::header(array('Content-Type' => 'text/plain; charset=UTF-8'));
    system("openssl x509 -text -in '{$escproxy}'");
    exit;
}
REST::fatal(REST::HTTP_NOT_FOUND, <<<EOS
<p>Couldn't find a proxy. You could try to delegate credentials here:</p>
<ul>
<li><a href="myproxy">./myproxy</a></li>
</ul>
EOS
);
Exemple #4
0
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 * $Id$
 **************************************************************************/
require_once 'include/global.php';
$escPool = Topos::escape_string($TOPOS_POOL);
//Deprecated:
if ($_SERVER['REQUEST_METHOD'] === 'DELETE') {
    Topos::real_query(<<<EOS
DELETE `Pools`, `Tokens`
FROM `Pools` NATURAL LEFT JOIN `Tokens`
WHERE `Pools`.`poolName` = {$escPool};
EOS
);
    REST::fatal(REST::HTTP_OK, 'Pool destroyed successfully.');
}
REST::require_method('HEAD', 'GET');
// Fetch number of tokens
$query = <<<EOS
SELECT COUNT(`tokenId`), SUM(UNIX_TIMESTAMP() < `tokenLockTimeout`)
FROM `Pools` NATURAL JOIN `Tokens`
WHERE `poolName`  = {$escPool};
EOS;
list($ntokens, $nlocks) = Topos::query($query)->fetch_row();
$form = <<<EOS
<h2>Forms</h2>
<h3>Getting the next token</h3>
<form action="nextToken" method="get">
<input type="text" name="name"/> Token name search string<br/>
<input type="text" name="timeout"/> Timeout in seconds (leave empty for shared tokens)<br/>
Exemple #5
0
    if (!Topos::mysqli()->affected_rows) {
        REST::fatal(REST::HTTP_NOT_FOUND);
    }
}
$result = Topos::query(<<<EOS
SELECT `tokenId`,
       `tokenName`,
       `tokenLockTimeout` - UNIX_TIMESTAMP(),
       `tokenLockDescription`
FROM `Tokens`
WHERE `tokenLockUUID` = {$escLockUUID}
  AND `tokenLockTimeout` > UNIX_TIMESTAMP();
EOS
);
if (!($row = $result->fetch_row())) {
    REST::fatal(REST::HTTP_NOT_FOUND);
}
$tokenURL = Topos::urlbase() . 'pools/' . REST::urlencode($TOPOS_POOL) . '/tokens/' . $row[0];
$xhtmltype = REST::best_xhtml_type();
$bct = REST::best_content_type(array($xhtmltype => 1, 'text/plain' => 1), $xhtmltype);
if ($bct === 'text/plain') {
    REST::header(array('Content-Type' => 'text/plain; charset=US-ASCII', 'Cache-Control' => 'no-cache'));
    if ($_SERVER['REQUEST_METHOD'] === 'HEAD') {
        exit;
    }
    echo <<<EOS
TokenId: {$row[0]}
TokenName: {$row[1]}
TokenURL: {$tokenURL}
Timeout: {$row[2]}
Description: {$row[3]}
Exemple #6
0
                    }
                    // if ( !$stmt2->execute() )
                }
                // if (isset($t_upload_map[$paramname][$key]))
            }
            // foreach ( $file['name'] as $key => $filename )
        }
        // foreach ($_FILES as $paramname => $file)
    } catch (Topos_MySQL $e) {
        Topos::mysqli()->rollback();
        throw $e;
    }
    if (!Topos::mysqli()->commit()) {
        REST::fatal(REST::HTTP_SERVICE_UNAVAILABLE, 'Transaction failed: ' . htmlentities(Topos::mysqli()->error));
    }
    REST::fatal(REST::HTTP_ACCEPTED);
}
REST::require_method('HEAD', 'GET');
$query = <<<EOS
SELECT `tokenId`,
       `tokenLength`,
       `tokenType`,
       `tokenName`,
       `tokenLockUUID`,
       `tokenLockTimeout` - UNIX_TIMESTAMP(),
       `tokenLockDescription`,
       `tokenLeases`,
       `tokenCreated`
FROM `Tokens`
WHERE `poolId`  = {$poolId}
ORDER BY 1;
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`
 WHERE `token_id`={$escjobid}
   AND `user_id`={$escuserid};
EOS
);
if (!($row = $result->fetch_row())) {
    // Can't find what the user is looking for
    REST::fatal(REST::HTTP_GONE);
}
if (empty($row[0])) {
    REST::fatal(REST::HTTP_NOT_FOUND, "<p>Your job hasn't been executed yet. Try again later.</p>");
}
REST::fatal(REST::HTTP_OK, '<p>Your job finished with the following error:</p><pre>' . REST::htmlspecialchars($row[0]) . '</pre>');
    /**
     * @param bool $required
     * @return Portal_User
     */
    public static function current()
    {
        if (self::$current === null) {
            switch ($_SERVER['SERVER_PORT']) {
                case Portal::PORT_PLAIN:
                    self::unauthorized();
                    break;
                    // strictly unnecessary, but syntactically nicer.
                // strictly unnecessary, but syntactically nicer.
                case Portal::PORT_SSL:
                    if (!isset($_SERVER['PHP_AUTH_USER'])) {
                        self::unauthorized();
                    }
                    $user_email = Portal_MySQL::escape_string($_SERVER['PHP_AUTH_USER']);
                    $user_password = md5($_SERVER['PHP_AUTH_PW']);
                    $result = Portal_MySQL::query(<<<EOS
SELECT `user_id`, `user_name`, `user_dn` FROM `User`
WHERE `user_email`   =  {$user_email}
  AND `user_password`= '{$user_password}';
EOS
);
                    if (!($row = $result->fetch_row())) {
                        self::unauthorized();
                    }
                    self::$current = new Portal_User((int) $row[0], $_SERVER['PHP_AUTH_USER'], $row[1], $row[2]);
                    break;
                case Portal::PORT_SSL_CSA:
                    $user_dn = self::csa_dn();
                    if (isset($_SERVER['PHP_AUTH_USER']) && (int) $_SERVER['PHP_AUTH_USER'] > 0 && preg_match('@^/O=dutchgrid/O=users/O=sara/CN=(?:Evert Lammerts|Pieter van Beek)@', $_SERVER['SSL_CLIENT_S_DN'])) {
                        $esc_user_id = (int) $_SERVER['PHP_AUTH_USER'];
                        $result = Portal_MySQL::query(<<<EOS
SELECT `user_email`, `user_name`, `user_dn` FROM `User`
WHERE `user_id` = {$esc_user_id};
EOS
);
                        if (!($row = $result->fetch_row())) {
                            REST::fatal(REST::HTTP_UNAUTHORIZED, "No such user id: {$esc_user_id}");
                        }
                        self::$current = new Portal_User($esc_user_id, $row[1], $row[0], $row[2], true);
                    } else {
                        $esc_user_dn = Portal_MySQL::escape_string($user_dn);
                        $result = Portal_MySQL::query(<<<EOS
SELECT `user_id`, `user_email`, `user_name` FROM `User`
WHERE `user_dn` =  {$esc_user_dn};
EOS
);
                        if (!($row = $result->fetch_row())) {
                            self::unauthorized();
                        }
                        self::$current = new Portal_User($row[0], $row[2], $row[1], $user_dn);
                    }
                    break;
                default:
                    REST::fatal(REST::HTTP_INTERNAL_SERVER_ERROR);
            }
        }
        return self::$current;
    }
    if (!$mailresult) {
        REST::fatal(REST::HTTP_INTERNAL_SERVER_ERROR, <<<EOS
Your registration was successful, but the email containing your password could not be sent.
The site administrator has been informed and will contact you as soon as possible.
EOS
);
    }
    $message = <<<EOS
<p>Registration successful.</p>
<p>An e-mail with password has been sent to
<a href="mailto:{$_GET['email']}">{$_GET['email']}</a>.</p>
EOS;
    if ($referrer) {
        $message .= <<<EOS
<p>Click here to continue:<br/>
<a href="{$referrer}">{$referrer}</a></p>
EOS;
    }
    REST::fatal(REST::HTTP_ACCEPTED, $message);
}
REST::header(REST::best_xhtml_type() . '; charset="UTF-8"');
echo REST::html_start('Register') . <<<EOS
<p>Fill in your e-mail address and display name below, and you'll recieve a password.</p>
<form action="register.php" method="get">
<input type="hidden" name="referrer" value="{$referrer}"/>
<input type="text" name="email" value=""/> E-mail address (invisible to other users)<br/>
<input type="text" name="name" value=""/> Display name (visible to other users if you share your databases)<br/>
<input type="submit" value="Request password"/>
</form>
EOS
 . REST::html_end();
#!/bin/bash

DATABASE={$escdatabase}
APPLICATION='{$applicationURL}'
USER_ID={$user_id}

function runJob() (
{$bashcode}
)

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
 if (empty($_POST['username']) || empty($_POST['password']) || empty($_POST['server'])) {
     REST::fatal(REST::HTTP_BAD_REQUEST, 'Missing required parameter.');
 }
 //$output = array();
 $userdnmd5 = md5(Portal::user_dn());
 $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;
    public function doPOST($sandbox, &$bashcode, &$database)
    {
        $bashstring = <<<EOS
DBDIR=\${DBFILE}.d/
rm -rf \${DBDIR} || true
mkdir \${DBDIR}
cd \${DBDIR}
tar xf \${DBFILE}
if   [ \$( ls -1d *.pal 2>/dev/null | wc -l ) -eq 1 ]; then
  DB=\$( basename *.pal .pal )
elif [ \$( ls -1d *.pin 2>/dev/null | wc -l ) -eq 1 ]; then
  DB=\$( basename *.pin .pin )
else
  echo "No valid database found"
  exit 2
fi
cd \${OUTDIR}
\${APPDIR}omssa-2.1.4/omssacl -d \${DBDIR}\${DB}
EOS;
        // Check -d parameter
        if (empty($_POST[$this->db_url])) {
            REST::fatal(REST::HTTP_BAD_REQUEST, "You need to specify a database URL");
        }
        $database = $_POST[$this->db_url];
        // File uploads
        $filecounter = 0;
        foreach ($this->files as $input => $required) {
            if (Portal::isUploaded($input)) {
                if (!move_uploaded_file($_FILES[$input]['tmp_name'], $sandbox . $filecounter)) {
                    REST::fatal(REST::HTTP_INTERNAL_SERVER_ERROR, "Couldn't store uploaded file.");
                }
                $bashstring .= " -{$input} \"\${INDIR}{$filecounter}\"";
                $filecounter++;
            } else {
                if ($required) {
                    REST::fatal(REST::HTTP_BAD_REQUEST, "Missing required file {$input}");
                }
            }
        }
        // Check flags
        foreach ($this->flags as $flag) {
            if (!empty($_POST[$flag])) {
                $bashstring .= " -{$flag}";
            }
        }
        // Check params
        foreach ($this->params as $paramname => $defaultvalue) {
            if (isset($_POST[$paramname]) && strlen($_POST[$paramname]) && $_POST[$paramname] != $defaultvalue) {
                $bashstring .= " -{$paramname} " . escapeshellarg($_POST[$paramname]);
            }
        }
        $bashcode = $bashstring . " || exit 2";
    }
Exemple #13
0
 * limitations under the License.
 * 
 * $Id$
 **************************************************************************/
require_once 'include/global.php';
$poolId = Topos::poolId($TOPOS_POOL);
// TODO: the DELETE handler was written by Evert, using a subquery. I'm used
// to doing this with a single JOIN query...
if ($_SERVER['REQUEST_METHOD'] === 'DELETE') {
    Topos::real_query(<<<EOS
UPDATE `Tokens`
SET `tokenLockTimeout` = 0, `tokenLockUUID` = null
WHERE `poolId` = {$poolId};
EOS
);
    REST::fatal(REST::HTTP_OK, 'Locks destroyed successfully');
}
REST::require_method('HEAD', 'GET');
$result = Topos::query(<<<EOS
SELECT `tokenId`, `tokenName`, `tokenLockUUID`,
       `tokenLockTimeout` - UNIX_TIMESTAMP(), `tokenLockDescription`
FROM `Tokens`
WHERE `poolId` = {$poolId}
  AND `tokenLockTimeout` > UNIX_TIMESTAMP()
ORDER BY 1;
EOS
);
$directory = RESTDir::factory();
while ($row = $result->fetch_row()) {
    $directory->line($row[2], array('Token name' => $row[1], 'Timeout' => $row[3] > 0 ? sprintf('%d:%02d:%02d', $row[3] / 3600, $row[3] / 60 % 60, $row[3] % 60) : '', 'LockDescription' => $row[3] > 0 ? $row[4] : ''));
}
            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();
    exit;
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 * $Id: myproxy_renew.php 2378 2009-07-14 14:00:34Z pieterb $
 **************************************************************************/
/**
 * File documentation.
 * @package Portal
 */
require_once 'include/global.php';
if (Portal::user_dn() != @$_SERVER['SSL_SERVER_S_DN']) {
    REST::fatal(REST::HTTP_UNAUTHORIZED);
}
REST::require_method('GET');
foreach (glob(Portal::PROXY_DIR . '*.pem') as $fullfilename) {
    $escfullfilename = escapeshellarg($fullfilename);
    exec("grid-proxy-info -f {$escfullfilename} -exists -valid 1:00", $output, $returnval);
    if (!$returnval) {
        continue;
    }
    // The proxy is valid for at least another hour
    $user_dn_md5 = Portal_MySQL::escape_string(basename($fullfilename, '.pem'));
    $result = Portal_MySQL::query(<<<EOS
SELECT `proxy_server`, `proxy_username`, `proxy_password` FROM `User`
 WHERE `user_dn_md5` = {$user_dn_md5};
EOS
);
<?php

/*·************************************************************************
 * Copyright ©2009 SARA Computing and Networking Services
 *                 Amsterdam, the Netherlands
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License. You may obtain
 * a copy of the License at <http://www.apache.org/licenses/LICENSE-2.0>
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 * $Id$
 **************************************************************************/
require_once 'include/global.php';
REST::require_method('HEAD', 'GET');
if (!empty($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
    REST::fatal(REST::HTTP_NOT_MODIFIED);
}
$directory = RESTDir::factory()->setHeaders('Description');
$directory->line('pools/', array('Description' => 'A list of all pools. Forbidden for most users, for security reasons.'));
$directory->line('newPool', array('Description' => 'Redirects to a new, empty pool.'));
$directory->line('reference_manual', array('Description' => 'The official reference manual for this version of ToPoS.'));
$directory->end();
 public static function exception_handler($e)
 {
     self::debug($e->getMessage() . "\n\n" . $e->getTraceAsString());
     REST::fatal(REST::HTTP_INTERNAL_SERVER_ERROR, $e->getMessage());
 }
function sara_exception_handler(Exception $e)
{
    REST::fatal(REST::HTTP_INTERNAL_SERVER_ERROR, '<pre id="message">' . $e->getMessage() . "</pre>\n<pre>" . $e->getTraceAsString() . '</pre>');
}
     // The client MAY specify an index=n query parameter, to select a specific
     // URL:
     $index = isset($_GET['index']) ? (int) $_GET['index'] : null;
     // If the client didn't specify an index, find the URL with the lowest index:
     if ($index === null) {
         foreach ($handle->type as $idx => $type) {
             if ($type == 'URL' && ($index === null || $idx < $index)) {
                 $index = $idx;
             }
         }
         // If there's no URL, return a 404 Not Found:
         if ($index === null) {
             REST::fatal(REST::HTTP_NOT_FOUND, 'No URL for this handle');
         }
     } elseif (!isset($handle->type[$index]) || $handle->type[$index] != 'URL') {
         REST::fatal(REST::HTTP_NOT_FOUND, 'No URL with that index');
     }
     // Finally, get the URL:
     $url = $handle->data[$index];
     // Append the URL with the current query string.
     // We leave out the "index" and "redirect" fields, though.
     unset($_GET['index']);
     unset($_GET['redirect']);
     if (!empty($_GET)) {
         $url .= '?' . http_build_query($_GET);
     }
     // Finally, perform the actual redirect:
     REST::redirect(REST::HTTP_TEMPORARY_REDIRECT, $url);
 }
 $xhtml_type = REST::best_xhtml_type() . '; charset=UTF-8';
 $content_type = REST::best_content_type(array($xhtml_type => 1.0, 'application/json' => 1.0, 'application/x-www-form-urlencoded' => 1.0, 'text/plain; charset=US-ASCII' => 0.5), $xhtml_type);
Exemple #20
0
  {$nameClause}
LIMIT 100;
EOS
);
        if ($result->num_rows) {
            break;
        }
        $result = Topos::query(<<<EOS
SELECT MIN(`tokenLeases`) FROM `Tokens`
WHERE `poolId` = {$poolId}
  AND `tokenLockTimeout` <= UNIX_TIMESTAMP();
EOS
);
        $row = $result->fetch_row();
        if ($row[0] === null) {
            REST::fatal(REST::HTTP_NOT_FOUND, 'No token available');
        }
        Topos::real_query(<<<EOS
UPDATE `Pools`
SET `minLeases` = {$row[0]}
WHERE `poolId` = {$poolId};
EOS
);
    }
    // while
    while ($row = $result->fetch_row()) {
        Topos::real_query(<<<EOS
UPDATE `Tokens` SET `tokenLeases` = {$row[1]} + 1 {$timeout}
WHERE `tokenId` = {$row[0]} AND `tokenLeases` = {$row[1]};
EOS
);
<input type="text" name="total"/> Total number of tokens<br/>
<input type="submit" value="Show progress bar"/>
</form>
EOS
);
}
$total = (int) $_GET['total'];
if ($total === 0) {
    $total = 1;
}
$percentage = 100 * $tokens / $total;
if ($percentage > 100) {
    REST::fatal(REST::HTTP_BAD_REQUEST, <<<EOS
<p>The total number of tokens cannot be smaller than the number of tokens in this pool.</p>
<form action="progress" method="get">
<input type="text" name="total"/> Total number of tokens<br/>
<input type="submit" value="Show progress bar"/>
</form>
EOS
);
}
$bct = REST::best_content_type(array('text/html' => 1, 'application/xhtml+xml' => 1, 'text/plain' => 1), 'text/html');
if ($bct === 'text/plain') {
    REST::header(array('Content-Type' => 'text/plain; charset=US-ASCII', 'Refresh' => '60; ' . $_SERVER['REQUEST_URI'], 'Cache-Control' => 'no-cache'));
    if ($_SERVER['REQUEST_METHOD'] === 'HEAD') {
        exit;
    }
    echo $tokens / $total;
    exit;
}
REST::header(array('Content-Type' => REST::best_xhtml_type() . '; charset=UTF-8', 'Refresh' => '60; ' . $_SERVER['REQUEST_URI'], 'Cache-Control' => 'no-cache'));
if ($_SERVER['REQUEST_METHOD'] === 'HEAD') {
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 * $Id$
 **************************************************************************/
require_once 'include/global.php';
REST::require_method('HEAD', 'GET');
if (!preg_match('/^(?:145\\.100\\.(?:6|7|15)\\.|82\\.93\\.61\\.215)/', $_SERVER['REMOTE_ADDR'])) {
    REST::fatal(REST::HTTP_FORBIDDEN, <<<EOS
<p>Sorry, for security reasons you're not allowed to get a directory
listing for this URL.</p>
<p>However, you <em>do</em> have access to any subdirectory,
such as <a href="example/">this</a>.</p>
EOS
);
}
$result = Topos::query(<<<EOS
SELECT `poolName`, COUNT(*)
FROM `Pools` NATURAL JOIN `Tokens`
GROUP BY `poolId`
ORDER BY 1;
EOS
);
$directory = RESTDir::factory();
while ($row = $result->fetch_row()) {
    $directory->line(urlencode($row[0]) . '/', array('Size' => $row[1] . ' tokens'));
}
    public function doPOST($sandbox, &$bashcode, &$database)
    {
        // Normaliseren van boolean options:
        //    foreach (self::$FLAGS as $value)
        //      if (!isset($_POST[$value]))
        //        $_POST[$value] = 'F';
        $options = array();
        foreach (self::$DEFAULT_OPTIONS as $option => $default) {
            if (array_key_exists($option, $_POST) and $_POST[$option] !== $default) {
                $options[$option] = $_POST[$option];
            }
        }
        foreach (self::$REQUIRED_OPTIONS as $req_opt) {
            if (empty($options[$req_opt])) {
                REST::fatal(REST::HTTP_BAD_REQUEST, "Missing required option {$req_opt}");
            }
        }
        // Optie 'd' wordt apart afgehandeld:
        $database = $options['d'];
        unset($options['d']);
        // Parse the C option
        // In the blastall command, the value of option '-C' may optionally be
        // appended by a 'U' character. See the blastall manual for more info.
        if (isset($options['Cu'])) {
            if ($options['Cu'] and isset($options['C']) and (int) $options['C'] > 0) {
                $options['C'] .= 'U';
            }
            unset($options['Cu']);
        }
        // The O options is interfaced as a flag,
        // but its value is not a boolean (either null or 'SeqAlign')
        if (!empty($options['O'])) {
            $options['O'] = 'SeqAlign';
        }
        // Check flags
        //    foreach (self::$FLAGS as $flag) {
        //        $bashstring .=   " -{$flag} " . (!empty($_POST[$flag]) ? 'T' : 'F');
        //    }
        // Handle incoming files:
        foreach (self::$INPUT_FILES as $infile => $required) {
            if (isset($_FILES[$infile]) && $_FILES[$infile]['error'] != UPLOAD_ERR_NO_FILE) {
                if ($_FILES[$infile]['error'] != UPLOAD_ERR_OK) {
                    REST::fatal(REST::HTTP_BAD_REQUEST, "File upload failed: {$_FILES[$infile]['error']}");
                }
                move_uploaded_file($_FILES[$infile]['tmp_name'], $sandbox . "in_{$infile}");
                $options[$infile] = "\"\${INDIR}in_{$infile}\"";
            } elseif ($required) {
                REST::fatal(REST::HTTP_BAD_REQUEST, "Missing required option -{$infile}");
            }
        }
        // Escape shell arguments to prevent code insertion:
        foreach (self::$DEFAULT_OPTIONS as $key => $value) {
            if (isset($options[$key])) {
                $options[$key] = escapeshellarg($options[$key]);
            }
        }
        $bashcode = <<<EOS
if [ ! -e "\${DBFILE}.d" ]; then
  mkdir -p "\${DBFILE}.d"
  tar -z -x -C "\${DBFILE}.d" -f "\${DBFILE}" || exit 1
fi
pushd "\${DBFILE}.d"
if   [ \\( \$( echo *.nal | wc -w ) -eq 1 \\) -a \\( -f *.nal \\) ]; then
  DBNAME=\$( basename *.nal .nal )
elif [ \\( \$( echo *.pal | wc -w ) -eq 1 \\) -a \\( -f *.pal \\) ]; then
  DBNAME=\$( basename *.pal .pal )
elif [ \\( \$( echo *.nin | wc -w ) -eq 1 \\) -a \\( -f *.nin \\) ]; then
  DBNAME=\$( basename *.nin .nin )
elif [ \\( \$( echo *.pin | wc -w ) -eq 1 \\) -a \\( -f *.pin \\) ]; then
  DBNAME=\$( basename *.pin .pin )
else
  exit 2
fi
popd
\${APPDIR}blastall -d \${DBFILE}.d/\${DBNAME}
EOS;
        foreach ($options as $key => $value) {
            $bashcode .= " -{$key} {$value}";
        }
        $bashcode .= ' >"blast.out" || exit 2';
    }
 /**
  * Handles a POST request.
  * The returned bash-code can use the following environment variables:
  * - INDIR
  * - OUTDIR
  * - DBFILE
  * The bashcode must return one of the following exit statuses:
  * - 0: OK
  * - 1: Transient error, try again.
  * - 2: Fatal error, this job will always fail.
  * @param string $sandbox name of the input sandbox directory,
  *        including trailing slash
  * @param string $bashcode (by reference) some bash code to execute.
  * @param string $database (by reference) URL of the database to use
  * @return void
  */
 public function doPOST($sandbox, &$bashcode, &$database)
 {
     REST::fatal(REST::HTTP_NOT_IMPLEMENTED, 'Portal_App::doPOST()');
 }
    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 function doPOST($sandbox, &$bashcode, &$database)
    {
        $options = array();
        foreach (self::$INTEGERS as $option => $default) {
            if (!isset($_POST[$option])) {
                continue;
            }
            if (!preg_match('/^\\s*\\d+\\s*$/', $_POST[$option])) {
                REST::fatal(REST::HTTP_BAD_REQUEST, "<p>Bad value for option '-{$option}'</p>");
            }
            if ($_POST[$option] !== $default) {
                $options[$option] = $_POST[$option];
            }
        }
        foreach (self::$FLOATS as $option => $default) {
            if (!isset($_POST[$option])) {
                continue;
            }
            if (!preg_match('/^\\s*(?:\\d+(?:\\.\\d+)?|\\.\\d+)(?:[eE][+\\-]?\\d+)?\\s*$/', $_POST[$option])) {
                REST::fatal(REST::HTTP_BAD_REQUEST, "<p>Bad value for option '-{$option}'</p>");
            }
            if ($_POST[$option] !== $default) {
                $options[$option] = $_POST[$option];
            }
        }
        foreach (self::$OUTPUT_FILES as $option => $filename) {
            if (!empty($_POST[$option])) {
                $options[$option] = $filename;
            }
        }
        foreach (self::$FLAGS as $option) {
            if (!empty($_POST[$option])) {
                $options[$option] = null;
            }
        }
        if (!empty($_POST['M'])) {
            if (!in_array(strtolower($_POST['M']), array('c', 'g'))) {
                REST::fatal(REST::HTTP_BAD_REQUEST, "<p>Bad value for option '-M'</p>");
            }
            $options['M'] = strtolower($_POST['M']);
        }
        if (!isset($_POST['chr'])) {
            REST::fatal(REST::HTTP_BAD_REQUEST, "<p>Missing required option 'chr'</p>");
        }
        $database = $_POST['chr'];
        // Handle incoming files:
        $input_files = '"${DBFILE}"';
        foreach (self::$INPUT_FILES as $infile => $required) {
            if (isset($_FILES[$infile]) && $_FILES[$infile]['error'] != UPLOAD_ERR_NO_FILE) {
                if ($_FILES[$infile]['error'] != UPLOAD_ERR_OK) {
                    REST::fatal(REST::HTTP_BAD_REQUEST, "File upload failed: {$_FILES[$infile]['error']}");
                }
                move_uploaded_file($_FILES[$infile]['tmp_name'], $sandbox . "in_{$infile}");
                $input_files .= " \"\${INDIR}in_{$infile}\"";
            } elseif ($required) {
                REST::fatal(REST::HTTP_BAD_REQUEST, "Missing required option input file '{$infile}'");
            }
        }
        $bashcode = <<<EOS
#if [ ! -e "\${DBFILE}.bfa" ]; then
#  "\${APPDIR}maq" fasta2bfa "\${DBFILE}" "\${DBFILE}.bfa" || exit 1
#fi
{ "\${APPDIR}maq" map
EOS;
        foreach ($options as $key => $value) {
            $bashcode .= " -{$key} {$value}";
        }
        $bashcode .= " out.map {$input_files} || exit 2; } || exit 1";
    }