viernes, 3 de noviembre de 2017

[PrestaShop][Mejora] Cambiar librería de minificar JS

Hola a todos,

Después de estar depurando lentitud en alguna de nuestras web, hacemos un profiler y nos da esto:

Más de 1 segundo en comprimir los JS!!

Según el propio autor de la librería (https://github.com/rgrove/jsmin-php) que utiliza PrestaShop, dice: "No deberías utilizar ninguna versión de JSMin". El proyecto lleva sin actualizarse desde hace más de 6 años.

Incluso nos recomienda otra, que es la que hemos probado, JShrink
https://github.com/tedivm/JShrink

Para poder sustituirla, podemos hacer lo siguiente.
Nos bajamos este fichero a nuestra carpeta /classes/, teniendo el fichero como /classes/Minifier.php
https://github.com/tedivm/JShrink/blob/master/src/JShrink/Minifier.php

En la clase /classes/Media.php cambiamos la función packJS por algo similar a lo de esta captura:

Posteriormente, en nuestra base de datos, agregamos el valor "PS_JS_MINIFIER", usando esto para poder determinar que librería de minify queremos usar.

Y así pasamos, del segundo, a cerca de 200ms, por hacer lo mismo:



Para recordatorio propio de lo que he hecho:
https://github.com/danidomen/materialescolar/commit/fa630fb28e001359365bfbf7a6f768ed9da9e4f7

UPDATE!!: OJO, contrariamente a mi pensamiento, la variable en la función de "minify" no es por referencia, con lo que la línea 178 de la captura, debería quedar así:
case 'jshrink': $js_content = Minifier::minify($js_content); break;

miércoles, 27 de septiembre de 2017

[PrestaShop][BugFix] Mostrar hilo de mensajes en el pedido en el backoffice

Hola a todos,

Os paso la curiosidad de como implementar el hilo de mensajes completo en el pedido. De otra manera, no se muestra nada más que el mensaje original del pedido, pero ninguno más (comentarios que haga el administrador desde el backoffice, comentarios que haga sobre ese pedido el cliente en su zona de pedidos, etc..)

Para ello, es tan simple como:


En las líneas siguientes sustituir la variable $messages:


Por la variable $customer_thread_message:

jueves, 27 de julio de 2017

Solución problemas OpenVPN y certificados VERIFY ERROR en Centos 7

[CentOS7:OpenVPN] VERIFY ERROR: depth=0, error=certificate signature failure

Problems

  • On CentOS 7, OpenVPN failes to make a connection to VPN.
  • OpenVPN conf used to work on CentIS 6.5

Errors

Sat Aug 30 10:52:03 2014 OpenVPN 2.3.2 x86_64-redhat-linux-gnu [SSL (OpenSSL)] [LZO] [EPOLL] [PKCS11] [eurephia] [MH] [IPv6] built on Feb 14 2014
Sat Aug 30 10:52:06 2014 VERIFY OK: depth=1, C=XX, ST=XX, L=MYTOWN, O=OpenVPN-Myprovider, CN=vpn.server.com, emailAddress=admin@vpn.server.com
Sat Aug 30 10:52:06 2014 VERIFY ERROR: depth=0, error=certificate signature failure: C=XX, ST=MYTOWN, O=OpenVPN-Myprovider, CN=vpn.server.com, emailAddress=admin@vpn.server.com
Sat Aug 30 10:52:06 2014 TLS_ERROR: BIO read tls_read_plaintext error: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed
Sat Aug 30 10:52:06 2014 TLS Error: TLS object -> incoming plaintext read error
Sat Aug 30 10:52:06 2014 TLS Error: TLS handshake failed
Sat Aug 30 10:52:06 2014 SIGUSR1[soft,tls-error] received, process restarting

Why this happened?

The certificate used for OpenVPN is encrypted with MD5 and SHA1, but CentOS 7 doesn’t support it as default.

How to resolve this problem?

There are two possible solution,
  1. Generate a certificate without using MD5
  2. Enable MD5 support on CentOS 7

How to enable MD5 support on CentOS 7?

  • Temporally enable it.
export NSS_HASH_ALG_SUPPORT=+MD5
export OPENSSL_ENABLE_MD5_VERIFY=1
  •  Enable MD5 support through NetworkManager
$ sudo vim /usr/lib/systemd/system/NetworkManager.service
Append this.
[Service]
Environment="OPENSSL_ENABLE_MD5_VERIFY=1 NSS_HASH_ALG_SUPPORT=+MD5"
And restart daemon
$ sudo systemctl daemon-reload
$ sudo systemctl restart NetworkManager.service


Fuente original: https://www.centos.org/forums/viewtopic.php?t=47210
I too ran into this problem, but I was not running NetworkManager so I did it (very) slightly differently.

I edited /usr/lib/systemd/system/openvpn-client@.service and added the "Environment" line to the "[Service]" section.

This way, only OpenVPN has the extra environment variables set.

My thanks for working out how to do this and yes the OpenVPN setup is scheduled to be upgraded. Adding the CentOS 7 system is the first step in that process.


#vi /usr/lib/systemd/system/openvpn-client@.service






------------------------------------- ESTO ERA LO DE ANTES -------
It took me a while to figure out why OpenVPN trough NetworkManager was not working on CentOS 7 with old MD5 certificates but I found a solution.

in:
/usr/lib/systemd/system/NetworkManager.service

CODE: SELECT ALL

[Service]
Environment="OPENSSL_ENABLE_MD5_VERIFY=1 NSS_HASH_ALG_SUPPORT=+MD5"


systemctl daemon-reload
systemctl restart NetworkManager.service

The relevant error messages were:

nm-openvpn TLS_ERROR: BIO read tls_read_plaintext error: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed


and on openssl verify -CAfile ca.pem cert.pem
error 7 at 0 depth lookup:certificate signature failure
139819312576416:error:0D0C50A1:asn1 encoding routines:ASN1_item_verify:unknown message digest algorithm:a_verify.c:179:

miércoles, 10 de agosto de 2016

Solución crash System.NotSupportedException aplicaciones Windows 10 [.NET Framework]



La verdad es que el nuevo Sistema Operativo de los de Redmond, Windows 10, me está resultando ser una maravilla. Si bien es cierto que tiene algunos aspectos que pulir y las quejas sobre actualizarse solo, se nota la nueva dirección de la compañía y que es un sistema de "10".

Aunque en este caso, este post va encaminado hacia un problema que he tenido personalmente que me ha traído un poco de cabeza hasta que he dado con la solución.

El caso, es que ciertas aplicaciones han dejado de funcionar con Windows 10. Lo primero que hice al ver que no conseguía hacerlas funcionar, es ver si el Visor de eventos me daba algo más de información al respecto. Para ello, basta con buscar en la nueva barra de búsqueda "Cortana": Visor de eventos.



Nos abrirá la ventana de eventos, debemos dirigirnos a: Registros de Windows -> Aplicación, y por la fecha, ver el evento que ha proporcionado el crash del programa. El "Origen" del error, será Windows Error Reporting, que es el programa encargado de recopilar este tipo de errores cuando "peta" una aplicación y guarda el registro para enviarlo a Microsoft.


Como veis, en mi caso, al final lo que detecto es que está dando un "System.NotSupportedException", que a fin de cuentas lo que quiere decir es que nuestro sistema no soporta dicha aplicación (o al menos en el estado actual).

Este tipo de errores, son los que se encuentran compilados bajo la librería de Microsoft, .NET Framework (en cualquiera de sus versiones como la 2.0, 3.5, 4.0, etc...). 

Me resultaba raro, porque antes siquiera de seguir todas las guías que hay por internet para instalar las versiones antiguas de .NET Framework (Windows 10 es "nativamente" instalado junto con la versión 4.6), y de hecho, no conseguí instalar más "frameworks" porque los tenía todos instalados, me estaba temiendo lo peor.

Pero, finalmente, y a través de los foros de Frontiers (creadores de Elite Dangerous), daban solución para su "launcher" (el cual también me daba errores).

El caso, es que es posible que donde se encuentre alojado el ejecutable (.exe) que nos está dando el problema, exista un ficherito "mágico" que da ciertas ordenes a la hora de ejecutar dicha aplicación. Este fichero, en su nomenclatura comparte el nombre del ejecutable, pero con la coletilla ".config", y de hecho nuestro sistema operativo lo pintará como un fichero con una llave inglesa si teneis instalado el Visual Studio 2015 :D

Como podréis apreciar, todo .exe va acompañado de su .config
Para solucionar dicho problema, bastará con editar el .config con cualquiera de nuestros editores de texto preferidos (en mi caso Notepad++) y cambiar las líneas que están en el fragmento de "startup" para, o bien eliminar la línea que hace referencia al framework "2.X", o añadir la del "4.0".

<configuration>
    <configsections>
    </configsections>
    <startup> 
       <supportedruntime version="v2.0.4.456"></supportedruntime>
       <supportedruntime version="v4.0"></supportedruntime>
    </startup>
  <runtime>
    <enforcefipspolicy enabled="false">
  </enforcefipspolicy></runtime>
  <usersettings>
    <cobrabay .properties.settings="">
      <setting name="DXCheck" serializeas="String">
        <value>True</value>
      </setting>
    </cobrabay>
  </usersettings>
</configuration>

La línea que indica el runtime 2.0.XXX debéis eliminarla.

También puede darse el caso, que exista el .exe pero no el .config. En este caso, basta con crear desde 0 un archivo .config (con el mismo nombre que vuestro ejecutable, incluido el .exe, pero en este caso la extensión debe ser .config) con el siguiente contenido:

<configuration>
    <startup> 
        <supportedruntime version="v4.0">
    </supportedruntime></startup>
</configuration>

Programas que sufrían este "mal" en mi ordenador (para el VorpX tuve que crear todos los ficheros .config):
- EDLaunch.exe (parte del juego Elite Dangerous)
- HardwareReporter.exe (parte del juego Elite Dangerous)
- CrashReporter.exe (parte del juego Elite Dangerous)
- wyUpdater.exe (parte de una aplicación externa creada por un fan para temas de rutas comerciales en el Elite Dangerous)
- vorpX_WebSetup.exe (instalador de aplicación para hacer compatibles juegos con HTC Vive)
- vorpConfig.exe
- vorpControl.exe
- vorpDestop.exe
- vorpDocViewer.exe

Si me da alguna aplicación más este fallo, intentaré dejarla aquí registrada, para que esto pueda servir de ayuda a quien esté buscando una solución.

martes, 17 de noviembre de 2015

Reading Images From Excel Sheet Using PHPExcel

ORIGINAL ARTICLE: http://www.walkswithme.net/reading-images-from-excel-sheet-using-phpexcel

How to reading images from Excel Sheet using phpExcel ? Ya its very interesting and useful, An attached image of excel can be read and upload to server directory is, simplifying the  file upload too.
Ok lets check how can we reading images from Excel Sheet using PHPExcel. Here I’am using PHPExcel Version PHPExcel 1.7.9 . There are two readers that supports Image reads facility right now from PHPExcel API. The reading of Excel cells data using PHP is simple and many example can be found on PHPExcel API Official sites.
Reading Images From Excel Sheet Using PHPExcel
Reading Images From Excel Sheet Using PHPExcel
Lets start with reading images from Excel Sheet using PHPExcel with 2007 reader class XLSXwill be as follows.

$xlsFile = 'sample.xlsx';
require_once 'PHPExcel/Reader/Excel2007.php';
$objReader = new PHPExcel_Reader_Excel2007();
//$objReader->setReadDataOnly(true);
$data = $objReader->load($xlsFile);
$objWorksheet = $data->getActiveSheet();
foreach ($objWorksheet->getDrawingCollection() as $drawing) {
//for XLSX format
$string = $drawing->getCoordinates();
$coordinate = PHPExcel_Cell::coordinateFromString($string);
if ($drawing instanceof PHPExcel_Worksheet_Drawing){
$filename = $drawing->getPath();
$drawing->getDescription();
copy($filename, 'uploads/' . $drawing->getDescription());
}}
The above codes simply reads the images from each row and save to the “uploads”  directory. Here one common question will arise what about all the rows don’t have images then How you guys save images to the corresponding rows right ? Have to get row and column index.

print_r($coordinate) ; //will return cols and rows index for the above case so you can create an array of list with these index.
Ok lets check How to read Images from Excel Sheet using PHPExcel in XLS formart 2005 reader.

$xlsFile = 'test.xls';
require_once 'PHPExcel/Reader/Excel5.php';
$objReader = new PHPExcel_Reader_Excel5();
//$objReader->setReadDataOnly(true);
$data = $objReader->load($xlsFile);
$objWorksheet = $data->getActiveSheet();
foreach ($objWorksheet->getDrawingCollection() as $drawing) {
//for XLSX format
$string = $drawing->getCoordinates();
$coordinate = PHPExcel_Cell::coordinateFromString($string);
if ($drawing instanceof PHPExcel_Worksheet_MemoryDrawing) {
$image = $drawing->getImageResource();
// save image to disk
$renderingFunction = $drawing->getRenderingFunction();
switch ($renderingFunction) {
case PHPExcel_Worksheet_MemoryDrawing::RENDERING_JPEG:
imagejpeg($image, 'uploads/' . $drawing->getIndexedFilename());
break;
case PHPExcel_Worksheet_MemoryDrawing::RENDERING_GIF:
imagegif($image, 'uploads/' . $drawing->getIndexedFilename());
break;
case PHPExcel_Worksheet_MemoryDrawing::RENDERING_PNG:
case PHPExcel_Worksheet_MemoryDrawing::RENDERING_DEFAULT:
imagepng($image, 'uploads/' . $drawing->getIndexedFilename());
break;
}
}
}
Yes Done ! Reading images from Excel Sheet using PHPExcel with XLSX and XLS format with 2007 and 2005 reader are just simply like above codes. If you have any issue or thoughts regarding the functionality just comment below..

jueves, 3 de septiembre de 2015

How to Install ImageMagick on CentOS, RHEL and Ubuntu http://tecadmin.net/install-imagemagick-on-linux/

ORIGINAL ARTICLE: http://tecadmin.net/install-imagemagick-on-linux/
ImageMagick is a software suite to create, edit, compose, or convert bitmap images. It can read and write images in a variety of formats like GIFJPEGPNGPostscript, and TIFF. We can also use ImageMagick to resizeflip, mirror, rotate, distort, shear and transform images, adjust image colors, apply various special effects, or draw text, lines, polygons, ellipses and Bézier curves.
ImageMagick is typically used from command line. Also we can use it from any programming language by using its interface like Magick.NET (.Net),IMagick (PHP), PerlMagick (Perl) etc.

Step 1. Install Required Packages

First we need to install required packages in order to install ImageMagic and IMagick PHP extension.
For CentOS,RHEL Users:
# yum install gcc php-devel php-pear
For Ubuntu Users:
$ sudo apt-get install gcc

Step 2. Install ImageMagick

After installing required packages, let’s install ImageMagick using following command.
For CentOS,RHEL Users:
# yum install ImageMagick ImageMagick-devel
For Ubuntu Users:
$ sudo apt-get install imagemagick

Step 3. Install ImageMagick PHP Extension

At this point you have successfully installed ImageMagick package on your system. Now are are going to install ImageMagick php extension, So that we can use it through php code.
For CentOS,RHEL Users:
# pecl install imagick
# echo "extension=imagick.so" > /etc/php.d/imagick.ini
For Ubuntu Users:
$ sudo apt-get install php5-imagick

Step 4. Restart Apache and Check Extension

After completing above steps you need to reload apache service to enable php exension using following command
CentOS,RHEL Users:
# service httpd reload

Ubuntu Users:
# service apache2 reload
Click here to read more details about ImageMagick setup and there uses.

-----------------------------

OTRA FORMA http://linuxhostingsupport.net/blog/howto-install-imagemagick-on-plesk

Howto: Install ImageMagick on Plesk

How to install ImageMagick on Linux/Plesk server? Follow the below steps to install ImageMagick on a Plesk server. Login to your server as root and execute the following commands:
1. Install “ImageMagick” package via YUM.
yum install ImageMagick
2. Now install “ImageMagick-devel”
yum install ImageMagick-devel
3. Install “php-pear” required for “pecl”. It will install and compile ImageMagick with PHP for you.
yum install php-pear
4. Now, you need to install ImageMagick using pecl
pecl install imagick
A imagick.so file will be created under /usr/lib/php/modules/ directory. Now, edit the php configuration file /etc/php.ini and add the following line after the “extension_dir” directive
extension = “imagick.so”
Save the file and restart the httpd service. That is it. You can verify using the command:
php -i | grep imagick