Passed
Branch develop (5cbde9)
by
unknown
26:38
created

fieldList()   F

Complexity

Conditions 40
Paths 1554

Size

Total Lines 115
Code Lines 69

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 40
eloc 69
c 1
b 0
f 0
nc 1554
nop 4
dl 0
loc 115
rs 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/* Copyright (C) 2004       Rodolphe Quiedeville    <[email protected]>
3
 * Copyright (C) 2004-2018  Laurent Destailleur     <[email protected]>
4
 * Copyright (C) 2004       Benoit Mortier          <[email protected]>
5
 * Copyright (C) 2005-2012  Regis Houssin           <[email protected]>
6
 * Copyright (C) 2010-2016  Juanjo Menent           <[email protected]>
7
 * Copyright (C) 2011-2018  Philippe Grand          <[email protected]>
8
 * Copyright (C) 2011       Remy Younes             <[email protected]>
9
 * Copyright (C) 2012-2015  Marcos García           <[email protected]>
10
 * Copyright (C) 2012       Christophe Battarel     <[email protected]>
11
 * Copyright (C) 2011-2016  Alexandre Spangaro      <[email protected]>
12
 * Copyright (C) 2015       Ferran Marcet           <[email protected]>
13
 * Copyright (C) 2016       Raphaël Doursenaud      <[email protected]>
14
 * Copyright (C) 2018       Frédéric France         <[email protected]>
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 <http://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
36
require '../main.inc.php';
37
require_once DOL_DOCUMENT_ROOT.'/core/class/html.formadmin.class.php';
38
require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php';
39
require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php';
40
require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
41
require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
42
require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php';
43
require_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', 'alpha')?GETPOST('action', 'alpha'):'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', 'alpha');
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
59
if (! empty($user->socid)) accessforbidden();
60
61
$acts[0] = "activate";
62
$acts[1] = "disable";
63
$actl[0] = img_picto($langs->trans("Disabled"), 'switch_off');
64
$actl[1] = img_picto($langs->trans("Activated"), 'switch_on');
65
66
$listoffset=GETPOST('listoffset', 'alpha');
67
$listlimit =GETPOST('listlimit', 'alpha')>0?GETPOST('listlimit', 'alpha'):1000;
68
$active = 1;
69
70
$sortfield = GETPOST("sortfield", 'alpha');
71
$sortorder = GETPOST("sortorder", 'alpha');
72
$page = GETPOST("page", 'int');
73
if (empty($page) || $page == -1) { $page = 0; }     // If $page is not defined, or '' or -1
74
$offset = $listlimit * $page ;
75
$pageprev = $page - 1;
76
$pagenext = $page + 1;
77
78
if (empty($sortfield)) $sortfield='type_template, lang, position, label';
79
if (empty($sortorder)) $sortorder='ASC';
80
81
// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
82
$hookmanager->initHooks(array('emailtemplates'));
83
84
// Name of SQL tables of dictionaries
85
$tabname=array();
86
$tabname[25]= MAIN_DB_PREFIX."c_email_templates";
87
88
// Nom des champs en resultat de select pour affichage du dictionnaire
89
$tabfield=array();
90
$tabfield[25]= "label,lang,type_template,fk_user,private,position,topic,joinfiles,content";
91
if (! empty($conf->global->MAIN_EMAIL_TEMPLATES_FOR_OBJECT_LINES)) $tabfield[25].=',content_lines';
92
93
// Nom des champs d'edition pour modification d'un enregistrement
94
$tabfieldvalue=array();
95
$tabfieldvalue[25]= "label,lang,type_template,fk_user,private,position,topic,joinfiles,content";
96
if (! empty($conf->global->MAIN_EMAIL_TEMPLATES_FOR_OBJECT_LINES)) $tabfieldvalue[25].=',content_lines';
97
98
// Nom des champs dans la table pour insertion d'un enregistrement
99
$tabfieldinsert=array();
100
$tabfieldinsert[25]= "label,lang,type_template,fk_user,private,position,topic,joinfiles,content";
101
if (! empty($conf->global->MAIN_EMAIL_TEMPLATES_FOR_OBJECT_LINES)) $tabfieldinsert[25].=',content_lines';
102
$tabfieldinsert[25].=',entity';     // Must be at end because not into other arrays
103
104
// Condition to show dictionary in setup page
105
$tabcond=array();
106
$tabcond[25]= true;
107
108
// List of help for fields
109
// Set MAIN_EMAIL_TEMPLATES_FOR_OBJECT_LINES to allow edit of template for lines
110
require_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
111
$formmail=new FormMail($db);
112
if (empty($conf->global->MAIN_EMAIL_TEMPLATES_FOR_OBJECT_LINES))
113
{
114
    $tmp=FormMail::getAvailableSubstitKey('formemail');
115
    $tmp['__(AnyTranslationKey)__']='Translation';
116
    $helpsubstit = $langs->trans("AvailableVariables").':<br>';
117
    $helpsubstitforlines = $langs->trans("AvailableVariables").':<br>';
118
    foreach($tmp as $key => $val)
119
    {
120
    	$helpsubstit.=$key.' -> '.$val.'<br>';
121
    	$helpsubstitforlines.=$key.' -> '.$val.'<br>';
122
    }
123
}
124
else
125
{
126
    $tmp=FormMail::getAvailableSubstitKey('formemailwithlines');
127
    $tmp['__(AnyTranslationKey)__']='Translation';
128
    $helpsubstit = $langs->trans("AvailableVariables").':<br>';
129
    $helpsubstitforlines = $langs->trans("AvailableVariables").':<br>';
130
    foreach($tmp as $key => $val)
131
    {
132
    	$helpsubstit.=$key.' -> '.$val.'<br>';
133
    }
134
    $tmp=FormMail::getAvailableSubstitKey('formemailforlines');
135
    foreach($tmp as $key => $val)
136
    {
137
    	$helpsubstitforlines.=$key.' -> '.$val.'<br>';
138
    }
139
}
140
141
142
$tabhelp=array();
143
$tabhelp[25] = array('topic'=>$helpsubstit,'joinfiles'=>$langs->trans('AttachMainDocByDefault'), 'content'=>$helpsubstit,'content_lines'=>$helpsubstitforlines,'type_template'=>$langs->trans("TemplateForElement"),'private'=>$langs->trans("TemplateIsVisibleByOwnerOnly"), 'position'=>$langs->trans("PositionIntoComboList"));
144
145
// List of check for fields (NOT USED YET)
146
$tabfieldcheck=array();
147
$tabfieldcheck[25] = array();
148
149
150
// Define elementList and sourceList (used for dictionary type of contacts "llx_c_type_contact")
151
$elementList = array();
152
$sourceList=array();
153
154
// We save list of template email Dolibarr can manage. This list can found by a grep into code on "->param['models']"
155
$elementList = array();
156
if ($conf->propal->enabled)            $elementList['propal_send']=$langs->trans('MailToSendProposal');
157
if ($conf->commande->enabled)          $elementList['order_send']=$langs->trans('MailToSendOrder');
158
if ($conf->facture->enabled)           $elementList['facture_send']=$langs->trans('MailToSendInvoice');
159
if ($conf->expedition->enabled)        $elementList['shipping_send']=$langs->trans('MailToSendShipment');
160
if ($conf->reception->enabled) 		   $elementList['reception_send']=$langs->trans('MailToSendReception');
161
if ($conf->ficheinter->enabled)        $elementList['fichinter_send']=$langs->trans('MailToSendIntervention');
162
if ($conf->supplier_proposal->enabled) $elementList['supplier_proposal_send']=$langs->trans('MailToSendSupplierRequestForQuotation');
163
if ($conf->fournisseur->enabled)       $elementList['order_supplier_send']=$langs->trans('MailToSendSupplierOrder');
164
if ($conf->fournisseur->enabled)       $elementList['invoice_supplier_send']=$langs->trans('MailToSendSupplierInvoice');
165
if ($conf->societe->enabled)           $elementList['thirdparty']=$langs->trans('MailToThirdparty');
166
if ($conf->adherent->enabled)          $elementList['member']=$langs->trans('MailToMember');
167
if ($conf->contrat->enabled)           $elementList['contract']=$langs->trans('MailToSendContract');
168
if ($conf->projet->enabled)            $elementList['project']=$langs->trans('MailToProject');
169
$elementList['user']=$langs->trans('MailToUser');
170
171
$parameters=array('elementList'=>$elementList);
172
$reshook=$hookmanager->executeHooks('emailElementlist', $parameters);    // Note that $action and $object may have been modified by some hooks
173
if ($reshook == 0) {
174
	foreach ($hookmanager->resArray as $item => $value) {
175
		$elementList[$item] = $value;
176
	}
177
}
178
179
// Add all and none after the sort
180
$elementList['all'] ='-- '.$langs->trans("All").' -- ('.$langs->trans('VisibleEverywhere').')';
181
$elementList['none']='-- '.$langs->trans("None").' -- ('.$langs->trans('VisibleNowhere').')';
182
183
asort($elementList);
184
185
$id = 25;
186
187
188
/*
189
 * Actions
190
 */
