Secciones

miércoles, 3 de febrero de 2016

Magento - Probar HTML de emails

Problema: Hacer cambios en plantillas de emails y guardar el contenido resultante en un archivo.html

Crear nuevo archivo en

app\code\local\Mage\Core\Model\Email\Template.php

Con el siguiente contenido


    /**
     * Send mail to recipient
     *
     * @param   array|string       $email        E-mail(s)
     * @param   array|string|null  $name         receiver name(s)
     * @param   array              $variables    template variables
     * @return  boolean
     **/
    public function send($email, $name = null, array $variables = array())
    {
        if (!$this->isValidForSend()) {
            Mage::logException(new Exception('This letter cannot be sent.')); // translation is intentionally omitted
            return false;
        }

        $emails = array_values((array)$email);
        $names = is_array($name) ? $name : (array)$name;
        $names = array_values($names);
        foreach ($emails as $key => $email) {
            if (!isset($names[$key])) {
                $names[$key] = substr($email, 0, strpos($email, '@'));
            }
        }

        $variables['email'] = reset($emails);
        $variables['name'] = reset($names);

        $this->setUseAbsoluteLinks(true);
        $text = $this->getProcessedTemplate($variables, true);
        $subject = $this->getProcessedTemplateSubject($variables);

        $setReturnPath = Mage::getStoreConfig(self::XML_PATH_SENDING_SET_RETURN_PATH);
        switch ($setReturnPath) {
            case 1:
                $returnPathEmail = $this->getSenderEmail();
                break;
            case 2:
                $returnPathEmail = Mage::getStoreConfig(self::XML_PATH_SENDING_RETURN_PATH_EMAIL);
                break;
            default:
                $returnPathEmail = null;
                break;
        }

        if ($this->hasQueue() && $this->getQueue() instanceof Mage_Core_Model_Email_Queue) {
            /** @var $emailQueue Mage_Core_Model_Email_Queue */
            $emailQueue = $this->getQueue();
            $emailQueue->setMessageBody($text);
            $emailQueue->setMessageParameters(array(
                    'subject'           => $subject,
                    'return_path_email' => $returnPathEmail,
                    'is_plain'          => $this->isPlain(),
                    'from_email'        => $this->getSenderEmail(),
                    'from_name'         => $this->getSenderName(),
                    'reply_to'          => $this->getMail()->getReplyTo(),
                    'return_to'         => $this->getMail()->getReturnPath(),
                ))
                ->addRecipients($emails, $names, Mage_Core_Model_Email_Queue::EMAIL_TYPE_TO)
                ->addRecipients($this->_bccEmails, array(), Mage_Core_Model_Email_Queue::EMAIL_TYPE_BCC);
            $emailQueue->addMessageToQueue();

            return true;
        }

        ini_set('SMTP', Mage::getStoreConfig('system/smtp/host'));
        ini_set('smtp_port', Mage::getStoreConfig('system/smtp/port'));

        $mail = $this->getMail();

        if ($returnPathEmail !== null) {
            $mailTransport = new Zend_Mail_Transport_Sendmail("-f".$returnPathEmail);
            Zend_Mail::setDefaultTransport($mailTransport);
        }

        foreach ($emails as $key => $email) {
            $mail->addTo($email, '=?utf-8?B?' . base64_encode($names[$key]) . '?=');
        }

        if ($this->isPlain()) {
            $mail->setBodyText($text);
        } else {
            $mail->setBodyHTML($text);
        }

        $mail->setSubject('=?utf-8?B?' . base64_encode($subject) . '?=');
        $mail->setFrom($this->getSenderEmail(), $this->getSenderName());

/* START LESS - (L)ocalhost (E)mail (S)erver (S)imulator */
$time = date('dmY_His');
/* END LESS - (L)ocalhost (E)mail (S)erver (S)imulator */

        try {
            $mail->send();
/* START LESS - (L)ocalhost (E)mail (S)erver (S)imulator */
if($this->isPlain()) {
 Mage::log($text, null, 'sacsi_less_email_ok_text_'.$time.'.log', true);
} else {
 Mage::log($text, null, 'sacsi_less_email_ok_text_'.$time.'.html', true);
}            
/* END LESS - (L)ocalhost (E)mail (S)erver (S)imulator */
            $this->_mail = null;
        }
        catch (Exception $e) {
            $this->_mail = null;
/* START LESS - (L)ocalhost (E)mail (S)erver (S)imulator */
if($this->isPlain()) {
 Mage::log($text, null, 'sacsi_less_email_exception_text_'.$time.'.log', true);
} else {
 Mage::log($text, null, 'sacsi_less_email_exception_text_'.$time.'.html', true);
}            
/* END LESS - (L)ocalhost (E)mail (S)erver (S)imulator */
            Mage::logException($e);
            return false;
        }

        return true;
    }

