-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathendpointManager.php
More file actions
542 lines (459 loc) · 21.5 KB
/
endpointManager.php
File metadata and controls
542 lines (459 loc) · 21.5 KB
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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
<?php
require_once "head.php";
require_once "classes/Endpoint.php";
require_once "classes/EndpointManager.php";
$manager = new EndpointManager();
// Lista de MIME types comunes
$mimeTypes = $manager->getMimetypes();
// Indica si estamos creando o editando
$CREATE = "create";
$EDIT = "edit";
// Valores por defecto
$mode = $CREATE;
$id = null;
$url = null;
$method = null;
$inputMime = null;
$outputMime = null;
$scheme = null;
$returnText = null;
$scriptName = null;
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if(isset($_POST['mode'])) {
$mode = $_POST['mode'];
}
if ( !isset($_POST['url'], $_POST['method'], $_POST['inputMime'], $_POST['outputMime'], $_POST['scheme']) || (!isset($_FILES['script']) && !isset($_POST['returntext'])) || ($mode==$EDIT && !isset($_POST['id'])) ) {
$error = "Todos los campos son obligatorios. Debe escoger un script PHP o indicar un texto a devolver.";
} else {
if($mode==$EDIT) {
$id = $_POST['id'];
}
$url = $_POST['url'];
$method = strtoupper($_POST['method']);
$inputMime = $_POST['inputMime'];
$outputMime = $_POST['outputMime'];
$scheme = $_POST['scheme'];
$returnText = "";
if(isset($_POST['returntext'])) {
$returnText = $_POST['returntext'];
}
$scriptName = "";
if(isset($_FILES['script'])) {
$scriptName = basename($_FILES['script']['name']);
}
$scriptPath = $scriptName;
// Ruta desde la raíz del sitio web
$ruta = $_SERVER['DOCUMENT_ROOT'] . "/apicreator/endpoints/$scheme";
// Creación
if(isset($_FILES['script'])) {
// Crear la carpeta si no existe
if (!is_dir($ruta)) {
if (mkdir($ruta, 0777, true)) {
switch ($mode) {
case $CREATE:
$success = "Esquema creado correctamente.";
break;
case $EDIT:
$success = "Esquema modificado correctamente.";
break;
default:
echo "No hay 'modo' indicado.";
break;
}
} else {
switch ($mode) {
case $CREATE:
$error = "Error al crear el esquema.";
break;
case $EDIT:
$error = "Error al modificar el esquema.";
break;
default:
echo "No hay 'modo' indicado.";
break;
}
}
}
// Solo intentamos suir el fichero si se ha indicado alguno al crear/modificar
if($scriptPath != "") {
if (!move_uploaded_file($_FILES['script']['tmp_name'], "endpoints/$scheme/".$scriptPath)) {
$error = "Error al subir el Script.";
}
}
}
$endpoint = new Endpoint($url, $method, $inputMime, $outputMime, $scriptPath, $returnText, $scheme);
if($mode==$CREATE) {
$manager->saveEndpoint($endpoint);
} elseif($mode==$EDIT) {
$manager->updateEndpoint($endpoint, $id);
$mode==$CREATE; // Restauramos modo de creación
}
}
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>API Creator - Mantenimiento de Endpoints</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet">
<link href="https://apalfrey.github.io/select2-bootstrap-5-theme/select2-bootstrap-5-theme.min.css" rel="stylesheet">
<style type="text/css">
#endpoints-table {
font-size: 12px;
}
</style>
</head>
<body>
<div class="container mt-5">
<h1 class="mb-4">API Creator - Mantenimiento de Endpoints</h1>
<?php if (isset($error)) { ?>
<div class="alert alert-danger" role="alert">
<?php echo $error; ?>
</div>
<?php } ?>
<?php
if (isset($success)) {
if($success!="") {
?>
<div class="alert alert-success" role="alert">
<?php echo $success; ?>
</div>
<?php
}
}
?>
<form method="POST" enctype="multipart/form-data" class="mb-4">
<input name="mode" id="mode" type="hidden" value="<?php echo (isset($mode) ? $mode : "" );?>">
<input name="id" id="id" type="hidden" value="<?php echo (isset($id) ? $id : "" );?>">
<div class="mb-3">
<label for="scheme" class="form-label">Esquema:</label>
<select class="form-select" id="scheme" name="scheme" data-placeholder="Selecciona o escribe nuevo esquema">
<?php
$schemes = $manager->getSchemes();
foreach ($schemes as $scheme) {
?>
<option value="<?php echo $scheme['scheme'];?>" <?php echo ($scheme['scheme'] == $scheme ? "selected" : "")?>><?php echo $scheme['scheme'];?></option>
<?php } ?>
</select>
</div>
<div class="mb-3">
<label for="url" class="form-label">URL del Endpoint:</label>
<input type="text" class="form-control" id="url" name="url" value="<?php echo (isset($url) ? $url : "" );?>" required>
</div>
<div class="mb-3">
<label for="method" class="form-label">Método:</label>
<select class="form-select" id="method" name="method" required>
<?php
foreach (["GET", "POST", "DELETE", "PUT"] as $m) {
$selected = "";
if(isset($method)) {
if($method == $m) {
$selected = " selected";
}
}
echo "<option$selected>$m</option>";
}
?>
</select>
</div>
<div class="mb-3">
<label for="inputMime" class="form-label">MIME Type Entrada:</label>
<select class="form-select" id="inputMime" name="inputMime" required>
<?php foreach ($mimeTypes as $mime):
$selected = "";
if(isset($inputMime)) {
if($inputMime == $mime['mime']) {
$selected = " selected";
}
}
?>
<option<?php echo $selected;?> value="<?php echo $mime['mime']; ?>"><?php echo $mime['name'].' ('.$mime['mime'].')'; ?></option>
<?php endforeach; ?>
</select>
</div>
<div class="mb-3">
<label for="outputMime" class="form-label">MIME Type Salida:</label>
<select class="form-select" id="outputMime" name="outputMime" required>
<?php foreach ($mimeTypes as $mime): ?>
$selected = "";
if(isset($outputMime)) {
if($outputMime == $mime['mime']) {
$selected = " selected";
}
}
<option<?php echo $selected;?> value="<?php echo $mime['mime']; ?>"><?php echo $mime['name'].' ('.$mime['mime'].')'; ?></option>
<?php endforeach; ?>
</select>
</div>
<!-- Pestañas código/texto -->
<ul class="nav nav-tabs" id="myTab" role="tablist">
<li class="nav-item" role="presentation">
<button class="nav-link active" id="input-tab" data-bs-toggle="tab" data-bs-target="#input" type="button" role="tab" aria-controls="input" aria-selected="true">
Ejecutable
</button>
</li>
<li class="nav-item" role="presentation">
<button class="nav-link" id="textarea-tab" data-bs-toggle="tab" data-bs-target="#textarea" type="button" role="tab" aria-controls="textarea" aria-selected="false">
Valor predefinido
</button>
</li>
</ul>
<!-- Tab panes -->
<div class="tab-content mt-3">
<div class="tab-pane fade show active" id="input" role="tabpanel" aria-labelledby="input-tab">
<div class="mb-3">
<label for="script" class="form-label">Código PHP:</label>
<!-- TODO: Al editar, dar opcion para no modificar el ejecutable o para descargarlo -->
<input type="file" class="form-control" id="script" name="script" accept=".php">
</div>
</div>
<div class="tab-pane fade" id="textarea" role="tabpanel" aria-labelledby="textarea-tab">
<div class="mb-3">
<label for="returntext" class="form-label">Texto a devolver:</label>
<textarea class="form-control" name="returntext" id="returntext" rows="4" placeholder="Escribe aquí..."><?php echo (isset($returnText) ? $returnText : "");?></textarea>
</div>
</div>
</div>
<div id="register-buttons">
<button id="register-button" type="submit" class="btn btn-primary">Registrar</button>
</div>
<div id="modify-buttons" style="display:none;">
<button id="modify-button" type="submit" class="btn btn-warning">Modificar</button>
<button id="cancel-modify-button" type="button" class="btn btn-secondary">Cancelar</button>
</div>
</form>
<h2 class="mb-3">Endpoints Registrados</h2>
<ul class="list-group">
<?php
$endpoints = $manager->getEndpoints();
?>
<div class="container mt-5">
<table id="endpoints-table" class="table table-bordered table-striped">
<thead class="table-dark">
<tr>
<th>ID - Esquema(Hits)</th>
<th>URL</th>
<th>Método</th>
<th>Input MIME</th>
<th>Output MIME</th>
<th>Script/Text</th>
<th>Acciones</th>
</tr>
</thead>
<tbody>
<?php
foreach ($endpoints as $ep) {
$title = htmlspecialchars($ep['return_text'], ENT_QUOTES, 'UTF-8');
?>
<tr>
<!-- Información de endpoint -->
<td><?php echo $ep['id'].' - '.$ep['scheme'].'('.$ep['hits'].')';?></td>
<td><?php echo $ep['url'];?></td>
<td><?php echo $ep['method'];?></td>
<td><?php echo $ep['input_mime'];?></td>
<td><?php echo $ep['output_mime'];?></td>
<td title="<?php echo $title;?>"><?php echo $ep['script'];?></td>
<td>
<!-- Botones de acción -->
<button id="editendpoint_<?php echo $ep['id'];?>" class="btn btn-primary btn-sm" data-id="<?php echo $ep['id'];?>">Editar</button>
<button id="deleteendpoint_<?php echo $ep['id'];?>" class="btn btn-danger btn-sm" data-id="<?php echo $ep['id'];?>">Eliminar</button>
</td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
</div>
<!-- jQuery -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<!-- Bootstrap JS Bundle -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<!-- Select2 JS -->
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script>
/**
* Selecciona un valor en un <select> por su valor.
* Si no existe, lo añade como nueva opción y lo selecciona.
* @param {string} selectId - ID del elemento <select>
* @param {string} valueToSelect - Valor a buscar o añadir
*/
function selectOrAddOption(selectId, valueToSelect) {
var select = document.getElementById(selectId);
if (!select) return; // Si no existe el select, salir
// Buscar si el valor ya existe
var found = false;
for (var i = 0; i < select.options.length; i++) {
if (select.options[i].value === valueToSelect) {
select.selectedIndex = i;
found = true;
break;
}
}
// Si no existe, añadirlo y seleccionarlo
if (!found) {
var newOption = document.createElement("option");
newOption.value = valueToSelect;
newOption.text = valueToSelect;
select.appendChild(newOption);
select.selectedIndex = select.options.length - 1;
}
}
/**
* Selecciona un valor en un select2 por su valor.
* Si no existe, lo añade como nueva opción y lo selecciona.
* @param {string} selectId - ID del elemento <select>
* @param {string} valueToSelect - Valor a buscar o añadir
*/
function select2OrAddOption(selectId, valueToSelect) {
var $select = $('#' + selectId);
// Buscar si el valor ya existe
var optionExists = $select.find('option[value="' + valueToSelect + '"]').length > 0;
if (!optionExists) {
// Añadir nueva opción
var newOption = new Option(valueToSelect, valueToSelect, true, true);
$select.append(newOption).trigger('change');
} else {
// Seleccionar la opción existente
$select.val(valueToSelect).trigger('change');
}
}
/**
* Selecciona un <option> en un <select> por valor o texto.
* @param {string} selectId - El id del elemento <select>.
* @param {string} valueToFind - El valor o texto a buscar.
* @returns {boolean} - true si encontró y seleccionó el option, false si no lo encontró.
*/
function selectOptionByValueOrText(selectId, valueToFind) {
var select = document.getElementById(selectId);
if (!select) return false;
for (var i = 0; i < select.options.length; i++) {
var option = select.options[i];
if (option.value === valueToFind || option.text === valueToFind) {
select.selectedIndex = i;
return true;
}
}
return false;
}
// Recorre todos los formularios de la página y los resetea
function resetForm() {
for (let i = 0; i < document.forms.length; i++) {
document.forms[i].reset();
}
}
function showRegisterZone() {
document.getElementById('mode').value = '<?php echo $CREATE;?>';
document.getElementById('register-buttons').style.display = '';
document.getElementById('modify-buttons').style.display = 'none';
enableEndpointButtons();
resetForm();
}
function showModifyZone() {
document.getElementById('mode').value = '<?php echo $EDIT;?>';
document.getElementById('register-buttons').style.display = 'none';
document.getElementById('modify-buttons').style.display = '';
disableEndpointButtons();
goTop();
}
function goTop() {
if (window.scrollY > 0) {
window.scrollTo({ top: 0, behavior: 'smooth' });
}
}
// Desactiva los botones de edición y borrado de endpoints
function disableEndpointButtons() {
document.querySelectorAll('button[id^="editendpoint_"], button[id^="deleteendpoint_"]').forEach(function(btn) {
btn.disabled = true;
});
}
// Activa los botones de edición y borrado de endpoints
function enableEndpointButtons() {
document.querySelectorAll('button[id^="editendpoint_"], button[id^="deleteendpoint_"]').forEach(function(btn) {
btn.disabled = false;
});
}
$(document).ready(function() {
$('#scheme').select2({
theme: "bootstrap-5",
width: '100%',
placeholder: $(this).data('placeholder'),
closeOnSelect: false,
tags: true // Permite añadir nuevos valores
});
resetForm();
document.getElementById('cancel-modify-button').addEventListener('click', function() {
showRegisterZone();
});
// Botones eliminar
document.querySelectorAll('button[id^="deleteendpoint_"]').forEach(function (btn) {
btn.addEventListener('click', function () {
const endpointId = this.getAttribute('data-id');
if (confirm("¿Seguro que quieres eliminar este endpoint?")) {
fetch('delete_endpoint.php', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: 'id=' + encodeURIComponent(endpointId)
})
.then(response => response.json())
.then(data => {
if (data.status === "success") {
alert(data.message);
// Opcional: eliminar el elemento de la vista
document.getElementById('deleteendpoint_' + endpointId).closest('tr').remove();
} else {
alert("Error: " + data.message);
}
})
.catch(error => {
alert("Error AJAX: " + error);
});
}
});
});
// Botones editar
document.querySelectorAll('button[id^="editendpoint_"]').forEach(function(btn) {
btn.addEventListener('click', function() {
var endpointId = this.getAttribute('data-id');
fetch('get_endpoint.php?id=' + encodeURIComponent(endpointId))
.then(response => response.json())
.then(data => {
//alert(JSON.stringify(data, null, 2)); // Para depuración
if (data.success && data.endpoint) {
resetForm();
document.getElementById('id').value = data.endpoint.id || '';
document.getElementById('url').value = data.endpoint.url || '';
document.getElementById('method').value = data.endpoint.method || '';
// Selecciona el <select> de inputMime y outputMime
selectOptionByValueOrText("inputMime", data.endpoint.input_mime);
selectOptionByValueOrText("outputMime", data.endpoint.output_mime);
document.getElementById('returntext').value = data.endpoint.return_text || '';
select2OrAddOption("scheme", data.endpoint.scheme);
// Asegúrate de que Bootstrap JS está cargado
var tabTrigger = document.getElementById('textarea-tab');
var tab = new bootstrap.Tab(tabTrigger);
tab.show();
showModifyZone();
} else {
alert('No se encontró el endpoint.');
showRegisterZone();
}
})
.catch(err => {
alert('Error al obtener los datos del endpoint.'+err);
showRegisterZone();
console.error(err);
});
});
});
});
</script>
<?php include "./footer.html"; ?>
</body>
</html>