Completed
Branch develop (09fbe4)
by
unknown
29:23
created

accountmodel.php ➔ fieldListAccountModel()   D

Complexity

Conditions 25
Paths 76

Size

Total Lines 63

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 25
nc 76
nop 4
dl 0
loc 63
rs 4.1666
c 0
b 0
f 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-2015  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
 *
15
 * This program is free software; you can redistribute it and/or modify
16
 * it under the terms of the GNU General Public License as published by
17
 * the Free Software Foundation; either version 3 of the License, or
18
 * (at your option) any later version.
19
 *
20
 * This program is distributed in the hope that it will be useful,
21
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
23
 * GNU General Public License for more details.
24
 *
25
 * You should have received a copy of the GNU General Public License
26
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
27
 */
28
29
/**
30
 *	    \file       htdocs/accountancy/admin/accountmodel.php
31
 *		\ingroup    Advanced accountancy
32
 *		\brief      Page to administer model of chart of accounts
33
 */
34
35
require '../../main.inc.php';
36
require_once DOL_DOCUMENT_ROOT.'/core/class/html.formadmin.class.php';
37
require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php';
38
require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php';
39
require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
40
require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
41
require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php';
42
if (! empty($conf->accounting->enabled)) require_once DOL_DOCUMENT_ROOT . '/core/class/html.formaccounting.class.php';
43
44
// Load translation files required by the page
45
$langs->loadLangs(array("errors","admin","companies","resource","holiday","compta","accountancy","hrm"));
46
47
$action=GETPOST('action','alpha')?GETPOST('action','alpha'):'view';
48
$confirm=GETPOST('confirm','alpha');
49
$id=31;
50
$rowid=GETPOST('rowid','alpha');
51
$code=GETPOST('code','alpha');
52
53
$acts[0] = "activate";
54
$acts[1] = "disable";
55
$actl[0] = img_picto($langs->trans("Disabled"),'switch_off');
56
$actl[1] = img_picto($langs->trans("Activated"),'switch_on');
57
58
$listoffset=GETPOST('listoffset');
59
$listlimit=GETPOST('listlimit')>0?GETPOST('listlimit'):1000;
60
$active = 1;
61
62
$sortfield = GETPOST("sortfield",'aZ09comma');
63
$sortorder = GETPOST("sortorder",'aZ09comma');
64
$page = GETPOST("page",'int');
65
if (empty($page) || $page == -1) { $page = 0; }     // If $page is not defined, or '' or -1
66
$offset = $listlimit * $page ;
67
$pageprev = $page - 1;
68
$pagenext = $page + 1;
69
70
$search_country_id = GETPOST('search_country_id','int');
71
72
73
// Security check
74
if ($user->societe_id > 0) accessforbidden();
75
if (! $user->rights->accounting->chartofaccount) accessforbidden();
76
77
78
// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
79
$hookmanager->initHooks(array('admin'));
80
81
// This page is a generic page to edit dictionaries
82
// Put here declaration of dictionaries properties
83
84
// Name of SQL tables of dictionaries
85
$tabname=array();
86
87
$tabname[31]= MAIN_DB_PREFIX."accounting_system";
88
89
// Dictionary labels
90
$tablib=array();
91
$tablib[31]= "Pcg_version";
92
93
// Requests to extract data
94
$tabsql=array();
95
$tabsql[31]= "SELECT s.rowid as rowid, pcg_version, s.label, s.fk_country as country_id, c.code as country_code, c.label as country, s.active FROM ".MAIN_DB_PREFIX."accounting_system as s, ".MAIN_DB_PREFIX."c_country as c WHERE s.fk_country=c.rowid and c.active=1";
96
97
// Criteria to sort dictionaries
98
$tabsqlsort=array();
99
$tabsqlsort[31]="pcg_version ASC";
100
101
// Nom des champs en resultat de select pour affichage du dictionnaire
102
$tabfield=array();
103
$tabfield[31]= "pcg_version,label,country_id,country";
104
105
// Nom des champs d'edition pour modification d'un enregistrement
106
$tabfieldvalue=array();
107
$tabfieldvalue[31]= "pcg_version,label,country";
108
109
// Nom des champs dans la table pour insertion d'un enregistrement
110
$tabfieldinsert=array();
111
$tabfieldinsert[31]= "pcg_version,label,fk_country";
112
113
// Nom du rowid si le champ n'est pas de type autoincrement
114
// Example: "" if id field is "rowid" and has autoincrement on
115
//          "nameoffield" if id field is not "rowid" or has not autoincrement on
116
$tabrowid=array();
117
$tabrowid[31]= "";
118
119
// Condition to show dictionary in setup page
120
$tabcond=array();
121
$tabcond[31]= ! empty($conf->accounting->enabled);
122
123
// List of help for fields
124
$tabhelp=array();
125
$tabhelp[31] = array('pcg_version'=>$langs->trans("EnterAnyCode"));
126
127
// List of check for fields (NOT USED YET)
128
$tabfieldcheck=array();
129
$tabfieldcheck[31] = array();
130
131
132
// Define elementList and sourceList (used for dictionary type of contacts "llx_c_type_contact")
133
$elementList = array();
134
$sourceList=array();
135
136
137
138
/*
139
 * Actions
140
 */
141
142
if (GETPOST('button_removefilter') || GETPOST('button_removefilter.x') || GETPOST('button_removefilter_x'))
143
{
144
	$search_country_id = '';
145
}
146
147
// Actions add or modify an entry into a dictionary
148
if (GETPOST('actionadd') || GETPOST('actionmodify'))
149
{
150
	$listfield=explode(',', str_replace(' ', '',$tabfield[$id]));
151
	$listfieldinsert=explode(',',$tabfieldinsert[$id]);
152
	$listfieldmodify=explode(',',$tabfieldinsert[$id]);
153
	$listfieldvalue=explode(',',$tabfieldvalue[$id]);
154
155
	// Check that all fields are filled
156
	$ok=1;
157
	foreach ($listfield as $f => $value)
158
	{
159
		if ($value == 'country_id' && in_array($tablib[$id],array('DictionaryVAT','DictionaryRegion','DictionaryCompanyType','DictionaryHolidayTypes','DictionaryRevenueStamp','DictionaryAccountancyCategory','Pcg_version'))) continue;		// For some pages, country is not mandatory
160
		if ($value == 'country' && in_array($tablib[$id],array('DictionaryCanton','DictionaryCompanyType','DictionaryRevenueStamp'))) continue;		// For some pages, country is not mandatory
161
		if ($value == 'localtax1' && empty($_POST['localtax1_type'])) continue;
162
		if ($value == 'localtax2' && empty($_POST['localtax2_type'])) continue;
163
		if ($value == 'color' && empty($_POST['color'])) continue;
164
		if ($value == 'formula' && empty($_POST['formula'])) continue;
165
		if ((! isset($_POST[$value]) || $_POST[$value]=='')
166
			&& (! in_array($listfield[$f], array('decalage','module','accountancy_code','accountancy_code_sell','accountancy_code_buy'))  // Fields that are not mandatory
167
			&& (! ($id == 10 && $listfield[$f] == 'code')) // Code is mandatory fir table 10
168
			)
169
		)
170
		{
171
			$ok=0;
172
			$fieldnamekey=$listfield[$f];
173
			// We take translate key of field
174
175
			if ($fieldnamekey == 'pcg_version')  $fieldnamekey='Pcg_version';
176
			if ($fieldnamekey == 'libelle' || ($fieldnamekey == 'label'))  $fieldnamekey='Label';
177
			if ($fieldnamekey == 'libelle_facture') $fieldnamekey = 'LabelOnDocuments';
178
			if ($fieldnamekey == 'nbjour')   $fieldnamekey='NbOfDays';
179
			if ($fieldnamekey == 'decalage') $fieldnamekey='Offset';
180
			if ($fieldnamekey == 'module')   $fieldnamekey='Module';
181
			if ($fieldnamekey == 'code') $fieldnamekey = 'Code';
182
			if ($fieldnamekey == 'note') $fieldnamekey = 'Note';
183
			if ($fieldnamekey == 'taux') $fieldnamekey = 'Rate';
184
			if ($fieldnamekey == 'type') $fieldnamekey = 'Type';
185
			if ($fieldnamekey == 'position') $fieldnamekey = 'Position';
186
			if ($fieldnamekey == 'unicode') $fieldnamekey = 'Unicode';
187
			if ($fieldnamekey == 'deductible') $fieldnamekey = 'Deductible';
188
			if ($fieldnamekey == 'sortorder') $fieldnamekey = 'SortOrder';
189
			if ($fieldnamekey == 'category_type') $fieldnamekey = 'Calculated';
190
191
			setEventMessages($langs->transnoentities("ErrorFieldRequired", $langs->transnoentities($fieldnamekey)), null, 'errors');
192
		}
193
	}
194
	// Other checks
195
	if ($tabname[$id] == MAIN_DB_PREFIX."c_actioncomm" && isset($_POST["type"]) && in_array($_POST["type"],array('system','systemauto'))) {
196
		$ok=0;
197
		setEventMessages($langs->transnoentities('ErrorReservedTypeSystemSystemAuto'), null, 'errors');
198
	}
199
	if (isset($_POST["code"]))
200
	{
201
		if ($_POST["code"]=='0')
202
		{
203
			$ok=0;
204
			setEventMessages($langs->transnoentities('ErrorCodeCantContainZero'), null, 'errors');
205
		}
206
		/*if (!is_numeric($_POST['code']))	// disabled, code may not be in numeric base
207
    	{
208
	    	$ok = 0;
209
	    	$msg .= $langs->transnoentities('ErrorFieldFormat', $langs->transnoentities('Code')).'<br>';
210
	    }*/
211
	}
212
	if (isset($_POST["country"]) && ($_POST["country"]=='0') && ($id != 2))
213
	{
214
		if (in_array($tablib[$id],array('DictionaryCompanyType','DictionaryHolidayTypes')))	// Field country is no mandatory for such dictionaries
215
		{
216
			$_POST["country"]='';
217
		}
218
		else
219
		{
220
			$ok=0;
221
			setEventMessages($langs->transnoentities("ErrorFieldRequired",$langs->transnoentities("Country")), null, 'errors');
222
		}
223
	}
224
	if ($id == 3 && ! is_numeric($_POST["code"]))
225
	{
226
	   	$ok=0;
227
	   	setEventMessages($langs->transnoentities("ErrorFieldMustBeANumeric",$langs->transnoentities("Code")), null, 'errors');
228
	}
229
230
	// Clean some parameters
231
	if (isset($_POST["localtax1"]) && empty($_POST["localtax1"])) $_POST["localtax1"]='0';	// If empty, we force to 0
232
	if (isset($_POST["localtax2"]) && empty($_POST["localtax2"])) $_POST["localtax2"]='0';	// If empty, we force to 0
233
	if ($_POST["accountancy_code"] <= 0) $_POST["accountancy_code"]='';	// If empty, we force to null
234
	if ($_POST["accountancy_code_sell"] <= 0) $_POST["accountancy_code_sell"]='';	// If empty, we force to null
235
	if ($_POST["accountancy_code_buy"] <= 0) $_POST["accountancy_code_buy"]='';	// If empty, we force to null
236
237
	// Si verif ok et action add, on ajoute la ligne
238
	if ($ok && GETPOST('actionadd'))
239
	{
240
		if ($tabrowid[$id])
241
		{
242
			// Recupere id libre pour insertion
243
			$newid=0;
244
			$sql = "SELECT max(".$tabrowid[$id].") newid from ".$tabname[$id];
245
			$result = $db->query($sql);
246
			if ($result)
247
			{
248
				$obj = $db->fetch_object($result);
249
				$newid=($obj->newid + 1);
250
251
			} else {
252
				dol_print_error($db);
253
			}
254
		}
255
256
		// Add new entry
257
		$sql = "INSERT INTO ".$tabname[$id]." (";
258
		// List of fields
259
		if ($tabrowid[$id] && ! in_array($tabrowid[$id],$listfieldinsert))
260
			$sql.= $tabrowid[$id].",";
261
		$sql.= $tabfieldinsert[$id];
262
		$sql.=",active)";
263
		$sql.= " VALUES(";
264
265
		// List of values
266
		if ($tabrowid[$id] && ! in_array($tabrowid[$id],$listfieldinsert))
267
			$sql.= $newid.",";
268
		$i=0;
269
		foreach ($listfieldinsert as $f => $value)
270
		{
271
			if ($value == 'price' || preg_match('/^amount/i',$value) || $value == 'taux') {
272
				$_POST[$listfieldvalue[$i]] = price2num($_POST[$listfieldvalue[$i]],'MU');
273
			}
274
			else if ($value == 'entity') {
275
				$_POST[$listfieldvalue[$i]] = $conf->entity;
276
			}
277
			if ($i) $sql.=",";
278
			if ($_POST[$listfieldvalue[$i]] == '') $sql.="null";
279
			else $sql.="'".$db->escape($_POST[$listfieldvalue[$i]])."'";
280
			$i++;
281
		}
282
		$sql.=",1)";
283
284
		dol_syslog("actionadd", LOG_DEBUG);
285
		$result = $db->query($sql);
286
		if ($result)	// Add is ok
287
		{
288
			setEventMessages($langs->transnoentities("RecordSaved"), null, 'mesgs');
289
			$_POST=array('id'=>$id);	// Clean $_POST array, we keep only
290
		}
291
		else
292
		{
293
			if ($db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
294
				setEventMessages($langs->transnoentities("ErrorRecordAlreadyExists"), null, 'errors');
295
			}
296
			else {
297
				dol_print_error($db);
298
			}
299
		}
300
	}
301
302
	// Si verif ok et action modify, on modifie la ligne
303
	if ($ok && GETPOST('actionmodify'))
304
	{
305
		if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; }
306
		else { $rowidcol="rowid"; }
307
308
		// Modify entry
309
		$sql = "UPDATE ".$tabname[$id]." SET ";
310
		// Modifie valeur des champs
311
		if ($tabrowid[$id] && ! in_array($tabrowid[$id],$listfieldmodify))
312
		{
313
			$sql.= $tabrowid[$id]."=";
314
			$sql.= "'".$db->escape($rowid)."', ";
315
		}
316
		$i = 0;
317
		foreach ($listfieldmodify as $field)
318
		{
319
			if ($field == 'price' || preg_match('/^amount/i',$field) || $field == 'taux') {
320
				$_POST[$listfieldvalue[$i]] = price2num($_POST[$listfieldvalue[$i]],'MU');
321
			}
322
			else if ($field == 'entity') {
323
				$_POST[$listfieldvalue[$i]] = $conf->entity;
324
			}
325
			if ($i) $sql.=",";
326
			$sql.= $field."=";
327
			if ($_POST[$listfieldvalue[$i]] == '') $sql.="null";
328
			else $sql.="'".$db->escape($_POST[$listfieldvalue[$i]])."'";
329
			$i++;
330
		}
331
		$sql.= " WHERE ".$rowidcol." = '".$rowid."'";
332
333
		dol_syslog("actionmodify", LOG_DEBUG);
334
		//print $sql;
335
		$resql = $db->query($sql);
336
		if (! $resql)
337
		{
338
			setEventMessages($db->error(), null, 'errors');
339
		}
340
	}
341
	//$_GET["id"]=GETPOST('id', 'int');       // Force affichage dictionnaire en cours d'edition
342
}
343
344
if (GETPOST('actioncancel'))
345
{
346
	//$_GET["id"]=GETPOST('id', 'int');       // Force affichage dictionnaire en cours d'edition
347
}
348
349
if ($action == 'confirm_delete' && $confirm == 'yes')       // delete
350
{
351
	if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; }
352
	else { $rowidcol="rowid"; }
353
354
	$sql = "DELETE from ".$tabname[$id]." WHERE ".$rowidcol."='".$rowid."'";
355
356
	dol_syslog("delete", LOG_DEBUG);
357
	$result = $db->query($sql);
358
	if (! $result)
359
	{
360
		if ($db->errno() == 'DB_ERROR_CHILD_EXISTS')
361
		{
362
			setEventMessages($langs->transnoentities("ErrorRecordIsUsedByChild"), null, 'errors');
363
		}
364
		else
365
		{
366
			dol_print_error($db);
367
		}
368
	}
369
}
370
371
// activate
372
if ($action == $acts[0])
373
{
374
	if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; }
375
	else { $rowidcol="rowid"; }
376
377
	if ($rowid) {
378
		$sql = "UPDATE ".$tabname[$id]." SET active = 1 WHERE ".$rowidcol."='".$rowid."'";
379
	}
380
	elseif ($code) {
381
		$sql = "UPDATE ".$tabname[$id]." SET active = 1 WHERE code='".$code."'";
382
	}
383
384
	$result = $db->query($sql);
385
	if (!$result)
386
	{
387
		dol_print_error($db);
388
	}
389
}
390
391
// disable
392
if ($action == $acts[1])
393
{
394
	if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; }
395
	else { $rowidcol="rowid"; }
396
397
	if ($rowid) {
398
		$sql = "UPDATE ".$tabname[$id]." SET active = 0 WHERE ".$rowidcol."='".$rowid."'";
399
	}
400
	elseif ($code) {
401
		$sql = "UPDATE ".$tabname[$id]." SET active = 0 WHERE code='".$code."'";
402
	}
403
404
	$result = $db->query($sql);
405
	if (!$result)
406
	{
407
		dol_print_error($db);
408
	}
409
}
410
411
// favorite
412
if ($action == 'activate_favorite')
413
{
414
	if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; }
415
	else { $rowidcol="rowid"; }
416
417
	if ($rowid) {
418
		$sql = "UPDATE ".$tabname[$id]." SET favorite = 1 WHERE ".$rowidcol."='".$rowid."'";
419
	}
420
	elseif ($code) {
421
		$sql = "UPDATE ".$tabname[$id]." SET favorite = 1 WHERE code='".$code."'";
422
	}
423
424
	$result = $db->query($sql);
425
	if (!$result)
426
	{
427
		dol_print_error($db);
428
	}
429
}
430
431
// disable favorite
432
if ($action == 'disable_favorite')
433
{
434
	if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; }
435
	else { $rowidcol="rowid"; }
436
437
	if ($rowid) {
438
		$sql = "UPDATE ".$tabname[$id]." SET favorite = 0 WHERE ".$rowidcol."='".$rowid."'";
439
	}
440
	elseif ($code) {
441
		$sql = "UPDATE ".$tabname[$id]." SET favorite = 0 WHERE code='".$code."'";
442
	}
443
444
	$result = $db->query($sql);
445
	if (!$result)
446
	{
447
		dol_print_error($db);
448
	}
449
}
450
451
452
/*
453
 * View
454
 */
455
456
$form = new Form($db);
457
$formadmin=new FormAdmin($db);
458
459
llxHeader();
460
461
$titre=$langs->trans($tablib[$id]);
462
$linkback='';
463
464
print load_fiche_titre($titre,$linkback,'title_accountancy');
465
466
if (empty($id))
467
{
468
	print $langs->trans("DictionaryDesc");
469
	print " ".$langs->trans("OnlyActiveElementsAreShown")."<br>\n";
470
}
471
print "<br>\n";
472
473
474
// Confirmation de la suppression de la ligne
475
if ($action == 'delete')
476
{
477
	print $form->formconfirm($_SERVER["PHP_SELF"].'?'.($page?'page='.urlencode($page).'&':'').'sortfield='.urlencode($sortfield).'&sortorder='.urlencode($sortorder).'&rowid='.urlencode($rowid).'&code='.urlencode($code).'&id='.urlencode($id), $langs->trans('DeleteLine'), $langs->trans('ConfirmDeleteLine'), 'confirm_delete','',0,1);
478
}
479
//var_dump($elementList);
480
481
/*
482
 * Show a dictionary
483
 */
484
if ($id)
485
{
486
	// Complete requete recherche valeurs avec critere de tri
487
	$sql=$tabsql[$id];
488
489
	if ($search_country_id > 0)
490
	{
491
		if (preg_match('/ WHERE /',$sql)) $sql.= " AND ";
492
		else $sql.=" WHERE ";
493
		$sql.= " c.rowid = ".$search_country_id;
494
	}
495
496
	// If sort order is "country", we use country_code instead
497
	if ($sortfield == 'country') $sortfield='country_code';
498
	$sql.=$db->order($sortfield,$sortorder);
499
	$sql.=$db->plimit($listlimit+1,$offset);
500
	//print $sql;
501
502
	$fieldlist=explode(',',$tabfield[$id]);
503
504
	print '<form action="'.$_SERVER['PHP_SELF'].'?id='.$id.'" method="POST">';
505
	print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
506
507
	print '<div class="div-table-responsive">';
508
	print '<table class="noborder" width="100%">';
509
510
	// Form to add a new line
511
	if ($tabname[$id])
512
	{
513
		$alabelisused=0;
514
		$var=false;
515
516
		$fieldlist=explode(',',$tabfield[$id]);
517
518
		// Line for title
519
		print '<tr class="liste_titre">';
520
		foreach ($fieldlist as $field => $value)
521
		{
522
			// Determine le nom du champ par rapport aux noms possibles
523
			// dans les dictionnaires de donnees
524
			$valuetoshow=ucfirst($fieldlist[$field]);   // Par defaut
525
			$valuetoshow=$langs->trans($valuetoshow);   // try to translate
526
			$align="left";
527
			if ($fieldlist[$field]=='code')            { $valuetoshow=$langs->trans("Code"); }
528
			if ($fieldlist[$field]=='libelle' || $fieldlist[$field]=='label')
529
			{
530
				$valuetoshow=$langs->trans("Label");
531
				if ($id != 25) $valuetoshow.="*";
532
			}
533
			if ($fieldlist[$field]=='country')         {
534
				if (in_array('region_id',$fieldlist)) { print '<td>&nbsp;</td>'; continue; }		// For region page, we do not show the country input
535
				$valuetoshow=$langs->trans("Country");
536
			}
537
			if ($fieldlist[$field]=='country_id') { $valuetoshow=''; }
538
			if ($fieldlist[$field]=='pcg_version' || $fieldlist[$field]=='fk_pcg_version') { $valuetoshow=$langs->trans("Pcg_version"); }
539
540
			if ($valuetoshow != '')
541
			{
542
				print '<td align="'.$align.'">';
543
				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>';
544
				else if (! empty($tabhelp[$id][$value])) print $form->textwithpicto($valuetoshow,$tabhelp[$id][$value]);
545
				else print $valuetoshow;
546
				print '</td>';
547
			 }
548
			 if ($fieldlist[$field]=='libelle' || $fieldlist[$field]=='label') $alabelisused=1;
549
		}
550
551
		print '<td>';
552
		print '<input type="hidden" name="id" value="'.$id.'">';
553
		print '</td>';
554
		print '<td style="min-width: 26px;"></td>';
555
		print '<td style="min-width: 26px;"></td>';
556
		print '</tr>';
557
558
		// Line to enter new values
559
		print "<tr ".$bcnd[$var].">";
560
561
		$obj = new stdClass();
562
		// If data was already input, we define them in obj to populate input fields.
563
		if (GETPOST('actionadd'))
564
		{
565
			foreach ($fieldlist as $key=>$val)
566
			{
567
				if (GETPOST($val))
568
					$obj->$val=GETPOST($val);
569
			}
570
		}
571
572
		$tmpaction = 'create';
573
		$parameters=array('fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]);
574
		$reshook=$hookmanager->executeHooks('createDictionaryFieldlist',$parameters, $obj, $tmpaction);    // Note that $action and $object may have been modified by some hooks
575
		$error=$hookmanager->error; $errors=$hookmanager->errors;
576
577
		if (empty($reshook))
578
		{
579
			fieldListAccountModel($fieldlist,$obj,$tabname[$id],'add');
580
		}
581
582
		print '<td colspan="3" align="right">';
583
		print '<input type="submit" class="button" name="actionadd" value="'.$langs->trans("Add").'">';
584
		print '</td>';
585
		print "</tr>";
586
587
		$colspan=count($fieldlist)+3;
588
589
		if (! empty($alabelisused))  // If there is one label among fields, we show legend of *
590
		{
591
			print '<tr><td colspan="'.$colspan.'">* '.$langs->trans("LabelUsedByDefault").'.</td></tr>';
592
		}
593
		print '<tr><td colspan="'.$colspan.'">&nbsp;</td></tr>';	// Keep &nbsp; to have a line with enough height
594
	}
595
596
597
598
	// List of available values in database
599
	dol_syslog("htdocs/admin/dict", LOG_DEBUG);
600
	$resql=$db->query($sql);
601
	if ($resql)
602
	{
603
		$num = $db->num_rows($resql);
604
		$i = 0;
605
606
		$param = '&id='.$id;
607
		if ($search_country_id > 0) $param.= '&search_country_id='.$search_country_id;
608
		$paramwithsearch = $param;
609
		if ($sortorder) $paramwithsearch.= '&sortorder='.$sortorder;
610
		if ($sortfield) $paramwithsearch.= '&sortfield='.$sortfield;
611
612
		// There is several pages
613
		if ($num > $listlimit)
614
		{
615
			print '<tr class="none"><td align="right" colspan="'.(3+count($fieldlist)).'">';
616
			print_fleche_navigation($page, $_SERVER["PHP_SELF"], $paramwithsearch, ($num > $listlimit), '<li class="pagination"><span>'.$langs->trans("Page").' '.($page+1).'</span></li>');
617
			print '</td></tr>';
618
		}
619
620
		// Title line with search boxes
621
		print '<tr class="liste_titre liste_titre_add">';
622
		foreach ($fieldlist as $field => $value)
623
		{
624
			$showfield=1;							  	// By defaut
625
626
			if ($fieldlist[$field]=='region_id' || $fieldlist[$field]=='country_id') { $showfield=0; }
627
628
			if ($showfield)
629
			{
630
				if ($value == 'country')
631
				{
632
					print '<td class="liste_titre">';
633
					print $form->select_country($search_country_id, 'search_country_id', '', 28, 'maxwidth200 maxwidthonsmartphone');
634
					print '</td>';
635
				}
636
				else
637
				{
638
					print '<td class="liste_titre"></td>';
639
				}
640
			}
641
		}
642
		print '<td class="liste_titre"></td>';
643
		print '<td class="liste_titre" colspan="2" align="right">';
644
		$searchpicto=$form->showFilterAndCheckAddButtons(0);
645
		print $searchpicto;
646
		print '</td>';
647
		print '</tr>';
648
649
		// Title of lines
650
		print '<tr class="liste_titre">';
651
		foreach ($fieldlist as $field => $value)
652
		{
653
			// Determine le nom du champ par rapport aux noms possibles
654
			// dans les dictionnaires de donnees
655
			$showfield=1;							  	// By defaut
656
			$align="left";
657
			$sortable=1;
658
			$valuetoshow='';
659
			/*
660
            $tmparray=getLabelOfField($fieldlist[$field]);
661
            $showfield=$tmp['showfield'];
662
            $valuetoshow=$tmp['valuetoshow'];
663
            $align=$tmp['align'];
664
            $sortable=$tmp['sortable'];
665
			*/
666
			$valuetoshow=ucfirst($fieldlist[$field]);   // By defaut
667
			$valuetoshow=$langs->trans($valuetoshow);   // try to translate
668
			if ($fieldlist[$field]=='code')            { $valuetoshow=$langs->trans("Code"); }
669
			if ($fieldlist[$field]=='libelle' || $fieldlist[$field]=='label')
670
			{
671
				$valuetoshow=$langs->trans("Label");
672
			   	if ($id != 25) $valuetoshow.="*";
673
			}
674
			if ($fieldlist[$field]=='country')         { $valuetoshow=$langs->trans("Country"); }
675
			if ($fieldlist[$field]=='country_id') { $showfield=0; }
676
			if ($fieldlist[$field]=='fk_pcg_version')  { $valuetoshow=$langs->trans("Pcg_version"); }
677
678
			// Affiche nom du champ
679
			if ($showfield)
680
			{
681
				print getTitleFieldOfList($valuetoshow, 0, $_SERVER["PHP_SELF"], ($sortable?$fieldlist[$field]:''), ($page?'page='.$page.'&':''), $param, "align=".$align, $sortfield, $sortorder);
682
			}
683
		}
684
		print getTitleFieldOfList($langs->trans("Status"), 0, $_SERVER["PHP_SELF"], "active", ($page?'page='.$page.'&':''), $param, 'align="center"', $sortfield, $sortorder);
685
		print getTitleFieldOfList('');
686
		print getTitleFieldOfList('');
687
		print '</tr>';
688
689
		if ($num)
690
		{
691
			// Lines with values
692
			while ($i < $num)
693
			{
694
				$obj = $db->fetch_object($resql);
695
				//print_r($obj);
696
				print '<tr class="oddeven" id="rowid-'.$obj->rowid.'">';
697
				if ($action == 'edit' && ($rowid == (! empty($obj->rowid)?$obj->rowid:$obj->code)))
698
				{
699
					print '<form action="'.$_SERVER['PHP_SELF'].'?id='.$id.'" method="POST">';
700
					print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
701
					print '<input type="hidden" name="page" value="'.$page.'">';
702
					print '<input type="hidden" name="rowid" value="'.$rowid.'">';
703
704
					$tmpaction='edit';
705
					$parameters=array('fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]);
706
					$reshook=$hookmanager->executeHooks('editDictionaryFieldlist',$parameters,$obj, $tmpaction);    // Note that $action and $object may have been modified by some hooks
707
					$error=$hookmanager->error; $errors=$hookmanager->errors;
708
709
					if (empty($reshook)) fieldListAccountModel($fieldlist,$obj,$tabname[$id],'edit');
710
711
					print '<td colspan="3" align="right"><a name="'.(! empty($obj->rowid)?$obj->rowid:$obj->code).'">&nbsp;</a><input type="submit" class="button" name="actionmodify" value="'.$langs->trans("Modify").'">';
712
					print '&nbsp;<input type="submit" class="button" name="actioncancel" value="'.$langs->trans("Cancel").'"></td>';
713
				}
714
				else
715
				{
716
				  	$tmpaction = 'view';
717
					$parameters=array('var'=>$var, 'fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]);
718
					$reshook=$hookmanager->executeHooks('viewDictionaryFieldlist',$parameters,$obj, $tmpaction);    // Note that $action and $object may have been modified by some hooks
719
720
					$error=$hookmanager->error; $errors=$hookmanager->errors;
721
722
					if (empty($reshook))
723
					{
724
						foreach ($fieldlist as $field => $value)
725
						{
726
727
							$showfield=1;
728
							$align="left";
729
							$valuetoshow=$obj->{$fieldlist[$field]};
730
							if ($value == 'type_template')
731
							{
732
								$valuetoshow = isset($elementList[$valuetoshow])?$elementList[$valuetoshow]:$valuetoshow;
733
							}
734
							if ($value == 'element')
735
							{
736
								$valuetoshow = isset($elementList[$valuetoshow])?$elementList[$valuetoshow]:$valuetoshow;
737
							}
738
							else if ($value == 'source')
739
							{
740
								$valuetoshow = isset($sourceList[$valuetoshow])?$sourceList[$valuetoshow]:$valuetoshow;
741
							}
742
							else if ($valuetoshow=='all') {
743
								$valuetoshow=$langs->trans('All');
744
							}
745
							else if ($fieldlist[$field]=='country') {
746
								if (empty($obj->country_code))
747
								{
748
									$valuetoshow='-';
749
								}
750
								else
751
								{
752
									$key=$langs->trans("Country".strtoupper($obj->country_code));
753
									$valuetoshow=($key != "Country".strtoupper($obj->country_code)?$obj->country_code." - ".$key:$obj->country);
754
								}
755
							}
756
							else if ($fieldlist[$field]=='country_id') {
757
								$showfield=0;
758
							}
759
760
							$class='tddict';
761
							if ($fieldlist[$field] == 'tracking') $class.=' tdoverflowauto';
762
							// Show value for field
763
							if ($showfield) print '<!-- '.$fieldlist[$field].' --><td align="'.$align.'" class="'.$class.'">'.$valuetoshow.'</td>';
764
						}
765
					}
766
767
					// Can an entry be erased or disabled ?
768
					$iserasable=1;$canbedisabled=1;$canbemodified=1;	// true by default
769
770
					$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):'');
771
					if ($param) $url .= '&'.$param;
772
					$url.='&';
773
774
					// Active
775
					print '<td align="center" class="nowrap">';
776
					if ($canbedisabled) print '<a href="'.$url.'action='.$acts[$obj->active].'">'.$actl[$obj->active].'</a>';
777
					else print $langs->trans("AlwaysActive");
778
					print "</td>";
779
780
					// Modify link
781
					if ($canbemodified) print '<td align="center"><a class="reposition" href="'.$url.'action=edit">'.img_edit().'</a></td>';
782
					else print '<td>&nbsp;</td>';
783
784
					// Delete link
785
					if ($iserasable) print '<td align="center"><a href="'.$url.'action=delete">'.img_delete().'</a></td>';
786
					else print '<td>&nbsp;</td>';
787
788
					print "</tr>\n";
789
				}
790
				$i++;
791
			}
792
		}
793
	}
794
	else {
795
		dol_print_error($db);
796
	}
797
798
	print '</table>';
799
	print '</div>';
800
801
	print '</form>';
802
}
803
804
print '<br>';
805
806
// End of page
807
llxFooter();
808
$db->close();
809
810
811
/**
812
 *	Show fields in insert/edit mode
813
 *
814
 * 	@param		array	$fieldlist		Array of fields
815
 * 	@param		Object	$obj			If we show a particular record, obj is filled with record fields
816
 *  @param		string	$tabname		Name of SQL table
817
 *  @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
818
 *	@return		void
819
 */
820
function fieldListAccountModel($fieldlist, $obj='', $tabname='', $context='')
821
{
822
	global $conf,$langs,$db;
823
	global $form;
824
	global $region_id;
825
	global $elementList,$sourceList;
826
827
	$formadmin = new FormAdmin($db);
828
	$formcompany = new FormCompany($db);
829
	$formaccounting = new FormAccounting($db);
830
831
	foreach ($fieldlist as $field => $value)
832
	{
833
		if ($fieldlist[$field] == 'country')
834
		{
835
			if (in_array('region_id',$fieldlist))
836
			{
837
				print '<td>';
838
				//print join(',',$fieldlist);
839
				print '</td>';
840
				continue;
841
			}	// For state page, we do not show the country input (we link to region, not country)
842
			print '<td>';
843
			$fieldname='country';
844
			print $form->select_country((! empty($obj->country_code)?$obj->country_code:(! empty($obj->country)?$obj->country:'')), $fieldname, '', 28, 'maxwidth200 maxwidthonsmartphone');
845
			print '</td>';
846
		}
847
		elseif ($fieldlist[$field] == 'country_id')
848
		{
849
			if (! in_array('country',$fieldlist))	// If there is already a field country, we don't show country_id (avoid duplicate)
850
			{
851
				$country_id = (! empty($obj->{$fieldlist[$field]}) ? $obj->{$fieldlist[$field]} : 0);
852
				print '<td>';
853
				print '<input type="hidden" name="'.$fieldlist[$field].'" value="'.$country_id.'">';
854
				print '</td>';
855
			}
856
		}
857
		elseif ($fieldlist[$field] == 'type_cdr') {
858
			if ($fieldlist[$field] == 'type_cdr') print '<td align="center">';
859
			else print '<td>';
860
			if ($fieldlist[$field] == 'type_cdr') {
861
				print $form->selectarray($fieldlist[$field], array(0=>$langs->trans('None'), 1=>$langs->trans('AtEndOfMonth'), 2=>$langs->trans('CurrentNext')), (! empty($obj->{$fieldlist[$field]})?$obj->{$fieldlist[$field]}:''));
862
			} else {
863
				print $form->selectyesno($fieldlist[$field],(! empty($obj->{$fieldlist[$field]})?$obj->{$fieldlist[$field]}:''),1);
864
			}
865
			print '</td>';
866
		}
867
		elseif ($fieldlist[$field] == 'code' && isset($obj->{$fieldlist[$field]})) {
868
			print '<td><input type="text" class="flat" value="'.(! empty($obj->{$fieldlist[$field]})?$obj->{$fieldlist[$field]}:'').'" size="10" name="'.$fieldlist[$field].'"></td>';
869
		}
870
		else
871
		{
872
			print '<td>';
873
			$size=''; $class='';
874
			if ($fieldlist[$field]=='code') $size='size="8" ';
875
			if ($fieldlist[$field]=='position') $size='size="4" ';
876
			if ($fieldlist[$field]=='libelle') $size='centpercent';
877
			if ($fieldlist[$field]=='sortorder' || $fieldlist[$field]=='sens' || $fieldlist[$field]=='category_type') $size='size="2" ';
878
			print '<input type="text" '.$size.' class="flat'.($class?' '.$class:'').'" value="'.(isset($obj->{$fieldlist[$field]})?$obj->{$fieldlist[$field]}:'').'" name="'.$fieldlist[$field].'">';
879
			print '</td>';
880
		}
881
	}
882
}
883
884