Jump to content

Password Reset email Doesn't Contain Password


Recommended Posts

If a user tries to reset their password, they first get an email titled Password Query Confirmation, with a link in it.  They click on the link to reset their password, then they get a second email, titled Your New Password.  Problem is, this second email doesn't actually contain the new password.  It has a section labelled YOUR NEW TRINITY STORE LOGIN DETAILS, that contains the user's email address, but no password.  User is then stuck and has to have admin intervention.

 

How do we fix this?

 

Thanks,

 

PacSD Inc., consultant for Trinity

 

 

Prestashop 1.6.1.1

Leo Watches theme

Link to comment
Share on other sites

For the record, here is how this was solved:

 

Go to Localization-->Translations. In Modify Translations section, choose Email Templates Translations, Trinity-Leo, and English. In next page, choose Core Emails, then Password. Edit HTML there.

Added this text in email:  Password: {passwd}

Link to comment
Share on other sites

  • 2 years later...
  • 1 year later...
  • 2 months later...
On 9/16/2019 at 12:40 AM, ender666 said:

same problem.. 1.7.6.1 is sending mail without password only with variable {passwd}

I solved this problem in my PrestaShop 1.7.6.1.

{passwd} variable was not defined in: /controllers/front/PasswordController.php ---> changePassword function --->  $mail_params Array

I added in $mail_params key and value: '{passwd}' => $password

                        $mail_params = [
                            '{email}' => $customer->email,
                            '{lastname}' => $customer->lastname,
                            '{firstname}' => $customer->firstname,
                            '{passwd}' => $password,
                        ];

It working for me.   

Link to comment
Share on other sites

On 12/10/2019 at 7:19 PM, Caracal said:

I solved this problem in my PrestaShop 1.7.6.1.

{passwd} variable was not defined in: /controllers/front/PasswordController.php ---> changePassword function --->  $mail_params Array

I added in $mail_params key and value: '{passwd}' => $password


                        $mail_params = [
                            '{email}' => $customer->email,
                            '{lastname}' => $customer->lastname,
                            '{firstname}' => $customer->firstname,
                            '{passwd}' => $password,
                        ];

It working for me.   

What was added to the email template?

GMUrKco.png

Password does not come.

The cache is cleared. In the var directory as well.

Edited by klymets1 (see edit history)
Link to comment
Share on other sites

9 minutes ago, klymets1 said:

What was added to the email template?

Nothing has been added. I use Alysum theme and instead of the user's password, a variable {passwd} was displayed.

My HTML template from Alysum theme:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/1999/REC-html401-19991224/strict.dtd">
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
	<title>Сообщение от {shop_name}</title>
