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

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);
}

Related

TYPO3 9.5 Extbase plugin cache implementation

I am trying to get a cache working in my plugin.
In ext_localconf.php
if (!is_array($GLOBALS['TYPO3_CONF_VARS']['SYS']['caching']['cacheConfigurations']['myextension'])) {
$GLOBALS['TYPO3_CONF_VARS']['SYS']['caching']['cacheConfigurations']['myextension'] = [];}
if (!isset($GLOBALS['TYPO3_CONF_VARS']['SYS']['caching']['cacheConfigurations']['myextension']['frontend'])) {
$GLOBALS['TYPO3_CONF_VARS']['SYS']['caching']['cacheConfigurations']['myextension']['frontend'] = 'TYPO3\\CMS\\Core\\Cache\\Frontend\\StringFrontend';}
if (!isset($GLOBALS['TYPO3_CONF_VARS']['SYS']['caching']['cacheConfigurations']['myextension']['options'])) {
$GLOBALS['TYPO3_CONF_VARS']['SYS']['caching']['cacheConfigurations']['myextension']['options'] = ['defaultLifetime' => 0];}
if (!isset($GLOBALS['TYPO3_CONF_VARS']['SYS']['caching']['cacheConfigurations']['myextension']['groups'])) {
$GLOBALS['TYPO3_CONF_VARS']['SYS']['caching']['cacheConfigurations']['myextension']['groups'] = ['pages'];}
In my controller action :
$cacheIdentifier = 'topic' . $topic->getUid();
$cache = GeneralUtility::makeInstance(CacheManager::class)->getCache('myextension');
$result = unserialize($cache->get($cacheIdentifier));
if ($result !== false ) {
DebuggerUtility::var_dump($result);
} else {
$result = $this->postRepository->findByTopic($topic->getUid(), $page, $itemsPerPage);
$cache->set($cacheIdentifier, serialize($result), ['tag1', 'tag2']);
DebuggerUtility::var_dump($result);
}
The first time the page with the action gets loaded all is ok and the entry has been made in de database (cf_myextension and cf_myextension_tags}.
But the 2nd time the cache gets loaded and I get an error. Even DebuggerUtility::var_dump($result); does not work:
Call to a member function map() on null
in ../typo3/sysext/extbase/Classes/Persistence/Generic/QueryResult.php line 96
*/
protected function initialize()
{
if (!is_array($this->queryResult)) {
$this->queryResult = $this->dataMapper->map($this->query->getType(), $this->persistenceManager->getObjectDataByQuery($this->query));
}
}
/**
A normal var_dump works and spits out the cache entry. What is the problem? Do I forget something? Can't a QueryResult together with some other variables not be stored as an array in the cache? I also tried VariableFrontend cache, which produced the same error.
The E-tools GUI application indents and pretty formats HTML, JavaScript, JSON and SQL. To install the e-tools snap package in all currently supported versions of Ubuntu open the terminal and type:
sudo snap install e-tools

Laravel mail queue and excel attachement causing JSON_ERROR_UTF8

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?

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);
}
}

Dompdf converts fine on local but not on production server

I'm using Laravel 4 with dompdf package: https://github.com/barryvdh/laravel-dompdf
When I generate a report and it converts it to PDF on my local, everything is fine and displays well, but when I do the same exact thing on my production server, it displays random letters where there is either dynamic or static content.
Screenshot of local vs production:
http://s28.postimg.org/u5zk3pc19/report_diff.png
Here is the code that creates the PDF:
/**
* Create PDF
*
*/
public function createPdf( $reportData )
{
if( $this->validate() )
{
// Get Final Data Information
$btu_hp = static::getBtuHp( $reportData['booth_cfm'], $reportData['cure_temp_hp'], $reportData['outside_temp'] );
$btu_current = static::getBtuCurrent( $reportData['booth_cfm'], $reportData['bake_temp_current'], $reportData['outside_temp'] );
$reportData['energy_percentage_per_unit'] = static::getEnergyPercentagePerUnit( $btu_hp, $btu_current );
$reportData['energy_dollar_per_unit'] = static::getEnergyDollarPerUnit( $reportData['cost_per_therm'], $reportData['bake_time_current'], $reportData['cure_time_hp'], $btu_current, $btu_hp );
$reportData['time_savings_per_unit'] = static::getTimeSavingsPerUnit( $reportData['bake_time_current'], $reportData['cure_time_hp'] );
$reportData['time_savings_per_year'] = static::getTimeSavingsPerYear( $reportData['time_savings_per_unit'][0], $reportData['units_per_day'], $reportData['production_days'] );
$reportData['labor_dollar_per_year'] = static::getLaborDollarPerYear( $reportData['labor_rate'], $reportData['time_savings_per_year'][0] );
$reportData['energy_dollar_per_year'] = static::getEnergyDollarPerYear( $reportData['energy_dollar_per_unit'][0], $reportData['units_per_day'], $reportData['production_days'] );
$view = View::make('pages.report.hp-report.print', array('report' => $reportData));
if( ! $this->saveAsPdf($view, $this->generateFileName()) )
{
return false;
}
return true;
}
return false;
}
/**
* Save report as PDF
* #param html HTML of PDF
* #param fileName Name of File
*
*/
public function saveAsPdf( $html, $fileName = null )
{
if(is_null($fileName))
$fileName = $this->generateFileName();
$htmlPath = $this->reportDirectory.'/'.$fileName.'.html';
$pdfPath = $this->reportDirectory.'/'.$fileName.'.pdf';
file_put_contents( $htmlPath, $html );
// set recent PDF to name of PDF
$this->recentReportFile = $fileName . '.pdf';
return PDF::loadFile($htmlPath)->save($pdfPath);
}
/**
* Get most recent uploaded PDF
*
*/
public function getRecentPdf()
{
return $this->recentReportFile;
}
/**
* Generate file name for PDF
*
*/
public function generateFileName()
{
return Auth::user()->id . '_hp_' . str_random(10) . '_' . time();
}
Everything writes fine and it uses the right template and has the styling... Only the static content and dynamic content (values written out with PHP variables) display badly, although you can see some of the static content like Energy Savings and such prints fine.
Is there a reason this could be all jumbled up on the live server, but not local?
Here is the HTML for the view that is being grabbed (the HTML the php variables are injected into): http://pastebin.com/5bMR6G2s
And here is my config file for dompdf:
http://pastebin.com/Ld6MQckG
There are two possible causes for this:
Missing font(s) on the production server. Make sure you have the correct fonts installed on the production site.
Character encoding issues. I'm not sure which site (dev/live) the issue is on, but it may be that one is outputting UTF-8 and the other is not. You could try to sort this out by detecting the encoding on the input file on both dev and live by using mb_detect_encoding and see if they're different. If they are, then use mb_convert_encoding before converting to PDF.

