1<?php
2/* Copyright (C) 2007-2017 Laurent Destailleur  <eldy@users.sourceforge.net>
3 * Copyright (C) 2018	   Ferran Marcet 		<fmarcet@2byte.es>
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 3 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <https://www.gnu.org/licenses/>.
17 */
18
19/**
20 *   	\file       htdocs/admin/mails_senderprofile_list.php
21 *		\ingroup    core
22 *		\brief      Page to adminsiter email sender profiles
23 */
24
25require '../main.inc.php';
26require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php';
27require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php';
28require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
29require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
30require_once DOL_DOCUMENT_ROOT.'/core/class/emailsenderprofile.class.php';
31
32// Load translation files required by the page
33$langs->loadLangs(array("errors", "admin", "mails", "languages"));
34
35$action     = GETPOST('action', 'aZ09') ?GETPOST('action', 'aZ09') : 'view'; // The action 'add', 'create', 'edit', 'update', 'view', ...
36$massaction = GETPOST('massaction', 'alpha'); // The bulk action (combo box choice into lists)
37$show_files = GETPOST('show_files', 'int'); // Show files area generated by bulk actions ?
38$confirm    = GETPOST('confirm', 'alpha'); // Result of a confirmation
39$cancel     = GETPOST('cancel', 'alpha'); // We click on a Cancel button
40$toselect   = GETPOST('toselect', 'array'); // Array of ids of elements selected into a list
41$contextpage = GETPOST('contextpage', 'aZ') ? GETPOST('contextpage', 'aZ') : 'emailsenderprofilelist'; // To manage different context of search
42$backtopage = GETPOST('backtopage', 'alpha'); // Go back to a dedicated page
43$optioncss  = GETPOST('optioncss', 'aZ'); // Option for the css output (always '' except when 'print')
44
45$id = GETPOST('id', 'int');
46$rowid = GETPOST('rowid', 'alpha');
47
48// Load variable for pagination
49$limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit;
50$sortfield = GETPOST('sortfield', 'aZ09comma');
51$sortorder = GETPOST('sortorder', 'aZ09comma');
52$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
53if (empty($page) || $page == -1 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha') || (empty($toselect) && $massaction === '0')) { $page = 0; }     // If $page is not defined, or '' or -1 or if we click on clear filters or if we select empty mass action
54$offset = $limit * $page;
55$pageprev = $page - 1;
56$pagenext = $page + 1;
57
58// Initialize technical objects
59$object = new EmailSenderProfile($db);
60$extrafields = new ExtraFields($db);
61$diroutputmassaction = $conf->admin->dir_output.'/temp/massgeneration/'.$user->id;
62$hookmanager->initHooks(array('emailsenderprofilelist')); // Note that conf->hooks_modules contains array
63
64// Fetch optionals attributes and labels
65$extrafields->fetch_name_optionals_label($object->table_element);
66
67$search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_');
68
69// Default sort order (if not yet defined by previous GETPOST)
70if (!$sortfield) $sortfield = "t.".key($object->fields); // Set here default search field. By default 1st field in definition.
71if (!$sortorder) $sortorder = "ASC";
72
73// Security check
74$socid = 0;
75if ($user->socid > 0)	// Protection if external user
76{
77	//$socid = $user->socid;
78	accessforbidden();
79}
80//$result = restrictedArea($user, 'mymodule', $id, '');
81
82// Initialize array of search criterias
83$search_all = GETPOST("search_all", 'alpha');
84$search = array();
85foreach ($object->fields as $key => $val)
86{
87	if (GETPOST('search_'.$key, 'alpha')) $search[$key] = GETPOST('search_'.$key, 'alpha');
88}
89
90// List of fields to search into when doing a "search in all"
91$fieldstosearchall = array();
92foreach ($object->fields as $key => $val)
93{
94	if ($val['searchall']) $fieldstosearchall['t.'.$key] = $val['label'];
95}
96
97// Definition of fields for list
98$arrayfields = array();
99foreach ($object->fields as $key => $val)
100{
101	// If $val['visible']==0, then we never show the field
102	if (!empty($val['visible'])) $arrayfields['t.'.$key] = array('label'=>$val['label'], 'checked'=>(($val['visible'] < 0) ? 0 : 1), 'enabled'=>($val['enabled'] && ($val['visible'] != 3)), 'position'=>$val['position']);
103}
104// Extra fields
105if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label']) > 0)
106{
107	foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val)
108	{
109		if (!empty($extrafields->attributes[$object->table_element]['list'][$key])) {
110			$arrayfields["ef.".$key] = array(
111				'label'=>$extrafields->attributes[$object->table_element]['label'][$key],
112				'checked'=>(($extrafields->attributes[$object->table_element]['list'][$key] < 0) ? 0 : 1),
113				'position'=>$extrafields->attributes[$object->table_element]['pos'][$key],
114				'enabled'=>(abs($extrafields->attributes[$object->table_element]['list'][$key]) != 3 && $extrafields->attributes[$object->table_element]['perms'][$key])
115			);
116		}
117	}
118}
119$object->fields = dol_sort_array($object->fields, 'position');
120$arrayfields = dol_sort_array($arrayfields, 'position');
121
122$permissiontoread = $user->admin;
123$permissiontoadd = $user->admin;
124$permissiontodelete = $user->admin;
125
126if ($id > 0) {
127	$object->fetch($id);
128}
129
130
131/*
132 * Actions
133 */
134
135if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; }
136if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; }
137
138$parameters = array();
139$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
140if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
141
142if (empty($reshook))
143{
144	// Actions cancel, add, update, delete or clone
145	$backurlforlist = $_SERVER["PHP_SELF"].'?action=list';
146	include DOL_DOCUMENT_ROOT.'/core/actions_addupdatedelete.inc.php';
147
148	// Selection of new fields
149	include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php';
150
151	// Purge search criteria
152	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
153	{
154		foreach ($object->fields as $key => $val)
155		{
156			$search[$key] = '';
157		}
158		$toselect = '';
159		$search_array_options = array();
160	}
161	if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')
162		|| GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha'))
163	{
164		$massaction = ''; // Protection to avoid mass action if we force a new search during a mass action confirmation
165	}
166
167	// Mass actions
168	$objectclass = 'EmailSenderProfile';
169	$objectlabel = 'EmailSenderProfile';
170	$uploaddir = $conf->admin->dir_output.'/senderprofiles';
171	include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php';
172
173	if ($action == 'delete')
174	{
175		$sql = "DELETE FROM ".MAIN_DB_PREFIX."c_email_senderprofile WHERE rowid = ".GETPOST('id', 'int');
176		$resql = $db->query($sql);
177		if ($resql) {
178			setEventMessages($langs->trans("RecordDeleted"), null, 'mesgs');
179		} else {
180			setEventMessages($langs->trans("Error").' '.$db->lasterror(), null, 'errors');
181		}
182	}
183}
184
185
186
187/*
188 * View
189 */
190
191$form = new Form($db);
192
193$now = dol_now();
194
195//$help_url="EN:Module_EmailSenderProfile|FR:Module_EmailSenderProfile_FR|ES:Módulo_EmailSenderProfile";
196$help_url = '';
197$title = $langs->trans("EMailsSetup");
198
199llxHeader('', $title);
200
201$linkback = '';
202$titlepicto = 'title_setup';
203
204print load_fiche_titre($title, $linkback, $titlepicto);
205
206$head = email_admin_prepare_head();
207
208print dol_get_fiche_head($head, 'senderprofiles', '', -1);
209
210print '<span class="opacitymedium">'.$langs->trans("EMailsSenderProfileDesc")."</span><br>\n";
211print "<br>\n";
212
213// Build and execute select
214// --------------------------------------------------------------------
215$sql = 'SELECT ';
216foreach ($object->fields as $key => $val)
217{
218	$sql .= 't.'.$key.', ';
219}
220// Add fields from extrafields
221if (!empty($extrafields->attributes[$object->table_element]['label'])) {
222	foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) $sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? "ef.".$key.' as options_'.$key.', ' : '');
223}
224// Add fields from hooks
225$parameters = array();
226$reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters, $object); // Note that $action and $object may have been modified by hook
227$sql .= preg_replace('/^,/', '', $hookmanager->resPrint);
228$sql = preg_replace('/,\s*$/', '', $sql);
229$sql .= " FROM ".MAIN_DB_PREFIX.$object->table_element." as t";
230if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (t.rowid = ef.fk_object)";
231if ($object->ismultientitymanaged == 1) $sql .= " WHERE t.entity IN (".getEntity($object->element).")";
232else $sql .= " WHERE 1 = 1";
233foreach ($search as $key => $val)
234{
235	if ($key == 'status' && $search[$key] == -1) continue;
236	$mode_search = (($object->isInt($object->fields[$key]) || $object->isFloat($object->fields[$key])) ? 1 : 0);
237	if (strpos($object->fields[$key]['type'], 'integer:') === 0 || $key == 'active') {
238		if ($search[$key] == '-1') $search[$key] = '';
239		$mode_search = 2;
240	}
241	if ($search[$key] != '') $sql .= natural_search($key, $search[$key], (($key == 'status') ? 2 : $mode_search));
242}
243if ($search_all) $sql .= natural_search(array_keys($fieldstosearchall), $search_all);
244//$sql.= dolSqlDateFilter("t.field", $search_xxxday, $search_xxxmonth, $search_xxxyear);
245// Add where from extra fields
246include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php';
247// Add where from hooks
248$parameters = array();
249$reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $object); // Note that $action and $object may have been modified by hook
250$sql .= $hookmanager->resPrint;
251
252/* If a group by is required
253$sql.= " GROUP BY "
254foreach($object->fields as $key => $val)
255{
256    $sql.='t.'.$key.', ';
257}
258// Add fields from extrafields
259if (! empty($extrafields->attributes[$object->table_element]['label'])) {
260	foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) $sql.=($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? "ef.".$key.', ' : '');
261}
262// Add where from hooks
263$parameters=array();
264$reshook=$hookmanager->executeHooks('printFieldListGroupBy',$parameters);    // Note that $action and $object may have been modified by hook
265$sql.=$hookmanager->resPrint;
266$sql=preg_replace('/,\s*$/','', $sql);
267*/
268
269$sql .= $db->order($sortfield, $sortorder);
270
271// Count total nb of records
272$nbtotalofrecords = '';
273if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST))
274{
275	$resql = $db->query($sql);
276	$nbtotalofrecords = $db->num_rows($resql);
277	if (($page * $limit) > $nbtotalofrecords)	// if total of record found is smaller than page * limit, goto and load page 0
278	{
279		$page = 0;
280		$offset = 0;
281	}
282}
283// if total of record found is smaller than limit, no need to do paging and to restart another select with limits set.
284if (is_numeric($nbtotalofrecords) && ($limit > $nbtotalofrecords || empty($limit)))
285{
286	$num = $nbtotalofrecords;
287} else {
288	if ($limit) $sql .= $db->plimit($limit + 1, $offset);
289
290	$resql = $db->query($sql);
291	if (!$resql)
292	{
293		dol_print_error($db);
294		exit;
295	}
296
297	$num = $db->num_rows($resql);
298}
299
300// Direct jump if only one record found
301if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all && !$page)
302{
303	$obj = $db->fetch_object($resql);
304	$id = $obj->rowid;
305	header("Location: ".DOL_URL_ROOT.'/monmodule/emailsenderprofile_card.php?id='.$id);
306	exit;
307}
308
309// Output page
310// --------------------------------------------------------------------
311
312// Example : Adding jquery code
313print '<script type="text/javascript" language="javascript">
314jQuery(document).ready(function() {
315	function init_myfunc()
316	{
317		jQuery("#myid").removeAttr(\'disabled\');
318		jQuery("#myid").attr(\'disabled\',\'disabled\');
319	}
320	init_myfunc();
321	jQuery("#mybutton").click(function() {
322		init_myfunc();
323	});
324});
325</script>';
326
327$arrayofselected = is_array($toselect) ? $toselect : array();
328
329$param = '';
330if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage);
331if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit);
332foreach ($search as $key => $val)
333{
334	if (is_array($search[$key]) && count($search[$key])) foreach ($search[$key] as $skey) $param .= '&search_'.$key.'[]='.urlencode($skey);
335	else $param .= '&search_'.$key.'='.urlencode($search[$key]);
336}
337if ($optioncss != '')     $param .= '&optioncss='.urlencode($optioncss);
338// Add $param from extra fields
339include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php';
340
341// List of mass actions available
342$arrayofmassactions = array(
343	//'presend'=>$langs->trans("SendByMail"),
344	//'builddoc'=>$langs->trans("PDFMerge"),
345);
346//if ($permissiontodelete) $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete");
347//if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions = array();
348$massactionbutton = $form->selectMassAction('', $arrayofmassactions);
349
350print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].'">';
351if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
352print '<input type="hidden" name="token" value="'.newToken().'">';
353print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">';
354print '<input type="hidden" name="action" value="'.($action == 'create' ? 'add' : ($action == 'edit' ? 'update' : 'list')).'">';
355print '<input type="hidden" name="sortfield" value="'.$sortfield.'">';
356print '<input type="hidden" name="sortorder" value="'.$sortorder.'">';
357print '<input type="hidden" name="page" value="'.$page.'">';
358print '<input type="hidden" name="id" value="'.$id.'">';
359print '<input type="hidden" name="contextpage" value="'.$contextpage.'">';
360
361$newcardbutton = '';
362if ($action != 'create') {
363	$newcardbutton = dolGetButtonTitle($langs->trans('New'), '', 'fa fa-plus-circle', $_SERVER['PHP_SELF'].'?action=create', '', $permissiontoadd);
364
365	if ($action == 'edit') {
366		print '<table class="border centpercent tableforfield">';
367		print '<tr><td class="fieldrequired">'.$langs->trans("Label").'</td><td><input type="text" name="label" value="'.(GETPOSTISSET('label') ? GETPOST('label', 'alphanohtml') : $object->label).'"></td></tr>';
368		print '<tr><td>'.$langs->trans("Email").'</td><td><input type="text" name="email" value="'.(GETPOSTISSET('email') ? GETPOST('email', 'alphanohtml') : $object->email).'"></td></tr>';
369		print '<tr><td>'.$langs->trans("Signature").'</td><td>';
370		require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
371		$doleditor = new DolEditor('signature', (GETPOSTISSET('signature') ? GETPOST('signature', 'restricthtml') : $object->signature), '', 138, 'dolibarr_notes', 'In', true, true, empty($conf->global->FCKEDITOR_ENABLE_USERSIGN) ? 0 : 1, ROWS_4, '90%');
372		print $doleditor->Create(1);
373		print '</td></tr>';
374		print '<tr><td>'.$langs->trans("User").'</td><td>';
375		print $form->select_dolusers((GETPOSTISSET('private') ? GETPOST('private', 'int') : $object->private), 'private', 1, null, 0, ($user->admin ? '' : $user->id));
376		print '</td></tr>';
377		print '<tr><td>'.$langs->trans("Position").'</td><td><input type="text" name="position" class="maxwidth50" value="'.(GETPOSTISSET('position') ? GETPOST('position', 'int') : $object->position).'"></td></tr>';
378		print '<tr><td>'.$langs->trans("Status").'</td><td>';
379		print $form->selectarray('active', $object->fields['active']['arrayofkeyval'], (GETPOSTISSET('active') ? GETPOST('active', 'int') : $object->active), 0, 0, 0, '', 1);
380		print '</td></tr>';
381		print '</table>';
382		print '<br>';
383		print '<div class="center">';
384		print '<input class="button button-save" type="submit" name="save" value="'.$langs->trans("Save").'">';
385		print ' &nbsp; ';
386		print '<input class="button button-cancel" type="submit" name="cancel" value="'.$langs->trans("Cancel").'">';
387		print '</div>';
388	}
389} else {
390	/*print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">';
391	if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
392	print '<input type="hidden" name="token" value="'.newToken().'">';
393	print '<input type="hidden" name="action" value="add">';
394	print '<input type="hidden" name="sortfield" value="'.$sortfield.'">';
395	print '<input type="hidden" name="sortorder" value="'.$sortorder.'">';
396	print '<input type="hidden" name="page" value="'.$page.'">';
397	print '<input type="hidden" name="contextpage" value="'.$contextpage.'">';
398	*/
399	print '<table class="border centpercent tableforfield">';
400	print '<tr><td class="fieldrequired">'.$langs->trans("Label").'</td><td><input type="text" name="label" value="'.GETPOST('label', 'alphanohtml').'"></td></tr>';
401	print '<tr><td>'.$langs->trans("Email").'</td><td><input type="text" name="email" value="'.GETPOST('email', 'alphanohtml').'"></td></tr>';
402	print '<tr><td>'.$langs->trans("Signature").'</td><td>';
403	require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
404	$doleditor = new DolEditor('signature', GETPOST('signature'), '', 138, 'dolibarr_notes', 'In', true, true, empty($conf->global->FCKEDITOR_ENABLE_USERSIGN) ? 0 : 1, ROWS_4, '90%');
405	print $doleditor->Create(1);
406	print '</td></tr>';
407	print '<tr><td>'.$langs->trans("User").'</td><td>';
408	print $form->select_dolusers((GETPOSTISSET('private') ? GETPOST('private', 'int') : -1), 'private', 1, null, 0, ($user->admin ? '' : $user->id));
409	print '</td></tr>';
410	print '<tr><td>'.$langs->trans("Position").'</td><td><input type="text" name="position" class="maxwidth50" value="'.GETPOST('position', 'int').'"></td></tr>';
411	print '<tr><td>'.$langs->trans("Status").'</td><td>';
412	print $form->selectarray('active', $object->fields['active']['arrayofkeyval'], GETPOST('active', 'int'), 0);
413	print '</td></tr>';
414	print '</table>';
415	print '<br>';
416	print '<div class="center">';
417	print '<input class="button button-save" type="submit" name="save" value="'.$langs->trans("Save").'">';
418	print ' &nbsp; ';
419	print '<input class="button button-cancel" type="submit" name="cancel" value="'.$langs->trans("Cancel").'">';
420	print '</div>';
421	//print '</form>';
422}
423
424print_barre_liste('', $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'title_companies', 0, $newcardbutton, '', $limit);
425//print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'title_companies', 0, '', '', $limit);
426
427$topicmail = "Information";
428//$modelmail="subscription";
429$objecttmp = new EmailSenderProfile($db);
430//$trackid = (($action == 'testhtml') ? "testhtml" : "test");
431include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php';
432
433if ($search_all)
434{
435	foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val);
436	print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $search_all).join(', ', $fieldstosearchall).'</div>';
437}
438
439$moreforfilter = '';
440/*$moreforfilter.='<div class="divsearchfield">';
441$moreforfilter.= $langs->trans('MyFilter') . ': <input type="text" name="search_myfield" value="'.dol_escape_htmltag($search_myfield).'">';
442$moreforfilter.= '</div>';*/
443
444$parameters = array();
445$reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook
446if (empty($reshook)) $moreforfilter .= $hookmanager->resPrint;
447else $moreforfilter = $hookmanager->resPrint;
448
449if (!empty($moreforfilter))
450{
451	print '<div class="liste_titre liste_titre_bydiv centpercent">';
452	print $moreforfilter;
453	print '</div>';
454}
455
456$varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage;
457$selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields
458$selectedfields .= (count($arrayofmassactions) ? $form->showCheckAddButtons('checkforselect', 1) : '');
459
460print '<div class="div-table-responsive">'; // You can use div-table-responsive-no-min if you dont need reserved height for your table
461print '<table class="tagtable liste'.($moreforfilter ? " listwithfilterbefore" : "").'">'."\n";
462
463
464// Fields title search
465// --------------------------------------------------------------------
466print '<tr class="liste_titre">';
467foreach ($object->fields as $key => $val)
468{
469	$cssforfield = (empty($val['css']) ? '' : $val['css']);
470	if ($key == 'status') $cssforfield .= ($cssforfield ? ' ' : '').'center';
471	elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'center';
472	elseif (in_array($val['type'], array('timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'nowrap';
473	elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') $cssforfield .= ($cssforfield ? ' ' : '').'right';
474	if (!empty($arrayfields['t.'.$key]['checked']))
475	{
476		print '<td class="liste_titre'.($cssforfield ? ' '.$cssforfield : '').'">';
477		if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) print $form->selectarray('search_'.$key, $val['arrayofkeyval'], $search[$key], $val['notnull'], 0, 0, '', 1, 0, 0, '', 'maxwidth100', 1);
478		elseif (strpos($val['type'], 'integer:') === 0) {
479			print $object->showInputField($val, $key, $search[$key], '', '', 'search_', 'maxwidth150', 1);
480		} elseif (!preg_match('/^(date|timestamp)/', $val['type'])) print '<input type="text" class="flat maxwidth75" name="search_'.$key.'" value="'.dol_escape_htmltag($search[$key]).'">';
481		print '</td>';
482	}
483}
484// Extra fields
485include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php';
486// Fields from hook
487$parameters = array('arrayfields'=>$arrayfields);
488$reshook = $hookmanager->executeHooks('printFieldListOption', $parameters, $object); // Note that $action and $object may have been modified by hook
489print $hookmanager->resPrint;
490// Action column
491print '<td class="liste_titre maxwidthsearch">';
492$searchpicto = $form->showFilterButtons();
493print $searchpicto;
494print '</td>';
495print '</tr>'."\n";
496
497
498// Fields title label
499// --------------------------------------------------------------------
500print '<tr class="liste_titre">';
501foreach ($object->fields as $key => $val)
502{
503	$cssforfield = (empty($val['css']) ? '' : $val['css']);
504	if ($key == 'status') $cssforfield .= ($cssforfield ? ' ' : '').'center';
505	elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'center';
506	elseif (in_array($val['type'], array('timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'nowrap';
507	elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') $cssforfield .= ($cssforfield ? ' ' : '').'right';
508	if (!empty($arrayfields['t.'.$key]['checked']))
509	{
510		print getTitleFieldOfList($arrayfields['t.'.$key]['label'], 0, $_SERVER['PHP_SELF'], 't.'.$key, '', $param, ($cssforfield ? 'class="'.$cssforfield.'"' : ''), $sortfield, $sortorder, ($cssforfield ? $cssforfield.' ' : ''))."\n";
511	}
512}
513// Extra fields
514include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php';
515
516// Hook fields
517$parameters = array('arrayfields'=>$arrayfields, 'param'=>$param, 'sortfield'=>$sortfield, 'sortorder'=>$sortorder);
518$reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook
519print $hookmanager->resPrint;
520// Action column
521print getTitleFieldOfList($selectedfields, 0, $_SERVER["PHP_SELF"], '', '', '', '', $sortfield, $sortorder, 'center maxwidthsearch ')."\n";
522print '</tr>'."\n";
523
524
525// Detect if we need a fetch on each output line
526$needToFetchEachLine = 0;
527if (is_array($extrafields->attributes[$object->table_element]['computed']) && count($extrafields->attributes[$object->table_element]['computed']) > 0)
528{
529	foreach ($extrafields->attributes[$object->table_element]['computed'] as $key => $val)
530	{
531		if (preg_match('/\$object/', $val)) $needToFetchEachLine++; // There is at least one compute field that use $object
532	}
533}
534
535
536// Loop on record
537// --------------------------------------------------------------------
538$i = 0;
539$totalarray = array();
540while ($i < ($limit ? min($num, $limit) : $num))
541{
542	$obj = $db->fetch_object($resql);
543	if (empty($obj)) break; // Should not happen
544
545	// Store properties in $object
546	$object->setVarsFromFetchObj($obj);
547
548	// Show here line of result
549	print '<tr class="oddeven">';
550	foreach ($object->fields as $key => $val)
551	{
552		$cssforfield = (empty($val['css']) ? '' : $val['css']);
553		if (in_array($val['type'], array('date', 'datetime', 'timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'center';
554		elseif ($key == 'status') $cssforfield .= ($cssforfield ? ' ' : '').'center';
555
556		if (in_array($val['type'], array('timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'nowrap';
557		elseif ($key == 'ref') $cssforfield .= ($cssforfield ? ' ' : '').'nowrap';
558
559		if (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $key != 'status') $cssforfield .= ($cssforfield ? ' ' : '').'right';
560
561		if (!empty($arrayfields['t.'.$key]['checked']))
562		{
563			print '<td'.($cssforfield ? ' class="'.$cssforfield.'"' : '').'>';
564			if ($key == 'status' || $key == 'active') print $object->getLibStatut(5);
565			else print $object->showOutputField($val, $key, $object->$key, '');
566			print '</td>';
567			if (!$i) $totalarray['nbfield']++;
568			if (!empty($val['isameasure']))
569			{
570				if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 't.'.$key;
571				$totalarray['val']['t.'.$key] += $object->$key;
572			}
573		}
574	}
575	// Extra fields
576	include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php';
577	// Fields from hook
578	$parameters = array('arrayfields'=>$arrayfields, 'object'=>$object, 'obj'=>$obj, 'i'=>$i, 'totalarray'=>&$totalarray);
579	$reshook = $hookmanager->executeHooks('printFieldListValue', $parameters, $object); // Note that $action and $object may have been modified by hook
580	print $hookmanager->resPrint;
581	// Action column
582	print '<td class="nowrap center">';
583	$url = $_SERVER["PHP_SELF"].'?id='.$obj->rowid;
584	if ($limit) $url .= '&limit='.urlencode($limit);
585	if ($page) $url .= '&page='.urlencode($page);
586	if ($sortfield) $url .= '&sortfield='.urlencode($sortfield);
587	if ($sortorder) $url .= '&page='.urlencode($sortorder);
588	print '<a class="editfielda reposition marginrightonly marginleftonly" href="'.$url.'&action=edit&rowid='.$obj->rowid.'">'.img_edit().'</a>';
589	//print ' &nbsp; ';
590	print '<a class=" marginrightonly marginleftonly" href="'.$url.'&action=delete&token='.newToken().'">'.img_delete().'</a>  &nbsp; ';
591	if ($massactionbutton || $massaction)   // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined
592	{
593		$selected = 0;
594		if (in_array($object->id, $arrayofselected)) $selected = 1;
595		print '<input id="cb'.$object->id.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$object->rowid.'"'.($selected ? ' checked="checked"' : '').'>';
596	}
597	print '</td>';
598	if (!$i) $totalarray['nbfield']++;
599
600	print '</tr>'."\n";
601
602	$i++;
603}
604
605// Show total line
606include DOL_DOCUMENT_ROOT.'/core/tpl/list_print_total.tpl.php';
607
608
609// If no record found
610if ($num == 0)
611{
612	$colspan = 1;
613	foreach ($arrayfields as $key => $val) { if (!empty($val['checked'])) $colspan++; }
614	print '<tr><td colspan="'.$colspan.'" class="opacitymedium">'.$langs->trans("NoRecordFound").'</td></tr>';
615}
616
617
618$db->free($resql);
619
620$parameters = array('arrayfields'=>$arrayfields, 'sql'=>$sql);
621$reshook = $hookmanager->executeHooks('printFieldListFooter', $parameters, $object); // Note that $action and $object may have been modified by hook
622print $hookmanager->resPrint;
623
624print '</table>'."\n";
625print '</div>'."\n";
626
627print '</form>'."\n";
628
629if (in_array('builddoc', $arrayofmassactions) && ($nbtotalofrecords === '' || $nbtotalofrecords))
630{
631	$hidegeneratedfilelistifempty = 1;
632	if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) $hidegeneratedfilelistifempty = 0;
633
634	require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
635	$formfile = new FormFile($db);
636
637	// Show list of available documents
638	$urlsource = $_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder;
639	$urlsource .= str_replace('&amp;', '&', $param);
640
641	$filedir = $diroutputmassaction;
642	$genallowed = $permissiontoread;
643	$delallowed = $permissiontoadd;
644
645	print $formfile->showdocuments('massfilesarea_emailsenderprofile', '', $filedir, $urlsource, 0, $delallowed, '', 1, 1, 0, 48, 1, $param, $title, '', '', '', null, $hidegeneratedfilelistifempty);
646}
647
648print dol_get_fiche_end();
649
650// End of page
651llxFooter();
652$db->close();
653