</head>
<body>
<table style="background: #f9f9f9; width: 100%;" border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr style="background: #000000;">
<td style="width: 25%;"> </td>
<td style="width: 50%;">
<table style="width: 650px; height: 25px;" border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td style="width: 80%; color: #5f5d5a;"><strong><a style="color: #7a7874; text-decoration: none; font-family: Verdana, Geneva, sans-serif; font-size: 12px;" href="{shop_url}">В магазин</a></strong><span>    |    </span><strong><a style="color: #7a7874; text-decoration: none; font-family: Verdana, Geneva, sans-serif; font-size: 12px;" href="{my_account_url}">В кабинет</a></strong><span>    |    </span><strong><a style="color: #7a7874; text-decoration: none; font-family: Verdana, Geneva, sans-serif; font-size: 12px;" href="{shop_url}?fc=module&module=blockwishlist&controller=mywishlist">Мой список</a></strong></td>
<td style="width: 20%; height: 25px;" align="right"><strong><a style="color: #7a7874; text-decoration: none; font-family: Verdana, Geneva, sans-serif; font-size: 12px;" href="{shop_url}?controller=order-opc">Моя корзина</a></strong></td>
</tr>
</tbody>
</table>
</td>
<td style="width: 25%;"> </td>
</tr>
<tr>
<td> </td>
<td>
<table style="font-family: Verdana,sans-serif; font-size: 11px; color: #374953; width: 650px;" border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td style="padding-top: 45px; padding-bottom: 45px; border-bottom: 5px solid #000000;" align="center"><a title="{shop_name}" href="{shop_url}"><img style="border: none;" src="{shop_logo}" alt="{shop_name}" /></a></td>
</tr>
<tr>
<td style="line-height: 2px; font-size: 2px; border-bottom: 1px solid #8a8a8c;"> </td>
</tr>
<tr>
<td style="padding-top: 40px;" align="center"><strong style="color: #6c6b68; font-size: 30px; font-family: Georgia; text-transform: uppercase; line-height: 45px;">здравствуйте</strong><br /> <span style="color: #6c6b68; font-family: Georgia; font-size: 55px;">{firstname} {lastname}</span>,</td>
</tr>
<tr>
<td style="text-align: center; border-bottom: 1px solid #8a8a8c; padding-bottom: 45px;"> </td>
</tr>
<tr>
<td style="line-height: 2px; font-size: 2px; border-bottom: 5px solid #000;"> </td>
</tr>
<tr>
<td style="line-height: 30px; height: 30px;"> </td>
</tr>
<tr>
<td style="padding: 20px; border: 1px solid #e0e0e0; background: #ffffff;">
<table style="width: 100%;" border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td style="padding-bottom: 15px;" colspan="2"><span style="font-family: Georgia, 'Times New Roman', Times, serif; font-size: 17px; color: #4a4a4a; text-transform: uppercase;">новая информация для входа в {shop_name}.<br /></span></td>
</tr>
<tr>
<td style="color: #595959; font-family: Georgia, 'Times New Roman', Times, serif; font-size: 16px; text-align: right; padding-right: 20px;">E-mail:</td>
<td>
<div style="width: 320px; border-radius: 4px; border: 1px solid #e0e0e0; background: #f8f8f8; height: 42px; line-height: 42px; text-indent: 20px; font-family: Verdana, Geneva, sans-serif; font-size: 16px; color: #666666; text-decoration: none;">{email}</div>
</td>
</tr>
<tr>
<td style="height: 20px;" colspan="2"> </td>
</tr>
<tr>
<td style="color: #595959; font-family: Georgia, 'Times New Roman', Times, serif; font-size: 16px; text-align: right; padding-right: 20px;">Пароль:</td>
<td>
<div style="width: 320px; border-radius: 4px; border: 1px solid #e0e0e0; background: #f8f8f8; height: 42px; line-height: 42px; text-indent: 20px; font-family: Verdana, Geneva, sans-serif; font-size: 16px; color: #666666;">{passwd}</div>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
<tr>
<td style="height: 20px;"> </td>
</tr>
<tr>
<td style="padding: 20px; border: 1px solid #e0e0e0; background: #ffffff;">{adv_img}
<table style="width: 100%;" border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td style="color: #757575; font-family: Verdana, Geneva, sans-serif; font-size: 13px; padding-right: 20px;" valign="top"><span id="result_box" lang="ru"><span class="hps alt-edited">Пожалуйста, будьте внимательны</span> <span class="hps">при использовании</span> <span class="hps">этих</span> <span class="hps">данных, не используйте их</span> <span class="hps"><span id="result_box" lang="ru"><span class="hps">совместно</span></span> с другими.</span></span><br /><br />Теперь вы можете совершать покупки в: {shop_url}</td>
</tr>
</tbody>
</table>
</td>
</tr>
<tr>
<td style="height: 60px;"> </td>
</tr>
</tbody>
</table>
</td>
<td> </td>
</tr>
<tr style="background: #000000;">
<td> </td>
<td style="padding-top: 20px;">
<table style="width: 650px; color: #888888;" border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td style="padding-bottom: 20px; width: 29%;" valign="top">
<table border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td style="padding-bottom: 20px; width: 29%;" valign="top" collspan="3">
<div style="padding-right: 30px;">
<h4 style="margin: 0 0 20px 0; color: #888888; text-transform: uppercase; font-size: 15px; font-family: Georgia;"><span style="font-size: 10pt;">наши контакты</span></h4>
<p style="line-height: 29px; color: #505050; font-size: 13px;">{email_addr}</p>
</div>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
<tr>
<td style="font-size: 12px; height: 50px; line-height: 50px; border-top: 1px solid #1e1e1e; color: #505050; font-family: Verdana, Geneva, sans-serif;" colspan="3" align="left"><a style="color: #505050; text-decoration: none;" href="{shop_url}">{shop_name}</a></td>
</tr>
</tbody>
</table>
</td>
<td> </td>
</tr>
</tbody>
</table>
</body>
</html>

 

Link to comment
Share on other sites

53 minutes ago, klymets1 said:

 

s2AGt38.png

check name mail-template: password

and compare your /classes/Mail.php with my file:

<?php
/**
 * 2007-2019 PrestaShop and Contributors
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Open Software License (OSL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * https://opensource.org/licenses/OSL-3.0
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to [email protected] so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade PrestaShop to newer
 * versions in the future. If you wish to customize PrestaShop for your
 * needs please refer to https://www.prestashop.com for more information.
 *
 * @author    PrestaShop SA <[email protected]>
 * @copyright 2007-2019 PrestaShop SA and Contributors
 * @license   https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
 * International Registered Trademark & Property of PrestaShop SA
 */

