Skip to content
Snippets Groups Projects
Commit 529a0a91 authored by Camille Simiand's avatar Camille Simiand
Browse files

WIP - refacto create capsule to legacy

parent 5aade3df
Branches
Tags
1 merge request!32tuleap-50-create-a-capsule-for-an-unexisting-project-in-the-legacy
......@@ -6,7 +6,10 @@
"require": {
"php": ">=7.4",
"ext-ctype": "*",
"ext-curl": "*",
"ext-iconv": "*",
"ext-json": "*",
"ext-zip": "^1.15",
"composer/package-versions-deprecated": "1.11.99.4",
"doctrine/annotations": "^1.0",
"doctrine/doctrine-bundle": "^2.4",
......@@ -47,8 +50,7 @@
"symfonycasts/reset-password-bundle": "^1.11",
"symfonycasts/verify-email-bundle": "^1.6",
"twig/extra-bundle": "^2.12|^3.0",
"twig/twig": "^2.12|^3.0",
"ext-curl": "*"
"twig/twig": "^2.12|^3.0"
},
"require-dev": {
"dama/doctrine-test-bundle": "^6.7",
......
......@@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
"content-hash": "c9f90e72255df1e77347e1bd4958fbb4",
"content-hash": "b63b0363576a36d88b7d444dc9451ce5",
"packages": [
{
"name": "composer/package-versions-deprecated",
......@@ -11959,7 +11959,10 @@
"platform": {
"php": ">=7.4",
"ext-ctype": "*",
"ext-iconv": "*"
"ext-curl": "*",
"ext-iconv": "*",
"ext-json": "*",
"ext-zip": "^1.15"
},
"platform-dev": [],
"plugin-api-version": "2.1.0"
......
......@@ -9,7 +9,7 @@
AllowOverride None
Require all granted
DirectoryIndex index.php, index.html
DirectoryIndex index1.php, index.html
</Directory>
# uncomment the following lines if you install assets as symlinks
......
......@@ -3,14 +3,14 @@
ServerAlias www.project.memorekall.com
DocumentRoot /sites/memorekall/www/web_dev/public
DirectoryIndex /index.php
DirectoryIndex /index1.php
<Directory /sites/memorekall/www/web_dev/public>
Require all granted
AllowOverride None
Order Allow,Deny
Allow from All
FallbackResource /index.php
FallbackResource /index1.php
RewriteEngine on
</Directory>
ErrorLog /sites/memorekall/www/web_dev/log/memorekall_member_error.log
......
<?php
function sanitize($string, $force_lowercase = true, $anal = false) {
$strip = array("~", "`", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "_", "=", "+", "[", "{", "]",
"}", "\\", "|", ";", ":", "\"", "'", "&#8216;", "&#8217;", "&#8220;", "&#8221;", "&#8211;", "&#8212;",
"—", "–", ",", "<", ".", ">", "/", "?");
$clean = trim(str_replace($strip, "", strip_tags($string)));
$clean = preg_replace('/\s+/', "-", $clean);
$clean = ($anal) ? preg_replace("/[^a-zA-Z0-9]/", "", $clean) : $clean ;
return ($force_lowercase) ?
(function_exists('mb_strtolower')) ?
mb_strtolower($clean, 'UTF-8') :
strtolower($clean) :
$clean;
}
//Créé un projet Rekall
function createProject($name, $videoUrl, $sha1password) {
$retours = array("success" => 0, "error" => "", "value" => "");
$name = sanitize($name);
if($name == "")
$name = sha1(rand());
if(!file_exists($name)) {
$zip = new ZipArchive;
$res = $zip->open("create.zip");
if ($res === TRUE) {
$zip->extractTo($name);
$zip->close();
file_put_contents($name."/file/project.xml", str_replace("__video__", $videoUrl, file_get_contents($name."/file/project.xml")));
file_put_contents($name."/file/projectPassword.txt", $sha1password);
$retours["success"] = 1;
} else {
$retours["success"] = -1;
$retours["error"] = "No seed found";
}
}
else {
$retours["success"] = 0;
$retours["error"] = "Project already exists";
}
$retours["value"] = $name;
echo json_encode($retours);
}
if((isset($_POST["create"])) && (isset($_POST["video"])) && (isset($_POST["p"]))) {
createProject($_POST["create"], $_POST["video"], $_POST["p"]);
exit();
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-type" content="text/html; charset=UTF-8">
<meta http-equiv="Content-Language" content="fr">
<meta name="language" content="fr">
<meta name="designer" content="buzzing light">
<meta name="copyright" content="buzzing light">
<meta name="HandheldFriendly" content="true" />
<meta name="viewport" content="width=device-width, user-scalable=no"><!--, minimum-scale=1.0, maximum-scale=1.0-->
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<link rel="apple-touch-icon" href="favicon.png" />
<link rel="stylesheet" type="text/css" href="css/reset.css" />
<title>Rekall</title>
<script language="javascript" type='text/javascript' src='js/jquery.min.js'></script>
<script language="javascript" type='text/javascript' src='js/sha1.js'></script>
<link rel="stylesheet" type="text/css" href="css/create-theme.css" />
<script language="javascript" type='text/javascript'>
$(document).ready(function() {
$("#formCreate").submit(function(event) {
event.stopPropagation();
if(($("input[name=create]").val() != "") && ($("input[name=video]").val() != "") /*&& ($("input[name=password]").val() != "")*/) {
var passwordRaw = "000000"; //$("input[name=p]").val();
var password = (CryptoJS.SHA1(passwordRaw) + "").toUpperCase();
$("#submitCreate").hide();
$.ajax("index.php", {
type: "POST",
dataType: "json",
data: {"create": $("input[name=create]").val(), "video": $("input[name=video]").val(), "p": password},
success: function(retour) {
console.log(retour);
if(retour.success == 1) {
window.document.location = document.URL.substr(0,document.URL.lastIndexOf('/')) + "/" + retour.value + "/?p=" + password;
}
else {
alert(retour.error)
$("#submitCreate").show();
}
},
error: function(retour) {
$("#submitCreate").show();
}
});
}
else
alert("Merci de saisir tous les champs");
return false;
});
});
</script>
</head>
<body id="createProjectBody">
<img id="createProjectLogo" src="css/images/logo.png" />
<br/><div class="col-md-12 row-title-box">
<div class="row-title">Create Capsule</div>
</div>
<form action="index.php" method="post" id='formCreate'>
<label>Name of the capsule</label>
<input type="text" name="create" placeholder="my-project-name" size="30"><br/>
<label>YouTube or Vimeo video URL</label>
<input type="text" name="video" placeholder="https://www.youtube.com/watch?v=4Rcw5GCXJnQ" size="30"><br/>
<!--<label>Edition password *</label>
<input type="password" name="p" placeholder="password" size="30"><br/>-->
<input id="submitCreate" type="submit" value="Create a capsule" name="submit">
</form>
</body>
</html>
\ No newline at end of file
<?php
// //Créé un projet Rekall
// function createProject($name, $videoUrl, $sha1password) {
// $retours = array("success" => 0, "error" => "", "value" => "");
// $name = sanitize($name);
//
// if($name == "")
// $name = sha1(rand());
//
// if(!file_exists($name)) {
// $zip = new ZipArchive;
// $res = $zip->open("create.zip");
// if ($res === TRUE) {
// $zip->extractTo($name);
// $zip->close();
// file_put_contents($name."/file/project.xml", str_replace("__video__", $videoUrl, file_get_contents($name."/file/project.xml")));
// file_put_contents($name."/file/projectPassword.txt", $sha1password);
// $retours["success"] = 1;
// } else {
// $retours["success"] = -1;
// $retours["error"] = "No seed found";
// }
// }
// else {
// $retours["success"] = 0;
// $retours["error"] = "Project already exists";
// }
// $retours["value"] = $name;
//
// echo json_encode($retours);
// }
//
// if((isset($_POST["create"])) && (isset($_POST["video"])) && (isset($_POST["p"]))) {
// createProject($_POST["create"], $_POST["video"], $_POST["p"]);
// exit();
// }
//?>
<!--<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">-->
<!--<html xmlns="http://www.w3.org/1999/xhtml">-->
<!--<head>-->
<!-- <meta http-equiv="Content-type" content="text/html; charset=UTF-8">-->
<!-- <meta http-equiv="Content-Language" content="fr">-->
<!-- <meta name="language" content="fr">-->
<!-- <meta name="designer" content="buzzing light"> -->
<!-- <meta name="copyright" content="buzzing light">-->
<!-- <meta name="HandheldFriendly" content="true" />-->
<!-- <meta name="viewport" content="width=device-width, user-scalable=no"><!--, minimum-scale=1.0, maximum-scale=1.0-->-->
<!-- <meta name="apple-mobile-web-app-capable" content="yes">-->
<!-- <meta name="apple-mobile-web-app-status-bar-style" content="black">-->
<!---->
<!-- <link rel="apple-touch-icon" href="favicon.png" />-->
<!-- <link rel="stylesheet" type="text/css" href="css/reset.css" />-->
<!---->
<!-- <title>Rekall</title>-->
<!-- -->
<!-- <script language="javascript" type='text/javascript' src='js/jquery.min.js'></script> -->
<!-- <script language="javascript" type='text/javascript' src='js/sha1.js'></script>-->
<!-- <link rel="stylesheet" type="text/css" href="css/create-theme.css" /> -->
<!-- -->
<!-- <script language="javascript" type='text/javascript'>-->
<!-- $(document).ready(function() {-->
<!-- $("#formCreate").submit(function(event) {-->
<!-- event.stopPropagation();-->
<!-- if(($("input[name=create]").val() != "") && ($("input[name=video]").val() != "") /*&& ($("input[name=password]").val() != "")*/) {-->
<!-- var passwordRaw = "000000"; //$("input[name=p]").val();-->
<!-- var password = (CryptoJS.SHA1(passwordRaw) + "").toUpperCase();-->
<!-- $("#submitCreate").hide();-->
<!-- $.ajax("index.php", {-->
<!-- type: "POST",-->
<!-- dataType: "json",-->
<!-- data: {"create": $("input[name=create]").val(), "video": $("input[name=video]").val(), "p": password},-->
<!-- success: function(retour) {-->
<!-- console.log(retour);-->
<!-- if(retour.success == 1) {-->
<!-- window.document.location = document.URL.substr(0,document.URL.lastIndexOf('/')) + "/" + retour.value + "/?p=" + password;-->
<!-- }-->
<!-- else {-->
<!-- alert(retour.error)-->
<!-- $("#submitCreate").show();-->
<!-- }-->
<!-- },-->
<!-- error: function(retour) {-->
<!-- $("#submitCreate").show();-->
<!-- }-->
<!-- }); -->
<!-- }-->
<!-- else-->
<!-- alert("Merci de saisir tous les champs");-->
<!-- return false;-->
<!-- }); -->
<!-- });-->
<!-- </script>-->
<!--</head>-->
<!--<body id="createProjectBody"> -->
<!-- <img id="createProjectLogo" src="css/images/logo.png" />-->
<!-- <br/><div class="col-md-12 row-title-box">-->
<!-- <div class="row-title">Create Capsule</div>-->
<!-- </div>-->
<!-- <form action="index.php" method="post" id='formCreate'>-->
<!-- <label>Name of the capsule</label>-->
<!-- <input type="text" name="create" placeholder="my-project-name" size="30"><br/>-->
<!-- <label>YouTube or Vimeo video URL</label>-->
<!-- <input type="text" name="video" placeholder="https://www.youtube.com/watch?v=4Rcw5GCXJnQ" size="30"><br/>-->
<!-- <!--<label>Edition password *</label>-->
<!-- <input type="password" name="p" placeholder="password" size="30"><br/>-->-->
<!---->
<!-- <input id="submitCreate" type="submit" value="Create a capsule" name="submit">-->
<!-- </form> -->
<!--</body>-->
<!--</html>-->
\ No newline at end of file
......@@ -4,6 +4,7 @@ namespace App\Controller;
use App\Entity\Capsule;
use App\Form\CreateCapsuleFormType;
use App\LegacyHelper;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\File\Exception\FileException;
......@@ -29,7 +30,7 @@ class CapsuleController extends AbstractController
}
/**
* @Route("/create", name="create_capsule")
* @Route("/create", name="create_capsule", methods={"POST"}, priority=-2)
*/
public function new(Request $request): Response
{
......@@ -40,6 +41,7 @@ class CapsuleController extends AbstractController
if ($form->isSubmitted() && $form->isValid()) {
$new_date_time = new \DateTime();
$capsule_name = $form->get('name')->getData();
$video_url = $form->get('video_url')->getData();
$preview_link = Uuid::v4();
$edition_link = $preview_link . '/?p=edit';
......@@ -54,175 +56,11 @@ class CapsuleController extends AbstractController
$entityManager->persist($capsule);
$entityManager->flush();
// return $this->redirectToRoute('capsule_list');
return $this->transferToLegacy($request);
$this->redirectToRoute('create_project', [$capsule_name, $video_url]);
}
return $this->render('capsule/create.html.twig', [
'capsuleCreationForm' => $form->createView()
]);
}
private function transferToLegacy(Request $request): Response
{
$prefix = $this->getParameter('app.legacy_external_prefix');
$originalController = preg_replace("@^$prefix@", '', $request->getPathInfo());
$originalQueryString = $request->getQueryString();
//@TODO : delete on linux server
// $originalController = str_replace("/", "\\", $originalController); //windows
$extension = strrchr($originalController, '.');
if ($extension != '.html' && $extension != '.php' && $extension != false) {
$url = "{$originalController}";
try {
$mime = $this->getMime($url, $extension);
$response = new BinaryFileResponse($url);
$response->headers->set('Content-Type', $mime ?: 'application/octet-stream');
return $response;
} catch (FileNotFoundException $e) {
// try normal access by url
}
}
$separator = '';
if (!$extension) {
$separator = '/';
}
$url = "{$this->getParameter('app.legacy_url')}{$originalController}{$separator}?{$originalQueryString}";
//open connection
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
// logs the connection (optional)
$stderr = fopen("{$this->getParameter('kernel.project_dir')}/log/curl.txt", "w");
if ($request->getMethod() == 'POST') {
$postParameters = $request->request->all()['create_capsule_form'];
error_log(print_r($postParameters, true));
// upload file to transfer
if (isset($_FILES['fileToUpload'])) {
$data = array(
'fileToUpload' => curl_file_create(
$_FILES['fileToUpload']['tmp_name'],
$_FILES['fileToUpload']['type'],
$_FILES['fileToUpload']['name']
)
);
$postParameters = array_merge($postParameters, $data);
curl_setopt($ch, CURLOPT_HEADER, 1);
}
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postParameters);
}
curl_setopt($ch, CURLOPT_COOKIESESSION, 0);
curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookies.txt');
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookies.txt');
//execute post
$result = curl_exec($ch);
$contentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
if ($result === false) {
$error_message = "Erreur - Page non trouvée : " .
curl_error($ch) .
' - ' . curl_errno($ch);
curl_close($ch);
throw new NotFoundHttpException($error_message);
}
curl_close($ch);
$response = new Response($result);
$response->headers->set('Content-Type', $contentType);
return $response;
}
private function getMime($filename, $extension): ?string
{
$mime_types = [
'txt' => 'text/plain',
'htm' => 'text/html',
'html' => 'text/html',
'php' => 'text/html',
'css' => 'text/css',
'js' => 'application/javascript',
'json' => 'application/json',
'xml' => 'application/xml',
'swf' => 'application/x-shockwave-flash',
'flv' => 'video/x-flv',
// images
'png' => 'image/png',
'jpe' => 'image/jpeg',
'jpeg' => 'image/jpeg',
'jpg' => 'image/jpeg',
'gif' => 'image/gif',
'bmp' => 'image/bmp',
'ico' => 'image/vnd.microsoft.icon',
'tiff' => 'image/tiff',
'tif' => 'image/tiff',
'svg' => 'image/svg+xml',
'svgz' => 'image/svg+xml',
// archives
'zip' => 'application/zip',
'rar' => 'application/x-rar-compressed',
'exe' => 'application/x-msdownload',
'msi' => 'application/x-msdownload',
'cab' => 'application/vnd.ms-cab-compressed',
// audio/video
'mp3' => 'audio/mpeg',
'qt' => 'video/quicktime',
'mov' => 'video/quicktime',
// adobe
'pdf' => 'application/pdf',
'psd' => 'image/vnd.adobe.photoshop',
'ai' => 'application/postscript',
'eps' => 'application/postscript',
'ps' => 'application/postscript',
// ms office
'doc' => 'application/msword',
'rtf' => 'application/rtf',
'xls' => 'application/vnd.ms-excel',
'ppt' => 'application/vnd.ms-powerpoint',
'docx' => 'application/msword',
'xlsx' => 'application/vnd.ms-excel',
'pptx' => 'application/vnd.ms-powerpoint',
// open office
'odt' => 'application/vnd.oasis.opendocument.text',
'ods' => 'application/vnd.oasis.opendocument.spreadsheet'
];
if (null === $filename) {
throw new \InvalidArgumentException('File cannot be null.');
}
$extension_without_dot = strtolower(str_replace('.', '', $extension));
if (array_key_exists($extension_without_dot, $mime_types)) {
return $mime_types[$extension_without_dot];
}
$file = new File((string) $filename, true);
if (!$file->isReadable()) {
throw new FileException('File must be readable.');
}
return $file->getMimeType();
}
}
......@@ -2,6 +2,8 @@
namespace App\Controller;
use App\Entity\Capsule;
use App\LegacyHelper;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
......@@ -9,71 +11,69 @@ use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\HttpFoundation\File\Exception\FileException;
use AppBundle\Entity\Capsule;
use Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class FallbackController extends AbstractController
{
/**
* @Route("/", name="get_legacy_resource_creation", methods={"POST"}, priority=-2)
* @Route("/{controller}", name="get_legacy_resource_creation_index",
* requirements={"controller" = "index.php"}, priority=-1)
*/
public function getCreationCapsuleAction(Request $request, $controller = null)
{
// $_POST parameters
$capsuleName = $request->request->get('create');
$capsulePass = $request->request->get('p');
$capsuleLink = $this->sanitize($capsuleName);
$this->denyAccessUnlessGranted('IS_AUTHENTICATED_REMEMBERED');
$user = $this->getUser();
/*
// memorykall legacy affichera un message si champ vide
//bloquer les noms à null
if($capsuleName == null || $capsuleName == '')
{
// rediriger sur une page demandant un nom
return $this->redirectToRoute('missing_name');
}*/
// TODO : the following code MUST be re-enabled with tuleap-51
// // check if capsule exist in database
// $capByName = $this->getDoctrine()
// ->getManager()
// ->getRepository('AppBundle:Capsule')
// ->findOneByNom($capsuleName)
// ;
// $capByLink = $this->getDoctrine()
// ->getManager()
// ->getRepository('AppBundle:Capsule')
// ->findOneByLink($capsuleLink)
// ;
// if (!$capByName instanceof Capsule && !$capByLink instanceof Capsule) {
// $dateCreation = new \DateTime();
// $cap = new Capsule();
// $cap->setNom($capsuleName);
// $cap->setLink($capsuleLink);
// $cap->setEditionLink($capsuleLink.'/?p='.$capsulePass);
// $cap->setAutCrea($user);
// $cap->setDtCrea($dateCreation);
// $cap->setDtMaj($dateCreation);
// $cap->addEditeur($user);
// /**
// * @Route("/", name="get_legacy_resource_creation", methods={"POST"}, priority=-2)
// * @Route("/{controller}", name="get_legacy_resource_creation_index",
// * requirements={"controller" = "index1.php"}, priority=-1)
// */
// public function getCreationCapsuleAction(Request $request, $controller = null)
// {
//
// $em = $this->getDoctrine()->getManager();
// $em->persist($cap);
// $em->flush();
// // $_POST parameters
// $capsuleName = $request->request->get('create');
// $capsulePass = $request->request->get('p');
// $capsuleLink = $this->sanitize($capsuleName);
//
// $this->denyAccessUnlessGranted('IS_AUTHENTICATED_REMEMBERED');
// $user = $this->getUser();
//
// /*
// // memorykall legacy affichera un message si champ vide
// //bloquer les noms à null
// if($capsuleName == null || $capsuleName == '')
// {
// // rediriger sur une page demandant un nom
// return $this->redirectToRoute('missing_name');
// }*/
//
//// TODO : the following code MUST be re-enabled with tuleap-51
//// // check if capsule exist in database
//// $capByName = $this->getDoctrine()
//// ->getManager()
//// ->getRepository('AppBundle:Capsule')
//// ->findOneByNom($capsuleName)
//// ;
//// $capByLink = $this->getDoctrine()
//// ->getManager()
//// ->getRepository('AppBundle:Capsule')
//// ->findOneByLink($capsuleLink)
//// ;
//// if (!$capByName instanceof Capsule && !$capByLink instanceof Capsule) {
//// $dateCreation = new \DateTime();
//// $cap = new Capsule();
//// $cap->setNom($capsuleName);
//// $cap->setLink($capsuleLink);
//// $cap->setEditionLink($capsuleLink.'/?p='.$capsulePass);
//// $cap->setAutCrea($user);
//// $cap->setDtCrea($dateCreation);
//// $cap->setDtMaj($dateCreation);
//// $cap->addEditeur($user);
////
//// $em = $this->getDoctrine()->getManager();
//// $em->persist($cap);
//// $em->flush();
//// }
//// // si la capsule existe déjà memorkall legacy affichera un message capsule existe déjà
//
// $response = $this->transfertToLegacy($request);
// return $response;
// }
// // si la capsule existe déjà memorkall legacy affichera un message capsule existe déjà
$response = $this->transfertToLegacy($request);
return $response;
}
/**
* @Route("/", name="get_legacy_resource", priority=-2)
......@@ -132,8 +132,8 @@ class FallbackController extends AbstractController
if ($controller == null) {
//if no controller, this is index.php
return $this->redirectToRoute('get_legacy_resource', array('controller' => 'index.php'));
//if no controller, this is index1.php
return $this->redirectToRoute('get_legacy_resource', array('controller' => 'index1.php'));
}
// use iframe to enhance speed but not for creation
......@@ -149,7 +149,8 @@ class FallbackController extends AbstractController
//$url = "{$path_to_legacy_code}{$originalController}";
$url = "{$originalController}";
try {
$mime = $this->getMime($url, $extension);
$legacy_helper = new LegacyHelper();
$mime = $legacy_helper->getMime($url, $extension);
$response = new BinaryFileResponse($url);
$response->headers->set('Content-Type', $mime ?: 'application/octet-stream');
return $response;
......@@ -166,206 +167,19 @@ class FallbackController extends AbstractController
$url = preg_replace('(^https?:\/\/[^/]+(:\d+)?)', '', $url);
$pattern = '/\/\//i';
$url = preg_replace($pattern, '/', $url);
// $logger->info("Capsule iframe configuration for none index.php ", ['url' => $url]);
// $logger->info("Capsule iframe configuration for none index1.php ", ['url' => $url]);
return $this->render("legacy/legacy.html.twig", array(
'url' => $url,
));
}
$response = $this->transfertToLegacy($request);
return $response;
}
private function transfertToLegacy(Request $request)
{
// relative path (to app/) of the legacy code (on the same filesystem)
//$path_to_legacy_code = $this->container->getParameter('kernel.root_dir').
// $this->container->getParameter('legacy_root_dir');
$prefix = $this->getParameter('app.legacy_external_prefix');
$originalController = preg_replace("@^$prefix@", '', $request->getPathInfo());
$originalQueryString = $request->getQueryString();
//@TODO : delete on linux server
// $originalController = str_replace("/", "\\", $originalController); //windows
$extension = strrchr($originalController, '.');
if ($extension != '.html' && $extension != '.php' && $extension != false) {
#$url = "{$path_to_legacy_code}{$originalController}";
$url = "{$originalController}";
try {
$mime = $this->getMime($url, $extension);
$response = new BinaryFileResponse($url);
$response->headers->set('Content-Type', $mime ?: 'application/octet-stream');
return $response;
} catch (FileNotFoundException $e) {
// try normal access by url
}
}
$separator = '';
if (!$extension) {
$separator = '/';
}
$url = "{$this->getParameter('app.legacy_url')}{$originalController}{$separator}?{$originalQueryString}";
//open connection
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
// logs the connection (optional)
$stderr = fopen("{$this->getParameter('kernel.project_dir')}/log/curl.txt", "w");
if ($request->getMethod() == 'POST') {
$postParameters = $request->request->all();
/*$postParametersString = '';
foreach ($postParameters as $key => $value) {
$postParametersString .= $key . '=' . $value . '&';
}
rtrim($postParametersString, '&');*/
// upload file to transfer
if (isset($_FILES['fileToUpload'])) {
$data = array(
'fileToUpload' => curl_file_create(
$_FILES['fileToUpload']['tmp_name'],
$_FILES['fileToUpload']['type'],
$_FILES['fileToUpload']['name']
)
);
$postParameters = array_merge($postParameters, $data);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
}
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postParameters);
}
curl_setopt($ch, CURLOPT_COOKIESESSION, 0);
curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookies.txt');
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookies.txt');
//execute post
$result = curl_exec($ch);
$contentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
if ($result === false) {
$mes = "Erreur - Page non trouvée : " .
sprintf(curl_error($ch)) .
' - ' . sprintf(curl_errno($ch));
curl_close($ch);
throw new NotFoundHttpException($mes);
}
curl_close($ch);
$response = new Response($result);
$response->headers->set('Content-Type', $contentType);
return $response;
}
// Mime Type Checker
private function getMime($filename, $extension, $mode = 0)
{
// mode 0 = full check
// mode 1 = extension check only
$mime_types = array(
'txt' => 'text/plain',
'htm' => 'text/html',
'html' => 'text/html',
'php' => 'text/html',
'css' => 'text/css',
'js' => 'application/javascript',
'json' => 'application/json',
'xml' => 'application/xml',
'swf' => 'application/x-shockwave-flash',
'flv' => 'video/x-flv',
// images
'png' => 'image/png',
'jpe' => 'image/jpeg',
'jpeg' => 'image/jpeg',
'jpg' => 'image/jpeg',
'gif' => 'image/gif',
'bmp' => 'image/bmp',
'ico' => 'image/vnd.microsoft.icon',
'tiff' => 'image/tiff',
'tif' => 'image/tiff',
'svg' => 'image/svg+xml',
'svgz' => 'image/svg+xml',
// archives
'zip' => 'application/zip',
'rar' => 'application/x-rar-compressed',
'exe' => 'application/x-msdownload',
'msi' => 'application/x-msdownload',
'cab' => 'application/vnd.ms-cab-compressed',
// audio/video
'mp3' => 'audio/mpeg',
'qt' => 'video/quicktime',
'mov' => 'video/quicktime',
// adobe
'pdf' => 'application/pdf',
'psd' => 'image/vnd.adobe.photoshop',
'ai' => 'application/postscript',
'eps' => 'application/postscript',
'ps' => 'application/postscript',
// ms office
'doc' => 'application/msword',
'rtf' => 'application/rtf',
'xls' => 'application/vnd.ms-excel',
'ppt' => 'application/vnd.ms-powerpoint',
'docx' => 'application/msword',
'xlsx' => 'application/vnd.ms-excel',
'pptx' => 'application/vnd.ms-powerpoint',
// open office
'odt' => 'application/vnd.oasis.opendocument.text',
'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
$legacy_helper = new LegacyHelper();
return $legacy_helper->transferToLegacy(
$request,
$this->getParameter('app.legacy_external_prefix'),
$this->getParameter('legacy_url'),
$this->getParameter('kernel.root_dir')
);
if (null === $filename) {
throw new \InvalidArgumentException('File cannot be null.');
}
$ext = strtolower(str_replace('.', '', $extension));
if (array_key_exists($ext, $mime_types)) {
return $mime_types[$ext];
}
$file = new File((string) $filename, true);
if (!$file->isReadable()) {
throw new FileException('File must be readable.');
}
$mime = $file->getMimeType();
return $mime;
}
// copy of function used by memorekall to calculate real project name !
public static function sanitize($string, $force_lowercase = true, $anal = false)
{
$strip = array("~", "`", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "_", "=", "+", "[", "{", "]",
"}", "\\", "|", ";", ":", "\"", "'", "&#8216;", "&#8217;", "&#8220;", "&#8221;", "&#8211;", "&#8212;",
"—", "–", ",", "<", ".", ">", "/", "?");
$clean = trim(str_replace($strip, "", strip_tags($string)));
$clean = preg_replace('/\s+/', "-", $clean);
$clean = ($anal) ? preg_replace("/[^a-zA-Z0-9]/", "", $clean) : $clean ;
return ($force_lowercase) ?
(function_exists('mb_strtolower')) ?
mb_strtolower($clean, 'UTF-8') :
strtolower($clean) :
$clean;
}
}
<?php
namespace App\Controller;
use App\LegacyHelper;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use ZipArchive;
class ProjectController extends AbstractController
{
/**
* @Route('/project/create' "name='create_project')
*/
public function createProject(
Request $request,
string $name,
string $video_url
) {
$retours = array("success" => 0, "error" => "", "value" => "");
chdir('../../legacy/');
if(! file_exists($name)) {
$zip = new ZipArchive;
$zip_file_archive = $zip->open("create.zip");
if ($zip_file_archive) {
$zip->extractTo($name);
$zip->close();
file_put_contents(
$name."/file/project.xml",
str_replace("__video__",
$video_url,
file_get_contents($name."/file/project.xml"
)));
$retours["success"] = 1;
} else {
$retours["success"] = -1;
$retours["error"] = "No seed found";
}
}
else {
$retours["success"] = 0;
$retours["error"] = "Project already exists";
}
$retours["value"] = $name;
echo json_encode($retours);
$legacy_helper = new LegacyHelper();
return $legacy_helper->transferToLegacy(
$request,
$this->getParameter('app.legacy_external_prefix'),
$this->getParameter('legacy_url'),
$this->getParameter('kernel.root_dir')
);
}
}
\ No newline at end of file
<?php
namespace App;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\File\Exception\FileException;
use Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException;
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class LegacyHelper
{
public static function transferToLegacy(
Request $request,
string $legacy_external_prefix,
string $legacy_url,
string $project_directory
): Response
{
$originalController = preg_replace(
"@^$legacy_external_prefix@",
'',
$request->getPathInfo());
$originalQueryString = $request->getQueryString();
//@TODO : delete on linux server
// $originalController = str_replace("/", "\\", $originalController); //windows
$extension = strrchr($originalController, '.');
if ($extension != '.html' && $extension != '.php' && $extension != false) {
$url = "{$originalController}";
try {
$mime = self::getMime($url, $extension);
$response = new BinaryFileResponse($url);
$response->headers->set('Content-Type', $mime ?: 'application/octet-stream');
return $response;
} catch (FileNotFoundException $e) {
// try normal access by url
}
}
$separator = '';
if (!$extension) {
$separator = '/';
}
$url = "{$legacy_url}{$originalController}{$separator}?{$originalQueryString}";
//open connection
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
// logs the connection (optional)
$stderr = fopen("{$project_directory}/log/curl.txt", "w");
if ($request->getMethod() == 'POST') {
$postParameters = $request->request->all()['create_capsule_form'];
error_log(print_r($postParameters, true));
// upload file to transfer
if (isset($_FILES['fileToUpload'])) {
$data = array(
'fileToUpload' => curl_file_create(
$_FILES['fileToUpload']['tmp_name'],
$_FILES['fileToUpload']['type'],
$_FILES['fileToUpload']['name']
)
);
$postParameters = array_merge($postParameters, $data);
curl_setopt($ch, CURLOPT_HEADER, 1);
}
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postParameters);
}
curl_setopt($ch, CURLOPT_COOKIESESSION, 0);
curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookies.txt');
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookies.txt');
//execute post
$result = curl_exec($ch);
$contentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
if ($result === false) {
$error_message = "Erreur - Page non trouvée : " .
curl_error($ch) .
' - ' . curl_errno($ch);
curl_close($ch);
throw new NotFoundHttpException($error_message);
}
curl_close($ch);
$response = new Response($result);
$response->headers->set('Content-Type', $contentType);
return $response;
}
public static function getMime($filename, $extension): ?string
{
$mime_types = [
'txt' => 'text/plain',
'htm' => 'text/html',
'html' => 'text/html',
'php' => 'text/html',
'css' => 'text/css',
'js' => 'application/javascript',
'json' => 'application/json',
'xml' => 'application/xml',
'swf' => 'application/x-shockwave-flash',
'flv' => 'video/x-flv',
// images
'png' => 'image/png',
'jpe' => 'image/jpeg',
'jpeg' => 'image/jpeg',
'jpg' => 'image/jpeg',
'gif' => 'image/gif',
'bmp' => 'image/bmp',
'ico' => 'image/vnd.microsoft.icon',
'tiff' => 'image/tiff',
'tif' => 'image/tiff',
'svg' => 'image/svg+xml',
'svgz' => 'image/svg+xml',
// archives
'zip' => 'application/zip',
'rar' => 'application/x-rar-compressed',
'exe' => 'application/x-msdownload',
'msi' => 'application/x-msdownload',
'cab' => 'application/vnd.ms-cab-compressed',
// audio/video
'mp3' => 'audio/mpeg',
'qt' => 'video/quicktime',
'mov' => 'video/quicktime',
// adobe
'pdf' => 'application/pdf',
'psd' => 'image/vnd.adobe.photoshop',
'ai' => 'application/postscript',
'eps' => 'application/postscript',
'ps' => 'application/postscript',
// ms office
'doc' => 'application/msword',
'rtf' => 'application/rtf',
'xls' => 'application/vnd.ms-excel',
'ppt' => 'application/vnd.ms-powerpoint',
'docx' => 'application/msword',
'xlsx' => 'application/vnd.ms-excel',
'pptx' => 'application/vnd.ms-powerpoint',
// open office
'odt' => 'application/vnd.oasis.opendocument.text',
'ods' => 'application/vnd.oasis.opendocument.spreadsheet'
];
if (null === $filename) {
throw new \InvalidArgumentException('File cannot be null.');
}
$extension_without_dot = strtolower(str_replace('.', '', $extension));
if (array_key_exists($extension_without_dot, $mime_types)) {
return $mime_types[$extension_without_dot];
}
$file = new File((string) $filename, true);
if (!$file->isReadable()) {
throw new FileException('File must be readable.');
}
return $file->getMimeType();
}
}
\ No newline at end of file
......@@ -574,6 +574,9 @@
"symfony/polyfill-php81": {
"version": "v1.23.0"
},
"symfony/polyfill-uuid": {
"version": "v1.23.0"
},
"symfony/process": {
"version": "v5.3.7"
},
......@@ -670,6 +673,9 @@
"templates/base.html.twig"
]
},
"symfony/uid": {
"version": "v5.3.10"
},
"symfony/validator": {
"version": "5.3",
"recipe": {
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment