Add config "mail_template_system" see BT#14894

Requires DB change, allow admins to setup custom email templates
pull/2729/head
Julio Montoya 7 years ago
parent 54a8d0d0a5
commit 0c1446077b
  1. 7
      main/admin/index.php
  2. 22
      main/admin/user_add.php
  3. 10
      main/admin/user_edit.php
  4. 18
      main/inc/ajax/mail.ajax.php
  5. 31
      main/inc/ajax/model.ajax.php
  6. 22
      main/inc/lib/MailTemplateManager.php
  7. 79
      main/inc/lib/formvalidator/FormValidator.class.php
  8. 1
      main/inc/lib/sessionmanager.lib.php
  9. 118
      main/inc/lib/usermanager.lib.php
  10. 13
      main/template/default/mail/user_edit_content.tpl

@ -277,6 +277,13 @@ if (api_is_platform_admin()) {
$items[] = ['url' => 'legal_add.php', 'label' => get_lang('TermsAndConditions')]; $items[] = ['url' => 'legal_add.php', 'label' => get_lang('TermsAndConditions')];
} }
if (api_get_configuration_value('mail_template_system')) {
$items[] = [
'url' => api_get_path(WEB_CODE_PATH).'mail_template/list.php',
'label' => get_lang('MailTemplate'),
];
}
$blocks['platform']['items'] = $items; $blocks['platform']['items'] = $items;
$blocks['platform']['extra'] = null; $blocks['platform']['extra'] = null;
} }