/**
 * Class MailCore.
 */
class MailCore extends ObjectModel
{
    public $id;

    /** @var string Recipient */
    public $recipient;

    /** @var string Template */
    public $template;

    /** @var string Subject */
    public $subject;

    /** @var int Language ID */
    public $id_lang;

    /** @var int Timestamp */
    public $date_add;

    /**
     * @see ObjectModel::$definition
     */
    public static $definition = [
        'table' => 'mail',
        'primary' => 'id_mail',
        'fields' => [
            'recipient' => [
                'type' => self::TYPE_STRING,
                'validate' => 'isEmail',
                'copy_post' => false,
                'required' => true,
                'size' => 255,
            ],
            'template' => [
                'type' => self::TYPE_STRING,
                'validate' => 'isTplName',
                'copy_post' => false,
                'required' => true,
                'size' => 62,
            ],
            'subject' => [
                'type' => self::TYPE_STRING,
                'validate' => 'isMailSubject',
                'copy_post' => false,
                'required' => true,
                'size' => 255,
            ],
            'id_lang' => [
                'type' => self::TYPE_INT,
                'validate' => 'isUnsignedId',
                'copy_post' => false,
                'required' => true,
            ],
            'date_add' => [
                'type' => self::TYPE_DATE,
                'validate' => 'isDate',
                'copy_post' => false,
                'required' => true,
            ],
        ],
    ];

    /**
     * Mail content type.
     */
    const TYPE_HTML = 1;
    const TYPE_TEXT = 2;
    const TYPE_BOTH = 3;

    /**
     * Send mail under SMTP server.
     */
    const METHOD_SMTP = 2;

    /**
     * Disable mail, will return immediately after calling send method.
     */
    const METHOD_DISABLE = 3;

