FabioFratini hai 6 meses
pai
achega
6e7e024a37

+ 101 - 38
app/Http/Controllers/NewsController.php

@@ -207,13 +207,15 @@ class NewsController extends Controller
         Log::info('=== NEWS STORE METHOD START ===');
         Log::info('Request data:', $request->all());
         Log::info('Request method:', [$request->method()]);
+        Log::info('Has files:', [$request->hasFile('image')]);
+        Log::info('Files data:', $request->file());
 
         try {
             $request->validate($this->rules);
             Log::info('Validation passed');
 
             $input = $request->all();
-            Log::info('Input data:', $input);
+            Log::info('Input data after validation:', $input);
 
             // Check which button was clicked
             if (isset($input['save'])) {
@@ -228,62 +230,109 @@ class NewsController extends Controller
             if (isset($input['unpublish'])) {
                 Log::info('UNPUBLISH button clicked');
             }
+            if (isset($input['crop'])) {
+                Log::info('CROP button clicked');
+            }
 
-            // Image handling
-            if (request()->image) {
-                Log::info('Processing main image upload');
-                $file = request()->image;
-                $filename  = time() . '_' . $file->getClientOriginalName();
+            // === IMAGE HANDLING SECTION ===
+            Log::info('=== IMAGE HANDLING START ===');
 
-                if (! File::exists(public_path() . "/files/news"))
-                    File::makeDirectory(public_path() . "/files/news");
+            // Check for filename from crop
+            if (isset($input["filename"]) && $input["filename"] != '') {
+                Log::info('Filename from crop found:', [$input["filename"]]);
 
-                $path = public_path('files/news');
-                request()->image->move($path, $filename);
-                $input["image"] = $filename;
-                Log::info('Main image uploaded:', [$filename]);
-            } else {
-                if (isset($input["filename"])) {
+                // Verify file exists
+                $filePath = public_path('files/news/' . $input["filename"]);
+                $fileExists = file_exists($filePath);
+
+                Log::info('Crop file verification:', [
+                    'filename' => $input["filename"],
+                    'full_path' => $filePath,
+                    'exists' => $fileExists,
+                    'is_readable' => $fileExists ? is_readable($filePath) : false,
+                    'file_size' => $fileExists ? filesize($filePath) : 0
+                ]);
+
+                if ($fileExists) {
                     $input["image"] = $input["filename"];
-                    Log::info('Using existing filename:', [$input["filename"]]);
+                    Log::info('Using cropped image filename:', [$input["filename"]]);
+                } else {
+                    Log::error('Cropped image file does not exist!');
                 }
             }
+            // Check for direct file upload
+            elseif ($request->hasFile('image')) {
+                Log::info('Direct image upload detected');
+
+                $file = $request->file('image');
+                Log::info('Upload file details:', [
+                    'original_name' => $file->getClientOriginalName(),
+                    'size' => $file->getSize(),
+                    'mime_type' => $file->getMimeType(),
+                    'is_valid' => $file->isValid()
+                ]);
+
+                if ($file->isValid()) {
+                    $filename = time() . '_' . $file->getClientOriginalName();
+
+                    if (!File::exists(public_path() . "/files/news")) {
+                        Log::info('Creating news directory');
+                        File::makeDirectory(public_path() . "/files/news");
+                    }
+
+                    $path = public_path('files/news');
+                    $file->move($path, $filename);
+                    $input["image"] = $filename;
+
+                    Log::info('Direct image uploaded successfully:', [
+                        'filename' => $filename,
+                        'path' => $path . '/' . $filename
+                    ]);
+                } else {
+                    Log::error('Invalid file upload');
+                }
+            } else {
+                Log::info('No image provided (neither crop nor direct upload)');
+            }
+
+            Log::info('Final image value:', [$input["image"] ?? 'none']);
+            Log::info('=== IMAGE HANDLING END ===');
 
             // Handle additional images
             for ($i = 1; $i <= 5; $i++) {
-                if (isset($input["image" . $i])) {
+                if ($request->hasFile("image" . $i)) {
                     Log::info("Processing image{$i} upload");
-                    $file = $input["image" . $i];
-                    $filename  = time() . '_' . $file->getClientOriginalName();
+                    $file = $request->file("image" . $i);
+                    $filename = time() . '_' . $file->getClientOriginalName();
 
-                    if (! File::exists(public_path() . "/files/news"))
+                    if (!File::exists(public_path() . "/files/news"))
                         File::makeDirectory(public_path() . "/files/news");
 
                     $path = public_path('files/news');
-                    $input["image" . $i]->move($path, $filename);
+                    $file->move($path, $filename);
                     $input["image" . $i] = $filename;
                     Log::info("Image{$i} uploaded:", [$filename]);
                 }
             }
 
             // Handle PDF
-            if (request()->pdf) {
+            if ($request->hasFile('pdf')) {
                 Log::info('Processing PDF upload');
-                $file = request()->pdf;
-                $filename  = time() . '_' . $file->getClientOriginalName();
+                $file = $request->file('pdf');
+                $filename = time() . '_' . $file->getClientOriginalName();
 
-                if (! File::exists(public_path() . "/files/news"))
+                if (!File::exists(public_path() . "/files/news"))
                     File::makeDirectory(public_path() . "/files/news");
 
                 $path = public_path('files/news');
-                request()->pdf->move($path, $filename);
+                $file->move($path, $filename);
                 $input["pdf"] = $filename;
                 Log::info('PDF uploaded:', [$filename]);
             }
 
             // Date processing
             $final_date = null;
-            if ($input["date"] != '') {
+            if (isset($input["date"]) && $input["date"] != '') {
                 list($dt, $time) = explode(" ", $input["date"]);
                 list($day, $month, $year) = explode("/", $dt);
                 $final_date = $year . "-" . $month . "-" . $day . " " . $time;
@@ -298,16 +347,29 @@ class NewsController extends Controller
             $input["breaking_news"] = isset($input["breaking_news"]) ? ($input["breaking_news"] == 'on' ? true : false) : false;
             $input["no_social"] = isset($input["no_social"]) ? ($input["no_social"] == 'on' ? true : false) : false;
 
-            Log::info('Checkbox values:', [
-                'homepage' => $input["homepage"],
-                'live' => $input["live"],
-                'breaking_news' => $input["breaking_news"],
-                'no_social' => $input["no_social"]
-            ]);
-
+            Log::info('Final input data before saving:', $input);
             Log::info('About to create news record');
+
             $news = News::create($input);
-            Log::info('News created with ID:', [$news->id]);
+            Log::info('News created successfully:', [
+                'id' => $news->id,
+                'title' => $news->title,
+                'image' => $news->image,
+                'created_at' => $news->created_at
+            ]);
+
+            // Verify the image was saved correctly
+            if ($news->image) {
+                $savedImagePath = public_path('files/news/' . $news->image);
+                $imageExists = file_exists($savedImagePath);
+
+                Log::info('Saved news image verification:', [
+                    'image_field' => $news->image,
+                    'full_path' => $savedImagePath,
+                    'exists' => $imageExists,
+                    'size' => $imageExists ? filesize($savedImagePath) : 0
+                ]);
+            }
 
             // Handle publish action
             if (isset($input['publish'])) {
@@ -320,21 +382,21 @@ class NewsController extends Controller
                 if ($final_date <= date("Y-m-d H:i:s")) {
                     Log::info('Date is not in future, processing positions');
 
-                    if ($input["section_position"] != '') {
+                    if (isset($input["section_position"]) && $input["section_position"] != '') {
                         Log::info('Processing section position:', [$input["section_position"]]);
                         $s = Section::findOrFail($input["section_id"]);
                         $s[$input["section_position"]] = $news->id;
                         $s->save();
                         $news->section_position = '';
                     }
-                    if ($input["region_1_position"] != '') {
+                    if (isset($input["region_1_position"]) && $input["region_1_position"] != '') {
                         Log::info('Processing region_1 position:', [$input["region_1_position"]]);
                         $s = Section::findOrFail($input["region_1_id"]);
                         $s[$input["region_1_position"]] = $news->id;
                         $s->save();
                         $news->region_1_position = '';
                     }
-                    if ($input["region_2_position"] != '') {
+                    if (isset($input["region_2_position"]) && $input["region_2_position"] != '') {
                         Log::info('Processing region_2 position:', [$input["region_2_position"]]);
                         $s = Section::findOrFail($input["region_2_id"]);
                         $s[$input["region_2_position"]] = $news->id;
@@ -367,7 +429,7 @@ class NewsController extends Controller
             }
 
             // Handle homepage position
-            if ($input["homepage_position"] != '' && $news->online) {
+            if (isset($input["homepage_position"]) && $input["homepage_position"] != '' && $news->online) {
                 Log::info('Processing homepage position:', [$input["homepage_position"]]);
                 $home = Home::first();
                 if ($home != null) {
@@ -404,6 +466,7 @@ class NewsController extends Controller
 
             Log::info('No specific action, redirecting to news.index');
             return redirect()->route('news.index')->with('success', 'News created successfully');
+
         } catch (\Exception $e) {
             Log::error('=== ERROR IN STORE METHOD ===');
             Log::error('Error message:', [$e->getMessage()]);

+ 3 - 2
resources/views/news/_form.blade.php

@@ -1,5 +1,6 @@
-@csrf
-<div class="box box-primary">
+@if (request()->has('filename'))
+    <input type="hidden" name="filename" value="{{ request()->get('filename') }}">
+@endif<div class="box box-primary">
     <div class="box-header with-border">
         <h3 class="box-title"></h3>
     </div>

+ 22 - 22
resources/views/news/crop.blade.php

@@ -10,20 +10,20 @@
 
 	<div class="row">
         <div class="col-lg-12">
-            
+
             <input type="file" id="upload" value="Choose a file" class="btn btn-info" accept="image/x-png,image/jpeg"><br>
-            
+
             <div id="upload-h"></div>
 
             <div id="upload-v"></div>
-            
+
             <a href="#" class="upload-result btn btn-success">Procedi</a>
 
             <form action="/admin/news/crop" id="form" method="POST">
                 {{ csrf_field() }}
                 <input type="hidden" name="imagebase64H" id="imagebase64H">
                 <input type="hidden" name="imagebase64V" id="imagebase64V">
-                <input type="hidden" name="news_id" id="news_id" value="{{isset($_GET["news_id"]) ? $_GET["news_id"] : ''}}">
+                <input type="hidden" name="news_id" id="news_id" value="{{isset($_GET['news_id']) ? $_GET['news_id'] : ''}}">
             </form>
 
         </div>
@@ -58,17 +58,17 @@
                   document.location.href = '/admin/news/crop?vertical=1';
                 } else if ($(this).val() === 'horizontal') {
                     document.location.href = '/admin/news/crop';
-                } 
+                }
               });*/
 
               $("#upload").change(function(){
                 setTimeout(function(){ $(".cr-image").show(); }, 500);
             });
-        
+
             function readFile(input) {
                 if (input.files && input.files[0]) {
-                    
-                    var reader = new FileReader();          
+
+                    var reader = new FileReader();
                     reader.onload = function (e) {
                         $uploadCropV.croppie('bind', {
                             url: e.target.result
@@ -81,14 +81,14 @@
                         }).then(function(){
                             $('.cr-slider').attr({'min':0.5000, 'max':3.5000});
                         });
-                        
+
                         $('.upload-h').addClass('ready');
-                    }           
+                    }
                     reader.readAsDataURL(input.files[0]);
                 }
             }
-        
-            
+
+
                 $uploadCropV = $('#upload-v').croppie({
                     viewport: {
                         width: 400,
@@ -100,7 +100,7 @@
                         height: 750
                     }
                 });
-            
+
                 $uploadCropH = $('#upload-h').croppie({
                     viewport: {
                         width: 550,
@@ -112,43 +112,43 @@
                         height: 500
                     }
                 });
-            
+
 
             $('#upload').on('change', function () { readFile(this); });
             $('.upload-result').on('click', function (ev) {
-                
+
                 $uploadCropH.croppie('result', {
                     type: 'canvas',
                     size: 'viewport'
                 }).then(function (resp) {
                     $('#imagebase64H').val(resp);
-                    
+
                 });
                 $uploadCropV.croppie('result', {
                     type: 'canvas',
                     size: 'viewport'
                 }).then(function (resp) {
                     $('#imagebase64V').val(resp);
-                    
+
                 });
 
                 setTimeout(function(){ $('#form').submit(); }, 3000);
 
             });
-        
+
         });
         /*
         function zoomin(ev) {
             targetZoom = self._currentZoom + 0.005;
-            
+
                     ev.preventDefault();
                     _setZoomerVal.call(self, targetZoom);
                     change.call(self);
                 }
-                
+
                 function zoomout(ev) {
                     targetZoom = self._currentZoom - 0.005;
-            
+
                     ev.preventDefault();
                     _setZoomerVal.call(self, targetZoom);
                     change.call(self);
@@ -156,4 +156,4 @@
         */
     </script>
 
-@stop
+@stop

+ 135 - 25
routes/web.php

@@ -2205,31 +2205,141 @@ Route::group(['middleware' => 'auth'], function () {
 
         Route::post('/news/crop', function () {
 
-            $image = $_POST["imagebase64H"];
-            $imageInfo = explode(";base64,", $image);
-            $imgExt = str_replace('data:image/', '', $imageInfo[0]);
-            $image = str_replace(' ', '+', $imageInfo[1]);
-            $imageName = time().".".$imgExt;
-            $path = public_path()."/files/news/".$imageName;
-            file_put_contents($path, base64_decode($image));
-
-            $imageV = $_POST["imagebase64V"];
-            $imageInfoV = explode(";base64,", $imageV);
-            $imgExtV = str_replace('data:image/', '', $imageInfoV[0]);
-            $imageV = str_replace(' ', '+', $imageInfoV[1]);
-            $imageNameV = "V_".time().".".$imgExt;
-            $pathV = public_path()."/files/news/".$imageNameV;
-            file_put_contents($pathV, base64_decode($imageV));
-
-            if ($_POST["news_id"] > 0)
-            {
-                $news = News::findOrFail($_POST["news_id"]);
-                $news->image = $imageName;
-                $news->save();
-                return Redirect::to('/admin/news/' . $_POST["news_id"] . "/edit");
-            }
-            else
-                return Redirect::to('/admin/news/create?filename=' . $imageName);
+            Log::info('=== CROP POST METHOD START ===');
+            Log::info('POST data received:', $_POST);
+            Log::info('FILES data:', $_FILES ?? 'No files');
+
+            try {
+                // Check if required data exists
+                if (!isset($_POST["imagebase64H"]) || !isset($_POST["imagebase64V"])) {
+                    Log::error('Missing required image data');
+                    Log::error('imagebase64H exists:', [isset($_POST["imagebase64H"])]);
+                    Log::error('imagebase64V exists:', [isset($_POST["imagebase64V"])]);
+                    return redirect()->back()->with('error', 'Missing image data');
+                }
+
+                $image = $_POST["imagebase64H"];
+                Log::info('Processing horizontal image, length:', [strlen($image)]);
+
+                $imageInfo = explode(";base64,", $image);
+                if (count($imageInfo) < 2) {
+                    Log::error('Invalid image format - missing base64 separator');
+                    return redirect()->back()->with('error', 'Invalid image format');
+                }
+
+                $imgExt = str_replace('data:image/', '', $imageInfo[0]);
+                $image = str_replace(' ', '+', $imageInfo[1]);
+                $imageName = time().".".$imgExt;
+
+                Log::info('Image details:', [
+                    'extension' => $imgExt,
+                    'filename' => $imageName,
+                    'base64_length' => strlen($image)
+                ]);
+
+                // Make sure the directory exists
+                $newsDir = public_path()."/files/news";
+                if (!File::exists($newsDir)) {
+                    Log::info('Creating news directory:', [$newsDir]);
+                    File::makeDirectory($newsDir, 0755, true);
+                } else {
+                    Log::info('News directory exists:', [$newsDir]);
+                }
+
+                $path = $newsDir."/".$imageName;
+                Log::info('Saving image to:', [$path]);
+
+                $result = file_put_contents($path, base64_decode($image));
+                if ($result === false) {
+                    Log::error('Failed to save horizontal image');
+                    return redirect()->back()->with('error', 'Failed to save image');
+                }
+
+                Log::info('Horizontal image saved successfully, bytes written:', [$result]);
+                Log::info('File exists after save:', [file_exists($path)]);
+
+                // Process vertical image
+                $imageV = $_POST["imagebase64V"];
+                Log::info('Processing vertical image, length:', [strlen($imageV)]);
+
+                $imageInfoV = explode(";base64,", $imageV);
+                $imgExtV = str_replace('data:image/', '', $imageInfoV[0]);
+                $imageV = str_replace(' ', '+', $imageInfoV[1]);
+                $imageNameV = "V_".time().".".$imgExt;
+                $pathV = $newsDir."/".$imageNameV;
+
+                Log::info('Vertical image details:', [
+                    'extension' => $imgExtV,
+                    'filename' => $imageNameV,
+                    'path' => $pathV
+                ]);
+
+                $resultV = file_put_contents($pathV, base64_decode($imageV));
+                if ($resultV === false) {
+                    Log::error('Failed to save vertical image');
+                } else {
+                    Log::info('Vertical image saved successfully, bytes written:', [$resultV]);
+                }
+
+                // Check news_id
+                $news_id = isset($_POST["news_id"]) ? $_POST["news_id"] : '';
+                Log::info('News ID from form:', [$news_id]);
+                Log::info('News ID > 0:', [$news_id > 0]);
+
+                if ($news_id > 0) {
+                    Log::info('Existing news - updating image');
+
+                    try {
+                        $news = News::findOrFail($news_id);
+                        Log::info('Found existing news:', [
+                            'id' => $news->id,
+                            'title' => $news->title,
+                            'current_image' => $news->image
+                        ]);
+
+                        $news->image = $imageName;
+                        $news->save();
+
+                        Log::info('Updated existing news with new image:', [$imageName]);
+
+                        $redirectUrl = '/admin/news/' . $news_id . "/edit";
+                        Log::info('Redirecting to edit page:', [$redirectUrl]);
+
+                        return redirect()->to($redirectUrl);
+
+                    } catch (\Exception $e) {
+                        Log::error('Error updating existing news:', [
+                            'message' => $e->getMessage(),
+                            'file' => $e->getFile(),
+                            'line' => $e->getLine()
+                        ]);
+                        return redirect()->back()->with('error', 'Error updating news: ' . $e->getMessage());
+                    }
+                } else {
+                    Log::info('New news - redirecting to create with filename');
+
+                    $redirectUrl = '/admin/news/create?filename=' . $imageName;
+                    Log::info('Redirecting to create page:', [$redirectUrl]);
+
+                    // Also try using the route method
+                    try {
+                        Log::info('Attempting route redirect with filename parameter');
+                        return redirect()->route('news.create', ['filename' => $imageName]);
+                    } catch (\Exception $e) {
+                        Log::error('Route redirect failed, using direct redirect:', [$e->getMessage()]);
+                        return redirect()->to($redirectUrl);
+                    }
+                }
+
+            } catch (\Exception $e) {
+                Log::error('=== CROP ERROR ===');
+                Log::error('Error message:', [$e->getMessage()]);
+                Log::error('Error file:', [$e->getFile()]);
+                Log::error('Error line:', [$e->getLine()]);
+                Log::error('Stack trace:', [$e->getTraceAsString()]);
+
+                return redirect()->back()->with('error', 'An error occurred while processing the image: ' . $e->getMessage());
+            }
 
         })->name('news.crop_save');