-
Notifications
You must be signed in to change notification settings - Fork 1
/
tokens.php
284 lines (270 loc) · 9.35 KB
/
tokens.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
<?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');
$escPool = Topos::escape_string($TOPOS_POOL);
$poolId = Topos::poolId($TOPOS_POOL);
if ($_SERVER['REQUEST_METHOD'] === 'DELETE') {
// Topos::real_query('START TRANSACTION;');
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.'
);
}
// Handle the creation of a number of tokens, set by the user.
$input = NULL;
if ( $_SERVER['REQUEST_METHOD'] === 'POST' &&
strpos( @$_SERVER['CONTENT_TYPE'], 'application/x-www-form-urlencoded' ) === 0 ) {
if ( isset( $_POST['pool'] ) ) {
if ( $_POST['pool'] === '' )
REST::fatal(
REST::HTTP_BAD_REQUEST,
'Empty parameter "pool"'
);
$tokens = isset( $_POST['tokens'] )
? preg_split('/[^\\d]+/', $_POST['tokens'], -1, PREG_SPLIT_NO_EMPTY)
: array();
$tgtPool = $poolId;
$srcPool = Topos::poolId($_POST['pool']);
$tokenIds = count($tokens)
? 'AND `tokenId` IN (' . implode(',', $tokens) . ')'
: '';
Topos::real_query(<<<EOS
UPDATE `Tokens`
SET `poolId` = $tgtPool
WHERE `poolId` = $srcPool
$tokenIds;
EOS
);
REST::fatal(
REST::HTTP_OK,
Topos::mysqli()->affected_rows . ' tokens moved'
);
} elseif ( isset( $_POST['ntokens'] ) ) {
$offset = (int)(@$_POST['offset']);
$ntokens = (int)($_POST['ntokens']);
if ($ntokens <= 0 || $ntokens > 1000000)
REST::fatal(
REST::HTTP_BAD_REQUEST,
'Bad values for "ntokens" or "offset"'
);
Topos::real_query(
"CALL `createTokens`({$escPool}, {$ntokens}, {$offset});"
);
REST::fatal(REST::HTTP_ACCEPTED);
} elseif ( isset( $_POST['tokens'] ) ) {
$input = tmpfile();
fwrite( $input, $_POST['tokens'] );
fseek( $input, 0 );
$_SERVER['CONTENT_TYPE'] = 'text/plain; charset="UTF-8"';
} else REST::fatal( REST::HTTP_BAD_REQUEST );
}
// Handle a upload of a single text file, of which each line will be a token.
if ( $_SERVER['REQUEST_METHOD'] === 'POST' &&
strpos( @$_SERVER['CONTENT_TYPE'], 'text/' ) === 0 ) {
$esccontenttype = Topos::escape_string($_SERVER['CONTENT_TYPE']);
if (!$input) $input = REST::inputhandle();
$stmt1 = Topos::mysqli()->prepare(<<<EOS
INSERT INTO `TokenValues` (
`tokenValue`
) VALUES (?);
EOS
);
$stmt2 = Topos::mysqli()->prepare(<<<EOS
INSERT INTO `Tokens` (
`tokenId`, `poolId`, `tokenType`, `tokenLength`, `tokenCreated`
) VALUES (?, {$poolId}, {$esccontenttype}, ?, UNIX_TIMESTAMP());
EOS
);
$bindTokenValue = $bindTokenId = $bindTokenLength = null;
$stmt1->bind_param("s", $bindTokenValue);
$stmt2->bind_param("ii", $bindTokenId, $bindTokenLength);
ini_set('auto_detect_line_endings', 1);
while ( ( $line = fgets( $input ) ) ) {
$bindTokenValue = rtrim( $line, "\r\n" );
if ( !$stmt1->execute() )
REST::fatal(
REST::HTTP_INTERNAL_SERVER_ERROR,
'stmt1: ' . $stmt1->error
);
$bindTokenId = $stmt1->insert_id;
$bindTokenLength = strlen($bindTokenValue);
if ( !$stmt2->execute() )
REST::fatal(
REST::HTTP_INTERNAL_SERVER_ERROR,
'stmt2: ' . $stmt2->error
);
}
REST::fatal(REST::HTTP_ACCEPTED);
}
// Handle upload of multiple tokens in a multipart/form-data request body:
if ( $_SERVER['REQUEST_METHOD'] === 'POST' ) {
// Check if we have the right mime type:
if ( strpos( @$_SERVER['CONTENT_TYPE'], 'multipart/form-data' ) !== 0 )
REST::fatal(REST::HTTP_UNSUPPORTED_MEDIA_TYPE);
if (empty($_FILES))
REST::fatal(REST::HTTP_BAD_REQUEST, "Nothing to process");
$stmt1 = Topos::mysqli()->prepare(<<<EOS
INSERT INTO `TokenValues` (
`tokenValue`
) VALUES (?);
EOS
);
$stmt2 = Topos::mysqli()->prepare(<<<EOS
INSERT INTO `Tokens` (
`tokenId`, `poolId`, `tokenName`, `tokenType`, `tokenLength`, `tokenCreated`
) VALUES (?, {$poolId}, ?, ?, ?, UNIX_TIMESTAMP());
EOS
);
$bindTokenValue = $bindTokenId = $bindTokenType = $bindTokenLength = $bindTokenName = null;
$stmt1->bind_param("b", $bindTokenValue);
$stmt2->bind_param("issi", $bindTokenId, $bindTokenName, $bindTokenType, $bindTokenLength);
$t_upload_map = array();
foreach ($_FILES as $paramname => $file) {
if (!is_array( $file['error'] ) ) {
$file['name' ] = array( $file['name' ] );
$file['error' ] = array( $file['error' ] );
$file['type' ] = array( $file['type' ] );
$file['tmp_name'] = array( $file['tmp_name'] );
$file['size' ] = array( $file['size' ] );
}
foreach ( $file['name'] as $key => $filename ) {
if ( $file['error'][$key] === UPLOAD_ERR_NO_FILE )
continue;
if ( $file['error'][$key] !== UPLOAD_ERR_OK )
REST::fatal(
REST::HTTP_BAD_REQUEST,
"Errno {$file['error'][$key]} occured during file upload."
);
$stream = fopen( $file['tmp_name'][$key], 'r' );
while ( !feof($stream) )
$stmt1->send_long_data( 0, fread( $stream, 8192 ) );
fclose($stream);
if ( !$stmt1->execute() )
REST::fatal(
REST::HTTP_INTERNAL_SERVER_ERROR,
'stmt1: ' . $stmt1->error
);
$t_upload_map[$paramname][$key] = $stmt1->insert_id;
} // foreach ( $file['name'] as $key => $filename )
} // foreach ($_FILES as $paramname => $file)
// For this operation, we need MySQL transactions.
Topos::real_query('START TRANSACTION;');
try {
foreach ($_FILES as $paramname => $file) {
foreach ( $file['name'] as $key => $filename ) {
if (isset($t_upload_map[$paramname][$key])) {
$bindTokenId = $t_upload_map[$paramname][$key];
$bindTokenName = empty($filename) ? '' : $filename;
$bindTokenType = empty($file['type'][$key])
? 'application/octet-stream' : $file['type'][$key];
$bindTokenLength = $file['size'][$key];
if ( !$stmt2->execute() ) {
Topos::mysqli()->rollback();
REST::fatal(
REST::HTTP_INTERNAL_SERVER_ERROR,
'stmt2: ' . $stmt2->error
);
} // if ( !$stmt2->execute() )
} // if (isset($t_upload_map[$paramname][$key]))
} // foreach ( $file['name'] as $key => $filename )
} // foreach ($_FILES as $paramname => $file)
} // try
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;
EOS;
$result = Topos::query($query);
$form = <<<EOS
<h2>Forms</h2>
<h3>Populate this pool with numbers</h3>
<form action="./" method="post">
<input type="text" name="ntokens"/> #tokens<br/>
<input type="text" name="offset"/> offset<br/>
<input type="submit" value="Populate"/>
</form>
<h3>Move tokens into this pool</h3>
<form action="./" method="post">
<input type="text" name="pool"/> Source pool name<br/>
<input type="text" name="tokens"/> Token IDs (separated by anything)<br/>
<input type="submit" value="Move"/>
</form>
<h3>Create tokens from a parameter list</h3>
<form action="./" method="post">
<textarea name="tokens"></textarea><br/>
<input type="submit" value="Create"/>
</form>
<h3>Create tokens from files</h3>
<form action="./" method="post" enctype="multipart/form-data">
<input type="file" name="create[]" /> File 1<br />
<input type="file" name="create[]" /> File 2<br />
<input type="file" name="create[]" /> File <i>n</i><br />
<input type="submit" value="Post file(s)" />
</form>
EOS;
$directory = RESTDir::factory('Tokens')->setForm($form);
header('X-Token-Count: ' . $result->num_rows);
while ($row = $result->fetch_row())
$directory->line(
$row[0], array(
'Size' => $row[1] . ' B',
'Content-Type' => $row[2],
'Original Name' => $row[3],
'LockTokenHTML' => ($row[5] > 0 ? "<a href=\"../locks/{$row[4]}\">{$row[4]}</a>" : ''),
'Timeout' => (
$row[5] > 0
? sprintf( '%d:%02d:%02d',
($row[5] / 3600),
($row[5] / 60 % 60),
($row[5] % 60)
)
: ''
),
'Created' => Topos::sortable_date( $row[8] ),
'Leases' => $row[7],
'LockDescription' => ($row[5] > 0 ? $row[6] : ''),
)
);
$directory->end();