    /**
     * Send Email.
     *
     * @param int $idLang Language ID of the email (to translate the template)
     * @param string $template Template: the name of template not be a var but a string !
     * @param string $subject Subject of the email
     * @param string $templateVars Template variables for the email
     * @param string $to To email
     * @param string $toName To name
     * @param string $from From email
     * @param string $fromName To email
     * @param array $fileAttachment array with three parameters (content, mime and name).
     *                              You can use an array of array to attach multiple files
     * @param bool $mode_smtp SMTP mode (deprecated)
     * @param string $templatePath Template path
     * @param bool $die Die after error
     * @param int $idShop Shop ID
     * @param string $bcc Bcc recipient address. You can use an array of array to send to multiple recipients
     * @param string $replyTo Reply-To recipient address
     * @param string $replyToName Reply-To recipient name
     *
     * @return bool|int Whether sending was successful. If not at all, false, otherwise amount of recipients succeeded.
     */
    public static function send(
        $idLang,
        $template,
        $subject,
        $templateVars,
        $to,
        $toName = null,
        $from = null,
        $fromName = null,
        $fileAttachment = null,
        $mode_smtp = null,
        $templatePath = _PS_MAIL_DIR_,
        $die = false,
        $idShop = null,
        $bcc = null,
        $replyTo = null,
        $replyToName = null
    ) {
        if (!$idShop) {
            $idShop = Context::getContext()->shop->id;
        }

        $hookBeforeEmailResult = Hook::exec(
            'actionEmailSendBefore',
            [
                'idLang' => &$idLang,
                'template' => &$template,
                'subject' => &$subject,
                'templateVars' => &$templateVars,
                'to' => &$to,
                'toName' => &$toName,
                'from' => &$from,
                'fromName' => &$fromName,
                'fileAttachment' => &$fileAttachment,
                'mode_smtp' => &$mode_smtp,
                'templatePath' => &$templatePath,
                'die' => &$die,
                'idShop' => &$idShop,
                'bcc' => &$bcc,
                'replyTo' => &$replyTo,
            ],
            null,
            true
        );

        if ($hookBeforeEmailResult === null) {
            $keepGoing = false;
        } else {
            $keepGoing = array_reduce(
                $hookBeforeEmailResult,
                function ($carry, $item) {
                    return ($item === false) ? false : $carry;
                },
                true
            );
        }

        if (!$keepGoing) {
            return true;
        }

        if (is_numeric($idShop) && $idShop) {
            $shop = new Shop((int) $idShop);
        }

        $configuration = Configuration::getMultiple(
            [
                'PS_SHOP_EMAIL',
                'PS_MAIL_METHOD',
                'PS_MAIL_SERVER',
                'PS_MAIL_USER',
                'PS_MAIL_PASSWD',
                'PS_SHOP_NAME',
                'PS_MAIL_SMTP_ENCRYPTION',
                'PS_MAIL_SMTP_PORT',
                'PS_MAIL_TYPE',
            ],
            null,
            null,
            $idShop
        );

        // Returns immediately if emails are deactivated
        if ($configuration['PS_MAIL_METHOD'] == self::METHOD_DISABLE) {
            return true;
        }

        // Hook to alter template vars
        Hook::exec(
            'sendMailAlterTemplateVars',
            [
                'template' => $template,
                'template_vars' => &$templateVars,
            ]
        );

        if (!isset($configuration['PS_MAIL_SMTP_ENCRYPTION']) ||
            Tools::strtolower($configuration['PS_MAIL_SMTP_ENCRYPTION']) === 'off'
        ) {
            $configuration['PS_MAIL_SMTP_ENCRYPTION'] = false;
        }

        if (!isset($configuration['PS_MAIL_SMTP_PORT'])) {
            $configuration['PS_MAIL_SMTP_PORT'] = 'default';
        }

        /*
         * Sending an e-mail can be of vital importance for the merchant, when his password
         * is lost for example, so we must not die but do our best to send the e-mail.
         */
        if (!isset($from) || !Validate::isEmail($from)) {
            $from = $configuration['PS_SHOP_EMAIL'];
        }

        if (!Validate::isEmail($from)) {
            $from = null;
        }

        // $from_name is not that important, no need to die if it is not valid
        if (!isset($fromName) || !Validate::isMailName($fromName)) {
            $fromName = $configuration['PS_SHOP_NAME'];
        }

        if (!Validate::isMailName($fromName)) {
            $fromName = null;
        }

        /*
         * It would be difficult to send an e-mail if the e-mail is not valid,
         * so this time we can die if there is a problem.
         */
        if (!is_array($to) && !Validate::isEmail($to)) {
            self::dieOrLog($die, 'Error: parameter "to" is corrupted');

            return false;
        }

        // if bcc is not null, make sure it's a vaild e-mail
        if (null !== $bcc && !is_array($bcc) && !Validate::isEmail($bcc)) {
            self::dieOrLog($die, 'Error: parameter "bcc" is corrupted');
            $bcc = null;
        }

        if (!is_array($templateVars)) {
            $templateVars = [];
        }

        // Do not crash for this error, that may be a complicated customer name
        if (is_string($toName) && !empty($toName) && !Validate::isMailName($toName)) {
            $toName = null;
        }

        if (!Validate::isTplName($template)) {
            self::dieOrLog($die, 'Error: invalid e-mail template');

            return false;
        }

        if (!Validate::isMailSubject($subject)) {
            self::dieOrLog($die, 'Error: invalid e-mail subject');

            return false;
        }

        /* Construct multiple recipients list if needed */
        $message = \Swift_Message::newInstance();
        if (is_array($to) && isset($to)) {
            foreach ($to as $key => $addr) {
                $addr = trim($addr);
                if (!Validate::isEmail($addr)) {
                    self::dieOrLog($die, 'Error: invalid e-mail address');

                    return false;
                }

                if (is_array($toName) && isset($toName[$key])) {
                    $addrName = $toName[$key];
                } else {
                    $addrName = $toName;
                }

                $addrName = ($addrName == null || $addrName == $addr || !Validate::isGenericName($addrName)) ?
                          '' :
                          self::mimeEncode($addrName);
                $message->addTo(self::toPunycode($addr), $addrName);
            }
            $toPlugin = $to[0];
        } else {
            /* Simple recipient, one address */
            $toPlugin = $to;
            $toName = (($toName == null || $toName == $to) ? '' : self::mimeEncode($toName));
            $message->addTo(self::toPunycode($to), $toName);
        }

        if (isset($bcc) && is_array($bcc)) {
            foreach ($bcc as $addr) {
                $addr = trim($addr);
                if (!Validate::isEmail($addr)) {
                    self::dieOrLog($die, 'Error: invalid e-mail address');

                    return false;
                }

                $message->addBcc(self::toPunycode($addr));
            }
        } elseif (isset($bcc)) {
            $message->addBcc(self::toPunycode($bcc));
        }

        try {
            /* Connect with the appropriate configuration */
            if ($configuration['PS_MAIL_METHOD'] == self::METHOD_SMTP) {
                if (empty($configuration['PS_MAIL_SERVER']) || empty($configuration['PS_MAIL_SMTP_PORT'])) {
                    self::dieOrLog($die, 'Error: invalid SMTP server or SMTP port');

                    return false;
                }

                $connection = \Swift_SmtpTransport::newInstance(
                    $configuration['PS_MAIL_SERVER'],
                    $configuration['PS_MAIL_SMTP_PORT'],
                    $configuration['PS_MAIL_SMTP_ENCRYPTION']
                )
                    ->setUsername($configuration['PS_MAIL_USER'])
                    ->setPassword($configuration['PS_MAIL_PASSWD']);
            } else {
                $connection = \Swift_MailTransport::newInstance();
            }

            if (!$connection) {
                return false;
            }

            $swift = \Swift_Mailer::newInstance($connection);
            /* Get templates content */
            $iso = Language::getIsoById((int) $idLang);
            $isoDefault = Language::getIsoById((int) Configuration::get('PS_LANG_DEFAULT'));
            $isoArray = [];
            if ($iso) {
                $isoArray[] = $iso;
            }

            if ($isoDefault && $iso !== $isoDefault) {
                $isoArray[] = $isoDefault;
            }

            if (!in_array('en', $isoArray)) {
                $isoArray[] = 'en';
            }

            $moduleName = false;

            // get templatePath
            if (preg_match('#' . $shop->physical_uri . 'modules/#', str_replace(DIRECTORY_SEPARATOR, '/', $templatePath)) &&
                preg_match('#modules/([a-z0-9_-]+)/#ui', str_replace(DIRECTORY_SEPARATOR, '/', $templatePath), $res)
            ) {
                $moduleName = $res[1];
            }

            foreach ($isoArray as $isoCode) {
                $isoTemplate = $isoCode . '/' . $template;
                $templatePath = self::getTemplateBasePath($isoTemplate, $moduleName, $shop->theme);

                if (!file_exists($templatePath . $isoTemplate . '.txt') &&
                    (
                        $configuration['PS_MAIL_TYPE'] == Mail::TYPE_BOTH ||
                        $configuration['PS_MAIL_TYPE'] == Mail::TYPE_TEXT
                    )
                ) {
                    PrestaShopLogger::addLog(
                        Context::getContext()->getTranslator()->trans(
                            'Error - The following e-mail template is missing: %s',
                            [$templatePath . $isoTemplate . '.txt'],
                            'Admin.Advparameters.Notification'
                        )
                    );
                } elseif (!file_exists($templatePath . $isoTemplate . '.html') &&
                          (
                              $configuration['PS_MAIL_TYPE'] == Mail::TYPE_BOTH ||
                              $configuration['PS_MAIL_TYPE'] == Mail::TYPE_HTML
                          )
                ) {
                    PrestaShopLogger::addLog(
                        Context::getContext()->getTranslator()->trans(
                            'Error - The following e-mail template is missing: %s',
                            [$templatePath . $isoTemplate . '.html'],
                            'Admin.Advparameters.Notification'
                        )
                    );
                } else {
                    $templatePathExists = true;

                    break;
                }
            }

            if (empty($templatePathExists)) {
                self::dieOrLog($die, 'Error - The following e-mail template is missing: %s', [$template]);

                return false;
            }

            $templateHtml = '';
            $templateTxt = '';
            Hook::exec(
                'actionEmailAddBeforeContent',
                [
                    'template' => $template,
                    'template_html' => &$templateHtml,
                    'template_txt' => &$templateTxt,
                    'id_lang' => (int) $idLang,
                ],
                null,
                true
            );
            $templateHtml .= Tools::file_get_contents($templatePath . $isoTemplate . '.html');
            $templateTxt .= strip_tags(
                html_entity_decode(
                    Tools::file_get_contents($templatePath . $isoTemplate . '.txt'),
                    null,
                    'utf-8'
                )
            );
            Hook::exec(
                'actionEmailAddAfterContent',
                [
                    'template' => $template,
                    'template_html' => &$templateHtml,
                    'template_txt' => &$templateTxt,
                    'id_lang' => (int) $idLang,
                ],
                null,
                true
            );

            /* Create mail and attach differents parts */
            $subject = '[' . $shop->name . '] ' . $subject;
            $message->setSubject($subject);

            $message->setCharset('utf-8');

            /* Set Message-ID - getmypid() is blocked on some hosting */
            $message->setId(Mail::generateId());

            if (!($replyTo && Validate::isEmail($replyTo))) {
                $replyTo = $from;
            }

            if (isset($replyTo) && $replyTo) {
                $message->setReplyTo($replyTo, ($replyToName !== '' ? $replyToName : null));
            }

            $templateVars = array_map(['Tools', 'htmlentitiesDecodeUTF8'], $templateVars);
            $templateVars = array_map(['Tools', 'stripslashes'], $templateVars);

            if (false !== Configuration::get('PS_LOGO_MAIL') &&
                file_exists(_PS_IMG_DIR_ . Configuration::get('PS_LOGO_MAIL', null, null, $idShop))
            ) {
                $logo = _PS_IMG_DIR_ . Configuration::get('PS_LOGO_MAIL', null, null, $idShop);
            } else {
                if (file_exists(_PS_IMG_DIR_ . Configuration::get('PS_LOGO', null, null, $idShop))) {
                    $logo = _PS_IMG_DIR_ . Configuration::get('PS_LOGO', null, null, $idShop);
                } else {
                    $templateVars['{shop_logo}'] = '';
                }
            }
            ShopUrl::cacheMainDomainForShop((int) $idShop);
            /* don't attach the logo as */
            if (isset($logo)) {
                $templateVars['{shop_logo}'] = $message->embed(\Swift_Image::fromPath($logo));
            }

            if ((Context::getContext()->link instanceof Link) === false) {
                Context::getContext()->link = new Link();
            }

            $templateVars['{shop_name}'] = Tools::safeOutput($shop->name);
            $templateVars['{shop_url}'] = Context::getContext()->link->getPageLink(
                'index',
                true,
                $idLang,
                null,
                false,
                $idShop
            );
            $templateVars['{my_account_url}'] = Context::getContext()->link->getPageLink(
                'my-account',
                true,
                $idLang,
                null,
                false,
                $idShop
            );
            $templateVars['{guest_tracking_url}'] = Context::getContext()->link->getPageLink(
                'guest-tracking',
                true,
                $idLang,
                null,
                false,
                $idShop
            );
            $templateVars['{history_url}'] = Context::getContext()->link->getPageLink(
                'history',
                true,
                $idLang,
                null,
                false,
                $idShop
            );
            $templateVars['{color}'] = Tools::safeOutput(Configuration::get('PS_MAIL_COLOR', null, null, $idShop));
            // Get extra template_vars
            $extraTemplateVars = [];
            Hook::exec(
                'actionGetExtraMailTemplateVars',
                [
                    'template' => $template,
                    'template_vars' => $templateVars,
                    'extra_template_vars' => &$extraTemplateVars,
                    'id_lang' => (int) $idLang,
                ],
                null,
                true
            );
            $templateVars = array_merge($templateVars, $extraTemplateVars);
            $swift->registerPlugin(new \Swift_Plugins_DecoratorPlugin(array($toPlugin => $templateVars)));
            if ($configuration['PS_MAIL_TYPE'] == Mail::TYPE_BOTH ||
                $configuration['PS_MAIL_TYPE'] == Mail::TYPE_TEXT
            ) {
                $message->addPart($templateTxt, 'text/plain', 'utf-8');
            }
            if ($configuration['PS_MAIL_TYPE'] == Mail::TYPE_BOTH ||
                $configuration['PS_MAIL_TYPE'] == Mail::TYPE_HTML
            ) {
                $message->addPart($templateHtml, 'text/html', 'utf-8');
            }

            if ($fileAttachment && !empty($fileAttachment)) {
                // Multiple attachments?
                if (!is_array(current($fileAttachment))) {
                    $fileAttachment = array($fileAttachment);
                }

                foreach ($fileAttachment as $attachment) {
                    if (isset($attachment['content'], $attachment['name'], $attachment['mime'])) {
                        $message->attach(
                            \Swift_Attachment::newInstance()->setFilename(
                                $attachment['name']
                            )->setContentType($attachment['mime'])
                            ->setBody($attachment['content'])
                        );
                    }
                }
            }
            /* Send mail */
            $message->setFrom(array($from => $fromName));

            // Hook to alter Swift Message before sending mail
            Hook::exec('actionMailAlterMessageBeforeSend', [
                'message' => &$message,
            ]);

            $send = $swift->send($message);

            ShopUrl::resetMainDomainCache();

            if ($send && Configuration::get('PS_LOG_EMAILS')) {
                $mail = new Mail();
                $mail->template = Tools::substr($template, 0, 62);
                $mail->subject = Tools::substr($subject, 0, 255);
                $mail->id_lang = (int) $idLang;
                $recipientsTo = $message->getTo();
                $recipientsCc = $message->getCc();
                $recipientsBcc = $message->getBcc();
                if (!is_array($recipientsTo)) {
                    $recipientsTo = [];
                }
                if (!is_array($recipientsCc)) {
                    $recipientsCc = [];
                }
                if (!is_array($recipientsBcc)) {
                    $recipientsBcc = [];
                }
                foreach (array_merge($recipientsTo, $recipientsCc, $recipientsBcc) as $email => $recipient_name) {
                    /* @var Swift_Address $recipient */
                    $mail->id = null;
                    $mail->recipient = Tools::substr($email, 0, 255);
                    $mail->add();
                }
            }

            return $send;
        } catch (\Swift_SwiftException $e) {
            PrestaShopLogger::addLog(
                'Swift Error: ' . $e->getMessage(),
                3,
                null,
                'Swift_Message'
            );

            return false;
        }
    }