191
192
if (GETPOST('cancel', 'alpha')) { $action='list'; $massaction=''; }
193
if (! GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction=''; }
194
195
$parameters=array();
196
$reshook=$hookmanager->executeHooks('doActions', $parameters, $object, $action);    // Note that $action and $object may have been modified by some hooks
197
if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
198
199
if (empty($reshook))
200
{
201
    // Purge search criteria
202
    if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') ||GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers
203
    {
204
        $search_label='';
205
        $search_type_template='';
206
        $search_lang='';
207
        $search_fk_user='';
208
        $search_topic='';
209
        $toselect='';
210
        $search_array_options=array();
211
    }
212
213
    // Actions add or modify an entry into a dictionary
214
    if (GETPOST('actionadd', 'alpha') || GETPOST('actionmodify', 'alpha'))
215
    {
216
        $listfield=explode(',', str_replace(' ', '', $tabfield[$id]));
217
        $listfieldinsert=explode(',', $tabfieldinsert[$id]);
218
        $listfieldmodify=explode(',', $tabfieldinsert[$id]);
219
        $listfieldvalue=explode(',', $tabfieldvalue[$id]);
220
221
        // Check that all fields are filled
222
        $ok=1;
223
        foreach ($listfield as $f => $value)
224
        {
225
        	// Not mandatory fields
226
            if ($value == 'joinfiles') continue;
227
            if ($value == 'content') continue;
228
            if ($value == 'content_lines') continue;
229
230
            if (GETPOST('actionmodify', 'alpha') && $value == 'topic') $_POST['topic']=$_POST['topic-'.$rowid];
231
232
            if ((! isset($_POST[$value]) || $_POST[$value]=='' || $_POST[$value]=='-1') && $value != 'lang' && $value != 'fk_user' && $value != 'position')
233
            {
234
                $ok=0;
235
                $fieldnamekey=$listfield[$f];
236
                // We take translate key of field
237
                if ($fieldnamekey == 'libelle' || ($fieldnamekey == 'label'))  $fieldnamekey='Code';
238
                if ($fieldnamekey == 'code') $fieldnamekey = 'Code';
239
                if ($fieldnamekey == 'note') $fieldnamekey = 'Note';
240
                if ($fieldnamekey == 'type_template') $fieldnamekey = 'TypeOfTemplate';
241
                if ($fieldnamekey == 'fk_user') $fieldnamekey = 'Owner';
242
                if ($fieldnamekey == 'private') $fieldnamekey = 'Private';
243
                if ($fieldnamekey == 'position') $fieldnamekey = 'Position';
244
                if ($fieldnamekey == 'topic') $fieldnamekey = 'Topic';
245
246
                setEventMessages($langs->transnoentities("ErrorFieldRequired", $langs->transnoentities($fieldnamekey)), null, 'errors');
247
            }
248
        }
249
250
        // Si verif ok et action add, on ajoute la ligne
251
        if ($ok && GETPOST('actionadd'))
252
        {
253
            // Add new entry
254
            $sql = "INSERT INTO ".$tabname[$id]." (";
255
            // List of fields
256
            $sql.= $tabfieldinsert[$id];
257
            $sql.=",active)";
258
            $sql.= " VALUES(";
259
260
            // List of values
261
            $i=0;
262
            foreach ($listfieldinsert as $f => $value)
263
            {
264
            	//var_dump($i.' - '.$listfieldvalue[$i].' - '.$_POST[$listfieldvalue[$i]].' - '.$value);
265
            	$keycode=$listfieldvalue[$i];
266
            	if ($value == 'lang') $keycode='langcode';
267
                if ($value == 'entity') $_POST[$keycode] = $conf->entity;
268
                if ($i) $sql.=",";
269
                if ($value == 'fk_user' && ! ($_POST[$keycode] > 0)) $_POST[$keycode]='';
270
                if ($value == 'private' && ! is_numeric($_POST[$keycode])) $_POST[$keycode]='0';
271
                if ($value == 'position' && ! is_numeric($_POST[$keycode])) $_POST[$keycode]='1';
272
                if ($_POST[$keycode] == '' && $keycode != 'langcode')      $sql.="null";	// lang must be '' if not defined so the unique key that include lang will work
273
                elseif ($_POST[$keycode] == '0' && $keycode == 'langcode') $sql.="''";		// lang must be '' if not defined so the unique key that include lang will work
274
                else $sql.="'".$db->escape($_POST[$keycode])."'";
275
                $i++;
276
            }
277
            $sql.=",1)";
278
279
            dol_syslog("actionadd", LOG_DEBUG);
280
            $result = $db->query($sql);
281
            if ($result)	// Add is ok
282
            {
283
                setEventMessages($langs->transnoentities("RecordSaved"), null, 'mesgs');
284
            	$_POST=array('id'=>$id);	// Clean $_POST array, we keep only
285
            }
286
            else
287
            {
288
                if ($db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
289
                    setEventMessages($langs->transnoentities("ErrorRecordAlreadyExists"), null, 'errors');
290
                }
291
                else {
292
                    dol_print_error($db);
293
                }
294
            }
295
        }
296
297
        // Si verif ok et action modify, on modifie la ligne
298
        if ($ok && GETPOST('actionmodify'))
299
        {
300
            $rowidcol="rowid";
301
302
            // Modify entry
303
            $sql = "UPDATE ".$tabname[$id]." SET ";
304
            // Modifie valeur des champs
305
            $i = 0;
306
            foreach ($listfieldmodify as $field)
307
            {
308
            	$keycode=$listfieldvalue[$i];
309
            	if ($field == 'lang') $keycode='langcode';
310
311
                if ($field == 'fk_user' && ! ($_POST['fk_user'] > 0)) $_POST['fk_user']='';
312
            	if ($field == 'topic') $_POST['topic']=$_POST['topic-'.$rowid];
313
            	if ($field == 'joinfiles') $_POST['joinfiles']=$_POST['joinfiles-'.$rowid];
314
            	if ($field == 'content') $_POST['content']=$_POST['content-'.$rowid];
315
            	if ($field == 'content_lines') $_POST['content_lines']=$_POST['content_lines-'.$rowid];
316
                if ($field == 'entity') $_POST[$keycode] = $conf->entity;
317
                if ($i) $sql.=",";
318
                $sql.= $field."=";
319
320
                //print $keycode.' - '.$_POST[$keycode].'<br>';
321
                if ($_POST[$keycode] == '' || ($keycode != 'langcode' && $keycode != 'position' && $keycode != 'private' && empty($_POST[$keycode]))) $sql.="null";  // lang must be '' if not defined so the unique key that include lang will work
322
                elseif ($_POST[$keycode] == '0' && $keycode == 'langcode') $sql.="''";	// lang must be '' if not defined so the unique key that include lang will work
323
                elseif ($keycode == 'private') $sql.=((int) $_POST[$keycode]);	        // private must be 0 or 1
324
                elseif ($keycode == 'position')	$sql.=((int) $_POST[$keycode]);
325
                else $sql.="'".$db->escape($_POST[$keycode])."'";
326
                $i++;
327
            }
328
            $sql.= " WHERE ".$rowidcol." = '".$rowid."'";
329
//print $sql;exit;
330
            dol_syslog("actionmodify", LOG_DEBUG);
331
            //print $sql;
332
            $resql = $db->query($sql);
333
            if ($resql)
334
            {
335
            	setEventMessages($langs->transnoentities("RecordSaved"), null, 'mesgs');
336
            }
337
            else
338
            {
339
                setEventMessages($db->error(), null, 'errors');
340
            }
341
        }
342
    }
343
344
    if ($action == 'confirm_delete' && $confirm == 'yes')       // delete
345
    {
346
        $rowidcol="rowid";
347
348
        $sql = "DELETE from ".$tabname[$id]." WHERE ".$rowidcol."='".$rowid."'";
349
350
        dol_syslog("delete", LOG_DEBUG);
351
        $result = $db->query($sql);
352
        if (! $result)
353
        {
354
            if ($db->errno() == 'DB_ERROR_CHILD_EXISTS')
355
            {
356
                setEventMessages($langs->transnoentities("ErrorRecordIsUsedByChild"), null, 'errors');
357
            }
358
            else
359
            {
360
                dol_print_error($db);
361
            }
362
        }
363
    }
364
365
    // activate
366
    if ($action == $acts[0])
367
    {
368
        $rowidcol="rowid";
369
370
        $sql = "UPDATE ".$tabname[$id]." SET active = 1 WHERE ".$rowidcol."='".$rowid."'";
371
372
        $result = $db->query($sql);
373
        if (!$result)
374
        {
375
            dol_print_error($db);
376
        }
377
    }
378
379
    // disable
380
    if ($action == $acts[1])
381
    {
382
        $rowidcol="rowid";
383
384
        $sql = "UPDATE ".$tabname[$id]." SET active = 0 WHERE ".$rowidcol."='".$rowid."'";
385
386
        $result = $db->query($sql);
387
        if (!$result)
388
        {
389
            dol_print_error($db);
390
        }
391
    }
392
}
393
394
395
/*
396
 * View
397
 */
