/** * @param $title string plain text * @return RESTDir */ public static function factory($title = null) { if ($title === null) { preg_match('@^(.*)/@', $_SERVER['REQUEST_URI'], $matches); $title = 'Index for ' . htmlspecialchars($matches[1] . '/', ENT_QUOTES, 'UTF-8'); } $best_xhtml_type = REST::best_xhtml_type(); $type = REST::best_content_type(array($best_xhtml_type => 1.0, 'text/plain' => 0.3, 'text/tdv' => 0.5, 'text/csv' => 0.8, 'application/json' => 1.0), $best_xhtml_type); REST::header("{$type}; charset=UTF-8"); switch ($type) { case 'application/xhtml+xml': case 'text/html': return new RESTDirHTML($title); case 'text/tdv': case 'text/plain': return new RESTDirPlain($title); case 'application/json': return new RESTDirJSON($title); case 'text/csv': return new RESTDirCSV($title); } }
<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') { exit; } echo REST::html_start('Progress'); ?> <table class="progress"><tbody> <tr> <td style="width: <?php echo $width * $tokens / $total; ?> pt;" class="done"> <?php if ($percentage >= 50) { echo sprintf('%.1f%%', $percentage); }
$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); // When was this handle last modified? $modified = 0; foreach ($handle->timestamp as $idx => $timestamp) { if ($timestamp > $modified) { $modified = $timestamp; } } REST::check_if_modified_since($modified); REST::header(array('status' => REST::HTTP_OK, 'Content-Type' => $content_type, 'Modified' => REST::http_date($modified))); // For a HEAD request, we can quit now: if ($_SERVER['REQUEST_METHOD'] === 'HEAD') { exit; } if ($content_type == $xhtml_type) { echo REST::html_start('Metadata for handle ' . htmlspecialchars($handle->handle(), ENT_COMPAT, 'UTF-8')); echo <<<EOS <table class="handledata"><tbody><tr> <th class="idx">idx</th> <th class="type">type</th> <th class="data">data</th> <th class="data">refs</th> <th class="modified">timestamp</th> </tr> EOS;
$tmpfilename = tempnam('/tmp', 'portal_'); $tmpfile = fopen($tmpfilename, 'w'); while (($block = fread(REST::inputhandle(), 8192)) !== "") { fwrite($tmpfile, $block); } fclose(REST::inputhandle()); fclose($tmpfile); if (isset($_SERVER['CONTENT_LENGTH']) && $_SERVER['CONTENT_LENGTH'] != filesize($tmpfilename)) { unlink($tmpfilename); REST::fatal(REST::HTTP_BAD_REQUEST, "Content-Length header doesn't match actual content length."); } if (!rename($tmpfilename, Portal::JOBRESULTS_DIR . $jobid)) { unlink($tmpfilename); REST::fatal(REST::HTTP_INTERNAL_SERVER_ERROR, "Couldn't store uploaded file."); } chmod(Portal::JOBRESULTS_DIR . $jobid, 0660); REST::header(array('status' => REST::HTTP_NO_CONTENT)); exit; } // The user tries to get information about his jobs if (file_exists($fullfilename = Portal::JOBRESULTS_DIR . $jobid)) { // The job has finished and we have a result $filename = basename($fullfilename); $fileinfo = @stat($fullfilename); REST::header(array('Content-Type' => 'application/x-compressed-tar', 'Content-Disposition' => "attachment; filename=\"{$filename}.tgz\"", 'Last-Modified' => REST::http_date($fileinfo['mtime']), 'Content-Length' => $fileinfo['size'])); if ($_SERVER['REQUEST_METHOD'] == 'GET') { readfile($fullfilename); } exit; } REST::fatal(REST::HTTP_NOT_FOUND);
} 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` WHERE `token_id`={$escjobid} AND `user_id`={$escuserid}; EOS ); if (!($row = $result->fetch_row())) { // Can't find what the user is looking for
} if ($handles === null) { $handles = $r_handles; } else { $handles = array_intersect_key($handles, $r_handles); } } ksort($handles); $handles = array_keys($handles); if ($p_max > 0) { $handles = array_slice($handles, $p_page * $p_max, $p_max); } //... And print everything $xhtml_type = REST::best_xhtml_type() . '; charset=UTF-8'; $content_type = REST::best_content_type(array($xhtml_type => 1.0, 'application/json' => 1.0), $xhtml_type); REST::header(array('status' => REST::HTTP_OK, 'Content-Type' => $content_type)); // For a HEAD request, we can quit now: if ($_SERVER['REQUEST_METHOD'] === 'HEAD') { exit; } if ($content_type == $xhtml_type) { echo REST::html_start('Searchresults'); echo <<<EOS <table class="searchresults"><tbody><tr> <th class="handle">Handle</th> </tr> EOS; $num_rows = 0; while ($search_stmt->fetch()) { $num_rows++; echo "<tr class=\"handle\"><td><a href=\"" . CP::PORTAL_URL . "{$handle}\">{$handle}</a></td></tr>";
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 );
} 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])) { REST::fatal(REST::HTTP_NOT_FOUND); } $user_id = Portal_User::current()->user_id(); $result = Portal_MySQL::query(<<<EOS SELECT `d`.`name`, `d`.`version`, `d`.`type`, `d`.`checksum`, `u`.`user_name` FROM `Database` AS d LEFT JOIN `User` AS u USING(`user_id`) WHERE `d`.`database_id` = {$database_id} AND (`d`.`user_id` = {$user_id} OR `d`.`is_shared` = 1); EOS ); if (!($row = $result->fetch_row())) { REST::fatal(REST::HTTP_NOT_FOUND); } $fileinfo = @stat($realfilepath); $filename = "{$row[0]}-{$row[1]}." . Portal_DB::databaseTypeExtension($row[2]); REST::header(array('Content-Type' => Portal_DB::databaseTypeContentType($row[2]), 'Content-Encoding' => 'identity', 'Content-Disposition' => "attachment; filename=\"{$filename}\"", 'Last-Modified' => REST::http_date($fileinfo['mtime']), 'ETag' => "\"{$row[3]}\"", 'X-Creator-Name' => $row[4], 'Content-Length' => $fileinfo['size'])); if ($_SERVER['REQUEST_METHOD'] == 'GET') { readfile($realfilepath); }
$result = Topos::query(<<<EOS SELECT `tokenLength`, `tokenType`, `tokenCreated`, `tokenName`, IF(`tokenLockTimeout` > UNIX_TIMESTAMP(), `tokenLockUUID`, NULL) AS 'tokenLockUUID', `tokenLeases` FROM `Tokens` WHERE `tokenId` = {$TOPOS_TOKEN} AND `poolId` = {$poolId}; EOS ); if (!($row = $result->fetch_array())) { REST::fatal(REST::HTTP_NOT_FOUND); } $result = Topos::query(<<<EOS SELECT `tokenValue` FROM `TokenValues` WHERE `tokenId` = {$TOPOS_TOKEN} EOS ); $tokenValue = $result->fetch_row(); $tokenValue = $tokenValue[0]; $headers = array('Content-Type' => $row['tokenType'], 'Content-Length' => $row['tokenLength'], 'Last-Modified' => REST::http_date($row['tokenCreated']), 'X-Number-Of-Leases' => $row['tokenLeases']); if (!empty($row['tokenName'])) { $headers['Content-Disposition'] = 'inline; filename="' . $row['tokenName'] . '"'; } if (array_key_exists('tokenLockUUID', $row)) { $headers['X-Topos-OpaqueLockToken'] = "opaquelocktoken:{$row['tokenLockUUID']}"; $headers['X-Topos-LockURL'] = Topos::urlbase() . 'pools/' . REST::urlencode($TOPOS_POOL) . '/locks/' . $row['tokenLockUUID']; } REST::header($headers); if ($_SERVER['REQUEST_METHOD'] === 'HEAD') { exit; } echo $tokenValue;
/** * Shows a message screen to the user. * @param string $message HTML message * @param string $status HTTP status * @param string $redirect URL for automatic redirection * @param string $location Location of the created URL */ public static function show_message($message, $status, $location) { REST::header(array('status' => $status, 'Content-Type' => REST::best_xhtml_type() . '; charset=UTF-8', 'Location' => REST::rel2url($location))); echo REST::html_start('Redirect') . <<<EOS <p>{$message}</p> <script type="text/javascript"><![CDATA[ setTimeout( 'window.location.href = "{$location}";', 1000 ); ]]></script> EOS; echo REST::html_end(); exit; }
INSERT INTO `OrphanValues` SELECT `TV`.`tokenId` FROM `TokenValues` AS `TV` NATURAL LEFT JOIN `Tokens` AS `T` WHERE `T`.`tokenId` IS NULL; EOS ); Topos::real_query(<<<EOS DELETE `TokenValues` FROM `OrphanValues` NATURAL JOIN `TokenValues`; EOS ); Topos::real_query(<<<EOS DROP TABLE `OrphanValues`; EOS ); REST::header(array('Content-Type' => REST::best_xhtml_type() . '; charset=UTF-8')); echo REST::html_start('Pool'); echo '<p>Pool destroyed successfully.</p>'; echo REST::html_end(); exit; } 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>
cat pilotstdout.txt >> pilotstderr.txt \${CURL} --upload-file pilotstderr.txt --header 'Content-Type: text/plain' "\${PORTAL_JOBS}\${TOKEN_ID}" || true; [ \${STATUS} -eq 2 ] && \${CURL} -X DELETE "\$TOKEN_URL" || true fi done EOS; } // function myPilotJob function myRemoveTempFiles() { global $TEMPNAM; exec("rm -rf {$TEMPNAM}*"); } REST::header('text/plain; charset=UTF-8'); $TEMPNAM = tempnam('/tmp', 'portal'); register_shutdown_function('myRemoveTempFiles'); foreach (glob(Portal::PROXY_DIR . '*.pem') as $fullproxyfile) { #$escfilename = escapeshellarg($filename); $proxyfile = basename($fullproxyfile); if (!preg_match('/^([a-f0-9]{32})\\.pem$/', $proxyfile, $matches)) { Portal::debug("Strange proxy filename: {$proxyfile}"); @unlink($fullproxyfile); continue; } $userdnmd5 = $matches[1]; $escuserdnmd5 = Portal_MySQL::escape_string($userdnmd5); $result = Portal_MySQL::query(<<<EOS SELECT `user_dn`, `proxy_server`, `proxy_username`, `proxy_password` FROM `User`
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"> <table border="0" cellpadding="0" cellspacing="0"><tbody> <tr><td>Username</td><td><input type="text" name="username" /></td></tr> <tr><td>Password</td><td><input type="password" name="password" /></td></tr> <tr><td>MyProxy server</td><td><input type="text" name="server" value="{$default_server}" /></td></tr> <tr><td> </td><td><input type="submit" value="Delegate" /></td></tr> </tbody></table> </form> EOS . Portal::html_end();
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();
$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]} EOS; exit; } REST::header(array('Content-Type' => $xhtmltype . '; charset=UTF-8', 'Cache-Control' => 'no-cache')); if ($_SERVER['REQUEST_METHOD'] === 'HEAD') { exit; } echo REST::html_start('Lock info'); ?> <h2>Lock info</h2> <table class="lockinfo"><tbody> <tr><th>TokenId:</th><td id="tokenId"><?php echo htmlentities($row[0]); ?> </td></tr> <tr><th>TokenName:</th><td id="tokenName"><?php echo htmlentities($row[1]); ?> </td></tr>
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 ); REST::header(REST::best_xhtml_type() . '; charset="UTF-8"'); echo REST::html_start('Usage statistics') . <<<EOS <!--<form action="stats" method="post"> token: <input type="text" name="token" value=""/> seconds: <input type="text" name="seconds" value=""/> <input type="submit"/> </form>--> <table class="usagestats"><tbody> <tr> <th class="date">Date</th> <th class="walltime">Walltime</th> <th class="status">Status</th> </tr> EOS; $STATUS_STRING = array(0 => 'OK', 1 => 'Transient error', 2 => 'Fatal error'); while ($row = $result->fetch_row()) {
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; } REST::require_method('GET', 'HEAD'); $options = ''; foreach (Portal_DB::databaseTypeIDs() as $databaseTypeID) { $databaseTypeName = Portal_DB::databaseTypeName($databaseTypeID); $options .= "\n<option value=\"{$databaseTypeName}\">{$databaseTypeName}</option>"; } $directory = RESTDir::factory("{$path_info[0]}, version {$path_info[1]}")->setForm(<<<EOS <h1>Database upload</h1> <form method="post" action="./" enctype="multipart/form-data"> <input type="file" name="dbfile" /><br /> <input type="checkbox" name="shared" value="1" /> Share this database with others<br /> Database type: <select name="type">