2727use Symfony \Component \HttpFoundation \Response ;
2828use Symfony \Component \Routing \Annotation \Route ;
2929use Symfony \Component \Security \Core \Exception \InvalidCsrfTokenException ;
30+ use Symfony \Component \Validator \Constraints \Url ;
31+ use Symfony \Component \Validator \Validator \ValidatorInterface ;
3032use Symfony \Contracts \Cache \TagAwareCacheInterface ;
3133use Throwable ;
3234
@@ -78,7 +80,7 @@ public function __construct(MediaFactory $mediaFactory,
7880 /**
7981 * @Route("/upload-url", name="bolt_async_upload_url", methods={"POST"})
8082 */
81- public function handleURLUpload (Request $ request ): Response
83+ public function handleURLUpload (Request $ request, ValidatorInterface $ validator ): Response
8284 {
8385 try {
8486 $ this ->validateCsrf ('upload ' );
@@ -91,18 +93,25 @@ public function handleURLUpload(Request $request): Response
9193 }
9294
9395 $ url = $ request ->get ('url ' , '' );
94- $ filename = basename ($ url );
9596
96- $ locationName = $ request ->get ('location ' , '' );
97- $ path = $ request ->get ('path ' ) . $ filename ;
98- $ folderpath = $ this ->config ->getPath ($ locationName , true , 'tmp/ ' );
99- $ target = $ this ->config ->getPath ($ locationName , true , 'tmp/ ' . $ path );
97+ // Make sure the submitting URL is a valid URL
98+ $ violations = $ validator ->validate ($ url , new Url ());
99+ if ($ violations ->count () !== 0 ) {
100+ return new JsonResponse ([
101+ 'error ' => [
102+ 'message ' => $ violations ->get (0 )->getMessage (),
103+ ],
104+ ], Response::HTTP_BAD_REQUEST );
105+ }
106+
107+ $ tmpFolder = $ this ->getParameter ('kernel.cache_dir ' ) . DIRECTORY_SEPARATOR . 'tmpupload ' ;
108+ $ tmpFile = $ tmpFolder . DIRECTORY_SEPARATOR . bin2hex (random_bytes (6 ));
100109
101110 try {
102111 // Make sure temporary folder exists
103- $ this ->filesystem ->mkdir ($ folderpath );
112+ $ this ->filesystem ->mkdir ($ tmpFolder );
104113 // Create temporary file
105- $ this ->filesystem ->copy ($ url , $ target );
114+ $ this ->filesystem ->copy ($ url , $ tmpFile );
106115 } catch (Throwable $ e ) {
107116 return new JsonResponse ([
108117 'error ' => [
@@ -111,15 +120,15 @@ public function handleURLUpload(Request $request): Response
111120 ], Response::HTTP_BAD_REQUEST );
112121 }
113122
114- $ file = new UploadedFile ($ target , $ filename );
123+ $ file = new UploadedFile ($ tmpFile , basename ( $ url ) );
115124 $ bag = new FileBag ();
116125 $ bag ->add ([$ file ]);
117126 $ request ->files = $ bag ;
118127
119128 $ response = $ this ->handleUpload ($ request );
120129
121130 // The file is automatically deleted. It may be that we don't need this.
122- $ this ->filesystem ->remove ($ target );
131+ $ this ->filesystem ->remove ($ tmpFile );
123132
124133 return $ response ;
125134 }
0 commit comments