Prestashop 1.7 , sending email in proaccount module - prestashop

We are using proaccount , this module allow users to register as professionnal. This module send and email to staff when an you customer is register. I tried to edit the code but nothing happen , send mail method is not the same in prestashop doc
{
$context = Context::getContext();
$id_lang = (int)$context->language->id;
$iso = Language::getIsoById($id_lang);
$id_shop = (int)$context->shop->id;
$address_text = '';
if ((int)Configuration::get('PROACCOUNT_REGISTER_WITH_ADDRESS')
&& (int)Configuration::get('PROACCOUNT_REGISTER_ADDRESS_PRO')) {
$addresses = $customer->getAddresses($id_lang);
$address = new Address($addresses[0]['id_address']);
$address_text = AddressFormat::generateAddress($address);
}
if (file_exists(dirname(__FILE__).'/mails/'.$iso.'/pro_account.txt')
&& file_exists(dirname(__FILE__).'/mails/'.$iso.'/pro_account.html')) {
$file_attachment = !empty($this->file_attachment['name']) ?
$this->file_attachment : null;
Mail::Send(
$id_lang,
'pro_account',
$this->l('Professional account register'),
array(
'{firstname}' => $customer->firstname,
'{lastname}' => $customer->lastname,
'{email}' => $customer->email,
'{company}' => $customer->company,
'{siret}' => $customer->siret,
'{address}' => $address_text,
),
Configuration::get('PS_SHOP_EMAIL'),
null,
(string)Configuration::get('PS_SHOP_EMAIL'),
(string)Configuration::get('PS_SHOP_NAME'),
$file_attachment,
null,
dirname(__FILE__).'/mails/',
null,
(int)$id_shop
);
}
}```
Any help please ?

Related

Prestashop : Can't make my module work : Get order details when order status is changed to “shipped”

I am developing a module, it gets order details when order status is changed to "shipped" by admin, to post them to a third-party application with API.
I am using Prestashop V 1.7.7.0.
The hook i'm using is hookActionOrderStatusPostUpdate
The module is installed successfully in the Backoffice and there's no syntax errors, But it doesn't do anything.
Can't figure out what's wrong in my code.
Need help please. Thanks
<?php
/**
* 2007-2021 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License (AFL 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:
* http://opensource.org/licenses/afl-3.0.php
* 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 license#prestashop.com 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 http://www.prestashop.com for more information.
*
* #author PrestaShop SA <contact#prestashop.com>
* #copyright 2007-2021 PrestaShop SA
* #license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
if (!defined('_PS_VERSION_')) {
exit;
}
class Cargo extends Module
{
protected $config_form = false;
public function __construct()
{
$this->name = 'cargo';
$this->tab = 'administration';
$this->version = '1.0.0';
$this->author = 'tekwave';
$this->need_instance = 1;
/**
* Set $this->bootstrap to true if your module is compliant with bootstrap (PrestaShop 1.6)
*/
$this->bootstrap = true;
parent::__construct();
$this->displayName = $this->l('cargo');
$this->description = $this->l('Ce module permet la synchronisation entre Prestashop et Cargo');
$this->confirmUninstall = $this->l('');
$this->ps_versions_compliancy = array('min' => '1.6', 'max' => _PS_VERSION_);
}
/**
* Don't forget to create update methods if needed:
* http://doc.prestashop.com/display/PS16/Enabling+the+Auto-Update
*/
public function install()
{
Configuration::updateValue('CARGO_LIVE_MODE', false);
return parent::install() &&
$this->registerHook('header') &&
$this->registerHook('backOfficeHeader') &&
$this->registerHook('actionOrderStatusPostUpdate');
}
public function uninstall()
{
Configuration::deleteByName('CARGO_LIVE_MODE');
return parent::uninstall();
}
/**
* Load the configuration form
*/
public function getContent()
{
/**
* If values have been submitted in the form, process.
*/
if (((bool)Tools::isSubmit('submitCargoModule')) == true) {
$this->postProcess();
}
$this->context->smarty->assign('module_dir', $this->_path);
$output = $this->context->smarty->fetch($this->local_path.'views/templates/admin/configure.tpl');
return $output.$this->renderForm();
}
/**
* Create the form that will be displayed in the configuration of your module.
*/
protected function renderForm()
{
$helper = new HelperForm();
$helper->show_toolbar = false;
$helper->table = $this->table;
$helper->module = $this;
$helper->default_form_language = $this->context->language->id;
$helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG', 0);
$helper->identifier = $this->identifier;
$helper->submit_action = 'submitCargoModule';
$helper->currentIndex = $this->context->link->getAdminLink('AdminModules', false)
.'&configure='.$this->name.'&tab_module='.$this->tab.'&module_name='.$this->name;
$helper->token = Tools::getAdminTokenLite('AdminModules');
$helper->tpl_vars = array(
'fields_value' => $this->getConfigFormValues(), /* Add values for your inputs */
'languages' => $this->context->controller->getLanguages(),
'id_language' => $this->context->language->id,
);
return $helper->generateForm(array($this->getConfigForm()));
}
/**
* Create the structure of your form.
*/
protected function getConfigForm()
{
return array(
'form' => array(
'legend' => array(
'title' => $this->l('Settings'),
'icon' => 'icon-cogs',
),
'input' => array(
array(
'type' => 'switch',
'label' => $this->l('Live mode'),
'name' => 'CARGO_LIVE_MODE',
'is_bool' => true,
'desc' => $this->l('Use this module in live mode'),
'values' => array(
array(
'id' => 'active_on',
'value' => true,
'label' => $this->l('Enabled')
),
array(
'id' => 'active_off',
'value' => false,
'label' => $this->l('Disabled')
)
),
),
array(
'col' => 3,
'type' => 'text',
'prefix' => '<i class="icon icon-envelope"></i>',
'desc' => $this->l('Enter a valid email address'),
'name' => 'CARGO_ACCOUNT_EMAIL',
'label' => $this->l('Email'),
),
array(
'type' => 'password',
'name' => 'CARGO_ACCOUNT_PASSWORD',
'label' => $this->l('Password'),
),
),
'submit' => array(
'title' => $this->l('Save'),
),
),
);
}
/**
* Set values for the inputs.
*/
protected function getConfigFormValues()
{
return array(
'CARGO_LIVE_MODE' => Configuration::get('CARGO_LIVE_MODE', true),
'CARGO_ACCOUNT_EMAIL' => Configuration::get('CARGO_ACCOUNT_EMAIL', 'contact#prestashop.com'),
'CARGO_ACCOUNT_PASSWORD' => Configuration::get('CARGO_ACCOUNT_PASSWORD', null),
);
}
/**
* Save form data.
*/
protected function postProcess()
{
$form_values = $this->getConfigFormValues();
foreach (array_keys($form_values) as $key) {
Configuration::updateValue($key, Tools::getValue($key));
}
}
/**
* Add the CSS & JavaScript files you want to be loaded in the BO.
*/
public function hookBackOfficeHeader()
{
if (Tools::getValue('module_name') == $this->name) {
$this->context->controller->addJS($this->_path.'views/js/back.js');
$this->context->controller->addCSS($this->_path.'views/css/back.css');
}
}
/**
* Add the CSS & JavaScript files you want to be added on the FO.
*/
public function hookHeader()
{
$this->context->controller->addJS($this->_path.'/views/js/front.js');
$this->context->controller->addCSS($this->_path.'/views/css/front.css');
}
This is my code under hookActionOrderStatusPostUpdate function :
public function hookActionOrderStatusPostUpdate($params)
{
if ($params['newOrderStatus']->id == 6) {
$order = new Order((int)$params['id_order']);
$address = new Address((int)$order->id_address_delivery);
$country = new Country((int)($address->id_country));
$state = new State((int)($address->id_state));
$message = new Message((int)($order->id_message));
$Products = $order->getProducts();
$tel_cl = $address->phone;
$nom_prenom_cl = $address->lastname . ' ' . $address->firstname;
$ville_cl = $country->name;
$delegation_cl = $state->name;
$adresse_cl = $address->address1 . ' ' . $address->address2;
$tel_2_cl = $address->phone_mobile;
$libelle = '';
$nb_piece = 0;
foreach ($Products as $product) {
$libelle .= $product['product_name'] . '<br/>';
$nb_piece += $product['product_quantity'];
}
$cod = $order->total_paid;
$remarque = $message->message;
$Url_str = 'http://admin.cargotunisie.com/cargo_api/set_colis_cargo_get.php?id=1&tel_cl='.$tel_cl.'&nom_prenom_cl='.$nom_prenom_cl.'&ville_cl='.$ville_cl.'&delegation_cl='.$delegation_cl.'&adresse_cl='.$adresse_cl.'&tel_2_cl='.$tel_2_cl.'&libelle='.$libelle.'&cod='.$cod.'&nb_piece='.$nb_piece.'&remarque='.$remarque;
$json = Tools::file_get_contents($Url_str);
$result = json_decode($json);
}
}
}
It could be due to several things.
First: make sure the hook is hooked.
Go to Design > Positions > Then add new hook
Choose your module's name and check if you can select the hook actionOrderStatusPostUpdate. If you can, then it means it was unhooked.
This happens more than we would like, and sometimes you can get crazy until you found it
If that doesn't work you can try this (only if is not on a production site). If it is, just wrap it by using an if that checks if it's from your IP.
Add Tools::dieObject($params); at the beginning of the function.
Then change the an order and check the results. You should see a user friendly list of the values stored in $params.
Make it sure the $params['newOrderStatus'] exists and $params['newOrderStatus']->id is an object.
Also, it should be pretty obvious, but make sure the order ID which are you doing the tests is 6.
With that you should be able to have a general clue of what may be happening.

Prestashop 1.7.4.x - Missing variables values when using order_conf as new email template

I have missing variables when using a new email template.
I have not changed any core code for this email template.
Is anyone can help me on this ?
[ I'm using Prestashop 1.7.4.x ]
Finally i found one solution for this. Maybe someone will get help from my solution.
I've modified classes/order/OrderHistory.php and replace following code.
$data = array(
'{lastname}' => $result['lastname'],
'{firstname}' => $result['firstname'],
'{id_order}' => (int)$this->id_order,
'{order_name}' => $order->getUniqReference()
);
Replaced above code with following one.
/*----------------------
-START OF INSERTED CODE-
----------------------*/
/* GET THE PRODUCTS */
$order_details = $order->getProducts();
$product_var_tpl_list = array();
foreach ($order_details as $id => &$order_detail) {
$product_var_tpl = array(
'reference' => $order_detail['product_reference'],
'name' => $order_detail['product_name'].(isset($order_detail['product_attributes']) ? ' - '.$order_detail['product_attributes'] : ''),
'unit_price' => Tools::displayPrice($order_detail['unit_price_tax_incl'], $this->context->currency, false),
'price' => Tools::displayPrice($order_detail['total_price_tax_incl'], $this->context->currency, false),
'quantity' => $order_detail['product_quantity'],
'customization' => $order_detail['customizedDatas']
);
$product_var_tpl_list[] = $product_var_tpl;
} // end foreach ($order_detail)
$product_list_txt = '';
$product_list_html = '';
if (count($product_var_tpl_list) > 0) {
$product_list_txt = $this->getEmailTemplateContent('order_conf_product_list.txt', Mail::TYPE_TEXT, $product_var_tpl_list);
$product_list_html = $this->getEmailTemplateContent('order_conf_product_list.tpl', Mail::TYPE_HTML, $product_var_tpl_list);
}
/* GET THE DISCOUNTS */
$cart_rules = $order->getCartRules();
foreach ($cart_rules as $id => &$cart_rule) {
$cart_rules_list[] = array(
'voucher_name' => $cart_rule['name'],
'voucher_reduction' => ($cart_rule['value'] != 0.00 ? '-' : '').Tools::displayPrice($cart_rule['value'], $this->context->currency, false)
);
}
$cart_rules_list_txt = '';
$cart_rules_list_html = '';
if (count($cart_rules_list) > 0) {
$cart_rules_list_txt = $this->getEmailTemplateContent('order_conf_cart_rules.txt', Mail::TYPE_TEXT, $cart_rules_list);
$cart_rules_list_html = $this->getEmailTemplateContent('order_conf_cart_rules.tpl', Mail::TYPE_HTML, $cart_rules_list);
}
/* GET ORDER DETAILS, delivery, invoice, amount... etc */
$invoice_address = new Address((int)$order->id_address_invoice);
$invoiceAddressPatternRules = Tools::jsonDecode(Configuration::get('PS_INVCE_INVOICE_ADDR_RULES'), true);
$deliveryAddressPatternRules = Tools::jsonDecode(Configuration::get('PS_INVCE_DELIVERY_ADDR_RULES'), true);
$country = new Country((int)$invoice_address->id_country);
$delivery_address = null;
$formatted_delivery_address = '';
if (isset($order->id_address_delivery) && $order->id_address_delivery) {
$delivery_address = new Address((int)$order->id_address_delivery);
}
$carrier = new Carrier((int)($order->id_carrier), $order->id_lang);
/* ATTACH INFORMATION TO SMARTY VARIABLE*/
$data = array(
'{lastname}' => $result['lastname'],
'{firstname}' => $result['firstname'],
'{id_order}' => (int)$this->id_order,
'{delivery_block_txt}' => AddressFormat::generateAddress($delivery_address, $deliveryAddressPatternRules, ', ', ' '),
'{invoice_block_txt}' => AddressFormat::generateAddress($invoice_address, $invoiceAddressPatternRules, ', ', ' '),
'{delivery_block_html}' => AddressFormat::generateAddress($delivery_address, $deliveryAddressPatternRules, '<br />',' ', array(
'firstname' => '<span style="font-weight:bold;">%s</span>',
'lastname' => '<span style="font-weight:bold;">%s</span>'
)),
'{invoice_block_html}' => AddressFormat::generateAddress($invoice_address, $invoiceAddressPatternRules, '<br />',' ', array(
'firstname' => '<span style="font-weight:bold;">%s</span>',
'lastname' => '<span style="font-weight:bold;">%s</span>'
)),
'{delivery_company}' => $delivery_address->company,
'{delivery_firstname}' => $delivery_address->firstname,
'{delivery_lastname}' => $delivery_address->lastname,
'{delivery_address1}' => $delivery_address->address1,
'{delivery_address2}' => $delivery_address->address2,
'{delivery_city}' => $delivery_address->city,
'{delivery_postal_code}' => $delivery_address->postcode,
'{delivery_country}' => $delivery_address->country,
'{delivery_state}' => $delivery_address->id_state ? $delivery_state->name : '',
'{delivery_phone}' => ($delivery_address->phone) ? $delivery_address->phone : $delivery_address->phone_mobile,
'{delivery_other}' => $delivery_address->other,
'{invoice_company}' => $invoice_address->company,
'{invoice_vat_number}' => $invoice_address->vat_number,
'{invoice_firstname}' => $invoice_address->firstname,
'{invoice_lastname}' => $invoice_address->lastname,
'{invoice_address2}' => $invoice_address->address2,
'{invoice_address1}' => $invoice_address->address1,
'{invoice_city}' => $invoice_address->city,
'{invoice_postal_code}' => $invoice_address->postcode,
'{invoice_country}' => $invoice_address->country,
'{invoice_state}' => $invoice_address->id_state ? $invoice_state->name : '',
'{invoice_phone}' => ($invoice_address->phone) ? $invoice_address->phone : $invoice_address->phone_mobile,
'{invoice_other}' => $invoice_address->other,
'{order_name}' => $order->getUniqReference(),
'{date}' => Tools::displayDate(date('Y-m-d H:i:s'), null, 1),
'{carrier}' => (!isset($carrier->name)) ? Tools::displayError('No carrier') : $carrier->name,
'{payment}' => Tools::substr($order->payment, 0, 32),
'{products}' => $product_list_html,
'{products_txt}' => $product_list_txt,
'{discounts}' => $cart_rules_list_html,
'{discounts_txt}' => $cart_rules_list_txt,
'{total_paid}' => Tools::displayPrice($order->total_paid, $this->context->currency, false),
'{total_products}' => Tools::displayPrice(Product::getTaxCalculationMethod() == PS_TAX_EXC ? $order->total_products : $order->total_products_wt, $this->context->currency, false),
'{total_discounts}' => Tools::displayPrice($order->total_discounts, $this->context->currency, false),
'{total_shipping}' => Tools::displayPrice($order->total_shipping, $this->context->currency, false),
'{total_wrapping}' => Tools::displayPrice($order->total_wrapping, $this->context->currency, false),
'{total_tax_paid}' => Tools::displayPrice(($order->total_products_wt - $order->total_products) + ($order->total_shipping_tax_incl - $order->total_shipping_tax_excl), $this->context->currency, false)
);
/*---------------------
!-END OF INSERTED CODE-
---------------------*/
I have also added following function to current class file.
protected function getEmailTemplateContent($template_name, $mail_type, $var)
{
$email_configuration = Configuration::get('PS_MAIL_TYPE');
if ($email_configuration != $mail_type && $email_configuration != Mail::TYPE_BOTH) {
}
$theme_template_path = _PS_THEME_DIR_.'mails'.DIRECTORY_SEPARATOR.Context::getContext()->language->iso_code.DIRECTORY_SEPARATOR.$template_name;
$default_mail_template_path = _PS_MAIL_DIR_.Context::getContext()->language->iso_code.DIRECTORY_SEPARATOR.$template_name;
if (Tools::file_exists_cache($theme_template_path)) {
$default_mail_template_path = $theme_template_path;
}
if (Tools::file_exists_cache($default_mail_template_path)) {
Context::getContext()->smarty->assign('list', $var);
return Context::getContext()->smarty->fetch($default_mail_template_path);
}
return ' ';
}
Bit late in the game, but I found this thread trying to do the same thing: use the "order_conf" template in a state where order details are not available.
Based on #viral answer to his own question, I had a few problems, so here is what I did to get things working in Presta Shop V1.7.3.2
Create file [WEBROOT]/override/classes/order/OrderHistory.php
Doing this, rather than changing core code will allow you to update Presta Shop without loosing your changes.
In that file I added the following content:
<?php
/**
* Make complete Order details available to email templates
*/
use PrestaShop\PrestaShop\Core\Stock\StockManager;
use PrestaShop\PrestaShop\Adapter\StockManager as StockManagerAdapter;
class OrderHistory extends OrderHistoryCore {
public function sendEmail($order, $template_vars = false)
{
$result = Db::getInstance()->getRow('
SELECT osl.`template`, c.`lastname`, c.`firstname`, osl.`name` AS osname, c.`email`, os.`module_name`, os.`id_order_state`, os.`pdf_invoice`, os.`pdf_delivery`
FROM `'._DB_PREFIX_.'order_history` oh
LEFT JOIN `'._DB_PREFIX_.'orders` o ON oh.`id_order` = o.`id_order`
LEFT JOIN `'._DB_PREFIX_.'customer` c ON o.`id_customer` = c.`id_customer`
LEFT JOIN `'._DB_PREFIX_.'order_state` os ON oh.`id_order_state` = os.`id_order_state`
LEFT JOIN `'._DB_PREFIX_.'order_state_lang` osl ON (os.`id_order_state` = osl.`id_order_state` AND osl.`id_lang` = o.`id_lang`)
WHERE oh.`id_order_history` = '.(int)$this->id.' AND os.`send_email` = 1');
if (isset($result['template']) && Validate::isEmail($result['email'])) {
ShopUrl::cacheMainDomainForShop($order->id_shop);
$topic = $result['osname'];
// JOHN
$this->context = Context::getContext();
/* GET THE PRODUCTS */
$order_details = $order->getProducts();
$product_var_tpl_list = array();
foreach ($order_details as $id => &$order_detail) {
$product_var_tpl = array(
'reference' => $order_detail['product_reference'],
'name' => $order_detail['product_name'].(isset($order_detail['product_attributes']) ? ' - '.$order_detail['product_attributes'] : ''),
'unit_price' => Tools::displayPrice($order_detail['unit_price_tax_incl'], $this->context->currency, false),
'price' => Tools::displayPrice($order_detail['total_price_tax_incl'], $this->context->currency, false),
'quantity' => $order_detail['product_quantity'],
'customization' => $order_detail['customizedDatas']
);
$product_var_tpl_list[] = $product_var_tpl;
} // end foreach ($order_detail)
$product_list_txt = '';
$product_list_html = '';
if (count($product_var_tpl_list) > 0) {
$product_list_txt = $this->getEmailTemplateContent('order_conf_product_list.txt', Mail::TYPE_TEXT, $product_var_tpl_list);
$product_list_html = $this->getEmailTemplateContent('order_conf_product_list.tpl', Mail::TYPE_HTML, $product_var_tpl_list);
}
/* GET THE DISCOUNTS */
$cart_rules_list = array();
$cart_rules = $order->getCartRules();
foreach ($cart_rules as $id => &$cart_rule) {
$cart_rules_list[] = array(
'voucher_name' => $cart_rule['name'],
'voucher_reduction' => ($cart_rule['value'] != 0.00 ? '-' : '').Tools::displayPrice($cart_rule['value'], $this->context->currency, false)
);
}
$cart_rules_list_txt = '';
$cart_rules_list_html = '';
if (count($cart_rules_list) > 0) {
$cart_rules_list_txt = $this->getEmailTemplateContent('order_conf_cart_rules.txt', Mail::TYPE_TEXT, $cart_rules_list);
$cart_rules_list_html = $this->getEmailTemplateContent('order_conf_cart_rules.tpl', Mail::TYPE_HTML, $cart_rules_list);
}
/* GET ORDER DETAILS, delivery, invoice, amount... etc */
$invoice_address = new Address((int)$order->id_address_invoice);
$invoiceAddressPatternRules = Tools::jsonDecode(Configuration::get('PS_INVCE_INVOICE_ADDR_RULES'), true);
$deliveryAddressPatternRules = Tools::jsonDecode(Configuration::get('PS_INVCE_DELIVERY_ADDR_RULES'), true);
$country = new Country((int)$invoice_address->id_country);
$delivery_address = null;
$formatted_delivery_address = '';
if (isset($order->id_address_delivery) && $order->id_address_delivery) {
$delivery_address = new Address((int)$order->id_address_delivery);
}
$carrier = new Carrier((int)($order->id_carrier), $order->id_lang);
$invoice = new Address((int)$order->id_address_invoice);
$delivery = new Address((int)$order->id_address_delivery);
$delivery_state = $delivery->id_state ? new State((int)$delivery->id_state) : false;
$invoice_state = $invoice->id_state ? new State((int)$invoice->id_state) : false;
/* ATTACH INFORMATION TO SMARTY VARIABLE*/
$data = array(
'{lastname}' => $result['lastname'],
'{firstname}' => $result['firstname'],
'{id_order}' => (int)$this->id_order,
'{delivery_block_txt}' => AddressFormat::generateAddress($delivery_address, $deliveryAddressPatternRules, ', ', ' '),
'{invoice_block_txt}' => AddressFormat::generateAddress($invoice_address, $invoiceAddressPatternRules, ', ', ' '),
'{delivery_block_html}' => AddressFormat::generateAddress($delivery_address, $deliveryAddressPatternRules, '<br />',' ', array(
'firstname' => '<span style="font-weight:bold;">%s</span>',
'lastname' => '<span style="font-weight:bold;">%s</span>'
)),
'{invoice_block_html}' => AddressFormat::generateAddress($invoice_address, $invoiceAddressPatternRules, '<br />',' ', array(
'firstname' => '<span style="font-weight:bold;">%s</span>',
'lastname' => '<span style="font-weight:bold;">%s</span>'
)),
'{delivery_company}' => $delivery_address->company,
'{delivery_firstname}' => $delivery_address->firstname,
'{delivery_lastname}' => $delivery_address->lastname,
'{delivery_address1}' => $delivery_address->address1,
'{delivery_address2}' => $delivery_address->address2,
'{delivery_city}' => $delivery_address->city,
'{delivery_postal_code}' => $delivery_address->postcode,
'{delivery_country}' => $delivery_address->country,
'{delivery_state}' => $delivery_address->id_state ? $delivery_state->name : '',
'{delivery_phone}' => ($delivery_address->phone) ? $delivery_address->phone : $delivery_address->phone_mobile,
'{delivery_other}' => $delivery_address->other,
'{invoice_company}' => $invoice_address->company,
'{invoice_vat_number}' => $invoice_address->vat_number,
'{invoice_firstname}' => $invoice_address->firstname,
'{invoice_lastname}' => $invoice_address->lastname,
'{invoice_address2}' => $invoice_address->address2,
'{invoice_address1}' => $invoice_address->address1,
'{invoice_city}' => $invoice_address->city,
'{invoice_postal_code}' => $invoice_address->postcode,
'{invoice_country}' => $invoice_address->country,
'{invoice_state}' => $invoice_address->id_state ? $invoice_state->name : '',
'{invoice_phone}' => ($invoice_address->phone) ? $invoice_address->phone : $invoice_address->phone_mobile,
'{invoice_other}' => $invoice_address->other,
'{order_name}' => $order->getUniqReference(),
'{date}' => Tools::displayDate(date('Y-m-d H:i:s'), null, 1),
'{carrier}' => (!isset($carrier->name)) ? Tools::displayError('No carrier') : $carrier->name,
'{payment}' => Tools::substr($order->payment, 0, 32),
'{products}' => $product_list_html,
'{products_txt}' => $product_list_txt,
'{discounts}' => $cart_rules_list_html,
'{discounts_txt}' => $cart_rules_list_txt,
'{total_paid}' => Tools::displayPrice($order->total_paid, $this->context->currency, false),
'{total_products}' => Tools::displayPrice(Product::getTaxCalculationMethod() == PS_TAX_EXC ? $order->total_products : $order->total_products_wt, $this->context->currency, false),
'{total_discounts}' => Tools::displayPrice($order->total_discounts, $this->context->currency, false),
'{total_shipping}' => Tools::displayPrice($order->total_shipping, $this->context->currency, false),
'{total_wrapping}' => Tools::displayPrice($order->total_wrapping, $this->context->currency, false),
'{total_tax_paid}' => Tools::displayPrice(($order->total_products_wt - $order->total_products) + ($order->total_shipping_tax_incl - $order->total_shipping_tax_excl), $this->context->currency, false)
);
// END JOHN
if ($result['module_name']) {
$module = Module::getInstanceByName($result['module_name']);
if (Validate::isLoadedObject($module) && isset($module->extra_mail_vars) && is_array($module->extra_mail_vars)) {
$data = array_merge($data, $module->extra_mail_vars);
}
}
if ($template_vars) {
$data = array_merge($data, $template_vars);
}
$data['{total_paid}'] = Tools::displayPrice((float)$order->total_paid, new Currency((int)$order->id_currency), false);
if (Validate::isLoadedObject($order)) {
// Attach invoice and / or delivery-slip if they exists and status is set to attach them
if (($result['pdf_invoice'] || $result['pdf_delivery'])) {
$context = Context::getContext();
$invoice = $order->getInvoicesCollection();
$file_attachement = array();
if ($result['pdf_invoice'] && (int)Configuration::get('PS_INVOICE') && $order->invoice_number) {
Hook::exec('actionPDFInvoiceRender', array('order_invoice_list' => $invoice));
$pdf = new PDF($invoice, PDF::TEMPLATE_INVOICE, $context->smarty);
$file_attachement['invoice']['content'] = $pdf->render(false);
$file_attachement['invoice']['name'] = Configuration::get('PS_INVOICE_PREFIX', (int)$order->id_lang, null, $order->id_shop).sprintf('%06d', $order->invoice_number).'.pdf';
$file_attachement['invoice']['mime'] = 'application/pdf';
}
if ($result['pdf_delivery'] && $order->delivery_number) {
$pdf = new PDF($invoice, PDF::TEMPLATE_DELIVERY_SLIP, $context->smarty);
$file_attachement['delivery']['content'] = $pdf->render(false);
$file_attachement['delivery']['name'] = Configuration::get('PS_DELIVERY_PREFIX', Context::getContext()->language->id, null, $order->id_shop).sprintf('%06d', $order->delivery_number).'.pdf';
$file_attachement['delivery']['mime'] = 'application/pdf';
}
} else {
$file_attachement = null;
}
if (!Mail::Send(
(int)$order->id_lang,
$result['template'],
$topic,
$data,
$result['email'],
$result['firstname'].' '.$result['lastname'],
null,
null,
$file_attachement,
null,
_PS_MAIL_DIR_,
false,
(int)$order->id_shop
)) {
return false;
}
}
ShopUrl::resetMainDomainCache();
}
return true;
}
/**
* Added by John
*/
protected function getEmailTemplateContent($template_name, $mail_type, $var) {
$email_configuration = Configuration::get('PS_MAIL_TYPE');
if ($email_configuration != $mail_type && $email_configuration != Mail::TYPE_BOTH) {
return '';
}
$pathToFindEmail = array(
_PS_THEME_DIR_.'mails'.DIRECTORY_SEPARATOR.$this->context->language->iso_code.DIRECTORY_SEPARATOR.$template_name,
_PS_THEME_DIR_.'mails'.DIRECTORY_SEPARATOR.'en'.DIRECTORY_SEPARATOR.$template_name,
_PS_MAIL_DIR_.$this->context->language->iso_code.DIRECTORY_SEPARATOR.$template_name,
_PS_MAIL_DIR_.'en'.DIRECTORY_SEPARATOR.$template_name,
);
foreach ($pathToFindEmail as $path) {
if (Tools::file_exists_cache($path)) {
$this->context->smarty->assign('list', $var);
return $this->context->smarty->fetch($path);
}
}
return 'Template Not Found';
}
}
f you search for "John" in that code, you will find the modifications from the standard "sendEmail" function and the over-ridden version.
Hope it's of help to someone.
Can't seem to make it work in 1.7.5.2..
Placed in /override/classes/order .
Erase the cache after that, every time you made changes. In prod/class_index.php. I made it work under 1.7.3.3
I was able to bring the variables to the shipped.html email template. The only problem is that the variables: {products} and {discounts} are not being displayed. Do you guys have any suggestion?
I´m using warehouse as theme and prestashop version is 1.7.8.7
HTML Preview: https://ibb.co/X8x91K6
Email Result: https://ibb.co/xSx5Pwb
As you can see in email result the variables aren´t fullfilled.

send payments to faucetbox

I have try to do my self this code to implement the automatic send bitcoin payments to faucet box but is some errors there I need help with.
and it give me this error
The bitcoinrotator.publiadds.org.pt page is not working bitcoinrotator.publiadds.org.pt can not process this request for time. 500
<?php
//custom parameters
$api_key = "my_api_key";
$userAddy = $_SESSION['user'];
require_once("faucetbox.php");
$currency = "BTC"; # or LTC or any other supported by FaucetBOX
$faucetbox = new FaucetBOX($api_key, $currency);
$users = array(
'user_id' => clean($user_id),
'user_name' => clean($user_name),
'user_email' => clean($user_email),
'user_pass' => clean($user_pass),
'user_points' => clean($user_points),
'user_wallet' => clean($user_wallet)
);
session_start();
include_once 'dbconnect.php';
if(!isset($_SESSION['user']))
{
header("Location: index.php");
}
$selfNav = mysqli_query($conn, "SELECT user_wallet, user_points FROM users WHERE user_id=".$_SESSION['user']);
$rowNav = mysqli_num_rows($selfNav);
$rowAssoc = mysqli_fetch_assoc($selfNav);
$balance = $rowAssoc['user_points'];
$wallet = $rowAssoc['user_wallet'];
//auto cashout if bal over 0.00010000
if($balance > 0.00010000){
$amount = $rowAssoc['user_points'];
$currency = "BTC";
$faucetbox = new Faucetbox($api_key, $currency);
$result = $faucetbox->send($wallet, $amount);
if($result["success"] === true){
$_SESSION['cashout'] = $result["html"];
//reset balance to zero
mysqli_query($conn, "UPDATE `users` SET user_points = 0 WHERE user_id = " . $_SESSION['user')];
header('Location: ../home.php');
?>
well there it is its work but it stay with some bug there but now its work
the error is
Array ( [user_wallet] => 111111111111111111111111111111111111 [user_points] => 0.00000010 ) Error en balance
<?php
session_start();//Session start is ALWAYS the first thing to do.
if(!isset($_SESSION['user']))
{
header("Location: index.php"); //Sending headers its the next thing to do. Always.
}
include_once 'dbconnect.php';
//custom parameters
$api_key = "my_api_key";
$userAddy = $_SESSION['user'];
require_once("faucetbox.php");
$currency = "BTC"; # or LTC or any other supported by FaucetBOX
$faucetbox = new FaucetBOX($api_key, $currency);
//$users = array(
// 'user_id' => clean($user_id),
// 'user_name' => clean($user_name),
// 'user_email' => clean($user_email),
// 'user_pass' => clean($user_pass),
// 'user_points' => clean($user_points),
// 'user_wallet' => clean($user_wallet)
//);
//You are mixing mysql and mysqli, you need to choose one. Since you are on a shared hosting, mysqli is probably
//not installed/available, so we will keep using mysql. mysqli is safer!
$selfNav = mysql_query("SELECT user_wallet, user_points FROM users WHERE user_id=".$_SESSION['user']);
$rowNav = mysql_num_rows($selfNav);
$rowAssoc = mysql_fetch_assoc($selfNav);
print_r($rowAssoc);
$balance = $rowAssoc['user_points'];
$wallet = $rowAssoc['user_wallet'];
//auto cashout if bal over 0.00010000
if($balance > 0.00010000){
$amount = $rowAssoc['user_points'];
$currency = "BTC";
$result = $faucetbox->send($wallet,$amount); //$amount);
if($result["success"] === true){
$_SESSION['cashout'] = $result["html"];
//reset balance to zero
mysql_query("UPDATE `users` SET user_points = 0 WHERE user_id = " . $_SESSION['user']);
echo "result sucess and location go";
//header('Location: ../home.php');
}else{
echo "Error on faucet";
var_dump($result);
//What happens if there is an error?
}
}else{
echo "do not have enough credit to cash out";
//what happens if they dont have enough balance?
}
?>

how to create logged in session in yii

i tried using hybrid auth for a facebook login on my yii app, but couldn't get it to work. so decided to work on my own. i managed to get it to retrieve data and store it in my DB. but yii, still doesn't detect user as logged in. here is part of my code in my controllers/FacebookController.php
if (app()->request->isAjaxRequest) {
$user = app()->request->getParam('user');
Shared::debug($user);
// verify one last time that facebook knows this guy
if ($user['id'] === app()->facebook->getUser()) {
if (!empty($user['email']))
{
$model = User::model()->findByEmail($user['email']);
}
else if (!empty($user['username']) && empty($user['email'])) //incase we don't get an email, we use a facebook email
{
$email = $user['username'].'#facebook.com';
$model = User::model()->findByEmail($email);
}
else
{
$model = false;
}
if (!empty($model))
{
// facebook email matches one in the user database
$identity = new UserIdentity( $model->email , null );
$identity->_ssoAuth = true;
$identity->authenticate();
if ($identity->errorCode === UserIdentity::ERROR_NONE) {
print_r($identity);
app()->user->login($identity, null);
echo json_encode(array('error' => false, 'success' => url('/')));
app()->end();
}
else {
echo json_encode(array('error' => 'System Authentication Failed', 'code' => 'auth'));
app()->end();
}
}
in my code above, when i print_r($identity); the object below is echoed. and FYI, the email xxxxxx#facebook.com is stored in the DB but app()->user->isGuest() still returns true. what am i doing wrong here?
UserIdentity Object
(
[_ssoAuth] => 1
[_id:UserIdentity:private] => 19
[username] => xxxxxx#facebook.com
[password] =>
[errorCode] => 0
[errorMessage] =>
[_state:CBaseUserIdentity:private] => Array
(
)
[_e:CComponent:private] =>
[_m:CComponent:private] =>
)
http://yiiframework.com/doc/api/1.1/CWebUser#login-detail
Instead of passing a null into app()->user->login($identity, null) try passing in a duration like
$duration = 3600*24*30; //30 days
app()->user->login($identity, $duration);
I have had problems setting duration to 0. Not sure why either. But this worked for me before

How can I automatically sign in users in a phpBB3 forum based on accounts in a Rails app?

I have a mobile app that uses Rails/MySQL as a backend (just serves JSON, I know we don't need full blown Rails, but this was the simplest solution to get started). My Rails app uses devise for auth. I'd like my users to be able to also access a Phpbb3 forum without having to sign up again. What's the best way to do this? Have the Phpbb3 forum read accounts right from the same MySQL?
Use the email address as a base.
name a file inside includes/ucp called ucp_my_rails_app_connect.php
<?php
/*
* #package My Package
* #author Me
* #license http://opensource.org/licenses/gpl-license.php GNU Public License
* #link my href
* #copyright (c) my copyright
*
* #license http://opensource.org/licenses/gpl-license.php GNU Public License
*
*/
/*
* #ignore
*/
if (!defined('IN_PHPBB'))
{
exit;
}
/*
* ucp_myclass
* my rails app connect
* #package my package
*/
class ucp_my_rails_app_connect
{
var $u_action;
function main($id, $mode)
{
global $config, $db, $user, $auth, $template, $phpbb_root_path, $phpEx;
/** Do some DB code here for rails or wrap it in a private function*/
$server_url = generate_board_url();
$key_len = 54 - strlen($server_url);
$key_len = max(6, $key_len); // we want at least 6
$key_len = ($config['max_pass_chars']) ? min($key_len, $config['max_pass_chars']) : $key_len; // we want at most $config['max_pass_chars']
$user_actkey = substr(gen_rand_string(10), 0, $key_len);
$new_user_password = gen_rand_string(8);
$data = array(
'username' => utf8_normalize_nfc(/** rails DB username*/),
'steam_id' => request_var('steam_id', ''),
'new_password' => $new_user_password,
'password_confirm' => $new_user_password,
'email' => strtolower(/** rails DB email*/),
'email_confirm' => strtolower(/** rails DB email*/)
);
if($my_rails_exec_func == $some_val) /* make some code so not just anyone can submit stuff to this area*/
{
//Check and initialize some variables if needed
$error = validate_data($data, array(
'username' => array(
array('string', false, $config['min_name_chars'], $config['max_name_chars']),
array('username', '')),
'new_password' => array(
array('string', false, $config['min_pass_chars'], $config['max_pass_chars']),
array('password')),
'password_confirm' => array('string', false, $config['min_pass_chars'], $config['max_pass_chars']),
'email' => array(
array('string', false, 6, 60),
array('email')),
'email_confirm' => array('string', false, 6, 60),
'tz' => array('num', false, -14, 14),
'lang' => array('match', false, '#^[a-z_\-]{2,}$#i'),
));
$error = preg_replace('#^([A-Z_]+)$#e', "(!empty(\$user->lang['\\1'])) ? \$user->lang['\\1'] : '\\1'", $error);
if (!sizeof($error))
{
// Which group by default?
$group_name = ($coppa) ? 'REGISTERED_COPPA' : 'REGISTERED';
$sql = 'SELECT group_id
FROM ' . GROUPS_TABLE . "
WHERE group_name = '" . $db->sql_escape($group_name) . "'
AND group_type = " . GROUP_SPECIAL;
$result = $db->sql_query($sql);
$row = $db->sql_fetchrow($result);
$db->sql_freeresult($result);
$group_id = $row['group_id'];
if (($config['require_activation'] == USER_ACTIVATION_SELF ||
$config['require_activation'] == USER_ACTIVATION_ADMIN) && $config['email_enable'])
{
$user_actkey = gen_rand_string(mt_rand(6, 10));
$user_type = USER_INACTIVE;
$user_inactive_reason = INACTIVE_REGISTER;
$user_inactive_time = time();
}
else
{
$user_type = USER_NORMAL;
$user_actkey = '';
$user_inactive_reason = 0;
$user_inactive_time = 0;
}
$user_row = array(
'username' => $data['username'],
'user_password' => phpbb_hash($data['new_password']),
'user_email' => $data['email'],
'group_id' => (int) $group_id,
'user_timezone' => (float) $data['tz'],
'user_dst' => $is_dst,
'user_lang' => $data['lang'],
'user_type' => $user_type,
'user_actkey' => $user_actkey,
'user_ip' => $user->ip,
'user_regdate' => time(),
'user_inactive_reason' => $user_inactive_reason,
'user_inactive_time' => $user_inactive_time,
);
if ($config['new_member_post_limit'])
{
$user_row['user_new'] = 1;
}
// Register user...
$user_id = user_add($user_row);
// This should not happen, because the required variables are listed above...
if ($user_id === false)
{
trigger_error('NO_USER', E_USER_ERROR);
}
// DB Error
if(!$result)
{
trigger_error('Unable to connect with phpBB database.');
}
// Okay, captcha, your job is done.
if ($config['enable_confirm'] && isset($captcha))
{
$captcha->reset();
}
if ($coppa && $config['email_enable'])
{
$message = $user->lang['ACCOUNT_COPPA'];
$email_template = 'coppa_welcome_inactive_steam';
}
else if ($config['require_activation'] == USER_ACTIVATION_SELF && $config['email_enable'])
{
$message = $user->lang['ACCOUNT_INACTIVE'];
$email_template = 'user_welcome_inactive_steam';
}
else if ($config['require_activation'] == USER_ACTIVATION_ADMIN && $config['email_enable'])
{
$message = $user->lang['ACCOUNT_INACTIVE_ADMIN'];
$email_template = 'admin_welcome_inactive_steam';
}
else
{
$message = $user->lang['ACCOUNT_ADDED'];
$email_template = 'user_welcome_steam';
}
if ($config['email_enable'])
{
include_once($phpbb_root_path . 'includes/functions_messenger.' . $phpEx);
$messenger = new messenger(false);
$messenger->template($email_template, $data['lang']);
$messenger->to($data['email'], $data['username']);
$messenger->headers('X-AntiAbuse: Board servername - ' . $config['server_name']);
$messenger->headers('X-AntiAbuse: User_id - ' . $user->data['user_id']);
$messenger->headers('X-AntiAbuse: Username - ' . $user->data['username']);
$messenger->headers('X-AntiAbuse: User IP - ' . $user->ip);
$messenger->assign_vars(array(
'WELCOME_MSG' => htmlspecialchars_decode(sprintf($user->lang['WELCOME_SUBJECT'], $config['sitename'])),
'USERNAME' => htmlspecialchars_decode($data['username']),
'U_ACTIVATE' => "$server_url/ucp.$phpEx?mode=activate&u=$user_id&k=$user_actkey")
);
if ($coppa)
{
$messenger->assign_vars(array(
'FAX_INFO' => $config['coppa_fax'],
'MAIL_INFO' => $config['coppa_mail'],
'EMAIL_ADDRESS' => $data['email'])
);
}
$messenger->send(NOTIFY_EMAIL);
if ($config['require_activation'] == USER_ACTIVATION_ADMIN)
{
// Grab an array of user_id's with a_user permissions ... these users can activate a user
$admin_ary = $auth->acl_get_list(false, 'a_user', false);
$admin_ary = (!empty($admin_ary[0]['a_user'])) ? $admin_ary[0]['a_user'] : array();
// Also include founders
$where_sql = ' WHERE user_type = ' . USER_FOUNDER;
if (sizeof($admin_ary))
{
$where_sql .= ' OR ' . $db->sql_in_set('user_id', $admin_ary);
}
$sql = 'SELECT user_id, username, user_email, user_lang, user_jabber, user_notify_type
FROM ' . USERS_TABLE . ' ' .
$where_sql;
$result = $db->sql_query($sql);
while ($row = $db->sql_fetchrow($result))
{
$messenger->template('admin_activate', $row['user_lang']);
$messenger->to($row['user_email'], $row['username']);
$messenger->im($row['user_jabber'], $row['username']);
$messenger->assign_vars(array(
'USERNAME' => htmlspecialchars_decode($data['username']),
'U_USER_DETAILS' => "$server_url/memberlist.$phpEx?mode=viewprofile&u=$user_id",
'U_ACTIVATE' => "$server_url/ucp.$phpEx?mode=activate&u=$user_id&k=$user_actkey")
);
$messenger->send($row['user_notify_type']);
}
$db->sql_freeresult($result);
}
}
$message = $message . '<br /><br />' . sprintf($user->lang['RETURN_INDEX'], '', '');
trigger_error($message);
}
}
}
}
?>
now we add the class to ucp.php
case 'register':
if ($user->data['is_registered'] || isset($_REQUEST['not_agreed']))
{
redirect(append_sid("{$phpbb_root_path}index.$phpEx"));
}
$module->load('ucp', 'register');
$module->display($user->lang['REGISTER']);
break;
case 'my_rails_app_connect':
if ($user->data['is_registered'])
{
redirect(append_sid("{$phpbb_root_path}index.$phpEx"));
}
$module->load('ucp', 'my_rails_app_connect');
$module->display($user->lang['REGISTER']);
break;
Now we add a login for the rails app
create a file called railsapp.php
<?php define('IN_PHPBB', true);
$phpbb_root_path = (defined('PHPBB_ROOT_PATH')) ? PHPBB_ROOT_PATH : '../';
$phpEx = substr(strrchr(__FILE__, '.'), 1);
// Load include files.
include($phpbb_root_path . 'common.' . $phpEx);
include_once($phpbb_root_path . 'includes/functions_user.' . $phpEx);
// Set up a new user session.
$user->session_begin();
$auth->acl($user->data);
$user->setup('ucp');
$my_rails_user_email = some_code_to_get_user_email_from_rails_database; //maybe use a cookie or make the user allow the phpBB script access to the rails DB or make them login into the rails app
$mysql = 'SELECT user_id
FROM ' . USERS_TABLE
. " WHERE user_email='$my_user_rails_email'";
// Execute the query.
$result = $db->sql_query($sql);
// Retrieve the row data.
$row = $db->sql_fetchrow($result);
// Free up the result handle from the query.
$db->sql_freeresult($result);
// Check to see if we found a user_id with the associated Facebook Id.
if ($row) // User is registered already, let's log him in!
{
// Check for user ban.
if($user->check_ban($row['user_id']))
{
trigger_error($user->lang['BAN_TRIGGERED_BY_USER']);
}
// Log user in.
$result = $user->session_create($row['user_id'], 0, 0, 1);
// Alert user if we failed to log them in.
if(!$result)
{
trigger_error($user->lang['LOGIN_FAILURE']);
}
$redirect = $phpbb_root_path . 'index.' . $phpEx;
$message = ($l_success) ? $l_success : $user->lang['LOGIN_REDIRECT'];
$l_redirect = ($admin) ? $user->lang['PROCEED_TO_ACP'] : (($redirect === "{$phpbb_root_path}index.$phpEx" || $redirect === "index.$phpEx") ? $user->lang['RETURN_INDEX'] : $user->lang['RETURN_PAGE']);
// append/replace SID (may change during the session for AOL users)
$redirect = reapply_sid($redirect);
// Special case... the user is effectively banned, but we allow founders to login
if (defined('IN_CHECK_BAN') && $result['user_row']['user_type'] != USER_FOUNDER)
{
return;
}
$redirect = meta_refresh(3, $redirect);
trigger_error($message . '<br /><br />' . sprintf($l_redirect, '', ''));
}
?>
In index_body.html in styles/your_template_name/templates/ add
Connect With Rails
If you need help just drop by MY phpBB mod support forums to discuss further