new_year_2020/save.php

80 lines
2.0 KiB
PHP
Raw Normal View History

2020-01-08 12:16:42 +01:00
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
// Vérification de base
if (empty($_GET['svg'])) {
die(json_encode(['status' => 'error']));
}
// Récupération du code SVG
$svg = stripslashes(urldecode($_GET['svg']));
// Création d'un nom de fichier aléatoire
$tod = gettimeofday();
$name = 'tetenrond-' . $tod['sec'] . $tod['usec'] . '-' . rand(0, 50);
$final_filename = $name . '.zip';
// Enregistrement du SVG et du PNG associé
file_put_contents('tmp/' . $name . '.svg', $svg);
$im = new \Imagick();
$im->readImageBlob($svg);
$im->setImageFormat("png24");
$im->writeImage('tmp/' . $name . '.png');
$im->clear();
$im->destroy();
//exec('PATH=$PATH:~/bin/&&convert tmp/'.$name.'.svg tmp/'.$name.'.png', $output, $return_var);
// Création du fichier zip contenant les 2 fichiers et renvoi de la réponse
if (create_zip(['tmp/' . $name . '.svg', 'tmp/' . $name . '.png'], 'tmp/' . $final_filename)) {
echo json_encode(['status' => '200', 'url' => $final_filename]);
} else {
echo json_encode(['status' => 'error']);
}
function create_zip($files = [], $destination = '', $overwrite = false)
{
//if the zip file already exists and overwrite is false, return false
if (file_exists($destination) && !$overwrite) {
return false;
}
//vars
$valid_files = array();
//if files were passed in...
if (is_array($files)) {
//cycle through each file
foreach ($files as $file) {
//make sure the file exists
if (file_exists($file)) {
$valid_files[] = $file;
}
}
}
//if we have good files...
if (count($valid_files)) {
//create the archive
$zip = new ZipArchive();
if ($zip->open($destination, $overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
return false;
}
//add the files
foreach ($valid_files as $file) {
$zip->addFile($file, substr($file, 4));
}
//close the zip -- done!
$zip->close();
foreach ($valid_files as $file) {
unlink($file);
}
//check to make sure the file exists
return file_exists($destination);
} else {
return false;
}
}