Laravel mail queue and excel attachement causing JSON_ERROR_UTF8 - laravel

Have a problem while trying to queue mail that have attachment.
I can send an email without any problems without queue. Attachment is correct and can be opened. Problem appear when I try to queue that email. Excel generated by maatwebsite/excel lib
Error:
InvalidPayloadException in Queue.php line 89:
5
I found that this part of code throws this error:
...\vendor\laravel\framework\src\Illuminate\Queue\Queue.php
protected function createPayload($job, $data = '', $queue = null)
{
$payload = json_encode($this->createPayloadArray($job, $data, $queue));
if (JSON_ERROR_NONE !== json_last_error()) {
throw new InvalidPayloadException;
}
return $payload;
}
My code looks like:
excel = Excel::create('Report', function($excel) {
$excel->sheet('Sheetname', function($sheet) {
$sheet->fromArray([['aaa']]);
});
})->string('xlsx');
Mail::to('mail#mail.com')
->queue(new Report($excel));
I've tried to utf8_encode($excel) but then I cannot open mail attachment and I think that any operation on generated excel will corrupt file...
This problem also appear when I try to attach excel file from disk.
Any help?

Related

Laravel Console Command Failing to Complete Execution

I have the script below which is used to send messages (sms, email & whatsapp) to some 300k customers. Things where working fine before but for some days now the script is bugging (it freezes at some point in the loop. I can see this with the progress bar which doesn't move further). I have checked laravel.log and there is no particular error message. The script itself does not output any error message.
Below is the code:
/**
* Execute the console command.
*
* #return mixed
*/
public function handle()
{
AccountsCstm::where('authentification_c', 1)->chunk(10000, function ($customer_details) {
$bar = $this->output->createProgressBar(count($customer_details));
$bar->start();
foreach ($customer_details as $customer_detail) {
// Get customer bills and send through the appropriate channel. He could have multiple bills
if (isset($customer_detail->account->sic_code)) {
$bills = TbBillsInfos::where('contract_number', $customer_detail->account->sic_code)->where('bill_status', 'UNPAID')->get();
if (isset($bills)){
foreach ($bills as $bill) {
// Send messages.
if ($customer_detail->is_whatsapp_c) {
$message = $this->bill_message($customer_detail, $bill, 'WhatsApp');
// Send the message
$this->send_whatsapp_message($customer_detail->phone_4_c, $message, $customer_detail->contract_number_c);
// Record the message in database
$this->save_message('WhatsApp', $customer_detail->phone_4_c, null, $message, $customer_detail->account->id);
} elseif ($customer_detail->is_sms_c) {
$message = $this->bill_message($customer_detail, $bill, 'SMS');
// Send the message
$this->send_sms($customer_detail->phone_4_c, $message);
// Record the message in database
$this->save_message('SMS', $customer_detail->phone_4_c, null, $message, $customer_detail->account->id);
} elseif ($customer_detail->is_mail_c) {
$message = $this->bill_message($customer_detail, $bill, 'Email');
// Send the message
$this->send_email($customer_detail, $bill, $message);
// Record the message in database
$this->save_message('Email', null, $customer_detail->mail_c, $message, $customer_detail->account->id);
}
}
}
}
$bar->advance();
}
$bar->finish();
});
// Delete all record from the tb_bills_infos table
// Set the auto-increment value to 0
TbBillsInfos::truncate();
Log::info('send:unpaid-bill-messages: Command executed successfully');
}
Please can someone point out what can be the issue with the above script? Why is it bugging and not completing execution ? Why is it freezing at some point in the loop?
See for example the command since April 21, where as before it will complete execution in about 15 minutes or less
I have equally checked RAM usage on the server and only 1GB out of 8GB is being used. So the server is stable

Laravel Excel handle error when file is open

I'm using Laravel Excel 2.1.0 in a local project to write a row into an excel file.
This is my code:
$filePath = storage_path('myfile.xls');
$rows = \Excel::load($filePath, function($reader) {
$sheet = $reader->sheet(0);
$sheet->appendRow(
array(
'Hello'
)
);
});
Everything works and a new line was appended to my file.
Sometimes can happens the excel file is opened while user try to append a new line. In this case Laravel, rightly, show me this error:
fopen(mypath\myfile.xls): failed to open stream: Resource temporarily unavailable
How can I handle this error in order to skip the function and go on with my code without append the row?
I solved in this way:
$filePath = storage_path('myfile.xls');
$fp = #fopen($filePath, "r+");
if($fp) {
$rows = \Excel::load($filePath, function($reader) {
$sheet = $reader->sheet(0);
$sheet->appendRow(
array(
'Hello'
)
);
});
}

'Media bulk upload' on site server using 'Dropzonejs module' in Drupal 8 gives "failed to open the output stream" error

My website uses Drupal 8 and we are using Dropzonejs module for "media bulk upload" option. In my local environment, I'm able to bulk upload media without any problems. However, on server environment (having same configuration as local) when I try to bulk upload media, it throws "failed to open the output stream" error.
Any solutions/answers/suggestions are most welcome and much needed.
NOTE: Single item uploads work fine. Also during bulk upload, the error happens once the progress bar reaches 100%.
The defect screenshot is here
As of Drupal 8.6, we need a patch in the core for this functionality to work properly. For the fix, three files need to be changed as under:
drupal/core/includes/files.inc (Line 234)
/* #var \Drupal\Core\StreamWrapper\StreamWrapperInterface $wrapper */
if ($wrapper = \Drupal::service('stream_wrapper_manager')->getViaUri($uri)) {
return $wrapper->getExternalUrl();
}
return FALSE;
drupal/core/modules/locale/src/StreamWrapper/TranslationsStream.php (line 48 replace function)
public function getExternalUrl() {
return FALSE;
}
3.drupal/core/modules/locale/tests/src/Functional/LocaleImportFunctionalTest.php
(Add at line 365)
* Tests that imported PO files aren't break the UI provided by "views".
*
* #throws \Behat\Mink\Exception\ExpectationException
*
* #link https://www.drupal.org/project/drupal/issues/2449895
*/
public function testPoFileImportAndAccessibilityOfFilesOverviewViewsPage() {
$this->container
->get('module_installer')
->install(['system', 'user', 'file', 'views']);
// Create and log in a user that's able to upload/import translations
// and has an access to the overview of files in a system.
$this->drupalLogin($this->drupalCreateUser([
'access administration pages',
'access files overview',
'administer languages',
'translate interface',
]));
// Import a dummy PO file.
$this->importPoFile($this->getPoFile(), [
'langcode' => 'fr',
]);
// The problem this test cover is exposed in an exception that is thrown
// by the "\Drupal\locale\StreamWrapper\TranslationsStream" when "views"
// module provides a page of files overview. Refer to the issue to find
// more information.
$this->drupalGet('admin/content/files');
$this->assertSession()->statusCodeEquals(200);
}
(At line 373, overwrite the following function)
public function importPoFile($contents, array $options = []) {
$file_system = $this->container->get('file_system');
$file_path = $file_system->tempnam('temporary://', 'po_') . '.po';
file_put_contents($file_path, $contents);
$options['files[file]'] = $file_path;
$this->drupalPostForm('admin/config/regional/translate/import', $options,
t('Import'));
$file_system->unlink($file_path);
}

Return Image as http-response from Listener Symfony2

This listener sends me reports on all kinds of exceptions that occur on the website. Sometimes I get reports of images that have been deleted but are still consulted by search engines and others.
I want to do, instead of displaying an error message " 404 Not Found " return the correct image. To do this I created a database table that stores the old links and new links of the images that have been deleted, moved or changed its name.
then, this listener find in db the links to fallen and gets the new links of images . The goal is to return the image as http-response with header content-type as image.
My code is:
class ExceptionListener
{
private $service_container;
private $router;
function __construct(Container $service_container, $router){
$this->service_container = $service_container;
$this->router = $router;
}
public function onKernelException(GetResponseForExceptionEvent $event){
$exception = $event->getException();
$request = $this->service_container->get('request');
...
$document_root = $request->server->get('DOCUMENT_ROOT');
$filename = realpath($document_root . '/'. '/path/to/new_image.jpg');
$response = new \Symfony\Component\HttpFoundation\Response();
$response->headers->set('Content-type', 'image/jpeg');
$response->headers->set('Content-Disposition', 'inline; filename="' . basename($filename) . '";');
$response->headers->set('Content-length', filesize($filename));
$response->sendHeaders();
$response->setContent(file_get_contents($filename));
return $response;
...
}
}
The following error occurs:
In the browser you can see a small box , it is as if trying to show the image but the image source could not be obtained . But if the same code is testing on controller , its working properly and the image is displayed .
What can I do to return image from a listener ? thanks
There's few things wrong about the code snippet from your question.
Firstly, you should never use the request service. It's deprecated since Symfony 2.4 and was removed in Symfony 3.0. Use the request stack (request_stack) instead.
Secondly, do not send the response yourself, but let the framework do it. Symfony events system is designed for flexibility (see the docs). In your case it's enough to set the response on the event object.
Finally, you don't need the service container to access the request at all, as it's available on the event.
Moreover, instead of the standard Response class you can use the BinaryFileResponse. It's purpose is to serve files (have a look at the docs).
You can greatly simplify your listener:
use Symfony\Component\HttpFoundation\BinaryFileResponse;
class ExceptionListener
{
private $router;
function __construct($router)
{
$this->router = $router;
}
public function onKernelException(GetResponseForExceptionEvent $event)
{
$exception = $event->getException();
// request is avialable on the event
$request = $event->getRequest();
// ...
$file = 'path/to/file.txt';
$response = new BinaryFileResponse($file);
// ... set response parameters ...
// finally, set the response on your event
$event->setResponse($response);
}
}

Getting Error in Library inclusion in Codeigniter controller

When i run my aaplication in external server i get eror ,
Message: Login::include_once(application/third_party/mpdf/mpdf.php) [function.Login-include-once]: failed to open stream: No such file or directory.
The same application was running perfect in local server. Can anyone please suggest what could be wrong with it. My controller function ,
function pdfapp() //for test run individually
{
$this->load->model('Registration_model');
$appno='4/SCSELB/2013/KL01';
$data['table'] = $this->Registration_model->getall_app($appno);
$data['own_land'] = $this->Registration_model->get_ownland($appno);
$data['loan_data'] = $this->Registration_model->getloan_data($appno);
$apppdf='4_SCSELB_2013_KL01';
$data['apppdf']=$apppdf;
$pdfFilePath = FCPATH."reports/application/$apppdf.pdf";
if (file_exists($pdfFilePath) == FALSE)
{
ini_set('memory_limit','32M');
$html = $this->load->view('pdf_report2', $data, true);
include_once APPPATH.'third_party/mpdf/mpdf.php';
$mpdf=new mPDF('c');
$mpdf->SetFooter(' copyright# KSDC'.'|{PAGENO}|'.'Applied on '.date('d-M-Y H.i.s'));
$mpdf->WriteHTML($html);
$mpdf->Output($pdfFilePath, 'F');
}
$this->load->view('pdf_report2',$data);
}
The error you're getting is of a file not existing, Did you you debug this line ?
APPPATH.'third_party/mpdf/mpdf.php'; ?
what path do you get if you var_dump it?

Resources