Files
2019-11-17 19:14:07 +01:00

505 lines
25 KiB
PHP

<?php
/**
* 2014 - 2017 MDWeb - Terms of Sale Send
*
* @author MDWeb
* @version 1.3.0
* @copyright MDWeb 2014 - 2017
* @license Commerciale
*/
class MDToSSend extends Module
{
public function __construct()
{
$this->name = 'mdtossend';
$this->tab = 'checkout';
$this->version = '1.3.0';
$this->author = 'MDWeb';
$this->module_key = '929fa9fa0938030f19c5002cbcf3f385';
$this->need_instance = 0;
$this->config = Configuration::get('MD_PDF_CGV');
parent::__construct();
$this->displayName = $this->l('Terms of Sale Send');
$this->description = $this->l('Send your Terms of Sale to your customers when they order');
/* Backward compatibility */
if (_PS_VERSION_ < '1.5')
require(_PS_MODULE_DIR_.$this->name.'/backward_compatibility/backward.php');
if (!isset($this->config) || empty($this->config))
$this->warning = $this->l('Please configure '.$this->displayName.' to use it.');
}
public function install()
{
if (parent::install() == false || !$this->installDb())
return false;
//Procedure d'installation pour Prestashop 1.5 et plus
if (version_compare(_PS_VERSION_, 1.5, '>'))
{
if (!$this->registerHook('actionObjectCmsUpdateAfter'))
return false;
if (!$this->registerHook('actionValidateOrder'))
return false;
if (!$this->registerHook('displayPDFInvoice'))
return false;
// Copie du fichier personnalisé Mail en sauvegardant celui d'origine
if (is_file( _PS_ROOT_DIR_.'/override/classes/Mail.php'))
{
if (!copy ( _PS_ROOT_DIR_.'/override/classes/Mail.php', _PS_ROOT_DIR_.'/modules/mdtossend/install/Mail_save.php' ))
return false;
}
else
{
if (!copy ( _PS_ROOT_DIR_.'/modules/mdtossend/install/Mail.php', _PS_ROOT_DIR_.'/override/classes/Mail.php' ))
return false;
}
}
//Procedure d'installation pour Prestashop 1.4
if (version_compare(_PS_VERSION_, 1.4, '>=') && version_compare(_PS_VERSION_, 1.5, '<'))
{
if (!$this->registerHook('newOrder'))
return false;
//Create hook : actionObjectCmsUpdateAfter
$sql = 'INSERT INTO `'._DB_PREFIX_.'hook` (
`id_hook` ,
`name` ,
`title` ,
`description` ,
`position`
)
VALUES (
NULL , \'actionObjectCmsUpdateAfter\', \'actionObjectCmsUpdateAfter\', NULL , 0);';
if (!Db::getInstance()->execute($sql))
{
if (!Db::getInstance()->execute('DELETE FROM '._DB_PREFIX_.'hook WHERE name = \'actionObjectCmsUpdateAfter\''))
return false;
if (!Db::getInstance()->execute($sql))
return false;
}
if (!$this->registerHook('actionObjectCmsUpdateAfter'))
return false;
// Copie du fichier personnalisé CMS en sauvegardant celui d'origine
if (is_file( _PS_ROOT_DIR_.'/override/classes/CMS.php'))
{
if (!copy ( _PS_ROOT_DIR_.'/override/classes/CMS.php', _PS_ROOT_DIR_.'/modules/mdtossend/install/CMS_save.php' ))
return false;
}
else
{
if (!copy ( _PS_ROOT_DIR_.'/modules/mdtossend/install/CMS.php', _PS_ROOT_DIR_.'/override/classes/CMS.php' ))
return false;
}
}
return true;
}
private function installDb()
{
$sql = 'CREATE TABLE IF NOT EXISTS `'._DB_PREFIX_.'mdtossend` (
`filename` varchar(250) NOT NULL,
`id_lang` int(2) NOT NULL,
`datetime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`filename`)
) ENGINE='._MYSQL_ENGINE_.' DEFAULT CHARSET=utf8;';
Db::getInstance()->execute($sql);
// Create history for PDF Invoice if Prestashop version is up to 1.5
if (version_compare(_PS_VERSION_, 1.5, '>'))
{
$sql_history = 'CREATE TABLE IF NOT EXISTS '._DB_PREFIX_.'mdtossend_history (
`id_cms` INT NOT NULL ,
`id_lang` INT NOT NULL ,
`date_add` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ,
`meta_title` VARCHAR(255) NOT NULL ,
`content` LONGTEXT NOT NULL ,
PRIMARY KEY ( `id_cms` , `id_lang` , `date_add` )
) ENGINE = '._MYSQL_ENGINE_.' DEFAULT CHARSET=utf8 ;';
Db::getInstance()->execute($sql_history);
}
return true;
}
public function uninstall()
{
if (!parent::uninstall() || !$this->uninstallDb())
return false;
return true;
}
public function uninstallDb()
{
if (!Configuration::deleteByName('MD_PDF_CGV')
|| !Configuration::deleteByName('MD_CGV_INVOICE')
|| !Configuration::deleteByName('MD_CGV_INVOICE_WITHDRAWAL')
|| !Configuration::deleteByName('MD_CGV_WITHDRAWALFORM'))
return false;
if (!Db::getInstance()->execute('DROP TABLE IF EXISTS '._DB_PREFIX_.'mdtossend'))
return false;
if (version_compare(_PS_VERSION_, 1.5, '>'))
if (!Db::getInstance()->execute('DROP TABLE IF EXISTS '._DB_PREFIX_.'mdtossend_history'))
return false;
return true;
}
public function hookActionValidateOrder($params)
{
// if ((Configuration::get('MD_CGV_INVOICE') == 0) || (version_compare(_PS_VERSION_, 1.4, '>=') && version_compare(_PS_VERSION_, 1.5, '<')))
if (version_compare(_PS_VERSION_, 1.4, '>=') && version_compare(_PS_VERSION_, 1.5, '<'))
{
$iso = Language::getIsoById((int)$params['order']->id_lang);
$mail_iso = $iso;
$pdf = '';
if (version_compare(_PS_VERSION_, 1.5, '>'))
{
$id_shop = $this->context->shop->id;
$pdf = dirname(__FILE__).'/pdf/cgv_'.$iso.'_'.$id_shop.'.pdf';
if (!is_file($pdf))
{
$iso = Language::getIsoById((int)Configuration::get('PS_LANG_DEFAULT'));
$pdf = dirname(__FILE__).'/pdf/cgv_'.$iso.'_'.$id_shop.'.pdf';
}
}
else
{
$pdf = dirname(__FILE__).'/pdf/cgv_'.$iso.'.pdf';
if (!is_file($pdf))
{
$iso = Language::getIsoById((int)Configuration::get('PS_LANG_DEFAULT'));
$pdf = dirname(__FILE__).'/pdf/cgv_'.$iso.'.pdf';
}
}
if (!in_array($mail_iso, array('fr', 'en')))
$mail_iso = Language::getIsoById((int)Configuration::get('PS_LANG_DEFAULT'));
if (!in_array($mail_iso, array('fr', 'en')))
$mail_iso = 'en';
if (is_file($pdf) && $mail_iso)
{
$pdf = array('content' => Tools::file_get_contents($pdf),
'name' => 'cgv.pdf',
'mime' => 'application/pdf');
Mail::Send(Language::getIdByIso($mail_iso),
'conditions',
$this->l('TOS for our shop', false, (int)Language::getIdByIso($mail_iso)),
array(),
pSQL($params['customer']->email),
null,
null,
null,
$pdf,
null,
dirname(__FILE__).'/mails/');
}
if (Configuration::get('MD_CGV_INVOICE_WITHDRAWAL') == 1 && $file = Configuration::get('MD_CGV_WITHDRAWALFORM'))
{
$pdf = dirname(__FILE__).'/form/'.$file;
if (is_file($pdf) && $mail_iso)
{
$pdf = array('content' => Tools::file_get_contents($pdf),
'name' => 'withdrawal_form.pdf',
'mime' => 'application/pdf');
Mail::Send(Language::getIdByIso($mail_iso),
'formulaire',
$this->l('Withdrawal form'),
array(),
pSQL($params['customer']->email),
pSQL($params['customer']->firstname).' '.pSQL($params['customer']->lastname),
null,
null,
$pdf,
null,
dirname(__FILE__).'/mails/');
}
}
}
return true;
}
/*Hook to Add Extra Content into the PDF Invoice
Add in V1.1*/
public function hookDisplayPDFInvoice($params)
{
if ((Configuration::get('MD_CGV_INVOICE') == 1) && (version_compare(_PS_VERSION_, 1.5, '>')))
{
$order_details = Db::getInstance()->getRow('select id_lang,date_add FROM '._DB_PREFIX_.'orders WHERE id_order = '.$params['object']->id_order);
$id_lang = $order_details['id_lang'];
$date_order = $order_details['date_add'];
$cms = Db::getInstance()->getRow('SELECT content,meta_title FROM '._DB_PREFIX_.'mdtossend_history
WHERE id_cms ='.Configuration::get('MD_PDF_CGV').'
AND id_lang = '.$id_lang.' AND \''.$date_order.'\' >= date_add ORDER BY date_add DESC ');
$title_cms = $cms['meta_title'];
$content_cms = $cms['content'];
//Si title_cms ou content_cms ne renvoie rien on ne rajoute rien au PDF. Par exemple si une commande a été passée avant le premier historique.
if ($title_cms || $content_cms)
return '<tcpdf method="AddPage"/><br pagebreak="true"><div align="center"><h1>'.$title_cms.'</h1></div>'.$content_cms;
}
}
public function hookNewOrder($params)
{
return $this->hookActionValidateOrder($params);
}
public function getContent()
{
$html = $this->addCSSJS();
$html .= $this->postProcess();
$html .= '<div id="md"'.(version_compare(_PS_VERSION_, 1.5, '<') ? 'style="min-height: 250px !important;"' : ' ' ).'>
<h2 style="margin-left:30px"><img src="'.__PS_BASE_URI__.'modules/mdtossend/views/img/mdweb.gif"/>'.$this->displayName.'</h2>';
$html .= '<ul id="tabs">
<li><a href="#settings" data-toggle="tab">'.$this->l('Settings').'</a></li>
<li><a href="#history" data-toggle="tab">'.$this->l('History').'</a></li>
</ul>';
$html .= '<div id="contenus-onglets"><div id="settings">'.$this->displayForm().'</div>';
$html .= '<div id="history">'.$this->history().'</div></div>';
$html .= '<div id="md_footer"><p><a href="http://addons.prestashop.com/fr/90_mdweb" target="_blank">'.$this->l('Our Shop').'</a></p>
</div>';
$html .= '</div>';
return $html;
}
public function hookActionObjectCmsUpdateAfter($params)
{
if (Configuration::get('MD_PDF_CGV') == $params['object']->id)
$this->generatePDFDispatcher( $params['object']->id );
}
private function generatePDFDispatcher($id_cms)
{
if (version_compare(_PS_VERSION_, 1.5, '>'))
{
$this->generatePDF($id_cms);
$sql = 'SELECT meta_title,content, id_lang FROM '._DB_PREFIX_.'cms_lang WHERE id_cms ='.$id_cms;
$content_cms = Db::getInstance()->executeS($sql);
foreach ($content_cms as $cms)
{
$meta_title = addslashes($cms['meta_title']);
$content = addslashes($cms['content']);
if (version_compare(_PS_VERSION_, 1.7, '>='))
{
$sql = 'INSERT INTO '._DB_PREFIX_.'mdtossend_history (id_cms, id_lang,meta_title,content) VALUES
('.(int)$id_cms.','.(int)$cms['id_lang'].', \''.pSQL($meta_title).'\', \''.pSQL($content, true).'\');';
}
else
{
$sql = 'INSERT INTO '._DB_PREFIX_.'mdtossend_history (id_cms, id_lang,meta_title,content) VALUES
('.(int)$id_cms.','.(int)$cms['id_lang'].', \''.pSQL($meta_title).'\', \''.pSQL($content).'\');';
}
Db::getInstance()->execute($sql);
}
}
if (version_compare(_PS_VERSION_, 1.4, '>=') && version_compare(_PS_VERSION_, 1.5, '<'))
return $this->generatePDF14($id_cms);
}
private function postProcess()
{
$post = '';
//CMS ID
if (Tools::isSubmit('submitSettings') && ($gai = Tools::getValue('chooseID')))
{
Configuration::updateValue('MD_PDF_CGV', $gai);
$success = $this->generatePDFDispatcher($gai);
if ($success == 'ok' || $success == '')
{
$post .= '
<div class="conf confirm width4" style="margin-left: auto;margin-right: auto;">
'.$this->l('Settings updated').'
</div>';
}
else
{
$post .= '
<div class="error width4" style="margin-left: auto;margin-right: auto;">
'.$success.'
</div>';
}
}
//Check option for PDF Invoice
if (Tools::isSubmit('submitSettings') && (Tools::getValue('invoice')))
Configuration::updateValue('MD_CGV_INVOICE', Tools::getValue('invoice'));
elseif (Tools::isSubmit('submitSettings') && (Tools::getValue('invoice') == 0))
Configuration::updateValue('MD_CGV_INVOICE', Tools::getValue('invoice'));
//Check option for withdrawal Invoice
if (Tools::isSubmit('submitSettings') && (Tools::getValue('invoice_withdrawal')))
Configuration::updateValue('MD_CGV_INVOICE_WITHDRAWAL', Tools::getValue('invoice_withdrawal'));
elseif (Tools::isSubmit('submitSettings') && (Tools::getValue('invoice_withdrawal') == 0))
Configuration::updateValue('MD_CGV_INVOICE_WITHDRAWAL', Tools::getValue('invoice_withdrawal'));
//Withdrawal form upload
if (Tools::isSubmit('submitSettings') && $_FILES['withdrawalform']['error'] === 0)
{
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $_FILES['withdrawalform']['tmp_name']);
if ($mime == 'application/pdf')
{
$uploaddir = _PS_ROOT_DIR_.'/modules/mdtossend/form/';
$uploadfile = $uploaddir.basename($_FILES['withdrawalform']['name']);
if (move_uploaded_file($_FILES['withdrawalform']['tmp_name'], $uploadfile))
Configuration::updateValue('MD_CGV_WITHDRAWALFORM', $_FILES['withdrawalform']['name']);
else
{
$post .= '<div class="error width4" style="margin-left: auto;margin-right: auto;">
'.$this->l('Directory is not writable. Please check the folder permissions: ').$uploaddir.'</div>';
}
}
else
$post .= '<div class="error width4" style="margin-left: auto;margin-right: auto;">'.$this->l('Upload a PDF File').'</div>';
}
return $post;
}
private function generatePDF14($id_cms)
{
include_once( _PS_ROOT_DIR_.'/modules/mdtossend/tcpdf/tcpdf.php');
$directory = _PS_ROOT_DIR_.'/modules/mdtossend/pdf/';
if ($id_cms != null)
{
$sql = 'SELECT content, cms.id_lang FROM '._DB_PREFIX_.'cms_lang cms INNER JOIN '._DB_PREFIX_.'lang l on cms.id_lang = l.id_lang
WHERE cms.id_cms ='.$id_cms.' AND l.active = 1';
$content_cms = Db::getInstance()->executeS($sql);
foreach ($content_cms as $cms)
{
$pdf = new TCPDF('P', 'mm', 'A4', true, 'UTF-8', false, false);
$pdf->setHeaderData('', 0, date('d/m/Y - H:i:s').' '.Configuration::get('PS_SHOP_NAME'), null, null);
$pdf->SetHeaderMargin(2);
$pdf->SetFooterMargin(8);
$pdf->setMargins(10, 40, 10);
$pdf->SetAutoPageBreak(true, PDF_MARGIN_BOTTOM);
$pdf->AddPage();
$pdf->writeHTML($cms['content'], true, false, true, false, '');
$code_iso = Language::getIsoById($cms['id_lang']);
if (is_writable($directory))
{
$filename = 'cgv_'.$code_iso.'_'.date('dmY_His').'.pdf';
$pdf->Output($directory.$filename, 'F');
$insert_pdf = 'INSERT INTO '._DB_PREFIX_.'mdtossend (filename,id_lang) VALUES (\''.pSQL($filename).'\','.(int)$cms['id_lang'].');';
if (!Db::getInstance()->execute($insert_pdf))
return $this->l('Could not insert in the database');
$filename = 'cgv_'.$code_iso.'.pdf';
$pdf->Output($directory.$filename, 'F');
}
else
return $this->l('Directory is not writable. Please check the folder permissions: ').$directory;
}
}
return 'ok';
}
private function generatePDF($id_cms)
{
$directory = _PS_ROOT_DIR_.'/modules/mdtossend/pdf/';
if ($id_cms != null)
{
$sql = 'SELECT content, cms.id_lang FROM '._DB_PREFIX_.'cms_lang cms INNER JOIN '._DB_PREFIX_.'lang l on cms.id_lang = l.id_lang
WHERE cms.id_cms ='.$id_cms.' AND l.active = 1';
$content_cms = Db::getInstance()->executeS($sql);
foreach ($content_cms as $cms)
{
$pdf = new PDFGenerator();
$contenu = htmlentities($cms['content'], null, 'utf-8');
$contenu = str_replace(utf8_encode('&ensp;'), '', $contenu);
$contenu = $pdf->unhtmlentities($contenu);
$pdf->createHeader(date('d/m/Y - H:i:s').' '.$this->context->shop->name);
$pdf->createContent($contenu);
$pdf->writePage();
$code_iso = Language::getIsoById($cms['id_lang']);
$id_shop = $this->context->shop->id;
if (is_writable($directory))
{
$filename = 'cgv_'.$code_iso.'_'.$id_shop.'_'.date('Ymd_His').'.pdf';
$pdf->Output($directory.$filename, 'F');
$insert_pdf = 'INSERT INTO '._DB_PREFIX_.'mdtossend (filename,id_lang) VALUES (\''.pSQL($filename).'\','.(int)$cms['id_lang'].');';
if (!Db::getInstance()->execute($insert_pdf))
return $this->l('Could not insert in the database');
$filename = 'cgv_'.$code_iso.'_'.$id_shop.'.pdf';
$pdf->Output($directory.$filename, 'F');
}
else
return $this->l('Directory is not writable. Please check the folder permissions: ').$directory;
}
}
return 'ok';
}
public function history()
{
$history = '<table id="historyTable">';
$history .= '<thead><tr><th>'.$this->l('Filename').'</th><th>'.$this->l('Language').'</th>
<th>'.$this->l('Date / Time').'</th><th>'.$this->l('Remove').'</th></tr></thead>';
$sql = 'SELECT filename, id_lang,datetime FROM '._DB_PREFIX_.'mdtossend';
$history_pdf = Db::getInstance()->executeS($sql);
foreach ($history_pdf as $file)
{
$lang = Language::getLanguage($file['id_lang']);
$history .= '<tr id="'.$file['filename'].'"><td><a href="/modules/mdtossend/pdf/'.$file['filename'].'" >&nbsp;'.$file['filename'].'<a/></td>';
$history .= '<td>'.$lang['name'].'</td><td>'.$file['datetime'].'</td>';
$history .= '<td><input class="css-checkbox" type="checkbox" name="'.$file['filename'].'" id="'.Tools::substr($file['filename'], 0, -4).'"
value="'.$file['filename'].'"><label for="'.Tools::substr($file['filename'], 0, -4).'" class="css-label"></label></td></tr>';
}
$history .= '</table>';
return $history;
}
private function addCSSJS()
{
return '
<link type="text/css" rel="stylesheet" href="'.__PS_BASE_URI__.'modules/mdtossend/views/css/style.css"/>
<link type="text/css" rel="stylesheet" href="'.__PS_BASE_URI__.'modules/mdtossend/views/css/jquery.dataTables.css"/>
<script src="'.__PS_BASE_URI__.'modules/mdtossend/views/js/jquery.dataTables.min.js"></script>
<script src="'.__PS_BASE_URI__.'modules/mdtossend/views/js/jquery.tabs-min.js"></script>
<script src="'.__PS_BASE_URI__.'modules/mdtossend/views/js/removePDF.js"></script>
<script>
$(document).ready(function($) {
$(\'#md\').tabs();
});
</script>
<script type="text/javascript">
$(document).ready(function() {
$(\'#historyTable\').dataTable();
} );</script>';
}
private function displayForm()
{
//CMS choose
$all_cms = CMS::getCMSPages($this->context->employee->id_lang);
$default = Configuration::get('MD_PDF_CGV');
$default = (empty($default)) ? 'selected' : '';
$form = '<form enctype="multipart/form-data" action="'.$_SERVER['REQUEST_URI'].'" method="post">
<label>'.$this->l('Select your CMS').'</label>
<select name="chooseID"><option value="0" disabled="disabled" '.$default.'>'.$this->l('Choose ...').'</option>';
foreach ($all_cms as $cmspage)
{
$select = ($cmspage['id_cms'] == Configuration::get('MD_PDF_CGV')) ? 'selected' : '';
$form .= '<option value="'.$cmspage['id_cms'].'" '.$select.'>'.$cmspage['meta_title'].'</option>';
}
$form .= '</select><p class="help-block"'.(version_compare(_PS_VERSION_, 1.5, '<') ? 'style="margin-left: 250px !important;"' : ' ' ).'>
'.$this->l('Choose the CMS page which correspond to your Terms of Sale').'</p>
<!--<input type="submit" name="submitID" value="'.$this->l('Select').'" class="button" />-->';
//TOS to PDF invoice
if (version_compare(_PS_VERSION_, 1.5, '>'))
{
$form .= '<label>'.$this->l('Add TOS to PDF invoice').'</label>
<input class="radio" type="radio" name="invoice" id="invoice_on" value="1"
'.(Tools::getValue('invoice', Configuration::get('MD_CGV_INVOICE')) ? 'checked="checked" ' : '').'/>
<label class="t" for="invoice_on">'.$this->l('Yes').'</label>
<input class="radio" type="radio" name="invoice" id="invoice_off" value="0"
'.(!Tools::getValue('invoice', Configuration::get('MD_CGV_INVOICE')) ? 'checked="checked" ' : '').'/>
<label class="t" for="invoice_off">'.$this->l('No').'</label><br>
<p class="help-block">'.$this->l('Add your Terms of Sale after the PDF Invoice instead of a new mail').'</p>';
}
//Withdrawal form
$form .= '<label>'.$this->l('Send Withdrawal form').'</label><input type="hidden" name="MAX_FILE_SIZE" value="3000000" />
<input name="withdrawalform" type="file" />';
if ($file = Configuration::get('MD_CGV_WITHDRAWALFORM'))
$form .= '<p class="help-block"'.(version_compare(_PS_VERSION_, 1.5, '<') ? 'style="margin-left: 250px !important;"' : ' ' ).'>
'.$this->l('Current withdrawal form').': <a href="http://'.$_SERVER['HTTP_HOST'].'/modules/mdtossend/form/'.$file.'">'.$file.'</a></p>';
else
{
$form .= '<p class="help-block"'.(version_compare(_PS_VERSION_, 1.5, '<') ? 'style="margin-left: 250px !important;"' : ' ' ).'>
'.$this->l('No withdrawal form').'</p>';
}
$form .= '<label>'.$this->l('Send the Withdrawal form').'</label>
<input class="radio" type="radio" name="invoice_withdrawal" id="invoice_withdrawal_on" value="1"
'.(Tools::getValue('invoice_withdrawal', Configuration::get('MD_CGV_INVOICE_WITHDRAWAL')) ? 'checked="checked" ' : '').'/>
<label class="t" for="invoice_withdrawal_on">'.$this->l('Yes').'</label>
<input class="radio" type="radio" name="invoice_withdrawal" id="invoice_withdrawal_off" value="0"
'.(!Tools::getValue('invoice_withdrawal', Configuration::get('MD_CGV_INVOICE_WITHDRAWAL')) ? 'checked="checked" ' : '').'/>
<label class="t" for="invoice_withdrawal_off">'.$this->l('No').'</label><br>
<p class="help-block"'.(version_compare(_PS_VERSION_, 1.5, '<') ? 'style="margin-left: 250px !important;"' : ' ' ).'>
'.$this->l('Send the withdrawal form with the PDF invoice').'</p>';
$form .= '<input id="bigbutton" type="submit" name="submitSettings" value="'.$this->l('Save').'" /></form>';
return $form;
}
}