398
399
$form = new Form($db);
400
$formadmin=new FormAdmin($db);
401
402
llxHeader();
403
404
$titre=$langs->trans("EMailsSetup");
405
$linkback='';
406
$titlepicto='title_setup';
407
408
print load_fiche_titre($titre, $linkback, $titlepicto);
409
410
$head = email_admin_prepare_head();
411
412
dol_fiche_head($head, 'templates', '', -1);
413
414
// Confirmation de la suppression de la ligne
415
if ($action == 'delete')
416
{
417
    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);
1 ignored issue
show
Bug introduced by
Are you sure $page of type integer|string|string[] can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

417
    print $form->formconfirm($_SERVER["PHP_SELF"].'?'.($page?'page='./** @scrutinizer ignore-type */ $page.'&':'').'sortfield='.$sortfield.'&sortorder='.$sortorder.'&rowid='.$rowid.'&code='.$code.'&id='.$id, $langs->trans('DeleteLine'), $langs->trans('ConfirmDeleteLine'), 'confirm_delete', '', 0, 1);
Loading history...
418
}
419
//var_dump($elementList);
420
421
422
$sql="SELECT rowid as rowid, label, type_template, lang, fk_user, private, position, topic, joinfiles, content_lines, content, enabled, active";
423
$sql.=" FROM ".MAIN_DB_PREFIX."c_email_templates";
424
$sql.=" WHERE entity IN (".getEntity('email_template').")";
425
if (! $user->admin)
426
{
427
	$sql.=" AND (private = 0 OR (private = 1 AND fk_user = ".$user->id."))";	// Show only public and private to me
428
	$sql.=" AND (active = 1 OR fk_user = ".$user->id.")";						// Show only active or owned by me
429
}
430
if (empty($conf->global->MAIN_MULTILANGS))
431
{
432
	$sql.= " AND (lang = '".$langs->defaultlang."' OR lang IS NULL OR lang = '')";
433
}
434
if ($search_label) $sql.=natural_search('label', $search_label);
435
if ($search_type_template != '' && $search_type_template != '-1') $sql.=natural_search('type_template', $search_type_template);
436
if ($search_lang) $sql.=natural_search('lang', $search_lang);
437
if ($search_fk_user != '' && $search_fk_user != '-1') $sql.=natural_search('fk_user', $search_fk_user, 2);
438
if ($search_topic) $sql.=natural_search('topic', $search_topic);
439
// If sort order is "country", we use country_code instead
440
if ($sortfield == 'country') $sortfield='country_code';
441
$sql.=$db->order($sortfield, $sortorder);
442
$sql.=$db->plimit($listlimit+1, $offset);
443
//print $sql;
444
445
$fieldlist=explode(',', $tabfield[$id]);
446
447
// Form to add a new line
448
print '<form action="'.$_SERVER['PHP_SELF'].'?id='.$id.'" method="POST">';
449
print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
450
print '<input type="hidden" name="from" value="'.dol_escape_htmltag(GETPOST('from', 'alpha')).'">';
451
452
print '<div class="div-table-responsive-no-min">';
453
print '<table class="noborder" width="100%">';
454
455
// Line to enter new values (title)
456
print '<tr class="liste_titre">';
457
foreach ($fieldlist as $field => $value)
458
{
459
	// Determine le nom du champ par rapport aux noms possibles
460
	// dans les dictionnaires de donnees
461
	$valuetoshow=ucfirst($fieldlist[$field]);   // Par defaut
462
	$valuetoshow=$langs->trans($valuetoshow);   // try to translate
463
	$align="left";
464
	if ($fieldlist[$field]=='fk_user')         { $valuetoshow=$langs->trans("Owner");}
465
	if ($fieldlist[$field]=='lang')            { $valuetoshow=(empty($conf->global->MAIN_MULTILANGS) ? '&nbsp;' : $langs->trans("Language")); }
466
	if ($fieldlist[$field]=='type')            { $valuetoshow=$langs->trans("Type"); }
467
	if ($fieldlist[$field]=='code')            { $valuetoshow=$langs->trans("Code"); }
468
	if ($fieldlist[$field]=='libelle' || $fieldlist[$field]=='label') { $valuetoshow=$langs->trans("Code"); }
469
	if ($fieldlist[$field]=='type_template')   { $valuetoshow=$langs->trans("TypeOfTemplate"); }
470
	if ($fieldlist[$field]=='private')         { $align='center'; }
471
	if ($fieldlist[$field]=='position')        { $align='center'; }
472
473
	if ($fieldlist[$field]=='topic')           { $valuetoshow=''; }
474
	if ($fieldlist[$field]=='joinfiles')       { $valuetoshow=''; }
475
	if ($fieldlist[$field]=='content')         { $valuetoshow=''; }
476
	if ($fieldlist[$field]=='content_lines')   { $valuetoshow=''; }
477
478
	if ($valuetoshow != '')
479
	{
480
		print '<td align="'.$align.'">';
481
		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>';
482
		elseif (! empty($tabhelp[$id][$value]))
483
		{
484
			if (in_array($value, array('topic'))) print $form->textwithpicto($valuetoshow, $tabhelp[$id][$value], 1, 'help', '', 0, 2, $value);   // Tooltip on click
485
			else print $form->textwithpicto($valuetoshow, $tabhelp[$id][$value], 1, 'help', '', 0, 2);                             // Tooltip on hover
486
		}
487
		else print $valuetoshow;
488
		print '</td>';
489
	}
490
}
491
print '<td>';
492
print '<input type="hidden" name="id" value="' . $id . '">';
493
print '</td>';
494
print '</tr>';
495
496
$obj = new stdClass();
497
// If data was already input, we define them in obj to populate input fields.
498
if (GETPOST('actionadd'))
499
{
500
	foreach ($fieldlist as $key => $val) {
501
		if (GETPOST($val) != '')
502
			$obj->$val = GETPOST($val);
503
	}
504
}
505
506
$tmpaction = 'create';
507
$parameters = array(
508
	'fieldlist' => $fieldlist,
509
	'tabname' => $tabname[$id]
510
);
511
$reshook = $hookmanager->executeHooks('createEmailTemplateFieldlist', $parameters, $obj, $tmpaction); // Note that $action and $object may have been modified by some hooks
512
$error = $hookmanager->error;
513
$errors = $hookmanager->errors;
514
515
516
// Line to enter new values (input fields)
517
print "<tr " . $bcnd[$var] . ">";
518
519
if (empty($reshook))
520
{
521
	if ($action == 'edit') {
522
		fieldList($fieldlist, $obj, $tabname[$id], 'hide');
523
	} else {
524
		fieldList($fieldlist, $obj, $tabname[$id], 'add');
525
	}
526
}
527
528
print '<td class="right">';
529
print '</td>';
530
print "</tr>";
531
532
// Show fields for topic, join files and body
533
$fieldsforcontent = array('topic', 'joinfiles', 'content');
534
if (! empty($conf->global->MAIN_EMAIL_TEMPLATES_FOR_OBJECT_LINES)) { $fieldsforcontent = array('content','content_lines'); }
535
foreach ($fieldsforcontent as $tmpfieldlist)
536
{
537
	print '<tr class="impair nodrag nodrop nohover"><td colspan="6" class="nobottom">';
538
	// Label
539
	if ($tmpfieldlist == 'topic')
540
	{
541
		print '<strong>' . $form->textwithpicto($langs->trans("Topic"), $tabhelp[$id][$tmpfieldlist], 1, 'help', '', 0, 2, $tmpfieldlist) . '</strong> ';
542
	}
543
	if ($tmpfieldlist == 'joinfiles')
544
	{
545
		print '<strong>' . $form->textwithpicto($langs->trans("FilesAttachedToEmail"), $tabhelp[$id][$tmpfieldlist], 1, 'help', '', 0, 2, $tmpfieldlist) . '</strong> ';
546
	}
547
	if ($tmpfieldlist == 'content')
548
		print $form->textwithpicto($langs->trans("Content"), $tabhelp[$id][$tmpfieldlist], 1, 'help', '', 0, 2, $tmpfieldlist).'<br>';
549
	if ($tmpfieldlist == 'content_lines')
550
		print $form->textwithpicto($langs->trans("ContentForLines"), $tabhelp[$id][$tmpfieldlist], 1, 'help', '', 0, 2, $tmpfieldlist) . '<br>';
551
	// Input field
552
	if ($tmpfieldlist == 'topic') {
553
		print '<input type="text" class="flat minwidth500" name="'.$tmpfieldlist.'" value="' . (! empty($obj->{$tmpfieldlist}) ? $obj->{$tmpfieldlist} : '') . '">';
554
	}
555
	elseif ($tmpfieldlist == 'joinfiles') {
556
		print '<input type="text" class="flat maxwidth50" name="'.$tmpfieldlist.'" value="' . (isset($obj->{$tmpfieldlist}) ? $obj->{$tmpfieldlist} : '1') . '">';
557
	}
558
	else
559
	{
560
		if ($context != 'hide') {
561
			// print '<textarea cols="3" rows="'.ROWS_2.'" class="flat" name="'.$fieldlist[$field].'">'.(! empty($obj->{$fieldlist[$field]})?$obj->{$fieldlist[$field]}:'').'</textarea>';
562
			$okforextended = true;
563
			if (empty($conf->global->FCKEDITOR_ENABLE_MAIL))
564
				$okforextended = false;
565
			$doleditor = new DolEditor($tmpfieldlist, (! empty($obj->{$tmpfieldlist}) ? $obj->{$tmpfieldlist} : ''), '', 120, 'dolibarr_mailings', 'In', 0, false, $okforextended, ROWS_4, '90%');
566
			print $doleditor->Create(1);
567
		}
568
		else
569
			print '&nbsp;';
570
	}
571
	print '</td>';
572
	if ($tmpfieldlist == 'topic') {
573
		print '<td align="center" rowspan="' . (count($fieldsforcontent)) . '">';
574
		if ($action != 'edit') {
575
			print '<input type="submit" class="button" name="actionadd" value="' . $langs->trans("Add") . '">';
576
		}
577
		print '</td>';
578
	}
579
	// else print '<td></td>';
580
	print '</tr>';
581
}
582
583
584
585
$colspan=count($fieldlist)+1;
586
//print '<tr><td colspan="'.$colspan.'">&nbsp;</td></tr>';	// Keep &nbsp; to have a line with enough height
587
588
print '</table>';
589
print '</div>';
590
print '</form>';
591
print '<br>';
592
593
594
print '<form action="'.$_SERVER['PHP_SELF'].'?id='.$id.'" method="POST">';
595
print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
596
print '<input type="hidden" name="from" value="'.dol_escape_htmltag(GETPOST('from', 'alpha')).'">';
597
598
print '<div class="div-table-responsive-no-min">';
599
print '<table class="noborder" width="100%">';
600
601
// List of available record in database
602
dol_syslog("htdocs/admin/dict", LOG_DEBUG);
603
$resql=$db->query($sql);
604
if ($resql)
605
{
606
    $num = $db->num_rows($resql);
607
    $i = 0;
608
609
    $param = '&id='.$id;
610
    if ($search_label)                 $param.= '&search_label='.urlencode($search_label);
611
    if ($search_lang > 0)              $param.= '&search_lang='.urlencode($search_lang);
612
    if ($search_type_template != '-1') $param.= '&search_type_template='.urlencode($search_type_template);
613
    if ($search_fk_user > 0)           $param.= '&search_fk_user='.urlencode($search_fk_user);
614
    if ($search_topic)                 $param.= '&search_topic='.urlencode($search_topic);
615
616
    $paramwithsearch = $param;
617
    if ($sortorder) $paramwithsearch.= '&sortorder='.urlencode($sortorder);
618
    if ($sortfield) $paramwithsearch.= '&sortfield='.urlencode($sortfield);
619
    if (GETPOST('from', 'alpha')) $paramwithsearch.= '&from='.urlencode(GETPOST('from', 'alpha'));
620
621
    // There is several pages
622
    if ($num > $listlimit)
623
    {
624
        print '<tr class="none"><td class="right" colspan="'.(3+count($fieldlist)).'">';
625
        print_fleche_navigation($page, $_SERVER["PHP_SELF"], $paramwithsearch, ($num > $listlimit), '<li class="pagination"><span>'.$langs->trans("Page").' '.($page+1).'</span></li>');
626
        print '</td></tr>';
627
    }
628
629
630
    // Title line with search boxes
631
    print '<tr class="liste_titre">';
632
    $filterfound=0;
633
    foreach ($fieldlist as $field => $value)
634
    {
635
        if ($value == 'label') print '<td class="liste_titre"><input type="text" name="search_label" class="maxwidth100" value="'.dol_escape_htmltag($search_label).'"></td>';
636
        elseif ($value == 'lang')
637
        {
638
        	print '<td class="liste_titre">';
639
        	print $formadmin->select_language($search_lang, 'search_lang', 0, null, 1, 0, 0, 'maxwidth100');
640
        	print '</td>';
641
        }
642
        elseif ($value == 'fk_user')
643
        {
644
        	print '<td class="liste_titre">';
645
        	$restrictid=array();
646
        	if (! $user->admin) $restrictid=array($user->id);
647
        	//var_dump($restrictid);
648
        	print $form->select_dolusers($search_fk_user, 'search_fk_user', 1, null, 0, 'hierarchyme', null, 0, 0, 1, '', 0, '', 'maxwidth100');
649
        	print '</td>';
650
        }
651
        elseif ($value == 'topic') print '<td class="liste_titre"><input type="text" name="search_topic" value="'.dol_escape_htmltag($search_topic).'"></td>';
652
        elseif ($value == 'type_template')
653
        {
654
        	print '<td class="liste_titre">'.$form->selectarray('search_type_template', $elementList, $search_type_template, 1, 0, 0, '', 0, 0, 0, '', 'maxwidth100 maxwidth100onsmartphone').'</td>';
655
        }
656
        elseif (! in_array($value, array('content', 'content_lines'))) print '<td class="liste_titre"></td>';
657
    }
658
    if (empty($conf->global->MAIN_EMAIL_TEMPLATES_FOR_OBJECT_LINES)) print '<td class="liste_titre"></td>';
659
    // Action column
660
    print '<td class="liste_titre right" width="64">';
661
    $searchpicto=$form->showFilterButtons();
662
    print $searchpicto;
663
    print '</td>';
664
    print '</tr>';
665
666
    // Title of lines
667
    print '<tr class="liste_titre">';
668
    foreach ($fieldlist as $field => $value)
669
    {
670
        // Determine le nom du champ par rapport aux noms possibles
671
        // dans les dictionnaires de donnees
672
        $showfield=1;							  	// By defaut
673
        $align="left";
674
        $sortable=1;
675
        $valuetoshow='';
676
        $forcenowrap=1;
677
        /*
678
        $tmparray=getLabelOfField($fieldlist[$field]);
679
        $showfield=$tmp['showfield'];
680
        $valuetoshow=$tmp['valuetoshow'];
681
        $align=$tmp['align'];
682
        $sortable=$tmp['sortable'];
683
		*/
684
        $valuetoshow=ucfirst($fieldlist[$field]);   // By defaut
685
        $valuetoshow=$langs->trans($valuetoshow);   // try to translate
686
        if ($fieldlist[$field]=='fk_user')         { $valuetoshow=$langs->trans("Owner"); }
687
        if ($fieldlist[$field]=='lang')            { $valuetoshow=$langs->trans("Language"); }
688
        if ($fieldlist[$field]=='type')            { $valuetoshow=$langs->trans("Type"); }
689
        if ($fieldlist[$field]=='libelle' || $fieldlist[$field]=='label') { $valuetoshow=$langs->trans("Code"); }
690
    	if ($fieldlist[$field]=='type_template')   { $valuetoshow=$langs->trans("TypeOfTemplate"); }
691
		if ($fieldlist[$field]=='private')         { $align='center'; }
692
		if ($fieldlist[$field]=='position')        { $align='center'; }
693
694
		if ($fieldlist[$field]=='joinfiles')       { $valuetoshow=$langs->trans("FilesAttachedToEmail"); $align='center'; $forcenowrap=0; }
695
		if ($fieldlist[$field]=='content')         { $valuetoshow=$langs->trans("Content"); $showfield=0;}
696
		if ($fieldlist[$field]=='content_lines')   { $valuetoshow=$langs->trans("ContentLines"); $showfield=0; }
697
698
        // Affiche nom du champ
699
        if ($showfield)
700
        {
701
            if (! empty($tabhelp[$id][$value]))
702
            {
703
            	if (in_array($value, array('topic'))) $valuetoshow = $form->textwithpicto($valuetoshow, $tabhelp[$id][$value], 1, 'help', '', 0, 2, 'tooltip'.$value, $forcenowrap);   // Tooltip on click
704
                else $valuetoshow = $form->textwithpicto($valuetoshow, $tabhelp[$id][$value], 1, 'help', '', 0, 2, '', $forcenowrap);	// Tooltip on hover
705
            }
706
            print getTitleFieldOfList($valuetoshow, 0, $_SERVER["PHP_SELF"], ($sortable?$fieldlist[$field]:''), ($page?'page='.$page.'&':''), $param, "align=".$align, $sortfield, $sortorder);
707
        }
708
    }
709
710
    print getTitleFieldOfList($langs->trans("Status"), 0, $_SERVER["PHP_SELF"], "active", ($page?'page='.$page.'&':''), $param, 'align="center"', $sortfield, $sortorder);
711
    print getTitleFieldOfList('');
712
    print '</tr>';
713
714
    if ($num)
715
    {
716
        // Lines with values
717
        while ($i < $num)
718
        {
719
            $obj = $db->fetch_object($resql);
720
721
            if ($action == 'edit' && ($rowid == (! empty($obj->rowid)?$obj->rowid:$obj->code)))
722
            {
723
            	print '<tr class="oddeven" id="rowid-'.$obj->rowid.'">';
724
725
            	$tmpaction='edit';
726
                $parameters=array('fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]);
727
                $reshook=$hookmanager->executeHooks('editEmailTemplateFieldlist', $parameters, $obj, $tmpaction);    // Note that $action and $object may have been modified by some hooks
728
                $error=$hookmanager->error; $errors=$hookmanager->errors;
729
730
                // Show fields
731
                if (empty($reshook)) fieldList($fieldlist, $obj, $tabname[$id], 'edit');
732
733
                print '<td></td><td></td><td></td>';
734
                print '<td align="center">';
735
                print '<input type="hidden" name="page" value="'.$page.'">';
736
                print '<input type="hidden" name="rowid" value="'.$rowid.'">';
737
                print '<input type="submit" class="button" name="actionmodify" value="'.$langs->trans("Modify").'">';
738
                print '<div name="'.(! empty($obj->rowid)?$obj->rowid:$obj->code).'"></div>';
739
                print '<input type="submit" class="button" name="actioncancel" value="'.$langs->trans("Cancel").'">';
740
                print '</td>';
741
742
                $fieldsforcontent = array('topic', 'joinfiles', 'content');
743
                if (! empty($conf->global->MAIN_EMAIL_TEMPLATES_FOR_OBJECT_LINES))
744
                {
745
                    $fieldsforcontent = array('topic', 'joinfiles', 'content', 'content_lines');
746
                }
747
                foreach ($fieldsforcontent as $tmpfieldlist)
748
                {
749
                    $showfield = 1;
750
                    $align = "left";
751
                    $valuetoshow = $obj->{$tmpfieldlist};
752
753
                    $class = 'tddict';
754
                    // Show value for field
755
                    if ($showfield) {
756
						// Show line for topic, joinfiles and content
757
                        print '</tr><tr class="oddeven" nohover tr-'.$tmpfieldlist.'-'.$rowid.' ">';
758
                        print '<td colspan="8">';
759
                        if ($tmpfieldlist == 'topic')
760
                        {
761
	                        print '<strong>' . $form->textwithpicto($langs->trans("Topic"), $tabhelp[$id][$tmpfieldlist], 1, 'help', '', 0, 2, $tmpfieldlist) . '</strong> ';
762
    	                    print '<input type="text" class="flat minwidth500" name="'.$tmpfieldlist.'-'.$rowid.'" value="' . (! empty($obj->{$tmpfieldlist}) ? $obj->{$tmpfieldlist} : '') . '">';
763
                        }
764
                        if ($tmpfieldlist == 'joinfiles')
765
                        {
766
                        	print '<strong>' . $form->textwithpicto($langs->trans("FilesAttachedToEmail"), $tabhelp[$id][$tmpfieldlist], 1, 'help', '', 0, 2, $tmpfieldlist) . '</strong> ';
767
                        	print '<input type="text" class="flat maxwidth50" name="'.$tmpfieldlist.'-'.$rowid.'" value="' . (! empty($obj->{$tmpfieldlist}) ? $obj->{$tmpfieldlist} : '') . '">';
768
                        }
769
                        if ($tmpfieldlist == 'content')
770
                        {
771
                        	print $form->textwithpicto($langs->trans("Content"), $tabhelp[$id][$tmpfieldlist], 1, 'help', '', 0, 2, $tmpfieldlist) . '<br>';
772
                        	$okforextended = true;
773
                        	if (empty($conf->global->FCKEDITOR_ENABLE_MAIL)) $okforextended = false;
774
                        	$doleditor = new DolEditor($tmpfieldlist.'-'.$rowid, (! empty($obj->{$tmpfieldlist}) ? $obj->{$tmpfieldlist} : ''), '', 140, 'dolibarr_mailings', 'In', 0, false, $okforextended, ROWS_6, '90%');
775
                        	print $doleditor->Create(1);
776
                        }
777
                        print '</td>';
778
                        print '<td></td>';
779
                        print '<td></td>';
780
                    }
781
                }
782
783
                print "</tr>\n";
784
            }
785
            else
786
            {
787
            	$keyforobj='type_template';
788
            	if (! in_array($obj->$keyforobj, array_keys($elementList)))
789
            	{
790
            		$i++;
791
            		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)
792
            	}
793
				// Test on 'enabled'
794
				if (! dol_eval($obj->enabled, 1))
795
				{
796
					$i++;
797
					continue;		// Email template not qualified
798
				}
799
800
            	print '<tr class="oddeven" id="rowid-'.$obj->rowid.'">';
801
802
            	$tmpaction = 'view';
803
                $parameters=array('var'=>$var, 'fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]);
804
                $reshook=$hookmanager->executeHooks('viewEmailTemplateFieldlist', $parameters, $obj, $tmpaction);    // Note that $action and $object may have been modified by some hooks
805
806
                $error=$hookmanager->error; $errors=$hookmanager->errors;
807
808
                if (empty($reshook))
809
                {
810
                    foreach ($fieldlist as $field => $value)
811
                    {
812
                        if (in_array($fieldlist[$field], array('content','content_lines'))) continue;
813
                        $showfield=1;
814
                    	$align="left";
815
                        $valuetoshow=$obj->{$fieldlist[$field]};
816
                        if ($value == 'type_template')
817
                        {
818
                            $valuetoshow = isset($elementList[$valuetoshow])?$elementList[$valuetoshow]:$valuetoshow;
819
                        }
820
                        if ($value == 'lang' && $valuetoshow)
821
                        {
822
                        	$valuetoshow = $valuetoshow.' - '.$langs->trans("Language_".$valuetoshow);
823
                        }
824
                        if ($value == 'fk_user')
825
                        {
826
                        	if ($valuetoshow > 0)
827
                        	{
828
                        		$fuser=new User($db);
829
                        		$fuser->fetch($valuetoshow);
830
                        		$valuetoshow = $fuser->getNomUrl(1);
831
                        	}
832
                        }
833
                        if ($value == 'private')
834
                        {
835
                        	$align="center";
836
                        	if ($valuetoshow) $valuetoshow=yn($valuetoshow);
837
                        	else $valuetoshow='';
838
                        }
839
                        if ($value == 'position')
840
                        {
841
                        	$align="center";
842
                        }
843
                        if ($value == 'joinfiles')
844
                        {
845
                        	$align="center";
846
                        	if ($valuetoshow) $valuetoshow=1;
847
                        	else $valuetoshow='';
848
                        }
849
850
                        $class='tddict';
851
						// Show value for field
852
						if ($showfield)
853
						{
854
                           	print '<!-- '.$fieldlist[$field].' -->';
855
                           	print '<td align="'.$align.'" class="'.$class.'">'.$valuetoshow.'</td>';
856
						}
857
                    }
858
                }
859
860
                // Can an entry be erased or disabled ?
861
                $iserasable=1;$canbedisabled=1;$canbemodified=1;	// true by default
862
                if (! $user->admin && $obj->fk_user != $user->id)
863
                {
864
                	$iserasable=0;
865
                	$canbedisabled=0;
866
                	$canbemodified=0;
867
                }
868
869
                $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):'');
870
                if ($param) $url .= '&'.$param;
871
                $url.='&';
872
873
                // Status / Active
874
                print '<td align="center" class="nowrap">';
875
                if ($canbedisabled) print '<a href="'.$url.'action='.$acts[$obj->active].'">'.$actl[$obj->active].'</a>';
876
                else print '<span class="opacitymedium">'.$actl[$obj->active].'</span>';
877
                print "</td>";
878
879
                // Modify link / Delete link
880
                print '<td class="center nowraponall" width="64">';
881
                if ($canbemodified) print '<a class="reposition" href="'.$url.'action=edit">'.img_edit().'</a>';
882
                if ($iserasable)
883
                {
884
                    print ' &nbsp; <a href="'.$url.'action=delete">'.img_delete().'</a>';
885
                    //else print '<a href="#">'.img_delete().'</a>';    // Some dictionary can be edited by other profile than admin
886
                }
887
                print '</td>';
888
889
                /*
890
                $fieldsforcontent = array('content');
891
                if (! empty($conf->global->MAIN_EMAIL_TEMPLATES_FOR_OBJECT_LINES))
892
                {
893
                    $fieldsforcontent = array('content', 'content_lines');
894
                }
895
                foreach ($fieldsforcontent as $tmpfieldlist)
896
                {
897
                    $showfield = 1;
898
                    $align = "left";
899
                    $valuetoshow = $obj->{$tmpfieldlist};
900
901
                    $class = 'tddict';
902
                    // Show value for field
903
                    if ($showfield) {
904
905
                        print '</tr><tr class="oddeven" nohover tr-'.$tmpfieldlist.'-'.$i.' "><td colspan="5">'; // To create an artificial CR for the current tr we are on
906
                        $okforextended = true;
907
                        if (empty($conf->global->FCKEDITOR_ENABLE_MAIL))
908
                            $okforextended = false;
909
                        $doleditor = new DolEditor($tmpfieldlist.'-'.$i, (! empty($obj->{$tmpfieldlist}) ? $obj->{$tmpfieldlist} : ''), '', 140, 'dolibarr_mailings', 'In', 0, false, $okforextended, ROWS_6, '90%', 1);
910
                        print $doleditor->Create(1);
911
                        print '</td>';
912
                        print '<td></td><td></td><td></td>';
913
914
                    }
915
                }*/
916
917
                print "</tr>\n";
918
            }
919
920
921
            $i++;
922
        }
923
    }