    protected static function getTemplateBasePath($isoTemplate, $moduleName, $theme)
    {
        $basePathList = [
            _PS_ROOT_DIR_ . '/themes/' . $theme->getName() . '/',
            _PS_ROOT_DIR_ . '/themes/' . $theme->get('parent') . '/',
            _PS_ROOT_DIR_,
        ];

        if ($moduleName !== false) {
            $templateRelativePath = '/modules/' . $moduleName . '/mails/';
        } else {
            $templateRelativePath = '/mails/';
        }

        foreach ($basePathList as $base) {
            $templatePath = $base . $templateRelativePath;
            if (file_exists($templatePath . $isoTemplate . '.txt') || file_exists($templatePath . $isoTemplate . '.html')) {
                return $templatePath;
            }
        }

        return '';
    }

    /**
     * @param $idMail Mail ID
     *
     * @return bool Whether removal succeeded
     */
    public static function eraseLog($idMail)
    {
        return Db::getInstance()->delete('mail', 'id_mail = ' . (int) $idMail);
    }

    /**
     * @return bool
     */
    public static function eraseAllLogs()
    {
        return Db::getInstance()->execute('TRUNCATE TABLE ' . _DB_PREFIX_ . 'mail');
    }

    /**
     * Send a test email.
     *
     * @param bool $smtpChecked Is SMTP checked?
     * @param string $smtp_server SMTP Server hostname
     * @param string $content Content of the email
     * @param string $subject Subject of the email
     * @param bool $type Deprecated
     * @param string $to To email address
     * @param string $from From email address
     * @param string $smtpLogin SMTP login name
     * @param string $smtpPassword SMTP password
     * @param int $smtpPort SMTP Port
     * @param bool|string $smtpEncryption Encryption type. "off" or false disable encryption.
     *
     * @return bool|string True if succeeded, otherwise the error message
     */
    public static function sendMailTest(
        $smtpChecked,
        $smtp_server,
        $content,
        $subject,
        $type,
        $to,
        $from,
        $smtpLogin,
        $smtpPassword,
        $smtpPort,
        $smtpEncryption
    ) {
        $result = false;

        try {
            if ($smtpChecked) {
                if (Tools::strtolower($smtpEncryption) === 'off') {
                    $smtpEncryption = false;
                }
                $smtp = \Swift_SmtpTransport::newInstance($smtp_server, $smtpPort, $smtpEncryption)
                    ->setUsername($smtpLogin)
                    ->setPassword($smtpPassword);
                $swift = \Swift_Mailer::newInstance($smtp);
            } else {
                $swift = \Swift_Mailer::newInstance(\Swift_MailTransport::newInstance());
            }

            $message = \Swift_Message::newInstance();

            $message
                ->setFrom($from)
                ->setTo($to)
                ->setSubject($subject)
                ->setBody($content);

            if ($swift->send($message)) {
                $result = true;
            }
        } catch (\Swift_SwiftException $e) {
            $result = $e->getMessage();
        }

        return $result;
    }