*-*
Sebastian A. Colombini

viernes, 24 de abril de 2015

wordpress - Quitar las revisiones - Delete revisions

Para quitar las revisiones desde la base de datos.

DELETE FROM wp_posts WHERE post_type = 'revision';


Para configurar que no se sigan generando las revisiones
editar el wp-config.php

define('AUTOSAVE_INTERVAL', 300 ); // segundos

define('WP_POST_REVISIONS', false );

o tambien 

define('WP_POST_REVISIONS', 0);

*-* Sebastian A. Colombini

lunes, 28 de abril de 2014

mysqldiff - Comparar diferencias entre 2 bases de datos

El siguiente comando realiza una comparacion de 2 bases en localhost

mysqldiff --server1=root:123456@localhost --server2=root:123456@localhost \ --changes-for=server1 --show-reverse nombreDB1:nombreDB2 \ --force --difftype=SQL > d:\diferencia.sql


El resultado se guarda en el archivo d:\diferencia.sql


*-*
 Sebastian A. Colombini

martes, 8 de abril de 2014

Magento - Database server does not support the InnoDB storage engine

Al instalar Magento 1.7.x
Da el siguiente error:
Database server does not support the InnoDB storage engin

El problema es debido al chequeo que hace sobre el MySql en el
archivo app/code/core/Mage/Install/Model/Installer/Db/Mysql4.php

en la funcion de la linea 59,

    public function supportEngine()
    {
        $variables  = $this->_getConnection()
            ->fetchPairs('SHOW VARIABLES');
        return (!isset($variables['have_innodb']) || $variables['have_innodb'] != 'YES') ? false : true;
    }

La forma rapida, es modificar la funcion para que devuelva siempre True

ej:

    public function supportEngine()
    {
        $variables  = $this->_getConnection()
            ->fetchPairs('SHOW VARIABLES');
//        return (!isset($variables['have_innodb']) || $variables['have_innodb'] != 'YES') ? false : true;
return true;
    }

y luego de la instalacion reestablecerlo como estaba originalmente

El problema radica en que la variable 'have_innodb' no se encuentra a partir de una determinada version en el MySql.

Saludos.

*-*
Sebastian A. Colombini

martes, 25 de marzo de 2014

Magento - Cambiar cantidad de productos por fila

Como cambiar la cantidad de productos que aparecen por fila en la vista de grilla.

modificar el archivo de layout

app/design/frontend/[paquete]/[theme]/layout/catalog.xml

colocar 3

antes de las entradas como por ejemplo

empty6

recordar, refrescar cache y compilador segun el caso.



*-*
Sebastian A. Colombini

Desarrollo PHP - instalación de entornos

Desarrollo PHP - instalación de entornos

Artículos sobre los entornos involucrados para todo el flujo de trabajo y desarrollo de un sistema a desarrollarse en lenguaje PHP.

