1<?php
2/* Copyright (C) 2006-2011  Laurent Destailleur     <eldy@users.sourceforge.net>
3 * Copyright (C) 2006       Rodolphe Quiedeville    <rodolphe@quiedeville.org>
4 * Copyright (C) 2007       Patrick Raguin          <patrick.raguin@gmail.com>
5 * Copyright (C) 2010-2012  Regis Houssin           <regis.houssin@inodbox.com>
6 * Copyright (C) 2013-2014  Florian Henry           <florian.henry@open-concept.pro>
7 * Copyright (C) 2013-2014  Juanjo Menent           <jmenent@2byte.es>
8 * Copyright (C) 2013       Christophe Battarel     <contact@altairis.fr>
9 * Copyright (C) 2013-2018  Alexandre Spangaro      <aspangaro@open-dsi.fr>
10 * Copyright (C) 2015-2021  Frédéric France         <frederic.france@netlogic.fr>
11 * Copyright (C) 2015       Raphaël Doursenaud      <rdoursenaud@gpcsolutions.fr>
12 * Copyright (C) 2017       Rui Strecht             <rui.strecht@aliartalentos.com>
13 * Copyright (C) 2018       Ferran Marcet           <fmarcet@2byte.es>
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 <https://www.gnu.org/licenses/>.
27 * or see https://www.gnu.org/
28 */
29
30/**
31 *	\file       htdocs/core/lib/company.lib.php
32 *	\brief      Ensemble de fonctions de base pour le module societe
33 *	\ingroup    societe
34 */
35
36/**
37 * Return array of tabs to used on pages for third parties cards.
38 *
39 * @param 	Societe	$object		Object company shown
40 * @return 	array				Array of tabs
41 */
42function societe_prepare_head(Societe $object)
43{
44	global $db, $langs, $conf, $user;
45	$h = 0;
46	$head = array();
47
48	$head[$h][0] = DOL_URL_ROOT.'/societe/card.php?socid='.$object->id;
49	$head[$h][1] = $langs->trans("ThirdParty");
50	$head[$h][2] = 'card';
51	$h++;
52
53	if (empty($conf->global->MAIN_SUPPORT_SHARED_CONTACT_BETWEEN_THIRDPARTIES)) {
54		if (empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && $user->rights->societe->contact->lire) {
55			//$nbContact = count($object->liste_contact(-1,'internal')) + count($object->liste_contact(-1,'external'));
56			$nbContact = 0;
57			// Enable caching of thirdrparty count Contacts
58			require_once DOL_DOCUMENT_ROOT.'/core/lib/memory.lib.php';
59			$cachekey = 'count_contacts_thirdparty_'.$object->id;
60			$dataretrieved = dol_getcache($cachekey);
61
62			if (!is_null($dataretrieved)) {
63				$nbContact = $dataretrieved;
64			} else {
65				$sql = "SELECT COUNT(p.rowid) as nb";
66				$sql .= " FROM ".MAIN_DB_PREFIX."socpeople as p";
67				$sql .= " WHERE p.fk_soc = ".$object->id;
68				$resql = $db->query($sql);
69				if ($resql) {
70					$obj = $db->fetch_object($resql);
71					$nbContact = $obj->nb;
72				}
73
74				dol_setcache($cachekey, $nbContact, 120);	// If setting cache fails, this is not a problem, so we do not test result.
75			}
76
77			$head[$h][0] = DOL_URL_ROOT.'/societe/contact.php?socid='.$object->id;
78			$head[$h][1] = $langs->trans('ContactsAddresses');
79			if ($nbContact > 0) {
80				$head[$h][1] .= '<span class="badge marginleftonlyshort">'.$nbContact.'</span>';
81			}
82			$head[$h][2] = 'contact';
83			$h++;
84		}
85	} else {
86		$head[$h][0] = DOL_URL_ROOT.'/societe/societecontact.php?socid='.$object->id;
87		$nbContact = count($object->liste_contact(-1, 'internal')) + count($object->liste_contact(-1, 'external'));
88		$head[$h][1] = $langs->trans("ContactsAddresses");
89		if ($nbContact > 0) {
90			$head[$h][1] .= '<span class="badge marginleftonlyshort">'.$nbContact.'</span>';
91		}
92		$head[$h][2] = 'contact';
93		$h++;
94	}
95
96	if ($object->client == 1 || $object->client == 2 || $object->client == 3) {
97		$head[$h][0] = DOL_URL_ROOT.'/comm/card.php?socid='.$object->id;
98		$head[$h][1] = '';
99		if (empty($conf->global->SOCIETE_DISABLE_PROSPECTS) && ($object->client == 2 || $object->client == 3)) {
100			$head[$h][1] .= $langs->trans("Prospect");
101		}
102		if (empty($conf->global->SOCIETE_DISABLE_PROSPECTS) && empty($conf->global->SOCIETE_DISABLE_CUSTOMERS) && $object->client == 3) {
103			$head[$h][1] .= ' | ';
104		}
105		if (empty($conf->global->SOCIETE_DISABLE_CUSTOMERS) && ($object->client == 1 || $object->client == 3)) {
106			$head[$h][1] .= $langs->trans("Customer");
107		}
108		$head[$h][2] = 'customer';
109		$h++;
110
111		if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) {
112			$langs->load("products");
113			// price
114			$head[$h][0] = DOL_URL_ROOT.'/societe/price.php?socid='.$object->id;
115			$head[$h][1] = $langs->trans("CustomerPrices");
116			$head[$h][2] = 'price';
117			$h++;
118		}
119	}
120	$supplier_module_enabled = 0;
121	if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)) || !empty($conf->supplier_proposal->enabled) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled)) {
122		$supplier_module_enabled = 1;
123	}
124	if ($supplier_module_enabled == 1 && $object->fournisseur && !empty($user->rights->fournisseur->lire)) {
125		$head[$h][0] = DOL_URL_ROOT.'/fourn/card.php?socid='.$object->id;
126		$head[$h][1] = $langs->trans("Supplier");
127		$head[$h][2] = 'supplier';
128		$h++;
129	}
130
131	if (!empty($conf->projet->enabled) && (!empty($user->rights->projet->lire))) {
132		$nbProject = 0;
133		// Enable caching of thirdrparty count projects
134		require_once DOL_DOCUMENT_ROOT.'/core/lib/memory.lib.php';
135		$cachekey = 'count_projects_thirdparty_'.$object->id;
136		$dataretrieved = dol_getcache($cachekey);
137
138		if (!is_null($dataretrieved)) {
139			$nbProject = $dataretrieved;
140		} else {
141			$sql = "SELECT COUNT(n.rowid) as nb";
142			$sql .= " FROM ".MAIN_DB_PREFIX."projet as n";
143			$sql .= " WHERE fk_soc = ".$object->id;
144			$sql .= " AND entity IN (".getEntity('project').")";
145			$resql = $db->query($sql);
146			if ($resql) {
147				$obj = $db->fetch_object($resql);
148				$nbProject = $obj->nb;
149			} else {
150				dol_print_error($db);
151			}
152			dol_setcache($cachekey, $nbProject, 120);	// If setting cache fails, this is not a problem, so we do not test result.
153		}
154		$head[$h][0] = DOL_URL_ROOT.'/societe/project.php?socid='.$object->id;
155		$head[$h][1] = $langs->trans("Projects");
156		if ($nbProject > 0) {
157			$head[$h][1] .= '<span class="badge marginleftonlyshort">'.$nbProject.'</span>';
158		}
159		$head[$h][2] = 'project';
160		$h++;
161	}
162
163	// Tab to link resources
164	if (!empty($conf->resource->enabled) && !empty($conf->global->RESOURCE_ON_THIRDPARTIES)) {
165		$head[$h][0] = DOL_URL_ROOT.'/resource/element_resource.php?element=societe&element_id='.$object->id;
166		$head[$h][1] = $langs->trans("Resources");
167		$head[$h][2] = 'resources';
168		$h++;
169	}
170
171	if (!empty($conf->global->ACCOUNTING_ENABLE_LETTERING)) {
172		// Tab to accountancy
173		if (!empty($conf->accounting->enabled) && $object->client > 0) {
174			$head[$h][0] = DOL_URL_ROOT.'/accountancy/bookkeeping/thirdparty_lettering_customer.php?socid='.$object->id;
175			$head[$h][1] = $langs->trans("TabLetteringCustomer");
176			$head[$h][2] = 'lettering_customer';
177			$h++;
178		}
179
180		// Tab to accountancy
181		if (!empty($conf->accounting->enabled) && $object->fournisseur > 0) {
182			$head[$h][0] = DOL_URL_ROOT.'/accountancy/bookkeeping/thirdparty_lettering_supplier.php?socid='.$object->id;
183			$head[$h][1] = $langs->trans("TabLetteringSupplier");
184			$head[$h][2] = 'lettering_supplier';
185			$h++;
186		}
187	}
188
189	// Related items
190	if ((!empty($conf->commande->enabled) || !empty($conf->propal->enabled) || !empty($conf->facture->enabled) || !empty($conf->ficheinter->enabled) || (!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled))
191		&& empty($conf->global->THIRPARTIES_DISABLE_RELATED_OBJECT_TAB)) {
192		$head[$h][0] = DOL_URL_ROOT.'/societe/consumption.php?socid='.$object->id;
193		$head[$h][1] = $langs->trans("Referers");
194		$head[$h][2] = 'consumption';
195		$h++;
196	}
197
198	// Bank accounts
199	if (empty($conf->global->SOCIETE_DISABLE_BANKACCOUNT)) {
200		$nbBankAccount = 0;
201		$foundonexternalonlinesystem = 0;
202		$langs->load("banks");
203
204		//$title = $langs->trans("BankAccounts");
205		$title = $langs->trans("PaymentInformation");
206
207		if (!empty($conf->stripe->enabled)) {
208			//$langs->load("stripe");
209			//$title = $langs->trans("BankAccountsAndGateways");
210
211			$servicestatus = 0;
212			if (!empty($conf->global->STRIPE_LIVE) && !GETPOST('forcesandbox', 'alpha')) {
213				$servicestatus = 1;
214			}
215
216			include_once DOL_DOCUMENT_ROOT.'/societe/class/societeaccount.class.php';
217			$societeaccount = new SocieteAccount($db);
218			$stripecu = $societeaccount->getCustomerAccount($object->id, 'stripe', $servicestatus); // Get thirdparty cu_...
219			if ($stripecu) {
220				$foundonexternalonlinesystem++;
221			}
222		}
223
224		$sql = "SELECT COUNT(n.rowid) as nb";
225		$sql .= " FROM ".MAIN_DB_PREFIX."societe_rib as n";
226		$sql .= " WHERE n.fk_soc = ".$object->id;
227		if (empty($conf->stripe->enabled)) {
228			$sql .= " AND n.stripe_card_ref IS NULL";
229		} else {
230			$sql .= " AND (n.stripe_card_ref IS NULL OR (n.stripe_card_ref IS NOT NULL AND n.status = ".((int) $servicestatus)."))";
231		}
232
233		$resql = $db->query($sql);
234		if ($resql) {
235			$obj = $db->fetch_object($resql);
236			$nbBankAccount = $obj->nb;
237		} else {
238			dol_print_error($db);
239		}
240
241		//if (! empty($conf->stripe->enabled) && $nbBankAccount > 0) $nbBankAccount = '...';	// No way to know exact number
242
243		$head[$h][0] = DOL_URL_ROOT.'/societe/paymentmodes.php?socid='.$object->id;
244		$head[$h][1] = $title;
245		if ($foundonexternalonlinesystem) {
246			$head[$h][1] .= '<span class="badge marginleftonlyshort">...</span>';
247		} elseif ($nbBankAccount > 0) {
248			$head[$h][1] .= '<span class="badge marginleftonlyshort">'.$nbBankAccount.'</span>';
249		}
250		$head[$h][2] = 'rib';
251		$h++;
252	}
253
254	if (!empty($conf->website->enabled) && (!empty($conf->global->WEBSITE_USE_WEBSITE_ACCOUNTS)) && (!empty($user->rights->societe->lire))) {
255		$head[$h][0] = DOL_URL_ROOT.'/societe/website.php?id='.$object->id;
256		$head[$h][1] = $langs->trans("WebSiteAccounts");
257		$nbNote = 0;
258		$sql = "SELECT COUNT(n.rowid) as nb";
259		$sql .= " FROM ".MAIN_DB_PREFIX."societe_account as n";
260		$sql .= " WHERE fk_soc = ".$object->id.' AND fk_website > 0';
261		$resql = $db->query($sql);
262		if ($resql) {
263			$obj = $db->fetch_object($resql);
264			$nbNote = $obj->nb;
265		} else {
266			dol_print_error($db);
267		}
268		if ($nbNote > 0) {
269			$head[$h][1] .= '<span class="badge marginleftonlyshort">'.$nbNote.'</span>';
270		}
271		$head[$h][2] = 'website';
272		$h++;
273	}
274
275	if (getDolGlobalString('PARTNERSHIP_IS_MANAGED_FOR') == 'thirdparty') {
276		if (!empty($user->rights->partnership->read)) {
277			$nbPartnership = is_array($object->partnerships) ? count($object->partnerships) : 0;
278			$head[$h][0] = DOL_URL_ROOT.'/societe/partnership.php?socid='.$object->id;
279			$head[$h][1] = $langs->trans("Partnership");
280			$head[$h][2] = 'partnership';
281			if ($nbPartnership > 0) {
282				$head[$h][1] .= '<span class="badge marginleftonlyshort">'.$nbPartnership.'</span>';
283			}
284			$h++;
285		}
286	}
287
288	// Show more tabs from modules
289	// Entries must be declared in modules descriptor with line
290	// $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__');   to add new tab
291	// $this->tabs = array('entity:-tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__');   to remove a tab
292	complete_head_from_modules($conf, $langs, $object, $head, $h, 'thirdparty');
293
294	if ($user->socid == 0) {
295		// Notifications
296		if (!empty($conf->notification->enabled)) {
297			$nbNotif = 0;
298			// Enable caching of thirdrparty count notifications
299			require_once DOL_DOCUMENT_ROOT.'/core/lib/memory.lib.php';
300			$cachekey = 'count_notifications_thirdparty_'.$object->id;
301			$dataretrieved = dol_getcache($cachekey);
302			if (!is_null($dataretrieved)) {
303				$nbNotif = $dataretrieved;
304			} else {
305				$sql = "SELECT COUNT(n.rowid) as nb";
306				$sql .= " FROM ".MAIN_DB_PREFIX."notify_def as n";
307				$sql .= " WHERE fk_soc = ".$object->id;
308				$resql = $db->query($sql);
309				if ($resql) {
310					$obj = $db->fetch_object($resql);
311					$nbNotif = $obj->nb;
312				} else {
313					dol_print_error($db);
314				}
315				dol_setcache($cachekey, $nbNotif, 120);		// If setting cache fails, this is not a problem, so we do not test result.
316			}
317
318			$head[$h][0] = DOL_URL_ROOT.'/societe/notify/card.php?socid='.$object->id;
319			$head[$h][1] = $langs->trans("Notifications");
320			if ($nbNotif > 0) {
321				$head[$h][1] .= '<span class="badge marginleftonlyshort">'.$nbNotif.'</span>';
322			}
323			$head[$h][2] = 'notify';
324			$h++;
325		}
326
327		// Notes
328		$nbNote = 0;
329		if (!empty($object->note_private)) {
330			$nbNote++;
331		}
332		if (!empty($object->note_public)) {
333			$nbNote++;
334		}
335		$head[$h][0] = DOL_URL_ROOT.'/societe/note.php?id='.$object->id;
336		$head[$h][1] = $langs->trans("Notes");
337		if ($nbNote > 0) {
338			$head[$h][1] .= '<span class="badge marginleftonlyshort">'.$nbNote.'</span>';
339		}
340		$head[$h][2] = 'note';
341		$h++;
342
343		// Attached files and Links
344		$totalAttached = 0;
345		// Enable caching of thirdrparty count attached files and links
346		require_once DOL_DOCUMENT_ROOT.'/core/lib/memory.lib.php';
347		$cachekey = 'count_attached_thirdparty_'.$object->id;
348		$dataretrieved = dol_getcache($cachekey);
349		if (!is_null($dataretrieved)) {
350			$totalAttached = $dataretrieved;
351		} else {
352			require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
353			require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php';
354			$upload_dir = $conf->societe->multidir_output[$object->entity]."/".$object->id;
355			$nbFiles = count(dol_dir_list($upload_dir, 'files', 0, '', '(\.meta|_preview.*\.png)$'));
356			$nbLinks = Link::count($db, $object->element, $object->id);
357			$totalAttached = $nbFiles + $nbLinks;
358			dol_setcache($cachekey, $totalAttached, 120);		// If setting cache fails, this is not a problem, so we do not test result.
359		}
360
361		$head[$h][0] = DOL_URL_ROOT.'/societe/document.php?socid='.$object->id;
362		$head[$h][1] = $langs->trans("Documents");
363		if (($totalAttached) > 0) {
364			$head[$h][1] .= '<span class="badge marginleftonlyshort">'.($totalAttached).'</span>';
365		}
366		$head[$h][2] = 'document';
367		$h++;
368	}
369
370	$head[$h][0] = DOL_URL_ROOT.'/societe/agenda.php?socid='.$object->id;
371	$head[$h][1] = $langs->trans("Events");
372	if (!empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read))) {
373		$nbEvent = 0;
374		// Enable caching of thirdrparty count actioncomm
375		require_once DOL_DOCUMENT_ROOT.'/core/lib/memory.lib.php';
376		$cachekey = 'count_events_thirdparty_'.$object->id;
377		$dataretrieved = dol_getcache($cachekey);
378		if (!is_null($dataretrieved)) {
379			$nbEvent = $dataretrieved;
380		} else {
381			$sql = "SELECT COUNT(id) as nb";
382			$sql .= " FROM ".MAIN_DB_PREFIX."actioncomm";
383			$sql .= " WHERE fk_soc = ".$object->id;
384			$resql = $db->query($sql);
385			if ($resql) {
386				$obj = $db->fetch_object($resql);
387				$nbEvent = $obj->nb;
388			} else {
389				dol_syslog('Failed to count actioncomm '.$db->lasterror(), LOG_ERR);
390			}
391			dol_setcache($cachekey, $nbEvent, 120);		// If setting cache fails, this is not a problem, so we do not test result.
392		}
393
394		$head[$h][1] .= '/';
395		$head[$h][1] .= $langs->trans("Agenda");
396		if ($nbEvent > 0) {
397			$head[$h][1] .= '<span class="badge marginleftonlyshort">'.$nbEvent.'</span>';
398		}
399	}
400	$head[$h][2] = 'agenda';
401	$h++;
402
403	// Log
404	/*$head[$h][0] = DOL_URL_ROOT.'/societe/info.php?socid='.$object->id;
405	$head[$h][1] = $langs->trans("Info");
406	$head[$h][2] = 'info';
407	$h++;*/
408
409	complete_head_from_modules($conf, $langs, $object, $head, $h, 'thirdparty', 'remove');
410
411	return $head;
412}
413
414
415/**
416 * Return array of tabs to used on page
417 *
418 * @param	Object	$object		Object for tabs
419 * @return	array				Array of tabs
420 */
421function societe_prepare_head2($object)
422{
423	global $langs, $conf, $user;
424	$h = 0;
425	$head = array();
426
427	$head[$h][0] = DOL_URL_ROOT.'/societe/card.php?socid='.$object->id;
428	$head[$h][1] = $langs->trans("ThirdParty");
429	$head[$h][2] = 'company';
430	$h++;
431
432	$head[$h][0] = 'commerciaux.php?socid='.$object->id;
433	$head[$h][1] = $langs->trans("SalesRepresentative");
434	$head[$h][2] = 'salesrepresentative';
435	$h++;
436
437	return $head;
438}
439
440
441
442/**
443 *  Return array head with list of tabs to view object informations.
444 *
445 *  @return	array   	        head array with tabs
446 */
447function societe_admin_prepare_head()
448{
449	global $langs, $conf, $user;
450
451	$h = 0;
452	$head = array();
453
454	$head[$h][0] = DOL_URL_ROOT.'/societe/admin/societe.php';
455	$head[$h][1] = $langs->trans("Miscellaneous");
456	$head[$h][2] = 'general';
457	$h++;
458
459	// Show more tabs from modules
460	// Entries must be declared in modules descriptor with line
461	// $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__');   to add new tab
462	// $this->tabs = array('entity:-tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__');   to remove a tab
463	complete_head_from_modules($conf, $langs, null, $head, $h, 'company_admin');
464
465	$head[$h][0] = DOL_URL_ROOT.'/societe/admin/societe_extrafields.php';
466	$head[$h][1] = $langs->trans("ExtraFieldsThirdParties");
467	$head[$h][2] = 'attributes';
468	$h++;
469
470	$head[$h][0] = DOL_URL_ROOT.'/societe/admin/contact_extrafields.php';
471	$head[$h][1] = $langs->trans("ExtraFieldsContacts");
472	$head[$h][2] = 'attributes_contacts';
473	$h++;
474
475	complete_head_from_modules($conf, $langs, null, $head, $h, 'company_admin', 'remove');
476
477	return $head;
478}
479
480
481
482/**
483 *    Return country label, code or id from an id, code or label
484 *
485 *    @param      int		$searchkey      Id or code of country to search
486 *    @param      string	$withcode   	'0'=Return label,
487 *    										'1'=Return code + label,
488 *    										'2'=Return code from id,
489 *    										'3'=Return id from code,
490 * 	   										'all'=Return array('id'=>,'code'=>,'label'=>)
491 *    @param      DoliDB	$dbtouse       	Database handler (using in global way may fail because of conflicts with some autoload features)
492 *    @param      Translate	$outputlangs	Langs object for output translation
493 *    @param      int		$entconv       	0=Return value without entities and not converted to output charset, 1=Ready for html output
494 *    @param      int		$searchlabel    Label of country to search (warning: searching on label is not reliable)
495 *    @return     mixed       				Integer with country id or String with country code or translated country name or Array('id','code','label') or 'NotDefined'
496 */
497function getCountry($searchkey, $withcode = '', $dbtouse = 0, $outputlangs = '', $entconv = 1, $searchlabel = '')
498{
499	global $db, $langs;
500
501	$result = '';
502
503	// Check parameters
504	if (empty($searchkey) && empty($searchlabel)) {
505		if ($withcode === 'all') {
506			return array('id'=>'', 'code'=>'', 'label'=>'');
507		} else {
508			return '';
509		}
510	}
511	if (!is_object($dbtouse)) {
512		$dbtouse = $db;
513	}
514	if (!is_object($outputlangs)) {
515		$outputlangs = $langs;
516	}
517
518	$sql = "SELECT rowid, code, label FROM ".MAIN_DB_PREFIX."c_country";
519	if (is_numeric($searchkey)) {
520		$sql .= " WHERE rowid = ".((int) $searchkey);
521	} elseif (!empty($searchkey)) {
522		$sql .= " WHERE code = '".$db->escape($searchkey)."'";
523	} else {
524		$sql .= " WHERE label = '".$db->escape($searchlabel)."'";
525	}
526
527	$resql = $dbtouse->query($sql);
528	if ($resql) {
529		$obj = $dbtouse->fetch_object($resql);
530		if ($obj) {
531			$label = ((!empty($obj->label) && $obj->label != '-') ? $obj->label : '');
532			if (is_object($outputlangs)) {
533				$outputlangs->load("dict");
534				if ($entconv) {
535					$label = ($obj->code && ($outputlangs->trans("Country".$obj->code) != "Country".$obj->code)) ? $outputlangs->trans("Country".$obj->code) : $label;
536				} else {
537					$label = ($obj->code && ($outputlangs->transnoentitiesnoconv("Country".$obj->code) != "Country".$obj->code)) ? $outputlangs->transnoentitiesnoconv("Country".$obj->code) : $label;
538				}
539			}
540			if ($withcode == 1) {
541				$result = $label ? "$obj->code - $label" : "$obj->code";
542			} elseif ($withcode == 2) {
543				$result = $obj->code;
544			} elseif ($withcode == 3) {
545				$result = $obj->rowid;
546			} elseif ($withcode === 'all') {
547				$result = array('id'=>$obj->rowid, 'code'=>$obj->code, 'label'=>$label);
548			} else {
549				$result = $label;
550			}
551		} else {
552			$result = 'NotDefined';
553		}
554		$dbtouse->free($resql);
555		return $result;
556	} else {
557		dol_print_error($dbtouse, '');
558	}
559	return 'Error';
560}
561
562/**
563 *    Return state translated from an id. Return value is always utf8 encoded and without entities.
564 *
565 *    @param    int			$id         	id of state (province/departement)
566 *    @param    int			$withcode   	'0'=Return label,
567 *    										'1'=Return string code + label,
568 *    						  				'2'=Return code,
569 *    						  				'all'=return array('id'=>,'code'=>,'label'=>)
570 *    @param	DoliDB		$dbtouse		Database handler (using in global way may fail because of conflicts with some autoload features)
571 *    @param    int			$withregion   	'0'=Ignores region,
572 *    										'1'=Add region name/code/id as needed to output,
573 *    @param    Translate	$outputlangs	Langs object for output translation, not fully implemented yet
574 *    @param    int		    $entconv       	0=Return value without entities and not converted to output charset, 1=Ready for html output
575 *    @return   string|array       			String with state code or state name or Array('id','code','label')/Array('id','code','label','region_code','region')
576 */
577function getState($id, $withcode = '', $dbtouse = 0, $withregion = 0, $outputlangs = '', $entconv = 1)
578{
579	global $db, $langs;
580
581	if (!is_object($dbtouse)) {
582		$dbtouse = $db;
583	}
584
585	$sql = "SELECT d.rowid as id, d.code_departement as code, d.nom as name, d.active, c.label as country, c.code as country_code, r.code_region as region_code, r.nom as region_name FROM";
586	$sql .= " ".MAIN_DB_PREFIX."c_departements as d, ".MAIN_DB_PREFIX."c_regions as r,".MAIN_DB_PREFIX."c_country as c";
587	$sql .= " WHERE d.fk_region=r.code_region and r.fk_pays=c.rowid and d.rowid=".((int) $id);
588	$sql .= " AND d.active = 1 AND r.active = 1 AND c.active = 1";
589	$sql .= " ORDER BY c.code, d.code_departement";
590
591	dol_syslog("Company.lib::getState", LOG_DEBUG);
592	$resql = $dbtouse->query($sql);
593	if ($resql) {
594		$obj = $dbtouse->fetch_object($resql);
595		if ($obj) {
596			$label = ((!empty($obj->name) && $obj->name != '-') ? $obj->name : '');
597			if (is_object($outputlangs)) {
598				$outputlangs->load("dict");
599				if ($entconv) {
600					$label = ($obj->code && ($outputlangs->trans("State".$obj->code) != "State".$obj->code)) ? $outputlangs->trans("State".$obj->code) : $label;
601				} else {
602					$label = ($obj->code && ($outputlangs->transnoentitiesnoconv("State".$obj->code) != "State".$obj->code)) ? $outputlangs->transnoentitiesnoconv("State".$obj->code) : $label;
603				}
604			}
605
606			if ($withcode == 1) {
607				if ($withregion == 1) {
608					return $label = $obj->region_name.' - '.$obj->code.' - '.($langs->trans($obj->code) != $obj->code ? $langs->trans($obj->code) : ($obj->name != '-' ? $obj->name : ''));
609				} else {
610					return $label = $obj->code.' - '.($langs->trans($obj->code) != $obj->code ? $langs->trans($obj->code) : ($obj->name != '-' ? $obj->name : ''));
611				}
612			} elseif ($withcode == 2) {
613				if ($withregion == 1) {
614					return $label = $obj->region_name.' - '.($langs->trans($obj->code) != $obj->code ? $langs->trans($obj->code) : ($obj->name != '-' ? $obj->name : ''));
615				} else {
616					return $label = ($langs->trans($obj->code) != $obj->code ? $langs->trans($obj->code) : ($obj->name != '-' ? $obj->name : ''));
617				}
618			} elseif ($withcode === 'all') {
619				if ($withregion == 1) {
620					return array('id'=>$obj->id, 'code'=>$obj->code, 'label'=>$label, 'region_code'=>$obj->region_code, 'region'=>$obj->region_name);
621				} else {
622					return array('id'=>$obj->id, 'code'=>$obj->code, 'label'=>$label);
623				}
624			} else {
625				if ($withregion == 1) {
626					return $label = $obj->region_name.' - '.$label;
627				} else {
628					return $label;
629				}
630			}
631		} else {
632			return $langs->transnoentitiesnoconv("NotDefined");
633		}
634	} else {
635		dol_print_error($dbtouse, '');
636	}
637}
638
639/**
640 *    Return label of currency or code+label
641 *
642 *    @param      string	$code_iso       Code iso of currency
643 *    @param      int		$withcode       '1'=show code + label
644 *    @param      Translate $outputlangs    Output language
645 *    @return     string     			    Label translated of currency
646 */
647function currency_name($code_iso, $withcode = '', $outputlangs = null)
648{
649	global $langs, $db;
650
651	if (empty($outputlangs)) {
652		$outputlangs = $langs;
653	}
654
655	$outputlangs->load("dict");
656
657	// If there is a translation, we can send immediatly the label
658	if ($outputlangs->trans("Currency".$code_iso) != "Currency".$code_iso) {
659		return ($withcode ? $code_iso.' - ' : '').$outputlangs->trans("Currency".$code_iso);
660	}
661
662	// If no translation, we read table to get label by default
663	$sql = "SELECT label FROM ".MAIN_DB_PREFIX."c_currencies";
664	$sql .= " WHERE code_iso='".$db->escape($code_iso)."'";
665
666	$resql = $db->query($sql);
667	if ($resql) {
668		$num = $db->num_rows($resql);
669
670		if ($num) {
671			$obj = $db->fetch_object($resql);
672			$label = ($obj->label != '-' ? $obj->label : '');
673			if ($withcode) {
674				return ($label == $code_iso) ? "$code_iso" : "$code_iso - $label";
675			} else {
676				return $label;
677			}
678		} else {
679			return $code_iso;
680		}
681	}
682	return 'ErrorWhenReadingCurrencyLabel';
683}
684
685/**
686 *    Retourne le nom traduit de la forme juridique
687 *
688 *    @param      string	$code       Code de la forme juridique
689 *    @return     string     			Nom traduit du pays
690 */
691function getFormeJuridiqueLabel($code)
692{
693	global $db, $langs;
694
695	if (!$code) {
696		return '';
697	}
698
699	$sql = "SELECT libelle FROM ".MAIN_DB_PREFIX."c_forme_juridique";
700	$sql .= " WHERE code='".$db->escape($code)."'";
701
702	dol_syslog("Company.lib::getFormeJuridiqueLabel", LOG_DEBUG);
703	$resql = $db->query($sql);
704	if ($resql) {
705		$num = $db->num_rows($resql);
706
707		if ($num) {
708			$obj = $db->fetch_object($resql);
709			$label = ($obj->libelle != '-' ? $obj->libelle : '');
710			return $label;
711		} else {
712			return $langs->trans("NotDefined");
713		}
714	}
715}
716
717
718/**
719 *  Return list of countries that are inside the EEC (European Economic Community)
720 *  Note: Try to keep this function as a "memory only" function for performance reasons.
721 *
722 *  @return     array					Array of countries code in EEC
723 */
724function getCountriesInEEC()
725{
726	// List of all country codes that are in europe for european vat rules
727	// List found on http://ec.europa.eu/taxation_customs/common/faq/faq_1179_en.htm#9
728	global $conf, $db;
729	$country_code_in_EEC = array();
730
731	if (!empty($conf->cache['country_code_in_EEC'])) {
732		// Use of cache to reduce number of database requests
733		$country_code_in_EEC = $conf->cache['country_code_in_EEC'];
734	} else {
735		$sql = "SELECT cc.code FROM ".MAIN_DB_PREFIX."c_country as cc";
736		$sql .= " WHERE cc.eec = 1";
737
738		$resql = $db->query($sql);
739		if ($resql) {
740			$num = $db->num_rows($resql);
741			$i = 0;
742			while ($i < $num) {
743				$objp = $db->fetch_object($resql);
744				$country_code_in_EEC[] = $objp->code;
745				$i++;
746			}
747		} else {
748			dol_print_error($db);
749		}
750		$conf->cache['country_code_in_EEC'] = $country_code_in_EEC;
751	}
752	return $country_code_in_EEC;
753}
754
755/**
756 *  Return if a country of an object is inside the EEC (European Economic Community)
757 *
758 *  @param      Object      $object    Object
759 *  @return     boolean		           true = country inside EEC, false = country outside EEC
760 */
761function isInEEC($object)
762{
763	if (empty($object->country_code)) {
764		return false;
765	}
766
767	$country_code_in_EEC = getCountriesInEEC();		// This make a database call but there is a cache done into $conf->cache['country_code_in_EEC']
768
769	//print "dd".$object->country_code;
770	return in_array($object->country_code, $country_code_in_EEC);
771}
772
773
774/**
775 * 		Show html area for list of projects
776 *
777 *		@param	Conf		$conf			Object conf
778 * 		@param	Translate	$langs			Object langs
779 * 		@param	DoliDB		$db				Database handler
780 * 		@param	Object		$object			Third party object
781 *      @param  string		$backtopage		Url to go once contact is created
782 *      @param  int         $nocreatelink   1=Hide create project link
783 *      @param	string		$morehtmlright	More html on right of title
784 *      @return	int
785 */
786function show_projects($conf, $langs, $db, $object, $backtopage = '', $nocreatelink = 0, $morehtmlright = '')
787{
788	global $user;
789
790	$i = -1;
791
792	if (!empty($conf->projet->enabled) && $user->rights->projet->lire) {
793		$langs->load("projects");
794
795		$newcardbutton = '';
796		if (!empty($conf->projet->enabled) && $user->rights->projet->creer && empty($nocreatelink)) {
797			$newcardbutton .= dolGetButtonTitle($langs->trans('AddProject'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/projet/card.php?socid='.$object->id.'&amp;action=create&amp;backtopage='.urlencode($backtopage));
798		}
799
800		print "\n";
801		print load_fiche_titre($langs->trans("ProjectsDedicatedToThisThirdParty"), $newcardbutton.$morehtmlright, '');
802		print '<div class="div-table-responsive">';
803		print "\n".'<table class="noborder" width=100%>';
804
805		$sql  = "SELECT p.rowid as id, p.entity, p.title, p.ref, p.public, p.dateo as do, p.datee as de, p.fk_statut as status, p.fk_opp_status, p.opp_amount, p.opp_percent, p.tms as date_update, p.budget_amount";
806		$sql .= ", cls.code as opp_status_code";
807		$sql .= " FROM ".MAIN_DB_PREFIX."projet as p";
808		$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_lead_status as cls on p.fk_opp_status = cls.rowid";
809		$sql .= " WHERE p.fk_soc = ".$object->id;
810		$sql .= " AND p.entity IN (".getEntity('project').")";
811		$sql .= " ORDER BY p.dateo DESC";
812
813		$result = $db->query($sql);
814		if ($result) {
815			$num = $db->num_rows($result);
816
817			print '<tr class="liste_titre">';
818			print '<td>'.$langs->trans("Ref").'</td>';
819			print '<td>'.$langs->trans("Name").'</td>';
820			print '<td class="center">'.$langs->trans("DateStart").'</td>';
821			print '<td class="center">'.$langs->trans("DateEnd").'</td>';
822			print '<td class="right">'.$langs->trans("OpportunityAmountShort").'</td>';
823			print '<td class="center">'.$langs->trans("OpportunityStatusShort").'</td>';
824			print '<td class="right">'.$langs->trans("OpportunityProbabilityShort").'</td>';
825			print '<td class="right">'.$langs->trans("Status").'</td>';
826			print '</tr>';
827
828			if ($num > 0) {
829				require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
830
831				$projecttmp = new Project($db);
832
833				$i = 0;
834
835				while ($i < $num) {
836					$obj = $db->fetch_object($result);
837					$projecttmp->fetch($obj->id);
838
839					// To verify role of users
840					$userAccess = $projecttmp->restrictedProjectArea($user);
841
842					if ($user->rights->projet->lire && $userAccess > 0) {
843						print '<tr class="oddeven">';
844
845						// Ref
846						print '<td>';
847						print $projecttmp->getNomUrl(1);
848						print '</td>';
849
850						// Label
851						print '<td>'.$obj->title.'</td>';
852						// Date start
853						print '<td class="center">'.dol_print_date($db->jdate($obj->do), "day").'</td>';
854						// Date end
855						print '<td class="center">'.dol_print_date($db->jdate($obj->de), "day").'</td>';
856						// Opp amount
857						print '<td class="right">';
858						if ($obj->opp_status_code) {
859							print price($obj->opp_amount, 1, '', 1, -1, -1, '');
860						}
861						print '</td>';
862						// Opp status
863						print '<td class="center">';
864						if ($obj->opp_status_code) {
865							print $langs->trans("OppStatus".$obj->opp_status_code);
866						}
867						print '</td>';
868						// Opp percent
869						print '<td class="right">';
870						if ($obj->opp_percent) {
871							print price($obj->opp_percent, 1, '', 1, 0).'%';
872						}
873						print '</td>';
874						// Status
875						print '<td class="right">'.$projecttmp->getLibStatut(5).'</td>';
876
877						print '</tr>';
878					}
879					$i++;
880				}
881			} else {
882				print '<tr class="oddeven"><td colspan="8" class="opacitymedium">'.$langs->trans("None").'</td></tr>';
883			}
884			$db->free($result);
885		} else {
886			dol_print_error($db);
887		}
888		print "</table>";
889		print '</div>';
890
891		print "<br>\n";
892	}
893
894	return $i;
895}
896
897
898/**
899 * 		Show html area for list of contacts
900 *
901 *		@param	Conf		$conf		Object conf
902 * 		@param	Translate	$langs		Object langs
903 * 		@param	DoliDB		$db			Database handler
904 * 		@param	Societe		$object		Third party object
905 *      @param  string		$backtopage	Url to go once contact is created
906 *      @return	int
907 */
908function show_contacts($conf, $langs, $db, $object, $backtopage = '')
909{
910	global $user, $conf, $extrafields, $hookmanager;
911	global $contextpage;
912
913	require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php';
914	$formcompany = new FormCompany($db);
915	$form = new Form($db);
916
917	$optioncss = GETPOST('optioncss', 'alpha');
918	$sortfield = GETPOST("sortfield", 'alpha');
919	$sortorder = GETPOST("sortorder", 'alpha');
920	$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
921
922	$search_status = GETPOST("search_status", 'int');
923	if ($search_status == '') {
924		$search_status = 1; // always display active customer first
925	}
926
927	$search_name    = GETPOST("search_name", 'alpha');
928	$search_address = GETPOST("search_address", 'alpha');
929	$search_poste   = GETPOST("search_poste", 'alpha');
930	$search_roles = GETPOST("search_roles", 'array');
931
932	$socialnetworks = getArrayOfSocialNetworks();
933
934	$searchAddressPhoneDBFields = array(
935		//Address
936		't.address',
937		't.zip',
938		't.town',
939
940		//Phone
941		't.phone',
942		't.phone_perso',
943		't.phone_mobile',
944
945		//Fax
946		't.fax',
947
948		//E-mail
949		't.email',
950	);
951	//Social media
952	//    foreach ($socialnetworks as $key => $value) {
953	//        if ($value['active']) {
954	//            $searchAddressPhoneDBFields['t.'.$key] = "t.socialnetworks->'$.".$key."'";
955	//        }
956	//    }
957
958	if (!$sortorder) {
959		$sortorder = "ASC";
960	}
961	if (!$sortfield) {
962		$sortfield = "t.lastname";
963	}
964
965	if (!empty($conf->clicktodial->enabled)) {
966		$user->fetch_clicktodial(); // lecture des infos de clicktodial du user
967	}
968
969
970	$contactstatic = new Contact($db);
971
972	$extrafields->fetch_name_optionals_label($contactstatic->table_element);
973
974	$contactstatic->fields = array(
975		'name'      =>array('type'=>'varchar(128)', 'label'=>'Name', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'showoncombobox'=>1, 'index'=>1, 'position'=>10, 'searchall'=>1),
976		'poste'     =>array('type'=>'varchar(128)', 'label'=>'PostOrFunction', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'showoncombobox'=>2, 'index'=>1, 'position'=>20),
977		'address'   =>array('type'=>'varchar(128)', 'label'=>'Address', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'showoncombobox'=>3, 'index'=>1, 'position'=>30),
978		'role'      =>array('type'=>'checkbox', 'label'=>'Role', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'showoncombobox'=>4, 'index'=>1, 'position'=>40),
979		'statut'    =>array('type'=>'integer', 'label'=>'Status', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'default'=>0, 'index'=>1, 'position'=>50, 'arrayofkeyval'=>array(0=>$contactstatic->LibStatut(0, 1), 1=>$contactstatic->LibStatut(1, 1))),
980	);
981
982	// Definition of fields for list
983	$arrayfields = array(
984		't.rowid'=>array('label'=>"TechnicalID", 'checked'=>(!empty($conf->global->MAIN_SHOW_TECHNICAL_ID) ? 1 : 0), 'enabled'=>(!empty($conf->global->MAIN_SHOW_TECHNICAL_ID) ? 1 : 0), 'position'=>1),
985		't.name'=>array('label'=>"Name", 'checked'=>1, 'position'=>10),
986		't.poste'=>array('label'=>"PostOrFunction", 'checked'=>1, 'position'=>20),
987		't.address'=>array('label'=>(empty($conf->dol_optimize_smallscreen) ? $langs->trans("Address").' / '.$langs->trans("Phone").' / '.$langs->trans("Email") : $langs->trans("Address")), 'checked'=>1, 'position'=>30),
988		'sc.role'=>array('label'=>"ContactByDefaultFor", 'checked'=>1, 'position'=>40),
989		't.statut'=>array('label'=>"Status", 'checked'=>1, 'position'=>50, 'class'=>'center'),
990	);
991	// Extra fields
992	if (!empty($extrafields->attributes[$contactstatic->table_element]['label']) && is_array($extrafields->attributes[$contactstatic->table_element]['label']) && count($extrafields->attributes[$contactstatic->table_element]['label'])) {
993		foreach ($extrafields->attributes[$contactstatic->table_element]['label'] as $key => $val) {
994			if (!empty($extrafields->attributes[$contactstatic->table_element]['list'][$key])) {
995				$arrayfields["ef.".$key] = array(
996					'label'=>$extrafields->attributes[$contactstatic->table_element]['label'][$key],
997					'checked'=>(($extrafields->attributes[$contactstatic->table_element]['list'][$key] < 0) ? 0 : 1),
998					'position'=>1000 + $extrafields->attributes[$contactstatic->table_element]['pos'][$key],
999					'enabled'=>(abs($extrafields->attributes[$contactstatic->table_element]['list'][$key]) != 3 && $extrafields->attributes[$contactstatic->table_element]['perms'][$key]));
1000			}
1001		}
1002	}
1003
1004	// Initialize array of search criterias
1005	$search = array();
1006	foreach ($arrayfields as $key => $val) {
1007		$queryName = 'search_'.substr($key, 2);
1008		if (GETPOST($queryName, 'alpha')) {
1009			$search[substr($key, 2)] = GETPOST($queryName, 'alpha');
1010		}
1011	}
1012	$search_array_options = $extrafields->getOptionalsFromPost($contactstatic->table_element, '', 'search_');
1013
1014	// Purge search criteria
1015	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
1016		$search_status = '';
1017		$search_name = '';
1018		$search_roles = array();
1019		$search_address = '';
1020		$search_poste = '';
1021		$search = array();
1022		$search_array_options = array();
1023
1024		foreach ($contactstatic->fields as $key => $val) {
1025			$search[$key] = '';
1026		}
1027	}
1028
1029	$contactstatic->fields = dol_sort_array($contactstatic->fields, 'position');
1030	$arrayfields = dol_sort_array($arrayfields, 'position');
1031
1032	$newcardbutton = '';
1033	if ($user->rights->societe->contact->creer) {
1034		$addcontact = (!empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("AddContact") : $langs->trans("AddContactAddress"));
1035		$newcardbutton .= dolGetButtonTitle($addcontact, '', 'fa fa-plus-circle', DOL_URL_ROOT.'/contact/card.php?socid='.$object->id.'&amp;action=create&amp;backtopage='.urlencode($backtopage));
1036	}
1037
1038	print "\n";
1039
1040	$title = (!empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("ContactsForCompany") : $langs->trans("ContactsAddressesForCompany"));
1041	print load_fiche_titre($title, $newcardbutton, '');
1042
1043	print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].'" name="formfilter">';
1044	print '<input type="hidden" name="token" value="'.newToken().'">';
1045	print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">';
1046	print '<input type="hidden" name="socid" value="'.$object->id.'">';
1047	print '<input type="hidden" name="sortorder" value="'.$sortorder.'">';
1048	print '<input type="hidden" name="sortfield" value="'.$sortfield.'">';
1049	print '<input type="hidden" name="page" value="'.$page.'">';
1050
1051	$varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage;
1052	$selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields
1053	//if ($massactionbutton) $selectedfields.=$form->showCheckAddButtons('checkforselect', 1);
1054
1055	print '<div class="div-table-responsive">'; // You can use div-table-responsive-no-min if you dont need reserved height for your table
1056	print "\n".'<table class="tagtable liste">'."\n";
1057
1058	$param = "socid=".urlencode($object->id);
1059	if ($search_status != '') {
1060		$param .= '&search_status='.urlencode($search_status);
1061	}
1062	if (count($search_roles) > 0) {
1063		$param .= implode('&search_roles[]=', $search_roles);
1064	}
1065	if ($search_name != '') {
1066		$param .= '&search_name='.urlencode($search_name);
1067	}
1068	if ($search_poste != '') {
1069		$param .= '&search_poste='.urlencode($search_poste);
1070	}
1071	if ($search_address != '') {
1072		$param .= '&search_address='.urlencode($search_address);
1073	}
1074	if ($optioncss != '') {
1075		$param .= '&optioncss='.urlencode($optioncss);
1076	}
1077
1078	// Add $param from extra fields
1079	$extrafieldsobjectkey = $contactstatic->table_element;
1080	include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php';
1081
1082	$sql = "SELECT t.rowid, t.lastname, t.firstname, t.fk_pays as country_id, t.civility, t.poste, t.phone as phone_pro, t.phone_mobile, t.phone_perso, t.fax, t.email, t.socialnetworks, t.statut, t.photo,";
1083	$sql .= " t.civility as civility_id, t.address, t.zip, t.town";
1084	$sql .= " FROM ".MAIN_DB_PREFIX."socpeople as t";
1085	$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."socpeople_extrafields as ef on (t.rowid = ef.fk_object)";
1086	$sql .= " WHERE t.fk_soc = ".$object->id;
1087	if ($search_status != '' && $search_status != '-1') {
1088		$sql .= " AND t.statut = ".((int) $search_status);
1089	}
1090	if ($search_name) {
1091		$sql .= natural_search(array('t.lastname', 't.firstname'), $search_name);
1092	}
1093	if ($search_poste) {
1094		$sql .= natural_search('t.poste', $search_poste);
1095	}
1096	if ($search_address) {
1097		$sql .= natural_search($searchAddressPhoneDBFields, $search_address);
1098	}
1099	if (count($search_roles) > 0) {
1100		$sql .= " AND t.rowid IN (SELECT sc.fk_socpeople FROM ".MAIN_DB_PREFIX."societe_contacts as sc WHERE sc.fk_c_type_contact IN (".$db->sanitize(implode(',', $search_roles))."))";
1101	}
1102	// Add where from extra fields
1103	$extrafieldsobjectkey = $contactstatic->table_element;
1104	include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php';
1105	if ($sortfield == "t.name") {
1106		$sql .= " ORDER BY t.lastname $sortorder, t.firstname $sortorder";
1107	} else {
1108		$sql .= " ORDER BY $sortfield $sortorder";
1109	}
1110
1111	dol_syslog('core/lib/company.lib.php :: show_contacts', LOG_DEBUG);
1112	$result = $db->query($sql);
1113	if (!$result) {
1114		dol_print_error($db);
1115	}
1116
1117	$num = $db->num_rows($result);
1118
1119	// Fields title search
1120	// --------------------------------------------------------------------
1121	print '<tr class="liste_titre">';
1122	foreach ($contactstatic->fields as $key => $val) {
1123		$align = '';
1124		if (in_array($val['type'], array('date', 'datetime', 'timestamp'))) {
1125			$align .= ($align ? ' ' : '').'center';
1126		}
1127		if (in_array($val['type'], array('timestamp'))) {
1128			$align .= ($align ? ' ' : '').'nowrap';
1129		}
1130		if ($key == 'status' || $key == 'statut') {
1131			$align .= ($align ? ' ' : '').'center';
1132		}
1133		if (!empty($arrayfields['t.'.$key]['checked']) || !empty($arrayfields['sc.'.$key]['checked'])) {
1134			print '<td class="liste_titre'.($align ? ' '.$align : '').'">';
1135			if (in_array($key, array('statut'))) {
1136				print $form->selectarray('search_status', array('-1'=>'', '0'=>$contactstatic->LibStatut(0, 1), '1'=>$contactstatic->LibStatut(1, 1)), $search_status);
1137			} elseif (in_array($key, array('role'))) {
1138				print $formcompany->showRoles("search_roles", $contactstatic, 'edit', $search_roles);
1139			} else {
1140				print '<input type="text" class="flat maxwidth75" name="search_'.$key.'" value="'.(!empty($search[$key]) ? dol_escape_htmltag($search[$key]) : '').'">';
1141			}
1142			print '</td>';
1143		}
1144	}
1145	// Extra fields
1146	$extrafieldsobjectkey = $contactstatic->table_element;
1147	include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php';
1148
1149	// Fields from hook
1150	$parameters = array('arrayfields'=>$arrayfields);
1151	$reshook = $hookmanager->executeHooks('printFieldListOption', $parameters, $contactstatic); // Note that $action and $object may have been modified by hook
1152	print $hookmanager->resPrint;
1153	// Action column
1154	print '<td class="liste_titre" align="right">';
1155	print $form->showFilterButtons();
1156	print '</td>';
1157	print '</tr>'."\n";
1158
1159
1160	// Fields title label
1161	// --------------------------------------------------------------------
1162	print '<tr class="liste_titre">';
1163	foreach ($contactstatic->fields as $key => $val) {
1164		$align = '';
1165		if (in_array($val['type'], array('date', 'datetime', 'timestamp'))) {
1166			$align .= ($align ? ' ' : '').'center';
1167		}
1168		if (in_array($val['type'], array('timestamp'))) {
1169			$align .= ($align ? ' ' : '').'nowrap';
1170		}
1171		if ($key == 'status' || $key == 'statut') {
1172			$align .= ($align ? ' ' : '').'center';
1173		}
1174		if (!empty($arrayfields['t.'.$key]['checked'])) {
1175			print getTitleFieldOfList($val['label'], 0, $_SERVER['PHP_SELF'], 't.'.$key, '', $param, ($align ? 'class="'.$align.'"' : ''), $sortfield, $sortorder, $align.' ')."\n";
1176		}
1177		if ($key == 'role') {
1178			$align .= ($align ? ' ' : '').'left';
1179		}
1180		if (!empty($arrayfields['sc.'.$key]['checked'])) {
1181			print getTitleFieldOfList($arrayfields['sc.'.$key]['label'], 0, $_SERVER['PHP_SELF'], '', '', $param, ($align ? 'class="'.$align.'"' : ''), $sortfield, $sortorder, $align.' ')."\n";
1182		}
1183	}
1184	// Extra fields
1185	$extrafieldsobjectkey = $contactstatic->table_element;
1186	include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php';
1187	// Hook fields
1188	$parameters = array('arrayfields'=>$arrayfields, 'param'=>$param, 'sortfield'=>$sortfield, 'sortorder'=>$sortorder);
1189	$reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook
1190	print $hookmanager->resPrint;
1191	print getTitleFieldOfList($selectedfields, 0, $_SERVER["PHP_SELF"], '', '', '', 'align="center"', $sortfield, $sortorder, 'maxwidthsearch ')."\n";
1192	print '</tr>'."\n";
1193
1194	$i = -1;
1195
1196	if ($num || (GETPOST('button_search') || GETPOST('button_search.x') || GETPOST('button_search_x'))) {
1197		$i = 0;
1198
1199		while ($i < $num) {
1200			$obj = $db->fetch_object($result);
1201
1202			$contactstatic->id = $obj->rowid;
1203			$contactstatic->ref = $obj->rowid;
1204			$contactstatic->statut = $obj->statut;
1205			$contactstatic->lastname = $obj->lastname;
1206			$contactstatic->firstname = $obj->firstname;
1207			$contactstatic->civility_id = $obj->civility_id;
1208			$contactstatic->civility_code = $obj->civility_id;
1209			$contactstatic->poste = $obj->poste;
1210			$contactstatic->address = $obj->address;
1211			$contactstatic->zip = $obj->zip;
1212			$contactstatic->town = $obj->town;
1213			$contactstatic->phone_pro = $obj->phone_pro;
1214			$contactstatic->phone_mobile = $obj->phone_mobile;
1215			$contactstatic->phone_perso = $obj->phone_perso;
1216			$contactstatic->email = $obj->email;
1217			$contactstatic->socialnetworks = $obj->socialnetworks;
1218			$contactstatic->photo = $obj->photo;
1219
1220			$country_code = getCountry($obj->country_id, 2);
1221			$contactstatic->country_code = $country_code;
1222
1223			$contactstatic->setGenderFromCivility();
1224			$contactstatic->fetch_optionals();
1225
1226			$resultRole = $contactstatic->fetchRoles();
1227			if ($resultRole < 0) {
1228				setEventMessages(null, $contactstatic->errors, 'errors');
1229			}
1230
1231			if (is_array($contactstatic->array_options)) {
1232				foreach ($contactstatic->array_options as $key => $val) {
1233					$obj->$key = $val;
1234				}
1235			}
1236
1237			print '<tr class="oddeven">';
1238
1239			// ID
1240			if (!empty($arrayfields['t.rowid']['checked'])) {
1241				print '<td>';
1242				print $contactstatic->id;
1243				print '</td>';
1244			}
1245
1246			// Photo - Name
1247			if (!empty($arrayfields['t.name']['checked'])) {
1248				print '<td>';
1249				print $form->showphoto('contact', $contactstatic, 0, 0, 0, 'photorefnoborder valignmiddle marginrightonly', 'small', 1, 0, 1);
1250				print $contactstatic->getNomUrl(0, '', 0, '&backtopage='.urlencode($backtopage));
1251				print '</td>';
1252			}
1253
1254			// Job position
1255			if (!empty($arrayfields['t.poste']['checked'])) {
1256				print '<td>';
1257				if ($obj->poste) {
1258					print $obj->poste;
1259				}
1260				print '</td>';
1261			}
1262
1263			// Address - Phone - Email
1264			if (!empty($arrayfields['t.address']['checked'])) {
1265				print '<td>';
1266				print $contactstatic->getBannerAddress('contact', $object);
1267				print '</td>';
1268			}
1269
1270			// Role
1271			if (!empty($arrayfields['sc.role']['checked'])) {
1272				print '<td>';
1273				print $formcompany->showRoles("roles", $contactstatic, 'view');
1274				print '</td>';
1275			}
1276
1277			// Status
1278			if (!empty($arrayfields['t.statut']['checked'])) {
1279				print '<td class="center">'.$contactstatic->getLibStatut(5).'</td>';
1280			}
1281
1282			// Extra fields
1283			$extrafieldsobjectkey = $contactstatic->table_element;
1284			include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php';
1285
1286			// Actions
1287			print '<td align="right">';
1288
1289			// Add to agenda
1290			if (!empty($conf->agenda->enabled) && $user->rights->agenda->myactions->create) {
1291				print '<a href="'.DOL_URL_ROOT.'/comm/action/card.php?action=create&actioncode=&contactid='.$obj->rowid.'&socid='.$object->id.'&backtopage='.urlencode($backtopage).'">';
1292				print img_object($langs->trans("Event"), "action");
1293				print '</a> &nbsp; ';
1294			}
1295
1296			// Edit
1297			if ($user->rights->societe->contact->creer) {
1298				print '<a class="editfielda paddingleft" href="'.DOL_URL_ROOT.'/contact/card.php?action=edit&id='.$obj->rowid.'&backtopage='.urlencode($backtopage).'">';
1299				print img_edit();
1300				print '</a>';
1301			}
1302
1303			print '</td>';
1304
1305			print "</tr>\n";
1306			$i++;
1307		}
1308	} else {
1309		$colspan = 1;
1310		foreach ($arrayfields as $key => $val) {
1311			if (!empty($val['checked'])) {
1312				$colspan++;
1313			}
1314		}
1315		print '<tr><td colspan="'.$colspan.'" class="opacitymedium">'.$langs->trans("None").'</td></tr>';
1316	}
1317	print "\n</table>\n";
1318	print '</div>';
1319
1320	print '</form>'."\n";
1321
1322	return $i;
1323}
1324
1325
1326/**
1327 *    	Show html area with actions to do
1328 *
1329 * 		@param	Conf		$conf		        Object conf
1330 * 		@param	Translate	$langs		        Object langs
1331 * 		@param	DoliDB		$db			        Object db
1332 * 		@param	Adherent|Societe    $filterobj  Object thirdparty or member
1333 * 		@param	Contact		$objcon	            Object contact
1334 *      @param  int			$noprint	        Return string but does not output it
1335 *      @param  int			$actioncode 	    Filter on actioncode
1336 *      @return	string|void					    Return html part or void if noprint is 1
1337 */
1338function show_actions_todo($conf, $langs, $db, $filterobj, $objcon = '', $noprint = 0, $actioncode = '')
1339{
1340	global $user, $conf;
1341
1342	$out = show_actions_done($conf, $langs, $db, $filterobj, $objcon, 1, $actioncode, 'todo');
1343
1344	if ($noprint) {
1345		return $out;
1346	} else {
1347		print $out;
1348	}
1349}
1350
1351/**
1352 *    	Show html area with actions (done or not, ignore the name of function).
1353 *      Note: Global parameter $param must be defined.
1354 *
1355 * 		@param	Conf		       $conf		   Object conf
1356 * 		@param	Translate	       $langs		   Object langs
1357 * 		@param	DoliDB		       $db			   Object db
1358 * 		@param	mixed			   $filterobj	   Filter on object Adherent|Societe|Project|Product|CommandeFournisseur|Dolresource|Ticket... to list events linked to an object
1359 * 		@param	Contact		       $objcon		   Filter on object contact to filter events on a contact
1360 *      @param  int			       $noprint        Return string but does not output it
1361 *      @param  string		       $actioncode     Filter on actioncode
1362 *      @param  string             $donetodo       Filter on event 'done' or 'todo' or ''=nofilter (all).
1363 *      @param  array              $filters        Filter on other fields
1364 *      @param  string             $sortfield      Sort field
1365 *      @param  string             $sortorder      Sort order
1366 *      @param	string			   $module		   You can add module name here if elementtype in table llx_actioncomm is objectkey@module
1367 *      @return	string|void				           Return html part or void if noprint is 1
1368 */
1369function show_actions_done($conf, $langs, $db, $filterobj, $objcon = '', $noprint = 0, $actioncode = '', $donetodo = 'done', $filters = array(), $sortfield = 'a.datep,a.id', $sortorder = 'DESC', $module = '')
1370{
1371	global $user, $conf;
1372	global $form;
1373	global $param, $massactionbutton;
1374
1375	$start_year = GETPOST('dateevent_startyear', 'int');
1376	$start_month = GETPOST('dateevent_startmonth', 'int');
1377	$start_day = GETPOST('dateevent_startday', 'int');
1378	$end_year = GETPOST('dateevent_endyear', 'int');
1379	$end_month = GETPOST('dateevent_endmonth', 'int');
1380	$end_day = GETPOST('dateevent_endday', 'int');
1381	$tms_start = '';
1382	$tms_end = '';
1383
1384	if (!empty($start_year) && !empty($start_month) && !empty($start_day)) {
1385		$tms_start = dol_mktime(0, 0, 0, $start_month, $start_day, $start_year, 'tzuserrel');
1386	}
1387	if (!empty($end_year) && !empty($end_month) && !empty($end_day)) {
1388		$tms_end = dol_mktime(23, 59, 59, $end_month, $end_day, $end_year, 'tzuserrel');
1389	}
1390	if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All test are required to be compatible with all browsers
1391		$tms_start = '';
1392		$tms_end = '';
1393	}
1394	dol_include_once('/comm/action/class/actioncomm.class.php');
1395
1396	// Check parameters
1397	if (!is_object($filterobj) && !is_object($objcon)) {
1398		dol_print_error('', 'BadParameter');
1399	}
1400
1401	$out = '';
1402	$histo = array();
1403	$numaction = 0;
1404	$now = dol_now('tzuser');
1405
1406	// Open DSI -- Fix order by -- Begin
1407	$sortfield_list = explode(',', $sortfield);
1408	$sortfield_label_list = array('a.id' => 'id', 'a.datep' => 'dp', 'a.percent' => 'percent');
1409	$sortfield_new_list = array();
1410	foreach ($sortfield_list as $sortfield_value) {
1411		$sortfield_new_list[] = $sortfield_label_list[trim($sortfield_value)];
1412	}
1413	$sortfield_new = implode(',', $sortfield_new_list);
1414
1415	$sql = '';
1416
1417	if (!empty($conf->agenda->enabled)) {
1418		// Recherche histo sur actioncomm
1419		if (is_object($objcon) && $objcon->id > 0) {
1420			$sql = "SELECT DISTINCT a.id, a.label as label,";
1421		} else {
1422			$sql = "SELECT a.id, a.label as label,";
1423		}
1424		$sql .= " a.datep as dp,";
1425		$sql .= " a.datep2 as dp2,";
1426		$sql .= " a.percent as percent, 'action' as type,";
1427		$sql .= " a.fk_element, a.elementtype,";
1428		$sql .= " a.fk_contact,";
1429		$sql .= " c.code as acode, c.libelle as alabel, c.picto as apicto,";
1430		$sql .= " u.rowid as user_id, u.login as user_login, u.photo as user_photo, u.firstname as user_firstname, u.lastname as user_lastname";
1431		if (is_object($filterobj) && in_array(get_class($filterobj), array('Societe', 'Client', 'Fournisseur'))) {
1432			$sql .= ", sp.lastname, sp.firstname";
1433		} elseif (is_object($filterobj) && get_class($filterobj) == 'Dolresource') {
1434			/* Nothing */
1435		} elseif (is_object($filterobj) && get_class($filterobj) == 'Project') {
1436			/* Nothing */
1437		} elseif (is_object($filterobj) && get_class($filterobj) == 'Adherent') {
1438			$sql .= ", m.lastname, m.firstname";
1439		} elseif (is_object($filterobj) && get_class($filterobj) == 'CommandeFournisseur') {
1440			$sql .= ", o.ref";
1441		} elseif (is_object($filterobj) && get_class($filterobj) == 'Product') {
1442			$sql .= ", o.ref";
1443		} elseif (is_object($filterobj) && get_class($filterobj) == 'Ticket') {
1444			$sql .= ", o.ref";
1445		} elseif (is_object($filterobj) && get_class($filterobj) == 'BOM') {
1446			$sql .= ", o.ref";
1447		} elseif (is_object($filterobj) && get_class($filterobj) == 'Contrat') {
1448			$sql .= ", o.ref";
1449		} elseif (is_object($filterobj) && is_array($filterobj->fields) && is_array($filterobj->fields['rowid']) && is_array($filterobj->fields['ref']) && $filterobj->table_element && $filterobj->element) {
1450			$sql .= ", o.ref";
1451		}
1452
1453		$sql .= " FROM ".MAIN_DB_PREFIX."actioncomm as a";
1454		$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as u on u.rowid = a.fk_user_action";
1455		$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_actioncomm as c ON a.fk_action = c.id";
1456
1457		$force_filter_contact = false;
1458		if (is_object($objcon) && $objcon->id > 0) {
1459			$force_filter_contact = true;
1460			$sql .= " INNER JOIN ".MAIN_DB_PREFIX."actioncomm_resources as r ON a.id = r.fk_actioncomm";
1461			$sql .= " AND r.element_type = '".$db->escape($objcon->table_element)."' AND r.fk_element = ".((int) $objcon->id);
1462		}
1463
1464		if (is_object($filterobj) && in_array(get_class($filterobj), array('Societe', 'Client', 'Fournisseur'))) {
1465			$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."socpeople as sp ON a.fk_contact = sp.rowid";
1466		} elseif (is_object($filterobj) && get_class($filterobj) == 'Dolresource') {
1467			$sql .= " INNER JOIN ".MAIN_DB_PREFIX."element_resources as er";
1468			$sql .= " ON er.resource_type = 'dolresource'";
1469			$sql .= " AND er.element_id = a.id";
1470			$sql .= " AND er.resource_id = ".((int) $filterobj->id);
1471		} elseif (is_object($filterobj) && get_class($filterobj) == 'Project') {
1472			/* Nothing */
1473		} elseif (is_object($filterobj) && get_class($filterobj) == 'Adherent') {
1474			$sql .= ", ".MAIN_DB_PREFIX."adherent as m";
1475		} elseif (is_object($filterobj) && get_class($filterobj) == 'CommandeFournisseur') {
1476			$sql .= ", ".MAIN_DB_PREFIX."commande_fournisseur as o";
1477		} elseif (is_object($filterobj) && get_class($filterobj) == 'Product') {
1478			$sql .= ", ".MAIN_DB_PREFIX."product as o";
1479		} elseif (is_object($filterobj) && get_class($filterobj) == 'Ticket') {
1480			$sql .= ", ".MAIN_DB_PREFIX."ticket as o";
1481		} elseif (is_object($filterobj) && get_class($filterobj) == 'BOM') {
1482			$sql .= ", ".MAIN_DB_PREFIX."bom_bom as o";
1483		} elseif (is_object($filterobj) && get_class($filterobj) == 'Contrat') {
1484			$sql .= ", ".MAIN_DB_PREFIX."contrat as o";
1485		} elseif (is_object($filterobj) && is_array($filterobj->fields) && is_array($filterobj->fields['rowid']) && is_array($filterobj->fields['ref']) && $filterobj->table_element && $filterobj->element) {
1486			$sql .= ", ".MAIN_DB_PREFIX.$filterobj->table_element." as o";
1487		}
1488
1489		$sql .= " WHERE a.entity IN (".getEntity('agenda').")";
1490		if ($force_filter_contact === false) {
1491			if (is_object($filterobj) && in_array(get_class($filterobj), array('Societe', 'Client', 'Fournisseur')) && $filterobj->id) {
1492				$sql .= " AND a.fk_soc = ".((int) $filterobj->id);
1493			} elseif (is_object($filterobj) && get_class($filterobj) == 'Dolresource') {
1494				/* Nothing */
1495			} elseif (is_object($filterobj) && get_class($filterobj) == 'Project' && $filterobj->id) {
1496				$sql .= " AND a.fk_project = ".((int) $filterobj->id);
1497			} elseif (is_object($filterobj) && get_class($filterobj) == 'Adherent') {
1498				$sql .= " AND a.fk_element = m.rowid AND a.elementtype = 'member'";
1499				if ($filterobj->id) {
1500					$sql .= " AND a.fk_element = ".((int) $filterobj->id);
1501				}
1502			} elseif (is_object($filterobj) && get_class($filterobj) == 'CommandeFournisseur') {
1503				$sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'order_supplier'";
1504				if ($filterobj->id) {
1505					$sql .= " AND a.fk_element = ".((int) $filterobj->id);
1506				}
1507			} elseif (is_object($filterobj) && get_class($filterobj) == 'Product') {
1508				$sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'product'";
1509				if ($filterobj->id) {
1510					$sql .= " AND a.fk_element = ".((int) $filterobj->id);
1511				}
1512			} elseif (is_object($filterobj) && get_class($filterobj) == 'Ticket') {
1513				$sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'ticket'";
1514				if ($filterobj->id) {
1515					$sql .= " AND a.fk_element = ".((int) $filterobj->id);
1516				}
1517			} elseif (is_object($filterobj) && get_class($filterobj) == 'BOM') {
1518				$sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'bom'";
1519				if ($filterobj->id) {
1520					$sql .= " AND a.fk_element = ".((int) $filterobj->id);
1521				}
1522			} elseif (is_object($filterobj) && get_class($filterobj) == 'Contrat') {
1523				$sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'contract'";
1524				if ($filterobj->id) {
1525					$sql .= " AND a.fk_element = ".((int) $filterobj->id);
1526				}
1527			} elseif (is_object($filterobj) && is_array($filterobj->fields) && is_array($filterobj->fields['rowid']) && is_array($filterobj->fields['ref']) && $filterobj->table_element && $filterobj->element) {
1528				// Generic case
1529				$sql .= " AND a.fk_element = o.rowid AND a.elementtype = '".$db->escape($filterobj->element).($module ? '@'.$module : '')."'";
1530				if ($filterobj->id) {
1531					$sql .= " AND a.fk_element = ".((int) $filterobj->id);
1532				}
1533			}
1534		}
1535
1536		if (!empty($tms_start) && !empty($tms_end)) {
1537			$sql .= " AND ((a.datep BETWEEN '".$db->idate($tms_start)."' AND '".$db->idate($tms_end)."') OR (a.datep2 BETWEEN '".$db->idate($tms_start)."' AND '".$db->idate($tms_end)."'))";
1538		} elseif (empty($tms_start) && !empty($tms_end)) {
1539			$sql .= " AND ((a.datep <= '".$db->idate($tms_end)."') OR (a.datep2 <= '".$db->idate($tms_end)."'))";
1540		} elseif (!empty($tms_start) && empty($tms_end)) {
1541			$sql .= " AND ((a.datep >= '".$db->idate($tms_start)."') OR (a.datep2 >= '".$db->idate($tms_start)."'))";
1542		}
1543
1544		if (is_array($actioncode) && !empty($actioncode)) {
1545			$sql .= ' AND (';
1546			foreach ($actioncode as $key => $code) {
1547				if ($key != 0) {
1548					$sql .= "OR (";
1549				}
1550				if (!empty($code)) {
1551					addEventTypeSQL($sql, $code);
1552				}
1553				if ($key != 0) {
1554					$sql .= ")";
1555				}
1556			}
1557			$sql .= ')';
1558		} elseif (!empty($actioncode)) {
1559			addEventTypeSQL($sql, $actioncode);
1560		}
1561
1562		addOtherFilterSQL($sql, $donetodo, $now, $filters);
1563
1564		if (is_array($actioncode)) {
1565			foreach ($actioncode as $code) {
1566				$sql2 = addMailingEventTypeSQL($code, $objcon, $filterobj);
1567				if (!empty($sql2)) {
1568					if (!empty($sql)) {
1569						$sql = $sql." UNION ".$sql2;
1570					} elseif (empty($sql)) {
1571						$sql = $sql2;
1572					}
1573					break;
1574				}
1575			}
1576		} else {
1577			$sql2 = addMailingEventTypeSQL($actioncode, $objcon, $filterobj);
1578			if (!empty($sql) && !empty($sql2)) {
1579				$sql = $sql." UNION ".$sql2;
1580			} elseif (empty($sql) && !empty($sql2)) {
1581				$sql = $sql2;
1582			}
1583		}
1584	}
1585
1586	//TODO Add limit in nb of results
1587	if ($sql) {
1588		$sql .= $db->order($sortfield_new, $sortorder);
1589		dol_syslog("company.lib::show_actions_done", LOG_DEBUG);
1590		$resql = $db->query($sql);
1591		if ($resql) {
1592			$i = 0;
1593			$num = $db->num_rows($resql);
1594
1595			while ($i < $num) {
1596				$obj = $db->fetch_object($resql);
1597
1598				if ($obj->type == 'action') {
1599					$contactaction = new ActionComm($db);
1600					$contactaction->id = $obj->id;
1601					$result = $contactaction->fetchResources();
1602					if ($result < 0) {
1603						dol_print_error($db);
1604						setEventMessage("company.lib::show_actions_done Error fetch ressource", 'errors');
1605					}
1606
1607					//if ($donetodo == 'todo') $sql.= " AND ((a.percent >= 0 AND a.percent < 100) OR (a.percent = -1 AND a.datep > '".$db->idate($now)."'))";
1608					//elseif ($donetodo == 'done') $sql.= " AND (a.percent = 100 OR (a.percent = -1 AND a.datep <= '".$db->idate($now)."'))";
1609					$tododone = '';
1610					if (($obj->percent >= 0 and $obj->percent < 100) || ($obj->percent == -1 && (!empty($obj->datep) && $obj->datep > $now))) {
1611						$tododone = 'todo';
1612					}
1613
1614					$histo[$numaction] = array(
1615						'type'=>$obj->type,
1616						'tododone'=>$tododone,
1617						'id'=>$obj->id,
1618						'datestart'=>$db->jdate($obj->dp),
1619						'dateend'=>$db->jdate($obj->dp2),
1620						'note'=>$obj->label,
1621						'percent'=>$obj->percent,
1622
1623						'userid'=>$obj->user_id,
1624						'login'=>$obj->user_login,
1625						'userfirstname'=>$obj->user_firstname,
1626						'userlastname'=>$obj->user_lastname,
1627						'userphoto'=>$obj->user_photo,
1628
1629						'contact_id'=>$obj->fk_contact,
1630						'socpeopleassigned' => $contactaction->socpeopleassigned,
1631						'lastname' => empty($obj->lastname) ? '' : $obj->lastname,
1632						'firstname' => empty($obj->firstname) ? '' : $obj->firstname,
1633						'fk_element'=>$obj->fk_element,
1634						'elementtype'=>$obj->elementtype,
1635						// Type of event
1636						'acode'=>$obj->acode,
1637						'alabel'=>$obj->alabel,
1638						'libelle'=>$obj->alabel, // deprecated
1639						'apicto'=>$obj->apicto
1640					);
1641				} else {
1642					$histo[$numaction] = array(
1643						'type'=>$obj->type,
1644						'tododone'=>'done',
1645						'id'=>$obj->id,
1646						'datestart'=>$db->jdate($obj->dp),
1647						'dateend'=>$db->jdate($obj->dp2),
1648						'note'=>$obj->label,
1649						'percent'=>$obj->percent,
1650						'acode'=>$obj->acode,
1651
1652						'userid'=>$obj->user_id,
1653						'login'=>$obj->user_login,
1654						'userfirstname'=>$obj->user_firstname,
1655						'userlastname'=>$obj->user_lastname,
1656						'userphoto'=>$obj->user_photo
1657					);
1658				}
1659
1660				$numaction++;
1661				$i++;
1662			}
1663		} else {
1664			dol_print_error($db);
1665		}
1666	}
1667
1668	if (!empty($conf->agenda->enabled) || (!empty($conf->mailing->enabled) && !empty($objcon->email))) {
1669		$delay_warning = $conf->global->MAIN_DELAY_ACTIONS_TODO * 24 * 60 * 60;
1670
1671		require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
1672		include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
1673		require_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php';
1674		require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
1675
1676		$formactions = new FormActions($db);
1677
1678		$actionstatic = new ActionComm($db);
1679		$userstatic = new User($db);
1680		$userlinkcache = array();
1681		$contactstatic = new Contact($db);
1682		$elementlinkcache = array();
1683
1684		$out .= '<form name="listactionsfilter" class="listactionsfilter" action="'.$_SERVER["PHP_SELF"].'" method="POST">';
1685		$out .= '<input type="hidden" name="token" value="'.newToken().'">';
1686		if ($objcon && get_class($objcon) == 'Contact' &&
1687			(is_null($filterobj) || get_class($filterobj) == 'Societe')) {
1688			$out .= '<input type="hidden" name="id" value="'.$objcon->id.'" />';
1689		} else {
1690			$out .= '<input type="hidden" name="id" value="'.$filterobj->id.'" />';
1691		}
1692		if ($filterobj && get_class($filterobj) == 'Societe') {
1693			$out .= '<input type="hidden" name="socid" value="'.$filterobj->id.'" />';
1694		}
1695
1696		$out .= "\n";
1697
1698		$out .= '<div class="div-table-responsive-no-min">';
1699		$out .= '<table class="noborder centpercent">';
1700
1701		$out .= '<tr class="liste_titre">';
1702		if ($donetodo) {
1703			$out .= '<td class="liste_titre"></td>';
1704		}
1705		$out .= '<td class="liste_titre"></td>';
1706		$out .= '<td class="liste_titre"></td>';
1707		$out .= '<td class="liste_titre">';
1708		$out .= $formactions->select_type_actions($actioncode, "actioncode", '', empty($conf->global->AGENDA_USE_EVENT_TYPE) ? 1 : -1, 0, (empty($conf->global->AGENDA_USE_MULTISELECT_TYPE) ? 0 : 1), 1);
1709		$out .= '</td>';
1710		$out .= '<td class="liste_titre maxwidth100onsmartphone"><input type="text" class="maxwidth100onsmartphone" name="search_agenda_label" value="'.$filters['search_agenda_label'].'"></td>';
1711		$out .= '<td class="liste_titre center">';
1712		$out .= $form->selectDateToDate($tms_start, $tms_end, 'dateevent', 1);
1713		$out .= '</td>';
1714		$out .= '<td class="liste_titre"></td>';
1715		$out .= '<td class="liste_titre"></td>';
1716		$out .= '<td class="liste_titre"></td>';
1717		// Action column
1718		$out .= '<td class="liste_titre" align="middle">';
1719		$searchpicto = $form->showFilterAndCheckAddButtons($massactionbutton ? 1 : 0, 'checkforselect', 1);
1720		$out .= $searchpicto;
1721		$out .= '</td>';
1722		$out .= '</tr>';
1723
1724		$out .= '<tr class="liste_titre">';
1725		if ($donetodo) {
1726			$tmp = '';
1727			if (get_class($filterobj) == 'Societe') {
1728				$tmp .= '<a href="'.DOL_URL_ROOT.'/comm/action/list.php?action=show_list&socid='.$filterobj->id.'&status=done">';
1729			}
1730			$tmp .= ($donetodo != 'done' ? $langs->trans("ActionsToDoShort") : '');
1731			$tmp .= ($donetodo != 'done' && $donetodo != 'todo' ? ' / ' : '');
1732			$tmp .= ($donetodo != 'todo' ? $langs->trans("ActionsDoneShort") : '');
1733			//$out.=$langs->trans("ActionsToDoShort").' / '.$langs->trans("ActionsDoneShort");
1734			if (get_class($filterobj) == 'Societe') {
1735				$tmp .= '</a>';
1736			}
1737			$out .= getTitleFieldOfList($tmp);
1738		}
1739		$out .= getTitleFieldOfList($langs->trans("Ref"), 0, $_SERVER["PHP_SELF"], 'a.id', '', $param, '', $sortfield, $sortorder);
1740		$out .= getTitleFieldOfList($langs->trans("Owner"));
1741		$out .= getTitleFieldOfList($langs->trans("Type"));
1742		$out .= getTitleFieldOfList($langs->trans("Label"), 0, $_SERVER["PHP_SELF"], '', '', $param, '', $sortfield, $sortorder);
1743		$out .= getTitleFieldOfList($langs->trans("Date"), 0, $_SERVER["PHP_SELF"], 'a.datep,a.id', '', $param, 'align="center"', $sortfield, $sortorder);
1744		$out .= getTitleFieldOfList($langs->trans("RelatedObjects"), 0, $_SERVER["PHP_SELF"], '', '', $param, '', $sortfield, $sortorder);
1745		$out .= getTitleFieldOfList($langs->trans("ActionOnContact"), 0, $_SERVER["PHP_SELF"], '', '', $param, '', $sortfield, $sortorder);
1746		$out .= getTitleFieldOfList($langs->trans("Status"), 0, $_SERVER["PHP_SELF"], 'a.percent', '', $param, 'align="center"', $sortfield, $sortorder);
1747		$out .= getTitleFieldOfList('', 0, $_SERVER["PHP_SELF"], '', '', $param, '', $sortfield, $sortorder, 'maxwidthsearch ');
1748		$out .= '</tr>';
1749
1750		require_once DOL_DOCUMENT_ROOT.'/comm/action/class/cactioncomm.class.php';
1751		$caction = new CActionComm($db);
1752		$arraylist = $caction->liste_array(1, 'code', '', (empty($conf->global->AGENDA_USE_EVENT_TYPE) ? 1 : 0), '', 1);
1753
1754		foreach ($histo as $key => $value) {
1755			$actionstatic->fetch($histo[$key]['id']); // TODO Do we need this, we already have a lot of data of line into $histo
1756
1757			$actionstatic->type_picto = $histo[$key]['apicto'];
1758			$actionstatic->type_code = $histo[$key]['acode'];
1759
1760			$out .= '<tr class="oddeven">';
1761
1762			// Done or todo
1763			if ($donetodo) {
1764				$out .= '<td class="nowrap">';
1765				$out .= '</td>';
1766			}
1767
1768			// Ref
1769			$out .= '<td class="nowraponall">';
1770			if (isset($histo[$key]['type']) && $histo[$key]['type'] == 'mailing') {
1771				$out .= '<a href="'.DOL_URL_ROOT.'/comm/mailing/card.php?id='.$histo[$key]['id'].'">'.img_object($langs->trans("ShowEMailing"), "email").' ';
1772				$out .= $histo[$key]['id'];
1773				$out .= '</a>';
1774			} else {
1775				$out .= $actionstatic->getNomUrl(1, -1);
1776			}
1777			$out .= '</td>';
1778
1779			// Author of event
1780			$out .= '<td class="tdoverflowmax200">';
1781			//$userstatic->id=$histo[$key]['userid'];
1782			//$userstatic->login=$histo[$key]['login'];
1783			//$out.=$userstatic->getLoginUrl(1);
1784			if ($histo[$key]['userid'] > 0) {
1785				if (isset($userlinkcache[$histo[$key]['userid']])) {
1786					$link = $userlinkcache[$histo[$key]['userid']];
1787				} else {
1788					$userstatic->fetch($histo[$key]['userid']);
1789					$link = $userstatic->getNomUrl(-1, '', 0, 0, 16, 0, 'firstelselast', '');
1790					$userlinkcache[$histo[$key]['userid']] = $link;
1791				}
1792				$out .= $link;
1793			}
1794			$out .= '</td>';
1795
1796			// Type
1797			$labeltype = $actionstatic->type_code;
1798			if (empty($conf->global->AGENDA_USE_EVENT_TYPE) && empty($arraylist[$labeltype])) {
1799				$labeltype = 'AC_OTH';
1800			}
1801			if ($actionstatic->type_code == 'AC_OTH' && $actionstatic->code == 'TICKET_MSG') {
1802				$labeltype = $langs->trans("Message");
1803			} else {
1804				if (!empty($arraylist[$labeltype])) {
1805					$labeltype = $arraylist[$labeltype];
1806				}
1807				if ($actionstatic->type_code == 'AC_OTH_AUTO' && ($actionstatic->type_code != $actionstatic->code) && $labeltype && !empty($arraylist[$actionstatic->code])) {
1808					$labeltype .= ' - '.$arraylist[$actionstatic->code]; // Use code in priority on type_code
1809				}
1810			}
1811			$out .= '<td class="tdoverflowmax200" title="'.$labeltype.'">';
1812			$out .= $actionstatic->getTypePicto();
1813			$out .= $labeltype;
1814			$out .= '</td>';
1815
1816			// Title
1817			$out .= '<td>';
1818			if (isset($histo[$key]['type']) && $histo[$key]['type'] == 'action') {
1819				$transcode = $langs->trans("Action".$histo[$key]['acode']);
1820				$libelle = ($transcode != "Action".$histo[$key]['acode'] ? $transcode : $histo[$key]['alabel']);
1821				//$actionstatic->libelle=$libelle;
1822				$libelle = $histo[$key]['note'];
1823				$actionstatic->id = $histo[$key]['id'];
1824				$out .= dol_trunc($libelle, 120);
1825			}
1826			if (isset($histo[$key]['type']) && $histo[$key]['type'] == 'mailing') {
1827				$out .= '<a href="'.DOL_URL_ROOT.'/comm/mailing/card.php?id='.$histo[$key]['id'].'">'.img_object($langs->trans("ShowEMailing"), "email").' ';
1828				$transcode = $langs->trans("Action".$histo[$key]['acode']);
1829				$libelle = ($transcode != "Action".$histo[$key]['acode'] ? $transcode : 'Send mass mailing');
1830				$out .= dol_trunc($libelle, 120);
1831			}
1832			$out .= '</td>';
1833
1834			// Date
1835			$out .= '<td class="center nowrap">';
1836			$out .= dol_print_date($histo[$key]['datestart'], 'dayhour', 'tzuserrel');
1837			if ($histo[$key]['dateend'] && $histo[$key]['dateend'] != $histo[$key]['datestart']) {
1838				$tmpa = dol_getdate($histo[$key]['datestart'], true);
1839				$tmpb = dol_getdate($histo[$key]['dateend'], true);
1840				if ($tmpa['mday'] == $tmpb['mday'] && $tmpa['mon'] == $tmpb['mon'] && $tmpa['year'] == $tmpb['year']) {
1841					$out .= '-'.dol_print_date($histo[$key]['dateend'], 'hour', 'tzuserrel');
1842				} else {
1843					$out .= '-'.dol_print_date($histo[$key]['dateend'], 'dayhour', 'tzuserrel');
1844				}
1845			}
1846			$late = 0;
1847			if ($histo[$key]['percent'] == 0 && $histo[$key]['datestart'] && $histo[$key]['datestart'] < ($now - $delay_warning)) {
1848				$late = 1;
1849			}
1850			if ($histo[$key]['percent'] == 0 && !$histo[$key]['datestart'] && $histo[$key]['dateend'] && $histo[$key]['datestart'] < ($now - $delay_warning)) {
1851				$late = 1;
1852			}
1853			if ($histo[$key]['percent'] > 0 && $histo[$key]['percent'] < 100 && $histo[$key]['dateend'] && $histo[$key]['dateend'] < ($now - $delay_warning)) {
1854				$late = 1;
1855			}
1856			if ($histo[$key]['percent'] > 0 && $histo[$key]['percent'] < 100 && !$histo[$key]['dateend'] && $histo[$key]['datestart'] && $histo[$key]['datestart'] < ($now - $delay_warning)) {
1857				$late = 1;
1858			}
1859			if ($late) {
1860				$out .= img_warning($langs->trans("Late")).' ';
1861			}
1862			$out .= "</td>\n";
1863
1864			// Title of event
1865			//$out.='<td>'.dol_trunc($histo[$key]['note'], 40).'</td>';
1866
1867			// Linked object
1868			$out .= '<td class="nowraponall">';
1869			if (isset($histo[$key]['elementtype']) && !empty($histo[$key]['fk_element'])) {
1870				if (isset($elementlinkcache[$histo[$key]['elementtype']]) && isset($elementlinkcache[$histo[$key]['elementtype']][$histo[$key]['fk_element']])) {
1871					$link = $elementlinkcache[$histo[$key]['elementtype']][$histo[$key]['fk_element']];
1872				} else {
1873					if (!isset($elementlinkcache[$histo[$key]['elementtype']])) {
1874						$elementlinkcache[$histo[$key]['elementtype']] = array();
1875					}
1876					$link = dolGetElementUrl($histo[$key]['fk_element'], $histo[$key]['elementtype'], 1);
1877					$elementlinkcache[$histo[$key]['elementtype']][$histo[$key]['fk_element']] = $link;
1878				}
1879				$out .= $link;
1880			} else {
1881				$out .= '&nbsp;';
1882			}
1883			$out .= '</td>';
1884
1885			// Contact(s) for action
1886			if (empty($objcon->id) && isset($histo[$key]['contact_id']) && $histo[$key]['contact_id'] > 0) {
1887				$contactstatic->lastname = $histo[$key]['lastname'];
1888				$contactstatic->firstname = $histo[$key]['firstname'];
1889				$contactstatic->id = $histo[$key]['contact_id'];
1890				$out .= '<td width="120">'.$contactstatic->getNomUrl(1, '', 10).'</td>';
1891			} elseif (isset($histo[$key]['socpeopleassigned']) && is_array($histo[$key]['socpeopleassigned']) && count($histo[$key]['socpeopleassigned']) > 0) {
1892				$out .= '<td>';
1893				$contact = new Contact($db);
1894				foreach ($histo[$key]['socpeopleassigned'] as $cid => $value) {
1895					$result = $contact->fetch($cid);
1896
1897					if ($result < 0) {
1898						dol_print_error($db, $contact->error);
1899					}
1900
1901					if ($result > 0) {
1902						$out .= $contact->getNomUrl(1, '', 16);
1903						if (isset($histo[$key]['acode']) && $histo[$key]['acode'] == 'AC_TEL') {
1904							if (!empty($contact->phone_pro)) {
1905								$out .= '('.dol_print_phone($contact->phone_pro).')';
1906							}
1907						}
1908						$out .= '<div class="paddingright"></div>';
1909					}
1910				}
1911				$out .= '</td>';
1912			} else {
1913				$out .= '<td>&nbsp;</td>';
1914			}
1915
1916			// Status
1917			$out .= '<td class="nowrap center">'.$actionstatic->LibStatut($histo[$key]['percent'], 2, 0, $histo[$key]['datestart']).'</td>';
1918
1919			// Actions
1920			$out .= '<td></td>';
1921
1922			$out .= "</tr>\n";
1923			$i++;
1924		}
1925		$out .= "</table>\n";
1926		$out .= "</div>\n";
1927
1928		$out .= '</form>';
1929	}
1930
1931	if ($noprint) {
1932		return $out;
1933	} else {
1934		print $out;
1935	}
1936}
1937
1938/**
1939 * 		Show html area for list of subsidiaries
1940 *
1941 *		@param	Conf		$conf		Object conf
1942 * 		@param	Translate	$langs		Object langs
1943 * 		@param	DoliDB		$db			Database handler
1944 * 		@param	Societe		$object		Third party object
1945 * 		@return	int
1946 */
1947function show_subsidiaries($conf, $langs, $db, $object)
1948{
1949	global $user;
1950
1951	$i = -1;
1952
1953	$sql = "SELECT s.rowid, s.client, s.fournisseur, s.nom as name, s.name_alias, s.email, s.address, s.zip, s.town, s.code_client, s.code_fournisseur, s.code_compta, s.code_compta_fournisseur, s.canvas";
1954	$sql .= " FROM ".MAIN_DB_PREFIX."societe as s";
1955	$sql .= " WHERE s.parent = ".((int) $object->id);
1956	$sql .= " AND s.entity IN (".getEntity('societe').")";
1957	$sql .= " ORDER BY s.nom";
1958
1959	$result = $db->query($sql);
1960	$num = $db->num_rows($result);
1961
1962	if ($num) {
1963		$socstatic = new Societe($db);
1964
1965		print load_fiche_titre($langs->trans("Subsidiaries"), '', '');
1966
1967		print "\n".'<div class="div-table-responsive-no-min">'."\n";
1968		print '<table class="noborder centpercent">'."\n";
1969
1970		print '<tr class="liste_titre"><td>'.$langs->trans("Company").'</td>';
1971		print '<td>'.$langs->trans("Address").'</td><td>'.$langs->trans("Zip").'</td>';
1972		print '<td>'.$langs->trans("Town").'</td><td>'.$langs->trans("CustomerCode").'</td>';
1973		print "<td>&nbsp;</td>";
1974		print "</tr>";
1975
1976		$i = 0;
1977
1978		while ($i < $num) {
1979			$obj = $db->fetch_object($result);
1980
1981			$socstatic->id = $obj->rowid;
1982			$socstatic->name = $obj->name;
1983			$socstatic->name_alias = $obj->name_alias;
1984			$socstatic->email = $obj->email;
1985			$socstatic->code_client = $obj->code_client;
1986			$socstatic->code_fournisseur = $obj->code_client;
1987			$socstatic->code_compta = $obj->code_compta;
1988			$socstatic->code_compta_fournisseur = $obj->code_compta_fournisseur;
1989			$socstatic->email = $obj->email;
1990			$socstatic->canvas = $obj->canvas;
1991			$socstatic->client = $obj->client;
1992			$socstatic->fournisseur = $obj->fournisseur;
1993
1994			print '<tr class="oddeven">';
1995
1996			print '<td class="tdoverflowmax150">';
1997			print $socstatic->getNomUrl(1);
1998			print '</td>';
1999
2000			print '<td class="tdoverflowmax400" title="'.dol_escape_htmltag($obj->address).'">'.dol_escape_htmltag($obj->address).'</td>';
2001			print '<td class="tdoverflowmax100" title="'.dol_escape_htmltag($obj->zip).'">'.$obj->zip.'</td>';
2002			print '<td class="tdoverflowmax200" title="'.dol_escape_htmltag($obj->town).'">'.$obj->town.'</td>';
2003			print '<td class="tdoverflowmax200" title="'.dol_escape_htmltag($obj->code_client).'">'.$obj->code_client.'</td>';
2004
2005			print '<td class="center">';
2006			print '<a class="editfielda" href="'.DOL_URL_ROOT.'/societe/card.php?socid='.((int) $obj->rowid).'&action=edit">';
2007			print img_edit();
2008			print '</a></td>';
2009
2010			print "</tr>\n";
2011			$i++;
2012		}
2013		print "\n</table>\n";
2014		print '</div>'."\n";
2015	}
2016
2017	print "<br>\n";
2018
2019	return $i;
2020}
2021/**
2022 * 		Add Event Type SQL
2023 *
2024 *		@param	string		$sql		    $sql modified
2025 * 		@param	string	    $actioncode		Action code
2026 * 		@param	string		$sqlANDOR		"AND", "OR" or "" sql condition
2027 * 		@return	string      sql request
2028 */
2029function addEventTypeSQL(&$sql, $actioncode, $sqlANDOR = "AND")
2030{
2031	global $conf, $db;
2032	// Condition on actioncode
2033
2034	if (empty($conf->global->AGENDA_USE_EVENT_TYPE)) {
2035		if ($actioncode == 'AC_NON_AUTO') {
2036			$sql .= " $sqlANDOR c.type != 'systemauto'";
2037		} elseif ($actioncode == 'AC_ALL_AUTO') {
2038			$sql .= " $sqlANDOR c.type = 'systemauto'";
2039		} else {
2040			if ($actioncode == 'AC_OTH') {
2041				$sql .= " $sqlANDOR c.type != 'systemauto'";
2042			} elseif ($actioncode == 'AC_OTH_AUTO') {
2043				$sql .= " $sqlANDOR c.type = 'systemauto'";
2044			}
2045		}
2046	} else {
2047		if ($actioncode == 'AC_NON_AUTO') {
2048			$sql .= " $sqlANDOR c.type != 'systemauto'";
2049		} elseif ($actioncode == 'AC_ALL_AUTO') {
2050			$sql .= " $sqlANDOR c.type = 'systemauto'";
2051		} else {
2052			$sql .= " $sqlANDOR c.code = '".$db->escape($actioncode)."'";
2053		}
2054	}
2055
2056	return $sql;
2057}
2058
2059/**
2060 * 		Add Event Type SQL
2061 *
2062 *		@param	string		$sql		    $sql modified
2063 * 		@param	string		$donetodo		donetodo
2064 * 		@param	string		$now		    now
2065 * 		@param	string		$filters		array
2066 * 		@return	string      sql request
2067 */
2068function addOtherFilterSQL(&$sql, $donetodo, $now, $filters)
2069{
2070	global $conf, $db;
2071	// Condition on actioncode
2072
2073	if ($donetodo == 'todo') {
2074		$sql .= " AND ((a.percent >= 0 AND a.percent < 100) OR (a.percent = -1 AND a.datep > '".$db->idate($now)."'))";
2075	} elseif ($donetodo == 'done') {
2076		$sql .= " AND (a.percent = 100 OR (a.percent = -1 AND a.datep <= '".$db->idate($now)."'))";
2077	}
2078	if (is_array($filters) && $filters['search_agenda_label']) {
2079		$sql .= natural_search('a.label', $filters['search_agenda_label']);
2080	}
2081
2082	return $sql;
2083}
2084
2085/**
2086 *  Add Mailing Event Type SQL
2087 *
2088 *  @param	string	    $actioncode		Action code
2089 *  @param	Object		$objcon		    objcon
2090 *  @param	Object		$filterobj      filterobj
2091 *  @return	string
2092 */
2093function addMailingEventTypeSQL($actioncode, $objcon, $filterobj)
2094{
2095	global $conf, $langs, $db;
2096	// Add also event from emailings. TODO This should be replaced by an automatic event ? May be it's too much for very large emailing.
2097	if (!empty($conf->mailing->enabled) && !empty($objcon->email)
2098		&& (empty($actioncode) || $actioncode == 'AC_OTH_AUTO' || $actioncode == 'AC_EMAILING')) {
2099		$langs->load("mails");
2100
2101		$sql2 = "SELECT m.rowid as id, m.titre as label, mc.date_envoi as dp, mc.date_envoi as dp2, '100' as percent, 'mailing' as type";
2102		$sql2 .= ", '' as fk_element, '' as elementtype, '' as contact_id";
2103		$sql2 .= ", 'AC_EMAILING' as acode, '' as alabel, '' as apicto";
2104		$sql2 .= ", u.rowid as user_id, u.login as user_login, u.photo as user_photo, u.firstname as user_firstname, u.lastname as user_lastname"; // User that valid action
2105		if (is_object($filterobj) && get_class($filterobj) == 'Societe') {
2106			$sql2 .= ", '' as lastname, '' as firstname";
2107		} elseif (is_object($filterobj) && get_class($filterobj) == 'Adherent') {
2108			$sql2 .= ", '' as lastname, '' as firstname";
2109		} elseif (is_object($filterobj) && get_class($filterobj) == 'CommandeFournisseur') {
2110			$sql2 .= ", '' as ref";
2111		} elseif (is_object($filterobj) && get_class($filterobj) == 'Product') {
2112			$sql2 .= ", '' as ref";
2113		} elseif (is_object($filterobj) && get_class($filterobj) == 'Ticket') {
2114			$sql2 .= ", '' as ref";
2115		}
2116		$sql2 .= " FROM ".MAIN_DB_PREFIX."mailing as m, ".MAIN_DB_PREFIX."mailing_cibles as mc, ".MAIN_DB_PREFIX."user as u";
2117		$sql2 .= " WHERE mc.email = '".$db->escape($objcon->email)."'"; // Search is done on email.
2118		$sql2 .= " AND mc.statut = 1";
2119		$sql2 .= " AND u.rowid = m.fk_user_valid";
2120		$sql2 .= " AND mc.fk_mailing=m.rowid";
2121		return $sql2;
2122	}
2123}
2124