    /**
     * This method is used to get the translation for email Object.
     * For an object is forbidden to use htmlentities,
     * we have to return a sentence with accents.
     *
     * @param string $string raw sentence (write directly in file)
     *
     * @return mixed
     */
    public static function l($string, $idLang = null, Context $context = null)
    {
        global $_LANGMAIL;

        if (!$context) {
            $context = Context::getContext();
        }

        if ($idLang === null) {
            $idLang = (!isset($context->language) || !is_object($context->language)) ?
                    (int) Configuration::get('PS_LANG_DEFAULT') :
                    (int) $context->language->id;
        }

        $isoCode = Language::getIsoById((int) $idLang);

        $file_core = _PS_ROOT_DIR_ . '/mails/' . $isoCode . '/lang.php';
        if (Tools::file_exists_cache($file_core) && empty($_LANGMAIL)) {
            include $file_core;
        }

        $fileTheme = _PS_THEME_DIR_ . 'mails/' . $isoCode . '/lang.php';
        if (Tools::file_exists_cache($fileTheme)) {
            include $fileTheme;
        }

        if (!is_array($_LANGMAIL)) {
            return str_replace('"', '&quot;', $string);
        }

        $key = str_replace('\'', '\\\'', $string);

        return str_replace(
            '"',
            '&quot;',
            Tools::stripslashes(
                (array_key_exists($key, $_LANGMAIL) && !empty($_LANGMAIL[$key])) ? $_LANGMAIL[$key] : $string
            )
        );
    }