La siguiente es un lista de artículos que voy a ir enlazando a medida que este listo el articulo.
FALTA: diagrama de los distintos entornos involucrados
  1. Entorno de desarrollo
    1. Instalacion de herramientas de desarrollo ( IDE + WAMP )
    2. http://phpqatools.org/ ( tambien revisar http://sebastian-bergmann.de/archives/856-Quality-Assurance-Tools-for-PHP.html)
      1. Instalar Pear : http://pear.php.net/manual/en/installation.getting.php
        1. PHPUnit is the de-facto standard for unit testing in PHP projects. It provides both a framework that makes the writing of tests easy as well as the functionality to easily run the tests and analyse their results.
        2. phploc is a tool for quickly measuring the size of a PHP project.
        3. pdepend can generate a large set of software metrics from a given code base. These values can be used to measure the quality of a software project and they help to identify the parts of an application where a code refactoringshould be applied
        4. phpcpd is a Copy/Paste Detector (CPD) for PHP code. It scans a PHP project for duplicated code.
        5. phpmd scans PHP source code and looks for potential problems such as possible bugs, dead code, suboptimal code, and overcomplicated expressions
        6. phpcs tokenises PHP, JavaScript and CSS files and detects violations of a defined set of coding standards. It is an essential development tool that ensures your code remains clean and consistent. It can also help prevent some common semantic errors made by developers.
        7. PHP_CodeBrowser provides a code browser for PHP files with syntax highlighting and colored error-sections found by quality assurance tools such as PHPUnit and PHP_CodeSniffer.
        8. NOTA: los anteriores del 1 al 7 se pueden instalar directamente 
        9. hphpa is a convenience wrapper for HipHop's static analyzer.
        10. Jenkins is the leading open-source continuous integrationserver. Thanks to its thriving plugin ecosystem, it supports building and testing virtually any project. The goal of theTemplate for Jenkins Jobs for PHP Projects is to provide a standard template for Jenkins jobs for PHP projects.
        11. vfsStream is a stream wrapper for a virtual file system that may be helpful in unit tests to mock the real file system.
        12. bytekit-cli provides a command-line tool that leverages the Bytekit extension to perform common code analysis tasks on the PHP bytecode level.
        13. Behat is a framework for Behavior Driven Development (BDD) that is inspired by Cucumber.
        14. phpdcd is a Dead Code Detector (DCD) for PHP code. It scans a PHP project for code that is no longer used.
        15. PHPLint is a validator and documentator for PHP 4 and PHP 5 programs. PHPLint extends the PHP language through transparent meta-code that can drive the parser to a even more strict check of the source. PHPLint is not simply a checker: it implements a new, strong typed, language implemented over the PHP language. You can build your programs from scratch with PHPLint in mind, or you can check and fix existing programs, or you can follow the quick-and-dirty PHP programming way and then add the PHPLint meta-code later once the program is finished. Whatever is the strategy you choose, PHPLint makes your programs safer, more secure, well documented and with drastically less bugs.
        16. phpDocumentor 2 is build to generate API documentation for all features available in PHP 5.3 and higher.
 NOTAs:
- de http://jenkins-ci.org/views/hudson-tutorials descargar e instalar jenkins
- de http://jenkins-php.org/ ejecutar la instalacion que indica en la pagina pero por algun motivo NO instala TODOS los que indica en http://phpqatools.org/ ... PERO luego de ejecutar el comando estos son los paquetes instalados
c:\AppServ\php5_2_17>pear list
INSTALLED PACKAGES, CHANNEL PEAR.PHP.NET:
=========================================
PACKAGE             VERSION STATE
Archive_Tar         1.3.10  stable
Console_CommandLine 1.1.3   stable
Console_Getopt      1.3.1   stable
PEAR                1.9.4   stable
PHP_CodeSniffer     1.4.0   stable
Structures_Graph    1.0.4   stable
XML_Util            1.2.1   stable

Instalando phpunit (2 formas):
1) desde consola pear
pear config-set auto_discover 1
pear install pear.phpunit.de/PHPUnit
2)
-download http://pear.phpunit.de/get/phpunit.phar 
- 
  1. Entorno de Integracion Continua
  2. Entorno de Test
  3. Entorno de Pre/Produccion
  4. Entorno de Produccion
*-*
Sebastian A. Colombini

viernes, 2 de agosto de 2013