924
}
925
else {
926
    dol_print_error($db);
927
}
928
929
print '</table>';
930
print '</div>';
931
932
print '</form>';
933
934
935
dol_fiche_end();
936
937
// End of page
938
llxFooter();
939
$db->close();
940
941
942
/**
943
 *	Show fields in insert/edit mode
944
 *
945
 * 	@param		array	$fieldlist		Array of fields
946
 * 	@param		Object	$obj			If we show a particular record, obj is filled with record fields
947
 *  @param		string	$tabname		Name of SQL table
948
 *  @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
949
 *	@return		void
950
 */
951
function fieldList($fieldlist, $obj = '', $tabname = '', $context = '')
952
{
953
	global $conf, $langs, $user, $db;
954
	global $form;
955
	global $region_id;
956
	global $elementList,$sourceList,$localtax_typeList;
957
	global $bc;
958
959
	$formadmin = new FormAdmin($db);
960
	$formcompany = new FormCompany($db);
961
962
	foreach ($fieldlist as $field => $value)
963
	{
964
		if ($fieldlist[$field] == 'fk_user')
965
		{
966
			print '<td>';
967
			if ($user->admin)
968
			{
969
				print $form->select_dolusers($obj->{$fieldlist[$field]}, 'fk_user', 1, null, 0, '', null, 0, 0, 1, '', 0, '', 'maxwidth200');
970
			}
971
			else
972
			{
973
				if ($context == 'add')	// I am not admin and we show the add form
974
				{
975
					print $user->getNomUrl(1);		// Me
976
					$forcedvalue=$user->id;
977
				}
978
				else
979
				{
980
					if ($obj && ! empty($obj->{$fieldlist[$field]}) && $obj->{$fieldlist[$field]} > 0)
981
					{
982
						$fuser=new User($db);
983
						$fuser->fetch($obj->{$fieldlist[$field]});
984
						print $fuser->getNomUrl(1);
985
						$forcedvalue=$fuser->id;
986
					}
987
					else
988
					{
989
						$forcedvalue=$obj->{$fieldlist[$field]};
990
					}
991
				}
992
				$keyname=$fieldlist[$field];
993
				print '<input type="hidden" value="'.$forcedvalue.'" name="'.$keyname.'">';
994
			}
995
			print '</td>';
996
		}
997
		elseif ($fieldlist[$field] == 'lang')
998
		{
999
			print '<td>';
1000
			if (! empty($conf->global->MAIN_MULTILANGS))
1001
			{
1002
				$selectedlang = GETPOSTISSET('langcode')?GETPOST('langcode', 'aZ09'):$langs->defaultlang;
1003
				if ($context == 'edit') $selectedlang = $obj->{$fieldlist[$field]};
1004
				print $formadmin->select_language($selectedlang, 'langcode', 0, null, 1, 0, 0, 'maxwidth150');
1005
			}
1006
			else
1007
			{
1008
				if (! empty($obj->{$fieldlist[$field]}))
1009
				{
1010
					print $obj->{$fieldlist[$field]}.' - '.$langs->trans('Language_'.$obj->{$fieldlist[$field]});
1011
				}
1012
				$keyname=$fieldlist[$field];
1013
				if ($keyname == 'lang') $keyname='langcode';	// Avoid conflict with lang param
1014
				print '<input type="hidden" value="'.$obj->{$fieldlist[$field]}.'" name="'.$keyname.'">';
1015
			}
1016
			print '</td>';
1017
		}
1018
		// Le type de template
1019
		elseif ($fieldlist[$field] == 'type_template')
1020
		{
1021
			print '<td>';
1022
			if ($context == 'edit' && ! empty($obj->{$fieldlist[$field]}) && ! in_array($obj->{$fieldlist[$field]}, array_keys($elementList)))
1023
			{
1024
				// Current tempalte type is an unknown type, so we must keep it as it is.
1025
				print '<input type="hidden" name="type_template" value="'.$obj->{$fieldlist[$field]}.'">';
1026
				print $obj->{$fieldlist[$field]};
1027
			}
1028
			else
1029
			{
1030
				print $form->selectarray('type_template', $elementList, (! empty($obj->{$fieldlist[$field]})?$obj->{$fieldlist[$field]}:''), 1, 0, 0, '', 0, 0, 0, '', 'maxwidth150 maxwidth100onsmartphone');
1031
			}
1032
			print '</td>';
1033
		}
1034
		elseif ($context == 'add'  && in_array($fieldlist[$field], array('topic', 'joinfiles', 'content', 'content_lines'))) continue;
1035
		elseif ($context == 'edit' && in_array($fieldlist[$field], array('topic', 'joinfiles', 'content', 'content_lines'))) continue;
1036
		elseif ($context == 'hide' && in_array($fieldlist[$field], array('topic', 'joinfiles', 'content', 'content_lines'))) continue;
1037
		else
1038
		{
1039
			$size=''; $class=''; $classtd='';
1040
			if ($fieldlist[$field]=='code') $class='maxwidth100';
1041
			if ($fieldlist[$field]=='label') $class='maxwidth100';
1042
			if ($fieldlist[$field]=='private') { $class='maxwidth50'; $classtd='center'; }
1043
			if ($fieldlist[$field]=='position') { $class='maxwidth50'; $classtd='center'; }
1044
			if ($fieldlist[$field]=='libelle') $class='quatrevingtpercent';
1045
			if ($fieldlist[$field]=='topic') $class='quatrevingtpercent';
1046
			if ($fieldlist[$field]=='sortorder' || $fieldlist[$field]=='sens' || $fieldlist[$field]=='category_type') $size='size="2" ';
1047
1048
			print '<td'.($classtd?' class="'.$classtd.'"':'').'>';
1049
			if ($fieldlist[$field]=='private')
1050
			{
1051
				if (empty($user->admin))
1052
				{
1053
					print $form->selectyesno($fieldlist[$field], '1', 1);
1054
				}
1055
				else
1056
				{
1057
					//print '<input type="text" '.$size.'class="flat'.($class?' '.$class:'').'" value="1" name="'.$fieldlist[$field].'">';
1058
					print $form->selectyesno($fieldlist[$field], (isset($obj->{$fieldlist[$field]})?$obj->{$fieldlist[$field]}:''), 1);
1059
				}
1060
			}
1061
			else
1062
			{
1063
				print '<input type="text" '.$size.'class="flat'.($class?' '.$class:'').'" value="'.(isset($obj->{$fieldlist[$field]})?$obj->{$fieldlist[$field]}:'').'" name="'.$fieldlist[$field].'">';
1064
			}
1065
			print '</td>';
1066
		}
1067
	}
1068
}
1069