Code Igniter - error when trying to config database.php to use PDO driver

I am trying to get the new PDO driver running in Code Igniter 2.1.1 in (to start with) the local (Mac OS 10.7) copy of my app.
I initially coded it using Active Record for all db operations, and I am now thinking I want to use PDO prepared statements in my model files, going forward.
I modified 'application/config/database.php' like so:
(note a couple minor embedded questions)
[snip]
$active_group = 'local_dev';
$active_record = TRUE;//<---BTW, will this need to stay TRUE to make CI sessions work? For better security, don't we want db-based CI sessions to use PDO too?
//http://codeigniter.com/user_guide/database/configuration.html:
//Note: that some CodeIgniter classes such as Sessions require Active Records be enabled to access certain functionality.
//this is the config setting that I am guessing (?) is my main problem:
$db['local_dev']['hostname'] = 'localhost:/tmp/mysql.sock';
// 1.) if $db['local_dev']['dbdriver']='mysql', then here ^^^ 'localhost:/tmp/mysql.sock' works, 2.) but if $db['local_dev']['dbdriver']='pdo', then it fails with error msg. shown below.
$db['local_dev']['username'] = 'root';
$db['local_dev']['password'] = '';
$db['local_dev']['database'] = 'mydbname';
$db['local_dev']['dbdriver'] = 'pdo';
$db['local_dev']['dbprefix'] = '';
$db['local_dev']['pconnect'] = TRUE;
$db['local_dev']['db_debug'] = TRUE;//TRUE
$db['local_dev']['cache_on'] = FALSE;
$db['local_dev']['cachedir'] = '';
$db['local_dev']['char_set'] = 'utf8';
$db['local_dev']['dbcollat'] = 'utf8_general_ci';
$db['local_dev']['swap_pre'] = '';
$db['local_dev']['autoinit'] = TRUE;
$db['local_dev']['stricton'] = FALSE;
[snip]
With the above config., as soon as I load a controller, I get this error message:
Fatal error: Uncaught exception 'PDOException' with message 'could not find driver' in
/Library/WebServer/Documents/system/database/drivers/pdo/pdo_driver.php:114 Stack trace: #0
/Library/WebServer/Documents/system/database/drivers/pdo/pdo_driver.php(114): PDO->__construct('localhost:/tmp/...', 'root', '', Array) #1 /Library/WebServer/Documents/system/database/DB_driver.php(115): CI_DB_pdo_driver->db_pconnect() #2
/Library/WebServer/Documents/system/database/DB.php(148): CI_DB_driver->initialize() #3
/Library/WebServer/Documents/system/core/Loader.php(346): DB('', NULL) #4
/Library/WebServer/Documents/system/core/Loader.php(1171): CI_Loader->database() #5
/Library/WebServer/Documents/system/core/Loader.php(152): CI_Loader->_ci_autoloader() #6
/Library/WebServer/Documents/system/core/Con in
/Library/WebServer/Documents/system/database/drivers/pdo/pdo_driver.php on line 114
I tried swapping out the 'pdo_driver.php' file from the one on github, as per this:
http://codeigniter.com/forums/viewthread/206124/
...but that just generates other errors, not to mention is disturbing to a newbie who does not want to touch the system files if at all possible.
This thread also seems to imply the need to be hacking the 'pdo_driver.php' system file:
CodeIgniter PDO database driver not working
It seems odd to me, though, that (someone thought that) a hack to a system file is needed to make PDO work in CI v.2.1.1, huh?
Thanks for any suggestions I can try.
I don't know if this might be helpful for you since you already started using the CI functions, but I made my own library for PDO with sqlite and just auto load it. My needs were simple, so it serves its purpose.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter PDO Library
*
*
* #author Michael Cruz
* #version 1.0
*/
class Sqlite_pdo
{
var $DB;
public function connect($path) {
try {
$this->DB = new PDO('sqlite:' . $path);
}
catch(PDOException $e) {
print "Error: " . $e->getMessage();
die();
}
}
public function simple_query($SQL) {
$results = $this->DB->query($SQL)
or die('SQL Error: ' . print_r($this->DB->errorInfo()));
return $results;
}
public function prepared_query($SQL, $bind = array()) {
$q = $this->DB->prepare($SQL)
or die('Prepare Error: ' . print_r($this->DB->errorInfo()));
$q->execute($bind)
or die('Execute Error: ' . print_r($this->DB->errorInfo()));
$q->setFetchMode(PDO::FETCH_BOTH);
return $q;
}
public function my_prepare($SQL) {
$q = $this->DB->prepare($SQL)
or die('Error: ' . print_r($this->DB->errorInfo()));
return $q;
}
public function my_execute($q, $bind) {
$q->execute($bind)
or die('Error: ' . print_r($this->DB->errorInfo()));
$q->setFetchMode(PDO::FETCH_BOTH);
return $q;
}
public function last_insert_id() {
return $this->DB->lastInsertId();
}
}
/* End of file Sqlite_pdo.php */
thanks to the noob thread http://codeigniter.com/forums/viewthread/180277/ (InsiteFX’s answer)..
I figured out the below seems to work (need to test more to be 100%... but at least the error messages are gone:
$db['local_dev']['hostname'] = 'mysql:host=127.0.0.1';

Resources