Magento - Ordenar Categorias programaticamente.

Obetivo: ordenar  categorias en forma mas rapida que con drag & drop desde el backend

Paso 1- Seleccionar la categoria desde el backend e identificar el ID de la categoria "Padre" que contiene las subcategorias a ordenar
Supuesto ID= 8

Paso 2 - ejecutar

select V.value , C.entity_id, C.parent_id, C.path, C.position from  catalog_category_entity C inner join catalog_category_entity_varchar V on C.entity_id=V.entity_id
where  V.attribute_id=41  and level=3 and path  like '1/2/8/%'
order by C.position;


Paso 3 - Manipular resultado
El resultado puede ser manipulado para generar las sentencias update de la forma

update catalog_category_entity set position=    12    where entity_id=    9    ;


*-*
Sebastian A. Colombini

martes, 16 de abril de 2013

Magento - SQLSTATE[42000]: Syntax error or access violation: 1067 Invalid default value for 'period'


En la instalacion desde 0 de Magento 1.6x
Puede aparecer el error: 
Error in file: "app\code\core\Mage\SalesRule\sql\salesrule_setup\upgrade-1.6.0.0-1.6.0.1.php" - SQLSTATE[42000]: Syntax error or access violation: 1067 Invalid default value for 'period'.
NOTA: para ver error de php modificar el index.php y descomentar la linea
ini_set('display_errors', 1);

Para solucionarlo:

1-modificar el archivo
install-1.6.0.0.php en app\code\core\Mage\SalesRule\sql\salesrule_setup. 
En la linea  333, cambiar
->addColumn('period', Varien_Db_Ddl_Table::TYPE_DATE, null, array(
'nullable' => false,
), 'Period')
por
->addColumn('period', Varien_Db_Ddl_Table::TYPE_DATE, null, array(
'nullable' => false,
'default' => '0000-00-00',
), 'Period')
En la linea 393, cambiar
->addColumn('period', Varien_Db_Ddl_Table::TYPE_DATE, null, array(
'nullable' => false,
), 'Period')
por
->addColumn('period', Varien_Db_Ddl_Table::TYPE_DATE, null, array(
'nullable' => false,
'default' => '0000-00-00',
), 'Period')

2-vaciar la base de datos (borrar todas la tablas...o borrar y crear base de datos)
3-vaciar cache
4-eliminar local.xml
5- Volver a acceder a la url del sitio, donde comenzara nuevamente el instalador.



*-*
Sebastian A. Colombini

martes, 9 de abril de 2013

Magento - Please enter a valid URL

Durante la instalacion de Magento
puede aparecer el mensaje de error

Please enter a valid URL. Protocol is required (http://, https:// or ftp://)

dicha validacion es realizada en el archivo
\js\prototype\validation.js:

en la linea #505 (aprox) esta la funcion que se debe modificar, dejandolo como sigue:

['validate-url', 'Please enter a valid URL. Protocol is required (http://, https:// or ftp://)', function (v) {
                // return Validation.get('IsEmpty').test(v) || /^(http|https|ftp):\/\/(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+)(:(\d+))?\/?/i.test(v)
                return true;
            }],


Donde // comenta la linea original y la reemplazo por return true.

NOTA: luego de la instalacion, recomiendo deshacer las modificaciones.

Saludos.
*-*
Sebastian A. Colombini

jueves, 27 de diciembre de 2012

Habilitar el trace de las consultas en SQL server express

Para habilitar el trace de las consultas en SQL server express
iniciar el servicio desde consola
net start MSSQL$SQLEXPRESS /T4032

Esto causara que todas las consultas de todas las conexion sean logeadas. Para lograrlo es necesario setear una bandera (3605) desde el Sql server management studio.

dbcc traceon(3605, -1) -- El -1 setea en forma global.

El archivo se puede encontrar ,por ej, en C:\Program Files\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQL\Log\ERRORLOG.

Ese archivo contendra todos las consultas ejecutadas desde todos los clientes.

*-*
Sebastian A. Colombini