1<?php
2/* Copyright (C) 2004       Rodolphe Quiedeville    <rodolphe@quiedeville.org>
3 * Copyright (C) 2004-2018  Laurent Destailleur     <eldy@users.sourceforge.net>
4 * Copyright (C) 2004       Benoit Mortier          <benoit.mortier@opensides.be>
5 * Copyright (C) 2005-2012  Regis Houssin           <regis.houssin@inodbox.com>
6 * Copyright (C) 2010-2016  Juanjo Menent           <jmenent@2byte.es>
7 * Copyright (C) 2011-2018  Philippe Grand          <philippe.grand@atoo-net.com>
8 * Copyright (C) 2011       Remy Younes             <ryounes@gmail.com>
9 * Copyright (C) 2012-2015  Marcos García           <marcosgdf@gmail.com>
10 * Copyright (C) 2012       Christophe Battarel     <christophe.battarel@ltairis.fr>
11 * Copyright (C) 2011-2016  Alexandre Spangaro      <aspangaro@open-dsi.fr>
12 * Copyright (C) 2015       Ferran Marcet           <fmarcet@2byte.es>
13 * Copyright (C) 2016       Raphaël Doursenaud      <rdoursenaud@gpcsolutions.fr>
14 * Copyright (C) 2018-2020  Frédéric France         <frederic.france@netlogic.fr>
15 *
16 * This program is free software; you can redistribute it and/or modify
17 * it under the terms of the GNU General Public License as published by
18 * the Free Software Foundation; either version 3 of the License, or
19 * (at your option) any later version.
20 *
21 * This program is distributed in the hope that it will be useful,
22 * but WITHOUT ANY WARRANTY; without even the implied warranty of
23 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
24 * GNU General Public License for more details.
25 *
26 * You should have received a copy of the GNU General Public License
27 * along with this program. If not, see <https://www.gnu.org/licenses/>.
28 */
29
30/**
31 *	    \file       htdocs/admin/mails_templates.php
32 *		\ingroup    core
33 *		\brief      Page to administer emails templates
34 */
35
36require '../main.inc.php';
37require_once DOL_DOCUMENT_ROOT.'/core/class/html.formadmin.class.php';
38require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php';
39require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php';
40require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
41require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
42require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php';
43require_once DOL_DOCUMENT_ROOT.'/core/class/html.formaccounting.class.php';
44
45// Load translation files required by the page
46$langs->loadLangs(array("errors", "admin", "mails", "languages"));
47
48$action = GETPOST('action', 'aZ09') ?GETPOST('action', 'aZ09') : 'view';
49$confirm = GETPOST('confirm', 'alpha'); // Result of a confirmation
50
51$id = GETPOST('id', 'int');
52$rowid = GETPOST('rowid', 'alpha');
53$search_label = GETPOST('search_label', 'alphanohtml'); // Must allow value like 'Abc Def' or '(MyTemplateName)'
54$search_type_template = GETPOST('search_type_template', 'alpha');
55$search_lang = GETPOST('search_lang', 'alpha');
56$search_fk_user = GETPOST('search_fk_user', 'intcomma');
57$search_topic = GETPOST('search_topic', 'alpha');
58
59if (!empty($user->socid)) accessforbidden();
60
61$acts = array();
62$actl = array();
63$acts[0] = "activate";
64$acts[1] = "disable";
65$actl[0] = img_picto($langs->trans("Disabled"), 'switch_off');
66$actl[1] = img_picto($langs->trans("Activated"), 'switch_on');
67
68$listoffset = GETPOST('listoffset', 'alpha');
69$listlimit = GETPOST('listlimit', 'alpha') > 0 ?GETPOST('listlimit', 'alpha') : 1000;
70
71$sortfield = GETPOST("sortfield", 'alpha');
72$sortorder = GETPOST("sortorder", 'alpha');
73$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
74if (empty($page) || $page == -1) { $page = 0; }     // If $page is not defined, or '' or -1
75$offset = $listlimit * $page;
76$pageprev = $page - 1;
77$pagenext = $page + 1;
78
79if (empty($sortfield)) $sortfield = 'type_template, lang, position, label';
80if (empty($sortorder)) $sortorder = 'ASC';
81
82// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
83$hookmanager->initHooks(array('emailtemplates'));
84
85// Name of SQL tables of dictionaries
86$tabname = array();
87$tabname[25] = MAIN_DB_PREFIX."c_email_templates";
88
89// Nom des champs en resultat de select pour affichage du dictionnaire
90$tabfield = array();
91$tabfield[25] = "label,lang,type_template,fk_user,private,position,topic,joinfiles,content";
92if (!empty($conf->global->MAIN_EMAIL_TEMPLATES_FOR_OBJECT_LINES)) $tabfield[25] .= ',content_lines';
93
94// Nom des champs d'edition pour modification d'un enregistrement
95$tabfieldvalue = array();
96$tabfieldvalue[25] = "label,lang,type_template,fk_user,private,position,topic,joinfiles,content";
97if (!empty($conf->global->MAIN_EMAIL_TEMPLATES_FOR_OBJECT_LINES)) $tabfieldvalue[25] .= ',content_lines';
98
99// Nom des champs dans la table pour insertion d'un enregistrement
100$tabfieldinsert = array();
101$tabfieldinsert[25] = "label,lang,type_template,fk_user,private,position,topic,joinfiles,content";
102if (!empty($conf->global->MAIN_EMAIL_TEMPLATES_FOR_OBJECT_LINES)) $tabfieldinsert[25] .= ',content_lines';
103$tabfieldinsert[25] .= ',entity'; // Must be at end because not into other arrays
104
105// Condition to show dictionary in setup page
106$tabcond = array();
107$tabcond[25] = true;
108
109// List of help for fields
110// Set MAIN_EMAIL_TEMPLATES_FOR_OBJECT_LINES to allow edit of template for lines
111require_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
112$formmail = new FormMail($db);
113if (empty($conf->global->MAIN_EMAIL_TEMPLATES_FOR_OBJECT_LINES))
114{
115	$tmp = FormMail::getAvailableSubstitKey('formemail');
116	$tmp['__(AnyTranslationKey)__'] = 'Translation';
117	$helpsubstit = $langs->trans("AvailableVariables").':<br>';
118	$helpsubstitforlines = $langs->trans("AvailableVariables").':<br>';
119	foreach ($tmp as $key => $val)
120	{
121		$helpsubstit .= $key.' -> '.$val.'<br>';
122		$helpsubstitforlines .= $key.' -> '.$val.'<br>';
123	}
124} else {
125	$tmp = FormMail::getAvailableSubstitKey('formemailwithlines');
126	$tmp['__(AnyTranslationKey)__'] = 'Translation';
127	$helpsubstit = $langs->trans("AvailableVariables").':<br>';
128	$helpsubstitforlines = $langs->trans("AvailableVariables").':<br>';
129	foreach ($tmp as $key => $val)
130	{
131		$helpsubstit .= $key.' -> '.$val.'<br>';
132	}
133	$tmp = FormMail::getAvailableSubstitKey('formemailforlines');
134	foreach ($tmp as $key => $val)
135	{
136		$helpsubstitforlines .= $key.' -> '.$val.'<br>';
137	}
138}
139
140
141$tabhelp = array();
142$tabhelp[25] = array(
143	'topic'=>$helpsubstit,
144	'joinfiles'=>$langs->trans('AttachMainDocByDefault'),
145	'content'=>$helpsubstit,
146	'content_lines'=>$helpsubstitforlines,
147	'type_template'=>$langs->trans("TemplateForElement"),
148	'private'=>$langs->trans("TemplateIsVisibleByOwnerOnly"),
149	'position'=>$langs->trans("PositionIntoComboList")
150);
151
152// List of check for fields (NOT USED YET)
153$tabfieldcheck = array();
154$tabfieldcheck[25] = array();
155
156
157$elementList = array();
158
159// We save list of template email Dolibarr can manage. This list can found by a grep into code on "->param['models']"
160$elementList = array();
161// Add all and none after the sort
162$elementList['all'] = '-- '.dol_escape_htmltag($langs->trans("All")).' --';
163$elementList['none'] = '-- '.dol_escape_htmltag($langs->trans("None")).' --';
164$elementList['user'] = img_picto('', 'user', 'class="paddingright"').dol_escape_htmltag($langs->trans('MailToUser'));
165if ($conf->adherent->enabled && $user->rights->adherent->lire) {
166	$elementList['member'] = img_picto('', 'object_member', 'class="paddingright"').dol_escape_htmltag($langs->trans('MailToMember'));
167}
168if ($conf->recruitment->enabled && $user->rights->recruitment->recruitmentjobposition->read) {
169	$elementList['recruitmentcandidature_send'] = img_picto('', 'recruitmentcandidature', 'class="paddingright"').dol_escape_htmltag($langs->trans('RecruitmentCandidatures'));
170}
171if ($conf->societe->enabled && $user->rights->societe->lire) {
172	$elementList['thirdparty'] = img_picto('', 'company', 'class="paddingright"').dol_escape_htmltag($langs->trans('MailToThirdparty'));
173}
174if ($conf->projet->enabled) {
175	$elementList['project'] = img_picto('', 'project', 'class="paddingright"').dol_escape_htmltag($langs->trans('MailToProject'));
176}
177if ($conf->propal->enabled && $user->rights->propal->lire) {
178	$elementList['propal_send'] = img_picto('', 'propal', 'class="paddingright"').dol_escape_htmltag($langs->trans('MailToSendProposal'));
179}
180if ($conf->commande->enabled && $user->rights->commande->lire) {
181	$elementList['order_send'] = img_picto('', 'order', 'class="paddingright"').dol_escape_htmltag($langs->trans('MailToSendOrder'));
182}
183if ($conf->facture->enabled && $user->rights->facture->lire) {
184	$elementList['facture_send'] = img_picto('', 'bill', 'class="paddingright"').dol_escape_htmltag($langs->trans('MailToSendInvoice'));
185}
186if ($conf->expedition->enabled) {
187	$elementList['shipping_send'] = img_picto('', 'dolly', 'class="paddingright"').dol_escape_htmltag($langs->trans('MailToSendShipment'));
188}
189if ($conf->reception->enabled) {
190	$elementList['reception_send'] = img_picto('', 'dolly', 'class="paddingright"').dol_escape_htmltag($langs->trans('MailToSendReception'));
191}
192if ($conf->ficheinter->enabled) {
193	$elementList['fichinter_send'] = img_picto('', 'intervention', 'class="paddingright"').dol_escape_htmltag($langs->trans('MailToSendIntervention'));
194}
195if ($conf->supplier_proposal->enabled) {
196	$elementList['supplier_proposal_send'] = img_picto('', 'propal', 'class="paddingright"').dol_escape_htmltag($langs->trans('MailToSendSupplierRequestForQuotation'));
197}
198if (($conf->fournisseur->enabled && $user->rights->fournisseur->commande->lire && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)) || ($conf->supplier_order->enabled && $user->rights->supplier_order->lire)) {
199	$elementList['order_supplier_send'] = img_picto('', 'order', 'class="paddingright"').dol_escape_htmltag($langs->trans('MailToSendSupplierOrder'));
200}
201if (($conf->fournisseur->enabled && $user->rights->fournisseur->facture->lire && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)) || ($conf->supplier_invoice->enabled && $user->rights->supplier_invoice->lire)) {
202	$elementList['invoice_supplier_send'] = img_picto('', 'bill', 'class="paddingright"').dol_escape_htmltag($langs->trans('MailToSendSupplierInvoice'));
203}
204if ($conf->contrat->enabled && $user->rights->contrat->lire) {
205	$elementList['contract'] = img_picto('', 'contract', 'class="paddingright"').dol_escape_htmltag($langs->trans('MailToSendContract'));
206}
207if ($conf->ticket->enabled && $user->rights->ticket->read) {
208	$elementList['ticket_send'] = img_picto('', 'ticket', 'class="paddingright"').dol_escape_htmltag($langs->trans('MailToTicket'));
209}
210if ($conf->agenda->enabled) {
211	$elementList['actioncomm_send'] = img_picto('', 'action', 'class="paddingright"').dol_escape_htmltag($langs->trans('MailToSendEventPush'));
212}
213
214$parameters = array('elementList'=>$elementList);
215$reshook = $hookmanager->executeHooks('emailElementlist', $parameters); // Note that $action and $object may have been modified by some hooks
216if ($reshook == 0) {
217	foreach ($hookmanager->resArray as $item => $value) {
218		$elementList[$item] = $value;
219	}
220}
221
222//asort($elementList);
223
224$id = 25;
225
226
227/*
228 * Actions
229 */
230
231if (GETPOST('cancel', 'alpha')) {
232	$action = 'list';
233	$massaction = '';
234}
235if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; }
236
237$parameters = array();
238$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
239if ($reshook < 0) {
240	setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
241}
242
243if (empty($reshook)) {
244	// Purge search criteria
245	if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) {
246		// All tests are required to be compatible with all browsers
247		$search_label = '';
248		$search_type_template = '';
249		$search_lang = '';
250		$search_fk_user = '';
251		$search_topic = '';
252		$toselect = '';
253		$search_array_options = array();
254	}
255
256	// Actions add or modify an entry into a dictionary
257	if (GETPOST('actionadd', 'alpha') || GETPOST('actionmodify', 'alpha')) {
258		$listfield = explode(',', str_replace(' ', '', $tabfield[$id]));
259		$listfieldinsert = explode(',', $tabfieldinsert[$id]);
260		$listfieldmodify = explode(',', $tabfieldinsert[$id]);
261		$listfieldvalue = explode(',', $tabfieldvalue[$id]);
262
263		// Check that all fields are filled
264		$ok = 1;
265		foreach ($listfield as $f => $value) {
266			// Not mandatory fields
267			if ($value == 'joinfiles') continue;
268			if ($value == 'content') continue;
269			if ($value == 'content_lines') continue;
270
271			// Rename some POST variables into a generic name
272			if (GETPOST('actionmodify', 'alpha') && $value == 'topic') $_POST['topic'] = $_POST['topic-'.$rowid];
273
274			if ((!GETPOSTISSET($value) || GETPOST($value) == '' || GETPOST($value) == '-1') && $value != 'lang' && $value != 'fk_user' && $value != 'position')
275			{
276				$ok = 0;
277				$fieldnamekey = $listfield[$f];
278				// We take translate key of field
279				if ($fieldnamekey == 'libelle' || ($fieldnamekey == 'label'))  $fieldnamekey = 'Code';
280				if ($fieldnamekey == 'code') $fieldnamekey = 'Code';
281				if ($fieldnamekey == 'note') $fieldnamekey = 'Note';
282				if ($fieldnamekey == 'type_template') $fieldnamekey = 'TypeOfTemplate';
283				if ($fieldnamekey == 'fk_user') $fieldnamekey = 'Owner';
284				if ($fieldnamekey == 'private') $fieldnamekey = 'Private';
285				if ($fieldnamekey == 'position') $fieldnamekey = 'Position';
286				if ($fieldnamekey == 'topic') $fieldnamekey = 'Topic';
287
288				setEventMessages($langs->transnoentities("ErrorFieldRequired", $langs->transnoentities($fieldnamekey)), null, 'errors');
289			}
290		}
291
292		// If previous test is ok action is add, we add the line
293		if ($ok && GETPOST('actionadd')) {
294			// Add new entry
295			$sql = "INSERT INTO ".$tabname[$id]." (";
296			// List of fields
297			$sql .= $tabfieldinsert[$id];
298            $sql .= ", active, enabled)";
299			$sql .= " VALUES(";
300
301			// List of values
302			$i = 0;
303			foreach ($listfieldinsert as $f => $value)
304			{
305				$keycode = $listfieldvalue[$i];
306				if ($value == 'lang') $keycode = 'langcode';
307				if (empty($keycode)) $keycode = $value;
308
309				// Clean input variables
310				if ($value == 'entity') $_POST[$keycode] = $conf->entity;
311				if ($value == 'fk_user' && !($_POST[$keycode] > 0)) $_POST[$keycode] = '';
312				if ($value == 'private' && !is_numeric($_POST[$keycode])) $_POST[$keycode] = '0';
313				if ($value == 'position' && !is_numeric($_POST[$keycode])) $_POST[$keycode] = '1';
314				//var_dump($keycode.' '.$value);
315
316				if ($i) $sql .= ", ";
317				if (GETPOST($keycode) == '' && $keycode != 'langcode')      $sql .= "null"; // langcode must be '' if not defined so the unique key that include lang will work
318				elseif (GETPOST($keycode) == '0' && $keycode == 'langcode') $sql .= "''"; // langcode must be '' if not defined so the unique key that include lang will work
319				elseif ($keycode == 'fk_user') {
320					if (!$user->admin) {	// A non admin user can only edit its own template
321						$sql .= " ".((int) $user->id);
322					} else {
323						$sql .= " ".((int) GETPOST($keycode, 'int'));
324					}
325				} elseif ($keycode == 'content') {
326					$sql .= "'".$db->escape(GETPOST($keycode, 'restricthtml'))."'";
327				} elseif (in_array($keycode, array('joinfiles', 'private', 'position'))) {
328					$sql .= (int) GETPOST($keycode, 'int');
329				} else {
330					$sql .= "'".$db->escape(GETPOST($keycode, 'nohtml'))."'";
331				}
332				$i++;
333			}
334			$sql .= ", 1, 1)";
335
336			dol_syslog("actionadd", LOG_DEBUG);
337			$result = $db->query($sql);
338			if ($result)	// Add is ok
339			{
340				setEventMessages($langs->transnoentities("RecordSaved"), null, 'mesgs');
341				$_POST = array('id'=>$id); // Clean $_POST array, we keep only id
342			} else {
343				if ($db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
344					setEventMessages($langs->transnoentities("ErrorRecordAlreadyExists"), null, 'errors');
345				} else {
346					dol_print_error($db);
347				}
348			}
349		}
350
351		// We modify the line
352		if ($ok && GETPOST('actionmodify'))
353		{
354			$rowidcol = "rowid";
355
356			// Modify entry
357			$sql = "UPDATE ".$tabname[$id]." SET ";
358			// Modifie valeur des champs
359			$i = 0;
360			foreach ($listfieldmodify as $field)
361			{
362				$keycode = $listfieldvalue[$i];
363				if ($field == 'lang') $keycode = 'langcode';
364				if (empty($keycode)) $keycode = $field;
365
366				// Rename some POST variables into a generic name
367				if ($field == 'fk_user' && !($_POST['fk_user'] > 0)) $_POST['fk_user'] = '';
368				if ($field == 'topic') $_POST['topic'] = $_POST['topic-'.$rowid];
369				if ($field == 'joinfiles') $_POST['joinfiles'] = $_POST['joinfiles-'.$rowid];
370				if ($field == 'content') $_POST['content'] = $_POST['content-'.$rowid];
371				if ($field == 'content_lines') $_POST['content_lines'] = $_POST['content_lines-'.$rowid];
372				if ($field == 'entity') $_POST[$keycode] = $conf->entity;
373
374				if ($i) $sql .= ", ";
375				$sql .= $field."=";
376
377				if (GETPOST($keycode) == '' || ($keycode != 'langcode' && $keycode != 'position' && $keycode != 'private' && !GETPOST($keycode))) $sql .= "null"; // langcode,... must be '' if not defined so the unique key that include lang will work
378				elseif (GETPOST($keycode) == '0' && $keycode == 'langcode') $sql .= "''"; // langcode must be '' if not defined so the unique key that include lang will work
379				elseif ($keycode == 'fk_user') {
380					if (!$user->admin) {	// A non admin user can only edit its own template
381						$sql .= " ".((int) $user->id);
382					} else {
383						$sql .= " ".((int) GETPOST($keycode, 'int'));
384					}
385				} elseif ($keycode == 'content') {
386					$sql .= "'".$db->escape(GETPOST($keycode, 'restricthtml'))."'";
387				} elseif (in_array($keycode, array('joinfiles', 'private', 'position'))) {
388					$sql .= (int) GETPOST($keycode, 'int');
389				} else {
390					$sql .= "'".$db->escape(GETPOST($keycode, 'nohtml'))."'";
391				}
392
393				$i++;
394			}
395
396			$sql .= " WHERE ".$rowidcol." = ".((int) $rowid);
397			if (!$user->admin) {	// A non admin user can only edit its own template
398				$sql .= " AND fk_user  = ".((int) $user->id);
399			}
400			//print $sql;exit;
401			dol_syslog("actionmodify", LOG_DEBUG);
402			//print $sql;
403			$resql = $db->query($sql);
404			if ($resql)
405			{
406				setEventMessages($langs->transnoentities("RecordSaved"), null, 'mesgs');
407			} else {
408				setEventMessages($db->error(), null, 'errors');
409			}
410		}
411	}
412
413	if ($action == 'confirm_delete' && $confirm == 'yes')       // delete
414	{
415		$rowidcol = "rowid";
416
417		$sql = "DELETE from ".$tabname[$id]." WHERE ".$rowidcol."=".((int) $rowid);
418		if (!$user->admin) {	// A non admin user can only edit its own template
419			$sql .= " AND fk_user  = ".((int) $user->id);
420		}
421		dol_syslog("delete", LOG_DEBUG);
422		$result = $db->query($sql);
423		if (!$result)
424		{
425			if ($db->errno() == 'DB_ERROR_CHILD_EXISTS')
426			{
427				setEventMessages($langs->transnoentities("ErrorRecordIsUsedByChild"), null, 'errors');
428			} else {
429				dol_print_error($db);
430			}
431		}
432	}
433
434	// activate
435	if ($action == $acts[0])
436	{
437		$rowidcol = "rowid";
438
439		$sql = "UPDATE ".$tabname[$id]." SET active = 1 WHERE ".$rowidcol."=".((int) $rowid);
440
441		$result = $db->query($sql);
442		if (!$result)
443		{
444			dol_print_error($db);
445		}
446	}
447
448	// disable
449	if ($action == $acts[1])
450	{
451		$rowidcol = "rowid";
452
453		$sql = "UPDATE ".$tabname[$id]." SET active = 0 WHERE ".$rowidcol."=".((int) $rowid);
454
455		$result = $db->query($sql);
456		if (!$result)
457		{
458			dol_print_error($db);
459		}
460	}
461}
462
463
464/*
465 * View
466 */
467
468$form = new Form($db);
469$formadmin = new FormAdmin($db);
470
471$help_url = '';
472$title = $langs->trans("EMailsSetup");
473
474llxHeader('', $title, $help_url);
475
476$linkback = '';
477$titlepicto = 'title_setup';
478
479print load_fiche_titre($title, $linkback, $titlepicto);
480
481$head = email_admin_prepare_head();
482
483print dol_get_fiche_head($head, 'templates', '', -1);
484
485// Confirmation de la suppression de la ligne
486if ($action == 'delete')
487{
488	print $form->formconfirm($_SERVER["PHP_SELF"].'?'.($page ? 'page='.$page.'&' : '').'sortfield='.$sortfield.'&sortorder='.$sortorder.'&rowid='.$rowid.'&code='.$code.'&id='.$id, $langs->trans('DeleteLine'), $langs->trans('ConfirmDeleteLine'), 'confirm_delete', '', 0, 1);
489}
490
491
492$sql = "SELECT rowid as rowid, module, label, type_template, lang, fk_user, private, position, topic, joinfiles, content_lines, content, enabled, active";
493$sql .= " FROM ".MAIN_DB_PREFIX."c_email_templates";
494$sql .= " WHERE entity IN (".getEntity('email_template').")";
495if (!$user->admin)
496{
497	$sql .= " AND (private = 0 OR (private = 1 AND fk_user = ".$user->id."))"; // Show only public and private to me
498	$sql .= " AND (active = 1 OR fk_user = ".$user->id.")"; // Show only active or owned by me
499}
500if (empty($conf->global->MAIN_MULTILANGS))
501{
502	$sql .= " AND (lang = '".$db->escape($langs->defaultlang)."' OR lang IS NULL OR lang = '')";
503}
504if ($search_label) $sql .= natural_search('label', $search_label);
505if ($search_type_template != '' && $search_type_template != '-1') $sql .= natural_search('type_template', $search_type_template);
506if ($search_lang) $sql .= natural_search('lang', $search_lang);
507if ($search_fk_user != '' && $search_fk_user != '-1') $sql .= natural_search('fk_user', $search_fk_user, 2);
508if ($search_topic) $sql .= natural_search('topic', $search_topic);
509// If sort order is "country", we use country_code instead
510if ($sortfield == 'country') $sortfield = 'country_code';
511$sql .= $db->order($sortfield, $sortorder);
512$sql .= $db->plimit($listlimit + 1, $offset);
513//print $sql;
514
515$fieldlist = explode(',', $tabfield[$id]);
516
517if ($action == 'view') {
518	// Form to add a new line
519	print '<form action="'.$_SERVER['PHP_SELF'].'?id='.$id.'" method="POST">';
520	print '<input type="hidden" name="token" value="'.newToken().'">';
521	print '<input type="hidden" name="from" value="'.dol_escape_htmltag(GETPOST('from', 'alpha')).'">';
522
523	print '<div class="div-table-responsive-no-min">';
524	print '<table class="noborder centpercent">';
525
526	// Line to enter new values (title)
527	print '<tr class="liste_titre">';
528	foreach ($fieldlist as $field => $value)
529	{
530		// Determine le nom du champ par rapport aux noms possibles
531		// dans les dictionnaires de donnees
532		$valuetoshow = ucfirst($fieldlist[$field]); // Par defaut
533		$valuetoshow = $langs->trans($valuetoshow); // try to translate
534		$align = "left";
535		if ($fieldlist[$field] == 'fk_user') { $valuetoshow = $langs->trans("Owner"); }
536		if ($fieldlist[$field] == 'lang') { $valuetoshow = (empty($conf->global->MAIN_MULTILANGS) ? '&nbsp;' : $langs->trans("Language")); }
537		if ($fieldlist[$field] == 'type') { $valuetoshow = $langs->trans("Type"); }
538		if ($fieldlist[$field] == 'code') { $valuetoshow = $langs->trans("Code"); }
539		if ($fieldlist[$field] == 'libelle' || $fieldlist[$field] == 'label') { $valuetoshow = $langs->trans("Code"); }
540		if ($fieldlist[$field] == 'type_template') { $valuetoshow = $langs->trans("TypeOfTemplate"); $align = "center"; }
541		if ($fieldlist[$field] == 'private') { $align = 'center'; }
542		if ($fieldlist[$field] == 'position') { $align = 'center'; }
543
544		if ($fieldlist[$field] == 'topic') { $valuetoshow = ''; }
545		if ($fieldlist[$field] == 'joinfiles') { $valuetoshow = ''; }
546		if ($fieldlist[$field] == 'content') { $valuetoshow = ''; }
547		if ($fieldlist[$field] == 'content_lines') { $valuetoshow = ''; }
548
549		if ($valuetoshow != '')
550		{
551			print '<td class="'.$align.'">';
552			if (!empty($tabhelp[$id][$value]) && preg_match('/^http(s*):/i', $tabhelp[$id][$value])) print '<a href="'.$tabhelp[$id][$value].'" target="_blank">'.$valuetoshow.' '.img_help(1, $valuetoshow).'</a>';
553			elseif (!empty($tabhelp[$id][$value]))
554			{
555				if (in_array($value, array('topic'))) print $form->textwithpicto($valuetoshow, $tabhelp[$id][$value], 1, 'help', '', 0, 2, $value); // Tooltip on click
556				else print $form->textwithpicto($valuetoshow, $tabhelp[$id][$value], 1, 'help', '', 0, 2); // Tooltip on hover
557			} else print $valuetoshow;
558			print '</td>';
559		}
560	}
561	print '<td>';
562	print '<input type="hidden" name="id" value="'.$id.'">';
563	print '</td>';
564	print '</tr>';
565
566	$obj = new stdClass();
567	// If data was already input, we define them in obj to populate input fields.
568	if (GETPOST('actionadd'))
569	{
570		foreach ($fieldlist as $key => $val) {
571			if (GETPOST($val) != '')
572			$obj->$val = GETPOST($val);
573		}
574	}
575
576	$tmpaction = 'create';
577	$parameters = array(
578	'fieldlist' => $fieldlist,
579	'tabname' => $tabname[$id]
580	);
581	$reshook = $hookmanager->executeHooks('createEmailTemplateFieldlist', $parameters, $obj, $tmpaction); // Note that $action and $object may have been modified by some hooks
582	$error = $hookmanager->error;
583	$errors = $hookmanager->errors;
584
585
586	// Line to enter new values (input fields)
587	print '<tr class="oddeven">';
588
589	if (empty($reshook))
590	{
591		if ($action == 'edit') {
592			fieldList($fieldlist, $obj, $tabname[$id], 'hide');
593		} else {
594			fieldList($fieldlist, $obj, $tabname[$id], 'add');
595		}
596	}
597
598	print '<td class="right">';
599	print '</td>';
600	print "</tr>";
601
602	// Show fields for topic, join files and body
603	$fieldsforcontent = array('topic', 'joinfiles', 'content');
604	if (!empty($conf->global->MAIN_EMAIL_TEMPLATES_FOR_OBJECT_LINES)) { $fieldsforcontent = array('topic', 'joinfiles', 'content', 'content_lines'); }
605	foreach ($fieldsforcontent as $tmpfieldlist)
606	{
607		print '<tr class="impair nodrag nodrop nohover"><td colspan="6" class="nobottom">';
608
609		// Label
610		if ($tmpfieldlist == 'topic')
611		{
612			print '<strong>'.$form->textwithpicto($langs->trans("Topic"), $tabhelp[$id][$tmpfieldlist], 1, 'help', '', 0, 2, $tmpfieldlist).'</strong> ';
613		}
614		if ($tmpfieldlist == 'joinfiles')
615		{
616			print '<strong>'.$form->textwithpicto($langs->trans("FilesAttachedToEmail"), $tabhelp[$id][$tmpfieldlist], 1, 'help', '', 0, 2, $tmpfieldlist).'</strong> ';
617		}
618		if ($tmpfieldlist == 'content')
619		print $form->textwithpicto($langs->trans("Content"), $tabhelp[$id][$tmpfieldlist], 1, 'help', '', 0, 2, $tmpfieldlist).'<br>';
620		if ($tmpfieldlist == 'content_lines')
621		print $form->textwithpicto($langs->trans("ContentForLines"), $tabhelp[$id][$tmpfieldlist], 1, 'help', '', 0, 2, $tmpfieldlist).'<br>';
622
623		// Input field
624		if ($tmpfieldlist == 'topic') {
625			print '<input type="text" class="flat minwidth500" name="'.$tmpfieldlist.'" value="'.(!empty($obj->{$tmpfieldlist}) ? $obj->{$tmpfieldlist} : '').'">';
626		} elseif ($tmpfieldlist == 'joinfiles') {
627			print '<input type="text" class="flat maxwidth50" name="'.$tmpfieldlist.'" value="'.(isset($obj->{$tmpfieldlist}) ? $obj->{$tmpfieldlist} : '1').'">';
628		} else {
629			// print '<textarea cols="3" rows="'.ROWS_2.'" class="flat" name="'.$fieldlist[$field].'">'.(! empty($obj->{$fieldlist[$field]})?$obj->{$fieldlist[$field]}:'').'</textarea>';
630			$okforextended = true;
631			if (empty($conf->global->FCKEDITOR_ENABLE_MAIL))
632			$okforextended = false;
633			$doleditor = new DolEditor($tmpfieldlist, (!empty($obj->{$tmpfieldlist}) ? $obj->{$tmpfieldlist} : ''), '', 180, 'dolibarr_mailings', 'In', 0, false, $okforextended, ROWS_4, '90%');
634			print $doleditor->Create(1);
635		}
636		print '</td>';
637		if ($tmpfieldlist == 'topic') {
638			print '<td class="center" rowspan="'.(count($fieldsforcontent)).'">';
639			if ($action != 'edit') {
640				print '<input type="submit" class="button" name="actionadd" value="'.$langs->trans("Add").'">';
641			}
642			print '</td>';
643		}
644		// else print '<td></td>';
645		print '</tr>';
646	}
647
648	print '</table>';
649	print '</div>';
650	print '</form>';
651	print '<br>';
652} // END IF not edit
653
654print '<form action="'.$_SERVER['PHP_SELF'].'?id='.$id.'" method="POST">';
655print '<input type="hidden" name="token" value="'.newToken().'">';
656print '<input type="hidden" name="from" value="'.dol_escape_htmltag(GETPOST('from', 'alpha')).'">';
657
658print '<div class="div-table-responsive-no-min">';
659print '<table class="noborder centpercent">';
660
661// List of available record in database
662dol_syslog("htdocs/admin/dict", LOG_DEBUG);
663$resql = $db->query($sql);
664if ($resql)
665{
666	$num = $db->num_rows($resql);
667	$i = 0;
668
669	$param = '&id='.$id;
670	if ($search_label)                 $param .= '&search_label='.urlencode($search_label);
671	if ($search_lang > 0)              $param .= '&search_lang='.urlencode($search_lang);
672	if ($search_type_template != '-1') $param .= '&search_type_template='.urlencode($search_type_template);
673	if ($search_fk_user > 0)           $param .= '&search_fk_user='.urlencode($search_fk_user);
674	if ($search_topic)                 $param .= '&search_topic='.urlencode($search_topic);
675
676	$paramwithsearch = $param;
677	if ($sortorder) $paramwithsearch .= '&sortorder='.urlencode($sortorder);
678	if ($sortfield) $paramwithsearch .= '&sortfield='.urlencode($sortfield);
679	if (GETPOST('from', 'alpha')) $paramwithsearch .= '&from='.urlencode(GETPOST('from', 'alpha'));
680
681	// There is several pages
682	if ($num > $listlimit)
683	{
684		print '<tr class="none"><td class="right" colspan="'.(3 + count($fieldlist)).'">';
685		print_fleche_navigation($page, $_SERVER["PHP_SELF"], $paramwithsearch, ($num > $listlimit), '<li class="pagination"><span>'.$langs->trans("Page").' '.($page + 1).'</span></li>');
686		print '</td></tr>';
687	}
688
689
690	// Title line with search boxes
691	print '<tr class="liste_titre">';
692
693	foreach ($fieldlist as $field => $value)
694	{
695		if ($value == 'label') {
696			print '<td class="liste_titre"><input type="text" name="search_label" class="maxwidth200" value="'.dol_escape_htmltag($search_label).'"></td>';
697		} elseif ($value == 'lang') {
698			print '<td class="liste_titre">';
699			print $formadmin->select_language($search_lang, 'search_lang', 0, null, 1, 0, 0, 'maxwidth150');
700			print '</td>';
701		} elseif ($value == 'fk_user') {
702			print '<td class="liste_titre">';
703			print $form->select_dolusers($search_fk_user, 'search_fk_user', 1, null, 0, ($user->admin ? '' : 'hierarchyme'), null, 0, 0, 1, '', 0, '', 'maxwidth150');
704			print '</td>';
705		} elseif ($value == 'topic') {
706			print '<td class="liste_titre"><input type="text" name="search_topic" value="'.dol_escape_htmltag($search_topic).'"></td>';
707		} elseif ($value == 'type_template') {
708			print '<td class="liste_titre center">';
709			print $form->selectarray('search_type_template', $elementList, $search_type_template, 1, 0, 0, '', 0, 0, 0, '', 'maxwidth200', 1, '', 0, 1);
710			print '</td>';
711		} elseif (!in_array($value, array('content', 'content_lines'))) {
712			print '<td class="liste_titre"></td>';
713		}
714	}
715
716	if (empty($conf->global->MAIN_EMAIL_TEMPLATES_FOR_OBJECT_LINES)) print '<td class="liste_titre"></td>';
717
718	// Action column
719	print '<td class="liste_titre right" width="64">';
720	$searchpicto = $form->showFilterButtons();
721	print $searchpicto;
722	print '</td>';
723	print '</tr>';
724
725	// Title of lines
726	print '<tr class="liste_titre">';
727	foreach ($fieldlist as $field => $value)
728	{
729		$showfield = 1; // By defaut
730		$align = "left";
731		$sortable = 1;
732		$valuetoshow = '';
733		$forcenowrap = 1;
734		/*
735        $tmparray=getLabelOfField($fieldlist[$field]);
736        $showfield=$tmp['showfield'];
737        $valuetoshow=$tmp['valuetoshow'];
738        $align=$tmp['align'];
739        $sortable=$tmp['sortable'];
740		*/
741		$valuetoshow = ucfirst($fieldlist[$field]); // By defaut
742		$valuetoshow = $langs->trans($valuetoshow); // try to translate
743		if ($fieldlist[$field] == 'fk_user') { $valuetoshow = $langs->trans("Owner"); }
744		if ($fieldlist[$field] == 'lang') { $valuetoshow = $langs->trans("Language"); }
745		if ($fieldlist[$field] == 'type') { $valuetoshow = $langs->trans("Type"); }
746		if ($fieldlist[$field] == 'libelle' || $fieldlist[$field] == 'label') { $valuetoshow = $langs->trans("Code"); }
747		if ($fieldlist[$field] == 'type_template') { $valuetoshow = $langs->trans("TypeOfTemplate"); }
748		if ($fieldlist[$field] == 'private') { $align = 'center'; }
749		if ($fieldlist[$field] == 'position') { $align = 'center'; }
750
751		if ($fieldlist[$field] == 'joinfiles') { $valuetoshow = $langs->trans("FilesAttachedToEmail"); $align = 'center'; $forcenowrap = 0; }
752		if ($fieldlist[$field] == 'content') { $valuetoshow = $langs->trans("Content"); $showfield = 0; }
753		if ($fieldlist[$field] == 'content_lines') { $valuetoshow = $langs->trans("ContentLines"); $showfield = 0; }
754
755		// Show fields
756		if ($showfield)
757		{
758			if (!empty($tabhelp[$id][$value]))
759			{
760				if (in_array($value, array('topic'))) $valuetoshow = $form->textwithpicto($valuetoshow, $tabhelp[$id][$value], 1, 'help', '', 0, 2, 'tooltip'.$value, $forcenowrap); // Tooltip on click
761				else $valuetoshow = $form->textwithpicto($valuetoshow, $tabhelp[$id][$value], 1, 'help', '', 0, 2, '', $forcenowrap); // Tooltip on hover
762			}
763			print getTitleFieldOfList($valuetoshow, 0, $_SERVER["PHP_SELF"], ($sortable ? $fieldlist[$field] : ''), ($page ? 'page='.$page.'&' : ''), $param, "align=".$align, $sortfield, $sortorder);
764		}
765	}
766
767	print getTitleFieldOfList($langs->trans("Status"), 0, $_SERVER["PHP_SELF"], "active", ($page ? 'page='.$page.'&' : ''), $param, 'align="center"', $sortfield, $sortorder);
768	print getTitleFieldOfList('');
769	print '</tr>';
770
771	if ($num)
772	{
773		// Lines with values
774		while ($i < $num)
775		{
776			$obj = $db->fetch_object($resql);
777
778			if ($action == 'edit' && ($rowid == (!empty($obj->rowid) ? $obj->rowid : $obj->code)))
779			{
780				print '<tr class="oddeven" id="rowid-'.$obj->rowid.'">';
781
782				$tmpaction = 'edit';
783				$parameters = array('fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]);
784				$reshook = $hookmanager->executeHooks('editEmailTemplateFieldlist', $parameters, $obj, $tmpaction); // Note that $action and $object may have been modified by some hooks
785				$error = $hookmanager->error; $errors = $hookmanager->errors;
786
787				// Show fields
788				if (empty($reshook)) fieldList($fieldlist, $obj, $tabname[$id], 'edit');
789
790				print '<td></td><td></td><td></td>';
791				print '<td class="center">';
792				print '<input type="hidden" name="page" value="'.$page.'">';
793				print '<input type="hidden" name="rowid" value="'.$rowid.'">';
794				print '<input type="submit" class="button buttongen" name="actionmodify" value="'.$langs->trans("Modify").'">';
795				print '<div name="'.(!empty($obj->rowid) ? $obj->rowid : $obj->code).'"></div>';
796				print '<input type="submit" class="button buttongen button-cancel" name="actioncancel" value="'.$langs->trans("Cancel").'">';
797				print '</td>';
798
799				$fieldsforcontent = array('topic', 'joinfiles', 'content');
800				if (!empty($conf->global->MAIN_EMAIL_TEMPLATES_FOR_OBJECT_LINES))
801				{
802					$fieldsforcontent = array('topic', 'joinfiles', 'content', 'content_lines');
803				}
804				foreach ($fieldsforcontent as $tmpfieldlist)
805				{
806					$showfield = 1;
807					$align = "left";
808					$valuetoshow = $obj->{$tmpfieldlist};
809
810					$class = 'tddict';
811					// Show value for field
812					if ($showfield) {
813						// Show line for topic, joinfiles and content
814						print '</tr><tr class="oddeven" nohover tr-'.$tmpfieldlist.'-'.$rowid.' ">';
815						print '<td colspan="8">';
816						if ($tmpfieldlist == 'topic')
817						{
818							print '<strong>'.$form->textwithpicto($langs->trans("Topic"), $tabhelp[$id][$tmpfieldlist], 1, 'help', '', 0, 2, $tmpfieldlist).'</strong> ';
819							print '<input type="text" class="flat minwidth500" name="'.$tmpfieldlist.'-'.$rowid.'" value="'.(!empty($obj->{$tmpfieldlist}) ? $obj->{$tmpfieldlist} : '').'">';
820						}
821						if ($tmpfieldlist == 'joinfiles')
822						{
823							print '<strong>'.$form->textwithpicto($langs->trans("FilesAttachedToEmail"), $tabhelp[$id][$tmpfieldlist], 1, 'help', '', 0, 2, $tmpfieldlist).'</strong> ';
824							print '<input type="text" class="flat maxwidth50" name="'.$tmpfieldlist.'-'.$rowid.'" value="'.(!empty($obj->{$tmpfieldlist}) ? $obj->{$tmpfieldlist} : '').'">';
825						}
826						if ($tmpfieldlist == 'content')
827						{
828							print $form->textwithpicto($langs->trans("Content"), $tabhelp[$id][$tmpfieldlist], 1, 'help', '', 0, 2, $tmpfieldlist).'<br>';
829							$okforextended = true;
830							if (empty($conf->global->FCKEDITOR_ENABLE_MAIL)) $okforextended = false;
831							$doleditor = new DolEditor($tmpfieldlist.'-'.$rowid, (!empty($obj->{$tmpfieldlist}) ? $obj->{$tmpfieldlist} : ''), '', 500, 'dolibarr_mailings', 'In', 0, false, $okforextended, ROWS_6, '90%');
832							print $doleditor->Create(1);
833						}
834						print '</td>';
835						print '<td></td>';
836						print '<td></td>';
837					}
838				}
839
840				print "</tr>\n";
841			} else {
842				// If template is for a module, check module is enabled.
843				if ($obj->module) {
844					$tempmodulekey = $obj->module;
845					if (empty($conf->$tempmodulekey) || empty($conf->$tempmodulekey->enabled)) {
846						$i++;
847						continue;
848					}
849				}
850
851				$keyforobj = 'type_template';
852				if (!in_array($obj->$keyforobj, array_keys($elementList)))
853				{
854					$i++;
855					continue; // It means this is a type of template not into elementList (may be because enabled condition of this type is false because module is not enabled)
856				}
857				// Test on 'enabled'
858				if (!dol_eval($obj->enabled, 1))
859				{
860					$i++;
861					continue; // Email template not qualified
862				}
863
864				print '<tr class="oddeven" id="rowid-'.$obj->rowid.'">';
865
866				$tmpaction = 'view';
867				$parameters = array('var'=>$var, 'fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]);
868				$reshook = $hookmanager->executeHooks('viewEmailTemplateFieldlist', $parameters, $obj, $tmpaction); // Note that $action and $object may have been modified by some hooks
869
870				$error = $hookmanager->error; $errors = $hookmanager->errors;
871
872				if (empty($reshook))
873				{
874					foreach ($fieldlist as $field => $value)
875					{
876						if (in_array($fieldlist[$field], array('content', 'content_lines'))) continue;
877						$showfield = 1;
878						$align = "";
879						$class = "tddict";
880						$valuetoshow = $obj->{$fieldlist[$field]};
881						if ($value == 'label' || $value == 'topic') {
882							$valuetoshow = dol_escape_htmltag($valuetoshow);
883						}
884						if ($value == 'label') {
885							$class .= ' tdoverflowmax100';
886						}
887						/*if ($value == 'topic') {
888							$class .= ' tdoverflowmax300';
889						}*/
890						if ($value == 'type_template') {
891							$valuetoshow = isset($elementList[$valuetoshow]) ? $elementList[$valuetoshow] : $valuetoshow;
892							$align = "center";
893						}
894						if ($value == 'lang' && $valuetoshow) {
895							$valuetoshow = $valuetoshow.' - '.$langs->trans("Language_".$valuetoshow);
896						}
897						if ($value == 'fk_user') {
898							if ($valuetoshow > 0)
899							{
900								$fuser = new User($db);
901								$fuser->fetch($valuetoshow);
902								$valuetoshow = $fuser->getNomUrl(1);
903							}
904						}
905						if ($value == 'private') {
906							$align = "center";
907							if ($valuetoshow) $valuetoshow = yn($valuetoshow);
908							else $valuetoshow = '';
909						}
910						if ($value == 'position') {
911							$align = "center";
912						}
913						if ($value == 'joinfiles') {
914							$align = "center";
915							if ($valuetoshow) $valuetoshow = 1;
916							else $valuetoshow = '';
917						}
918						if ($align) $class .= ' '.$align;
919
920						// Show value for field
921						if ($showfield) {
922						   	print '<!-- '.$fieldlist[$field].' -->';
923						   	print '<td class="'.$class.'">'.$valuetoshow.'</td>';
924						}
925					}
926				}
927
928				// Can an entry be erased or disabled ?
929				$iserasable = 1; $canbedisabled = 1; $canbemodified = 1; // true by default
930				if (!$user->admin && $obj->fk_user != $user->id)
931				{
932					$iserasable = 0;
933					$canbedisabled = 0;
934					$canbemodified = 0;
935				}
936
937				$url = $_SERVER["PHP_SELF"].'?'.($page ? 'page='.$page.'&' : '').'sortfield='.$sortfield.'&sortorder='.$sortorder.'&rowid='.(!empty($obj->rowid) ? $obj->rowid : (!empty($obj->code) ? $obj->code : '')).'&code='.(!empty($obj->code) ?urlencode($obj->code) : '');
938				if ($param) $url .= '&'.$param;
939				$url .= '&';
940
941				// Status / Active
942				print '<td class="center nowrap">';
943				if ($canbedisabled) print '<a href="'.$url.'action='.$acts[$obj->active].'">'.$actl[$obj->active].'</a>';
944				else print '<span class="opacitymedium">'.$actl[$obj->active].'</span>';
945				print "</td>";
946
947				// Modify link / Delete link
948				print '<td class="center nowraponall" width="64">';
949				if ($canbemodified) print '<a class="reposition editfielda" href="'.$url.'action=edit&token='.newToken().'">'.img_edit().'</a>';
950				if ($iserasable)
951				{
952					print '<a class="marginleftonly" href="'.$url.'action=delete&token='.newToken().'">'.img_delete().'</a>';
953					//else print '<a href="#">'.img_delete().'</a>';    // Some dictionary can be edited by other profile than admin
954				}
955				print '</td>';
956
957				/*
958                $fieldsforcontent = array('content');
959                if (! empty($conf->global->MAIN_EMAIL_TEMPLATES_FOR_OBJECT_LINES))
960                {
961                    $fieldsforcontent = array('content', 'content_lines');
962                }
963                foreach ($fieldsforcontent as $tmpfieldlist)
964                {
965                    $showfield = 1;
966                    $align = "left";
967                    $valuetoshow = $obj->{$tmpfieldlist};
968
969                    $class = 'tddict';
970                    // Show value for field
971                    if ($showfield) {
972
973                        print '</tr><tr class="oddeven" nohover tr-'.$tmpfieldlist.'-'.$i.' "><td colspan="5">'; // To create an artificial CR for the current tr we are on
974                        $okforextended = true;
975                        if (empty($conf->global->FCKEDITOR_ENABLE_MAIL))
976                            $okforextended = false;
977                        $doleditor = new DolEditor($tmpfieldlist.'-'.$i, (! empty($obj->{$tmpfieldlist}) ? $obj->{$tmpfieldlist} : ''), '', 140, 'dolibarr_mailings', 'In', 0, false, $okforextended, ROWS_6, '90%', 1);
978                        print $doleditor->Create(1);
979                        print '</td>';
980                        print '<td></td><td></td><td></td>';
981
982                    }
983                }*/
984
985				print "</tr>\n";
986			}
987
988
989			$i++;
990		}
991	}
992} else {
993	dol_print_error($db);
994}
995
996print '</table>';
997print '</div>';
998
999print '</form>';
1000
1001
1002print dol_get_fiche_end();
1003
1004// End of page
1005llxFooter();
1006$db->close();
1007
1008
1009/**
1010 *	Show fields in insert/edit mode
1011 *
1012 * 	@param		array	$fieldlist		Array of fields
1013 * 	@param		Object	$obj			If we show a particular record, obj is filled with record fields
1014 *  @param		string	$tabname		Name of SQL table
1015 *  @param		string	$context		'add'=Output field for the "add form", 'edit'=Output field for the "edit form", 'hide'=Output field for the "add form" but we dont want it to be rendered
1016 *	@return		void
1017 */
1018function fieldList($fieldlist, $obj = '', $tabname = '', $context = '')
1019{
1020	global $conf, $langs, $user, $db;
1021	global $form;
1022	global $elementList;
1023
1024	$formadmin = new FormAdmin($db);
1025
1026	foreach ($fieldlist as $field => $value)
1027	{
1028		if ($fieldlist[$field] == 'fk_user')
1029		{
1030			print '<td>';
1031			if ($user->admin) {
1032				print $form->select_dolusers($obj->{$fieldlist[$field]}, 'fk_user', 1, null, 0, ($user->admin ? '' : 'hierarchyme'), null, 0, 0, 1, '', 0, '', 'maxwidth200');
1033			} else {
1034				if ($context == 'add')	// I am not admin and we show the add form
1035				{
1036					print $user->getNomUrl(1); // Me
1037					$forcedvalue = $user->id;
1038				} else {
1039					if ($obj && !empty($obj->{$fieldlist[$field]}) && $obj->{$fieldlist[$field]} > 0)
1040					{
1041						$fuser = new User($db);
1042						$fuser->fetch($obj->{$fieldlist[$field]});
1043						print $fuser->getNomUrl(1);
1044						$forcedvalue = $fuser->id;
1045					} else {
1046						$forcedvalue = $obj->{$fieldlist[$field]};
1047					}
1048				}
1049				$keyname = $fieldlist[$field];
1050				print '<input type="hidden" value="'.$forcedvalue.'" name="'.$keyname.'">';
1051			}
1052			print '</td>';
1053		} elseif ($fieldlist[$field] == 'lang')
1054		{
1055			print '<td>';
1056			if (!empty($conf->global->MAIN_MULTILANGS))
1057			{
1058				$selectedlang = GETPOSTISSET('langcode') ?GETPOST('langcode', 'aZ09') : $langs->defaultlang;
1059				if ($context == 'edit') $selectedlang = $obj->{$fieldlist[$field]};
1060				print $formadmin->select_language($selectedlang, 'langcode', 0, null, 1, 0, 0, 'maxwidth150');
1061			} else {
1062				if (!empty($obj->{$fieldlist[$field]}))
1063				{
1064					print $obj->{$fieldlist[$field]}.' - '.$langs->trans('Language_'.$obj->{$fieldlist[$field]});
1065				}
1066				$keyname = $fieldlist[$field];
1067				if ($keyname == 'lang') $keyname = 'langcode'; // Avoid conflict with lang param
1068				print '<input type="hidden" value="'.$obj->{$fieldlist[$field]}.'" name="'.$keyname.'">';
1069			}
1070			print '</td>';
1071		}
1072		// Le type de template
1073		elseif ($fieldlist[$field] == 'type_template')
1074		{
1075			print '<td class="center">';
1076			if ($context == 'edit' && !empty($obj->{$fieldlist[$field]}) && !in_array($obj->{$fieldlist[$field]}, array_keys($elementList)))
1077			{
1078				// Current template type is an unknown type, so we must keep it as it is.
1079				print '<input type="hidden" name="type_template" value="'.$obj->{$fieldlist[$field]}.'">';
1080				print $obj->{$fieldlist[$field]};
1081			} else {
1082				print $form->selectarray('type_template', $elementList, (!empty($obj->{$fieldlist[$field]}) ? $obj->{$fieldlist[$field]}:''), 1, 0, 0, '', 0, 0, 0, '', 'maxwidth200', 1, '', 0, 1);
1083			}
1084			print '</td>';
1085		} elseif ($context == 'add' && in_array($fieldlist[$field], array('topic', 'joinfiles', 'content', 'content_lines'))) continue;
1086		elseif ($context == 'edit' && in_array($fieldlist[$field], array('topic', 'joinfiles', 'content', 'content_lines'))) continue;
1087		elseif ($context == 'hide' && in_array($fieldlist[$field], array('topic', 'joinfiles', 'content', 'content_lines'))) continue;
1088		else {
1089			$size = ''; $class = ''; $classtd = '';
1090			if ($fieldlist[$field] == 'code') $class = 'maxwidth100';
1091			if ($fieldlist[$field] == 'label') $class = 'maxwidth200';
1092			if ($fieldlist[$field] == 'private') { $class = 'maxwidth50'; $classtd = 'center'; }
1093			if ($fieldlist[$field] == 'position') { $class = 'maxwidth50'; $classtd = 'center'; }
1094			if ($fieldlist[$field] == 'libelle') $class = 'quatrevingtpercent';
1095			if ($fieldlist[$field] == 'topic') $class = 'quatrevingtpercent';
1096			if ($fieldlist[$field] == 'sortorder' || $fieldlist[$field] == 'sens' || $fieldlist[$field] == 'category_type') $size = 'size="2" ';
1097
1098			print '<td'.($classtd ? ' class="'.$classtd.'"' : '').'>';
1099			if ($fieldlist[$field] == 'private')
1100			{
1101				if (empty($user->admin))
1102				{
1103					print $form->selectyesno($fieldlist[$field], '1', 1);
1104				} else {
1105					//print '<input type="text" '.$size.'class="flat'.($class?' '.$class:'').'" value="1" name="'.$fieldlist[$field].'">';
1106					print $form->selectyesno($fieldlist[$field], (isset($obj->{$fieldlist[$field]}) ? $obj->{$fieldlist[$field]}:''), 1);
1107				}
1108			} else {
1109				print '<input type="text" '.$size.'class="flat'.($class ? ' '.$class : '').'" value="'.(isset($obj->{$fieldlist[$field]}) ? $obj->{$fieldlist[$field]}:'').'" name="'.$fieldlist[$field].'">';
1110			}
1111			print '</td>';
1112		}
1113	}
1114}
1115