@ -305,6 +305,19 @@ $returnParams = $extraField->addElements(
[], [],
true true
); );
$allowEmailTemplate = api_get_configuration_value('mail_template_system');
if ($allowEmailTemplate) {
$form->addEmailTemplate(
[
'subject_registration_platform.tpl',
'content_registration_platform.tpl',
'new_user_first_email_confirmation.tpl',
'new_user_second_email_confirmation.tpl',
]
);
}
$jquery_ready_content = $returnParams['jquery_ready_content']; $jquery_ready_content = $returnParams['jquery_ready_content'];
// the $jquery_ready_content variable collects all functions that will be load in the $(document).ready javascript function // the $jquery_ready_content variable collects all functions that will be load in the $(document).ready javascript function
@ -381,6 +394,8 @@ if ($form->validate()) {
} }
} }
$template = isset($user['email_template_option']) ? $user['email_template_option'] : [];
$user_id = UserManager::create_user( $user_id = UserManager::create_user(
$firstname, $firstname,
$lastname, $lastname,
@ -399,7 +414,12 @@ if ($form->validate()) {
$extra, $extra,
null, null,
$send_mail, $send_mail,
$platform_admin $platform_admin,
'',
false,
null,
0,
$template
); );
Security::clear_token(); Security::clear_token();

@ -329,6 +329,11 @@ $returnParams = $extraField->addElements(
); );
$jqueryReadyContent = $returnParams['jquery_ready_content']; $jqueryReadyContent = $returnParams['jquery_ready_content'];
$allowEmailTemplate = api_get_configuration_value('mail_template_system');
if ($allowEmailTemplate) {
$form->addEmailTemplate(['user_edit_content.tpl']);
}
// the $jqueryReadyContent variable collects all functions that will be load in the // the $jqueryReadyContent variable collects all functions that will be load in the
// $(document).ready javascript function // $(document).ready javascript function
$htmlHeadXtra[] = '<script> $htmlHeadXtra[] = '<script>
@ -431,6 +436,8 @@ if ($form->validate()) {
$username = $email; $username = $email;
} }
$template = isset($user['email_template_option']) ? $user['email_template_option'] : [];
UserManager::update_user( UserManager::update_user(
$user_id, $user_id,
$firstname, $firstname,
@ -452,7 +459,8 @@ if ($form->validate()) {
null, null,
$send_mail, $send_mail,
$reset_password, $reset_password,
$address $address,
$template
); );
if (isset($user['student_boss'])) { if (isset($user['student_boss'])) {

@ -10,8 +10,20 @@ $action = isset($_REQUEST['a']) ? $_REQUEST['a'] : null;
switch ($action) { switch ($action) {
case 'select_option': case 'select_option':
$id = isset($_REQUEST['id']) ? $_REQUEST['id'] : null; $id = isset($_REQUEST['id']) ? $_REQUEST['id'] : null;
$mail = new MailTemplateManager(); if (!empty($id)) {
$item = $mail->get($id); $mail = new MailTemplateManager();
echo $item['template']; $item = $mail->get($id);
echo $item['template'];
} else {
$templateName = isset($_REQUEST['template_name']) ? $_REQUEST['template_name'] : null;
if (!empty($templateName)) {
$templatePath = api_get_path(SYS_CODE_PATH).'template/default/mail/';
if (Security::check_abs_path($templatePath.$templateName, $templatePath)) {
if (file_exists($templatePath.$templateName)) {
echo file_get_contents($templatePath.$templateName);
}
}
}
}
break; break;
} }

@ -743,6 +743,10 @@ switch ($action) {
$obj = new Promotion(); $obj = new Promotion();
$count = $obj->get_count(); $count = $obj->get_count();
break; break;
case 'get_mail_template':
$obj = new MailTemplateManager();
$count = $obj->get_count();
break;
case 'get_grade_models': case 'get_grade_models':
$obj = new GradeModel(); $obj = new GradeModel();
$count = $obj->get_count(); $count = $obj->get_count();
@ -1940,6 +1944,32 @@ switch ($action) {
} }
$result = $new_result; $result = $new_result;
break; break;
case 'get_mail_template':
$columns = ['name', 'type', 'default_template', 'actions'];
if (!in_array($sidx, $columns)) {
$sidx = 'name';
}
if (!in_array($sidx, $columns)) {
$sidx = 'name';
}
$result = Database::select(
'*',
$obj->table,
[
'where' => ['url_id = ? ' => api_get_current_access_url_id()],
'order' => "$sidx $sord",
'LIMIT' => "$start , $limit",
]
);
$new_result = [];
foreach ($result as $item) {
$new_result[] = $item;
}
$result = $new_result;
break;
case 'get_grade_models': case 'get_grade_models':
$columns = ['name', 'description', 'actions']; $columns = ['name', 'description', 'actions'];
if (!in_array($sidx, $columns)) { if (!in_array($sidx, $columns)) {
@ -2189,6 +2219,7 @@ switch ($action) {
$allowed_actions = [ $allowed_actions = [
'get_careers', 'get_careers',
'get_promotions', 'get_promotions',
'get_mail_template',
'get_usergroups', 'get_usergroups',
'get_usergroups_teacher', 'get_usergroups_teacher',
'get_gradebooks', 'get_gradebooks',

@ -183,4 +183,26 @@ class MailTemplateManager extends Model
return true; return true;
} }
/**
* @param int $templateId
* @param array $userInfo
*
* @return string
*/
public function parseTemplate($templateId, $userInfo)
{
$templateInfo = $this->get($templateId);
$emailTemplate = $templateInfo['template'];
$keys = array_keys($userInfo);
foreach ($keys as $key) {
$emailTemplate = str_replace("{{user.$key}}", $userInfo[$key], $emailTemplate);
}
$template = new Template();
$template->twig->setLoader(new \Twig_Loader_String());
$emailBody = $template->twig->render($emailTemplate);
return $emailBody;
}
} }

@ -1749,6 +1749,85 @@ EOT;
return $this->addElement('UserAvatar', $name, $label, ['image_size' => $imageSize, 'sub_title' => $subtitle]); return $this->addElement('UserAvatar', $name, $label, ['image_size' => $imageSize, 'sub_title' => $subtitle]);
} }
/**
* @param array $typeList
*/
public function addEmailTemplate($typeList)
{
$mailManager = new MailTemplateManager();
foreach ($typeList as $type) {
$list = $mailManager->get_all(
['where' => ['type = ? AND url_id = ?' => [$type, api_get_current_access_url_id()]]]
);
$options = [get_lang('Select')];
$name = $type;
$defaultId = '';
foreach ($list as $item) {
$options[$item['id']] = $item['name'];
$name = $item['name'];
if (empty($defaultId)) {
$defaultId = $item['default_template'] == 1 ? $item['id'] : '';
}
}
$url = api_get_path(WEB_AJAX_PATH).'mail.ajax.php?a=select_option';
$typeNoDots = 'email_template_option_'.str_replace('.tpl', '', $type);
$this->addSelect(
'email_template_option['.$type.']',
$name,
$options,
['id' => $typeNoDots]
);
$templateNoDots = 'email_template_'.str_replace('.tpl', '', $type);
$templateNoDotsBlock = 'email_template_block_'.str_replace('.tpl', '', $type);
$this->addHtml('<div id="'.$templateNoDotsBlock.'" style="display:none">');
$this->addTextarea(
$templateNoDots,
get_lang('Preview'),
['disabled' => 'disabled ', 'id' => $templateNoDots, 'rows' => '5']
);
$this->addHtml('</div>');
$this->addHtml("<script>
$(document).on('ready', function() {
var defaultValue = '$defaultId';
$('#$typeNoDots').val(defaultValue);
$('#$typeNoDots').selectpicker('render');
if (defaultValue != '') {
var selected = $('#$typeNoDots option:selected').val();
$.ajax({
url: '$url' + '&id=' + selected+ '&template_name=$type',
success: function (data) {
$('#$templateNoDots').html(data);
$('#$templateNoDotsBlock').show();
return;
},
});
}
$('#$typeNoDots').on('change', function(){
var selected = $('#$typeNoDots option:selected').val();
$.ajax({
url: '$url' + '&id=' + selected,
success: function (data) {
$('#$templateNoDots').html(data);
$('#$templateNoDotsBlock').show();
return;
},
});
});
});
</script>");
}
}
/** /**
* @param string $url page that will handle the upload * @param string $url page that will handle the upload
* @param string $inputName * @param string $inputName

@ -139,6 +139,7 @@ class SessionManager
* @param int|null $accessUrlId Optional. * @param int|null $accessUrlId Optional.
* *
* @return mixed Session ID on success, error message otherwise * @return mixed Session ID on success, error message otherwise
*
* @todo use an array to replace all this parameters or use the model.lib.php ... * @todo use an array to replace all this parameters or use the model.lib.php ...
*/ */
public static function create_session( public static function create_session(

@ -183,6 +183,7 @@ class UserManager
* @param bool $sendEmailToAllAdmins * @param bool $sendEmailToAllAdmins
* @param FormValidator $form * @param FormValidator $form
* @param int $creatorId * @param int $creatorId
* @param array $emailTemplate
* *
* @return mixed new user id - if the new user creation succeeds, false otherwise * @return mixed new user id - if the new user creation succeeds, false otherwise
* @desc The function tries to retrieve user id from the session. * @desc The function tries to retrieve user id from the session.
@ -212,7 +213,8 @@ class UserManager
$address = '', $address = '',
$sendEmailToAllAdmins = false, $sendEmailToAllAdmins = false,
$form = null, $form = null,
$creatorId = 0 $creatorId = 0,
$emailTemplate = []
) { ) {
$creatorId = empty($creatorId) ? api_get_user_id() : 0; $creatorId = empty($creatorId) ? api_get_user_id() : 0;
$hook = HookCreateUser::create(); $hook = HookCreateUser::create();
@ -432,9 +434,7 @@ class UserManager
false, false,
false false
); );
$layoutSubject = $tplSubject->get_template( $layoutSubject = $tplSubject->get_template('mail/subject_registration_platform.tpl');
'mail/subject_registration_platform.tpl'
);
$emailSubject = $tplSubject->fetch($layoutSubject); $emailSubject = $tplSubject->fetch($layoutSubject);
$sender_name = api_get_person_name( $sender_name = api_get_person_name(
api_get_setting('administratorName'), api_get_setting('administratorName'),
@ -473,6 +473,9 @@ class UserManager
$layoutContent = $tplContent->get_template('mail/content_registration_platform.tpl'); $layoutContent = $tplContent->get_template('mail/content_registration_platform.tpl');
$emailBody = $tplContent->fetch($layoutContent); $emailBody = $tplContent->fetch($layoutContent);
$userInfo = api_get_user_info($userId);
$mailTemplateManager = new MailTemplateManager();
/* MANAGE EVENT WITH MAIL */ /* MANAGE EVENT WITH MAIL */
if (EventsMail::check_if_using_class('user_registration')) { if (EventsMail::check_if_using_class('user_registration')) {
$values["about_user"] = $return; $values["about_user"] = $return;
@ -490,11 +493,30 @@ class UserManager
'password' => $original_password, 'password' => $original_password,
]; ];
$emailBodyTemplate = '';
if (!empty($emailTemplate)) {
if (isset($emailTemplate['content_registration_platform.tpl'])) {
$emailBodyTemplate = $mailTemplateManager->parseTemplate(
$emailTemplate['content_registration_platform.tpl'],
$userInfo
);
}
}
$twoEmail = api_get_configuration_value('send_two_inscription_confirmation_mail'); $twoEmail = api_get_configuration_value('send_two_inscription_confirmation_mail');
if ($twoEmail === true) { if ($twoEmail === true) {
$layoutContent = $tplContent->get_template('mail/new_user_first_email_confirmation.tpl'); $layoutContent = $tplContent->get_template('mail/new_user_first_email_confirmation.tpl');
$emailBody = $tplContent->fetch($layoutContent); $emailBody = $tplContent->fetch($layoutContent);
if (!empty($emailBodyTemplate) &&
isset($emailTemplate['new_user_first_email_confirmation.tpl'])
) {
$emailBody = $mailTemplateManager->parseTemplate(
$emailTemplate['new_user_first_email_confirmation.tpl'],
$userInfo
);
}
api_mail_html( api_mail_html(
$recipient_name, $recipient_name,
$email, $email,
@ -511,6 +533,15 @@ class UserManager
$layoutContent = $tplContent->get_template('mail/new_user_second_email_confirmation.tpl'); $layoutContent = $tplContent->get_template('mail/new_user_second_email_confirmation.tpl');
$emailBody = $tplContent->fetch($layoutContent); $emailBody = $tplContent->fetch($layoutContent);
if (!empty($emailBodyTemplate) &&
isset($emailTemplate['new_user_second_email_confirmation.tpl'])
) {
$emailBody = $mailTemplateManager->parseTemplate(
$emailTemplate['new_user_second_email_confirmation.tpl'],
$userInfo
);
}
api_mail_html( api_mail_html(
$recipient_name, $recipient_name,
$email, $email,
@ -524,6 +555,9 @@ class UserManager
$additionalParameters $additionalParameters
); );
} else { } else {
if (!empty($emailBodyTemplate)) {
$emailBody = $emailBodyTemplate;
}
$sendToInbox = api_get_configuration_value('send_inscription_msg_to_inbox'); $sendToInbox = api_get_configuration_value('send_inscription_msg_to_inbox');
if ($sendToInbox) { if ($sendToInbox) {
$adminList = self::get_all_administrators(); $adminList = self::get_all_administrators();
@ -592,6 +626,17 @@ class UserManager
$layoutContent = $tplContent->get_template('mail/content_registration_platform_to_admin.tpl'); $layoutContent = $tplContent->get_template('mail/content_registration_platform_to_admin.tpl');
$emailBody = $tplContent->fetch($layoutContent); $emailBody = $tplContent->fetch($layoutContent);
if (!empty($emailBodyTemplate) &&
isset($emailTemplate['content_registration_platform_to_admin.tpl'])
) {
$emailBody = $mailTemplateManager->parseTemplate(
$emailTemplate['content_registration_platform_to_admin.tpl'],
$userInfo
);
}
$subject = get_lang('UserAdded'); $subject = get_lang('UserAdded');
foreach ($adminList as $adminId => $data) { foreach ($adminList as $adminId => $data) {
@ -1062,6 +1107,7 @@ class UserManager
* @param bool $send_email Whether to send an e-mail to the user after the update is complete * @param bool $send_email Whether to send an e-mail to the user after the update is complete
* @param int $reset_password Method used to reset password (0, 1, 2 or 3 - see usage examples for details) * @param int $reset_password Method used to reset password (0, 1, 2 or 3 - see usage examples for details)
* @param string $address * @param string $address
* @param array $emailTemplate
* *
* @return bool|int False on error, or the user ID if the user information was updated * @return bool|int False on error, or the user ID if the user information was updated
* @assert (false, false, false, false, false, false, false, false, false, false, false, false, false) === false * @assert (false, false, false, false, false, false, false, false, false, false, false, false, false) === false
@ -1087,7 +1133,8 @@ class UserManager
$encrypt_method = '', $encrypt_method = '',
$send_email = false, $send_email = false,
$reset_password = 0, $reset_password = 0,
$address = null $address = null,
$emailTemplate = []
) { ) {
$hook = HookUpdateUser::create(); $hook = HookUpdateUser::create();
if (!empty($hook)) { if (!empty($hook)) {
@ -1209,47 +1256,48 @@ class UserManager
PERSON_NAME_EMAIL_ADDRESS PERSON_NAME_EMAIL_ADDRESS
); );
$email_admin = api_get_setting('emailAdministrator'); $email_admin = api_get_setting('emailAdministrator');
$url = api_get_path(WEB_PATH);
if (api_is_multiple_url_enabled()) { if (api_is_multiple_url_enabled()) {
$access_url_id = api_get_current_access_url_id(); $access_url_id = api_get_current_access_url_id();
if ($access_url_id != -1) { if ($access_url_id != -1) {
$url = api_get_access_url($access_url_id); $url = api_get_access_url($access_url_id);
$emailbody = get_lang('Dear')." ".stripslashes(api_get_person_name($firstname, $lastname)).",\n\n". $url = $url['url'];
get_lang('YouAreReg')." ".api_get_setting('siteName')." ".get_lang('WithTheFollowingSettings')."\n\n".
get_lang('Username')." : ".$username.(($reset_password > 0) ? "\n".
get_lang('Pass')." : ".stripslashes($original_password) : "")."\n\n".
get_lang('Address')." ".api_get_setting('siteName')." ".get_lang('Is')." : ".$url['url']."\n\n".
get_lang('Problem')."\n\n".
get_lang('SignatureFormula').",\n\n".
api_get_person_name(
api_get_setting('administratorName'),
api_get_setting('administratorSurname')
)."\n".
get_lang('Manager')." ".api_get_setting('siteName')."\nT. ".api_get_setting('administratorTelephone')."\n".
get_lang('Email')." : ".api_get_setting('emailAdministrator');
} }
} else {
$emailbody = get_lang('Dear')." ".stripslashes(api_get_person_name($firstname, $lastname)).",\n\n".
get_lang('YouAreReg')." ".api_get_setting('siteName')." ".get_lang('WithTheFollowingSettings')."\n\n".
get_lang('Username')." : ".$username.(($reset_password > 0) ? "\n".
get_lang('Pass')." : ".stripslashes($original_password) : "")."\n\n".
get_lang('Address')." ".api_get_setting('siteName')." ".get_lang('Is')." : ".api_get_path(WEB_PATH)."\n\n".
get_lang('Problem')."\n\n".
get_lang('SignatureFormula').",\n\n".
api_get_person_name(
api_get_setting('administratorName'),
api_get_setting('administratorSurname')
)."\n".
get_lang('Manager')." ".api_get_setting('siteName')."\nT. ".api_get_setting('administratorTelephone')."\n".
get_lang('Email')." : ".api_get_setting('emailAdministrator');
} }
$emailbody = nl2br($emailbody); $tplContent = new Template(
null,
false,
false,
false,
false,
false
);
// variables for the default template
$tplContent->assign('complete_name', stripslashes(api_get_person_name($firstname, $lastname)));
$tplContent->assign('login_name', $username);
$originalPassword = '';
if ($reset_password > 0) {
$originalPassword = stripslashes($original_password);
}
$tplContent->assign('original_password', $originalPassword);
$tplContent->assign('portal_url', $url);
$layoutContent = $tplContent->get_template('mail/user_edit_content.tpl');
$emailBody = $tplContent->fetch($layoutContent);
$mailTemplateManager = new MailTemplateManager();
if (!empty($emailTemplate) && isset($emailTemplate['user_edit_content.tpl'])) {
$userInfo = api_get_user_info($user_id);
$emailBody = $mailTemplateManager->parseTemplate($emailTemplate['user_edit_content.tpl'], $userInfo);
}
api_mail_html( api_mail_html(
$recipient_name, $recipient_name,
$email, $email,
$emailsubject, $emailsubject,
$emailbody, $emailBody,
$sender_name, $sender_name,
$email_admin $email_admin
); );

@ -0,0 +1,13 @@
<p>{{ 'Dear'|get_lang }} {{ complete_name }},</p>
<p>{{ 'YouAreReg'|get_lang }} {{ _s.site_name }} {{ 'WithTheFollowingSettings'|get_lang }}</p>
<p>{{ 'Username'|get_lang }} : {{ login_name }}<br>
{% if original_password != '' %}
{{ 'Pass'|get_lang }} : {{ original_password }}</p>
{% endif %}
<p>{{ 'Address'|get_lang }} {{ _s.site_name }} {{ 'Is'|get_lang }} : {{ portal_url }}</p>
<p>{{ 'Problem'|get_lang }}</p>
<p>{{ 'SignatureFormula'|get_lang }}</p>
<p>{{ _admin.name }}, {{ _admin.surname }}<br>
{{ 'Manager'|get_lang }} {{ _s.site_name }}<br>
{{ _admin.telephone ? 'T. ' ~ _admin.telephone }}<br>
{{ _admin.email ? 'Email'|get_lang ~ ': ' ~ _admin.email }}</p>
Loading…
Cancel
Save