    /* Rewrite of Swift_Message::generateId() without getmypid() */
    protected static function generateId($idstring = null)
    {
        $midparams = [
            'utctime' => gmstrftime('%Y%m%d%H%M%S'),
            'randint' => mt_rand(),
            'customstr' => (preg_match('/^(?<!\\.)[a-z0-9\\.]+(?!\\.)$/iD', $idstring) ? $idstring : 'swift'),
            'hostname' => !empty($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : php_uname('n'),
        ];

        return vsprintf('%s.%d.%s@%s', $midparams);
    }

    /**
     * Check if a multibyte character set is used for the data.
     *
     * @param string $data Data
     *
     * @return bool Whether the string uses a multibyte character set
     */
    public static function isMultibyte($data)
    {
        $length = Tools::strlen($data);
        for ($i = 0; $i < $length; ++$i) {
            if (ord(($data[$i])) > 128) {
                return true;
            }
        }

        return false;
    }

    /**
     * MIME encode the string.
     *
     * @param string $string The string to encode
     * @param string $charset The character set to use
     * @param string $newline The newline character(s)
     *
     * @return mixed|string MIME encoded string
     */
    public static function mimeEncode($string, $charset = 'UTF-8', $newline = "\r\n")
    {
        if (!self::isMultibyte($string) && Tools::strlen($string) < 75) {
            return $string;
        }

        $charset = Tools::strtoupper($charset);
        $start = '=?' . $charset . '?B?';
        $end = '?=';
        $sep = $end . $newline . ' ' . $start;
        $length = 75 - Tools::strlen($start) - Tools::strlen($end);
        $length = $length - ($length % 4);

        if ($charset === 'UTF-8') {
            $parts = [];
            $maxchars = floor(($length * 3) / 4);
            $stringLength = Tools::strlen($string);

            while ($stringLength > $maxchars) {
                $i = (int) $maxchars;
                $result = ord($string[$i]);

                while ($result >= 128 && $result <= 191) {
                    $result = ord($string[--$i]);
                }

                $parts[] = base64_encode(Tools::substr($string, 0, $i));
                $string = Tools::substr($string, $i);
                $stringLength = Tools::strlen($string);
            }

            $parts[] = base64_encode($string);
            $string = implode($sep, $parts);
        } else {
            $string = chunk_split(base64_encode($string), $length, $sep);
            $string = preg_replace('/' . preg_quote($sep) . '$/', '', $string);
        }

        return $start . $string . $end;
    }

    /**
     * Automatically convert email to Punycode.
     *
     * Try to use INTL_IDNA_VARIANT_UTS46 only if defined, else use INTL_IDNA_VARIANT_2003
     * See https://wiki.php.net/rfc/deprecate-and-remove-intl_idna_variant_2003
     *
     * @param string $to Email address
     *
     * @return string
     */
    public static function toPunycode($to)
    {
        $address = explode('@', $to);
        if (empty($address[0]) || empty($address[1])) {
            return $to;
        }

        if (defined('INTL_IDNA_VARIANT_UTS46')) {
            return $address[0] . '@' . idn_to_ascii($address[1], 0, INTL_IDNA_VARIANT_UTS46);
        }

        /*
         * INTL_IDNA_VARIANT_2003 const will be removed in PHP 8.
         * See https://wiki.php.net/rfc/deprecate-and-remove-intl_idna_variant_2003
         */
        if (defined('INTL_IDNA_VARIANT_2003')) {
            return $address[0] . '@' . idn_to_ascii($address[1], 0, INTL_IDNA_VARIANT_2003);
        }

        return $address[0] . '@' . idn_to_ascii($address[1]);
    }

    /**
     * Generic function to dieOrLog with translations.
     *
     * @param bool $die Should die
     * @param string $message Message
     * @param array $templates Templates list
     * @param string $domain Translation domain
     */
    protected static function dieOrLog(
        $die,
        $message,
        $templates = [],
        $domain = 'Admin.Advparameters.Notification'
    ) {
        Tools::dieOrLog(
            Context::getContext()->getTranslator()->trans(
                $message,
                $templates,
                $domain
            ),
            $die
        );
    }
}

 

Link to comment
Share on other sites

  • 10 months later...

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...