Passed
Branch develop (07a336)
by
unknown
39:19
created

Contact::update()   F

Complexity

Conditions 47
Paths > 20000

Size

Total Lines 191
Code Lines 116

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 47
eloc 116
c 0
b 0
f 0
nop 5
dl 0
loc 191
rs 0
nc 216268800

How to fix   Long Method    Complexity   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
/* Copyright (C) 2002-2004 Rodolphe Quiedeville        <[email protected]>
3
 * Copyright (C) 2004      Benoit Mortier              <[email protected]>
4
 * Copyright (C) 2004-2013 Laurent Destailleur         <[email protected]>
5
 * Copyright (C) 2005-2012 Regis Houssin               <[email protected]>
6
 * Copyright (C) 2007      Franky Van Liedekerke       <[email protected]>
7
 * Copyright (C) 2008      Raphael Bertrand (Resultic) <[email protected]>
8
 * Copyright (C) 2013      Florian Henry		  	   <[email protected]>
9
 * Copyright (C) 2013      Alexandre Spangaro 	       <[email protected]>
10
 * Copyright (C) 2013      Juanjo Menent	 	       <[email protected]>
11
 * Copyright (C) 2015      Marcos García               <[email protected]>
12
 * Copyright (C) 2019      Nicolas ZABOURI 	           <[email protected]>
13
 * Copyright (C) 2020      Open-Dsi  	               <[email protected]>
14
 *
15
 * This program is free software; you can redistribute it and/or modify
16
 * it under the terms of the GNU General Public License as published by
17
 * the Free Software Foundation; either version 3 of the License, or
18
 * (at your option) any later version.
19
 *
20
 * This program is distributed in the hope that it will be useful,
21
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
23
 * GNU General Public License for more details.
24
 *
25
 * You should have received a copy of the GNU General Public License
26
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
27
 */
28
29
/**
30
 *	\file       htdocs/contact/class/contact.class.php
31
 *	\ingroup    societe
32
 *	\brief      File of contacts class
33
 */
34
require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
35
36
37
/**
38
 *	Class to manage contact/addresses
39
 */
40
class Contact extends CommonObject
41
{
42
	/**
43
	 * @var string ID to identify managed object
44
	 */
45
	public $element = 'contact';
46
47
	/**
48
	 * @var string Name of table without prefix where object is stored
49
	 */
50
	public $table_element = 'socpeople';
51
52
	/**
53
	 * 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
54
	 * @var int
55
	 */
56
	public $ismultientitymanaged = 1;
57
58
	/**
59
	 * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png
60
	 */
61
	public $picto = 'contact';
62
63
	/**
64
	 *  'type' if the field format ('integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter]]', 'varchar(x)', 'double(24,8)', 'real', 'price', 'text', 'html', 'date', 'datetime', 'timestamp', 'duration', 'mail', 'phone', 'url', 'password')
65
	 *         Note: Filter can be a string like "(t.ref:like:'SO-%') or (t.date_creation:<:'20160101') or (t.nature:is:NULL)"
66
	 *  'label' the translation key.
67
	 *  'enabled' is a condition when the field must be managed.
68
	 *  'position' is the sort order of field.
69
	 *  'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
70
	 *  'visible' says if field is visible in list (Examples: 0=Not visible, 1=Visible on list and create/update/view forms, 2=Visible on list only, 3=Visible on create/update/view form only (not list), 4=Visible on list and update/view form only (not create). 5=Visible on list and view only (not create/not update). Using a negative value means field is not shown by default on list but can be selected for viewing)
71
	 *  'noteditable' says if field is not editable (1 or 0)
72
	 *  'default' is a default value for creation (can still be overwrote by the Setup of Default Values if field is editable in creation form). Note: If default is set to '(PROV)' and field is 'ref', the default value will be set to '(PROVid)' where id is rowid when a new record is created.
73
	 *  'index' if we want an index in database.
74
	 *  'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommanded to name the field fk_...).
75
	 *  'searchall' is 1 if we want to search in this field when making a search from the quick search button.
76
	 *  'isameasure' must be set to 1 if you want to have a total on list for this field. Field type must be summable like integer or double(24,8).
77
	 *  'css' is the CSS style to use on field. For example: 'maxwidth200'
78
	 *  'help' is a string visible as a tooltip on field
79
	 *  'showoncombobox' if value of the field must be visible into the label of the combobox that list record
80
	 *  'disabled' is 1 if we want to have the field locked by a 'disabled' attribute. In most cases, this is never set into the definition of $fields into class, but is set dynamically by some part of code.
81
	 *  'arraykeyval' to set list of value if type is a list of predefined values. For example: array("0"=>"Draft","1"=>"Active","-1"=>"Cancel")
82
	 *  'comment' is not used. You can store here any text of your choice. It is not used by application.
83
	 *
84
	 *  Note: To have value dynamic, you can set value to 0 in definition and edit the value on the fly into the constructor.
85
	 */
86
87
	// BEGIN MODULEBUILDER PROPERTIES
88
	/**
89
	 * @var array  Array with all fields and their property. Do not use it as a static var. It may be modified by constructor.
90
	 */
91
	public $fields = array(
92
		'rowid' =>array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>10),
93
		'datec' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-1, 'position'=>15),
94
		'tms' =>array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>20),
95
		'fk_soc' =>array('type'=>'integer', 'label'=>'ThirdParty', 'enabled'=>1, 'visible'=>1, 'position'=>25, 'searchall'=>1),
96
		'entity' =>array('type'=>'integer', 'label'=>'Entity', 'default'=>1, 'enabled'=>1, 'visible'=>3, 'notnull'=>1, 'position'=>30, 'index'=>1),
97
		'ref_ext' =>array('type'=>'varchar(255)', 'label'=>'Ref ext', 'enabled'=>1, 'visible'=>3, 'position'=>35),
98
		'civility' =>array('type'=>'varchar(6)', 'label'=>'Civility', 'enabled'=>1, 'visible'=>3, 'position'=>40),
99
		'lastname' =>array('type'=>'varchar(50)', 'label'=>'Lastname', 'enabled'=>1, 'visible'=>1, 'position'=>45, 'showoncombobox'=>1, 'searchall'=>1),
100
		'firstname' =>array('type'=>'varchar(50)', 'label'=>'Firstname', 'enabled'=>1, 'visible'=>1, 'position'=>50, 'showoncombobox'=>1, 'searchall'=>1),
101
		'address' =>array('type'=>'varchar(255)', 'label'=>'Address', 'enabled'=>1, 'visible'=>-1, 'position'=>55),
102
		'zip' =>array('type'=>'varchar(25)', 'label'=>'Zip', 'enabled'=>1, 'visible'=>1, 'position'=>60),
103
		'town' =>array('type'=>'text', 'label'=>'Town', 'enabled'=>1, 'visible'=>1, 'position'=>65),
104
		'fk_departement' =>array('type'=>'integer', 'label'=>'Fk departement', 'enabled'=>1, 'visible'=>3, 'position'=>70),
105
		'fk_pays' =>array('type'=>'integer', 'label'=>'Fk pays', 'enabled'=>1, 'visible'=>3, 'position'=>75),
106
		'birthday' =>array('type'=>'date', 'label'=>'Birthday', 'enabled'=>1, 'visible'=>3, 'position'=>80),
107
		'poste' =>array('type'=>'varchar(80)', 'label'=>'PostOrFunction', 'enabled'=>1, 'visible'=>-1, 'position'=>85),
108
		'phone' =>array('type'=>'varchar(30)', 'label'=>'Phone', 'enabled'=>1, 'visible'=>1, 'position'=>90, 'searchall'=>1),
109
		'phone_perso' =>array('type'=>'varchar(30)', 'label'=>'PhonePerso', 'enabled'=>1, 'visible'=>1, 'position'=>95, 'searchall'=>1),
110
		'phone_mobile' =>array('type'=>'varchar(30)', 'label'=>'PhoneMobile', 'enabled'=>1, 'visible'=>1, 'position'=>100, 'searchall'=>1),
111
		'fax' =>array('type'=>'varchar(30)', 'label'=>'Fax', 'enabled'=>1, 'visible'=>1, 'position'=>105, 'searchall'=>1),
112
		'email' =>array('type'=>'varchar(255)', 'label'=>'Email', 'enabled'=>1, 'visible'=>1, 'position'=>110, 'searchall'=>1),
113
		'socialnetworks' =>array('type'=>'text', 'label'=>'SocialNetworks', 'enabled'=>1, 'visible'=>3, 'position'=>115),
114
		'photo' =>array('type'=>'varchar(255)', 'label'=>'Photo', 'enabled'=>1, 'visible'=>3, 'position'=>170),
115
		'priv' =>array('type'=>'smallint(6)', 'label'=>'ContactVisibility', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'position'=>175),
116
		'fk_stcommcontact' =>array('type'=>'integer', 'label'=>'Fk stcommcontact', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>220),
117
		'fk_prospectlevel' =>array('type'=>'varchar(12)', 'label'=>'ProspectLevel', 'enabled'=>1, 'visible'=>-1, 'position'=>255),
118
		'no_email' =>array('type'=>'smallint(6)', 'label'=>'No_Email', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>180),
119
		'fk_user_creat' =>array('type'=>'integer', 'label'=>'UserAuthor', 'enabled'=>1, 'visible'=>3, 'position'=>185),
120
		'fk_user_modif' =>array('type'=>'integer', 'label'=>'UserModif', 'enabled'=>1, 'visible'=>3, 'position'=>190),
121
		'note_private' =>array('type'=>'text', 'label'=>'NotePrivate', 'enabled'=>1, 'visible'=>3, 'position'=>195, 'searchall'=>1),
122
		'note_public' =>array('type'=>'text', 'label'=>'NotePublic', 'enabled'=>1, 'visible'=>3, 'position'=>200, 'searchall'=>1),
123
		'default_lang' =>array('type'=>'varchar(6)', 'label'=>'Default lang', 'enabled'=>1, 'visible'=>3, 'position'=>205),
124
		'canvas' =>array('type'=>'varchar(32)', 'label'=>'Canvas', 'enabled'=>1, 'visible'=>3, 'position'=>210),
125
		'statut' =>array('type'=>'tinyint(4)', 'label'=>'Status', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'position'=>500),
126
		'import_key' =>array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-1, 'position'=>1000),
127
	);
128
129
	public $civility_id; // In fact we store civility_code
130
	public $civility_code;
131
	public $civility;
132
133
	/**
134
	 * @var string Address
135
	 */
136
	public $address;
137
138
	/**
139
	 * @var string zip code
140
	 */
141
	public $zip;
142
143
	/**
144
	 * @var string Town
145
	 */
146
	public $town;
147
148
	public $state_id; // Id of department
149
	public $state_code; // Code of department
150
	public $state; // Label of department
151
152
	public $poste; // Position
153
154
	public $socid; // fk_soc
155
	public $statut; // 0=inactif, 1=actif
156
157
	public $code;
158
159
	/**
160
	 * Email
161
	 * @var string
162
	 */
163
	public $email;
164
165
	/**
166
	 * Unsuscribe all : 1 = contact has globaly unsubscribe of all mass emailings
167
	 * @var int
168
	 */
169
	public $no_email;
170
171
	/**
172
	 * @var array array of socialnetworks
173
	 */
174
	public $socialnetworks;
175
176
	/**
177
	 * Skype username
178
	 * @var string
179
	 * @deprecated
180
	 */
181
	public $skype;
182
183
	/**
184
	 * Twitter username
185
	 * @var string
186
	 * @deprecated
187
	 */
188
	public $twitter;
189
190
	 /**
191
	  * Facebook username
192
	  * @var string
193
	  * @deprecated
194
	  */
195
	public $facebook;
196
197
	 /**
198
	  * Linkedin username
199
	  * @var string
200
	  * @deprecated
201
	  */
202
	public $linkedin;
203
204
	/**
205
	 * Jabber username
206
	 * @var string
207
	 * @deprecated
208
	 */
209
	public $jabberid;
210
211
	/**
212
	 * @var string filename for photo
213
	 */
214
	public $photo;
215
216
	/**
217
	 * @var string phone pro
218
	 */
219
	public $phone_pro;
220
221
	/**
222
	 * @var string phone perso
223
	 */
224
	public $phone_perso;
225
226
	/**
227
	 * @var string phone mobile
228
	 */
229
	public $phone_mobile;
230
231
	/**
232
	 * @var string fax
233
	 */
234
	public $fax;
235
236
	/**
237
	 * Private or public
238
	 * @var int
239
	 */
240
	public $priv;
241
242
	public $birthday;
243
	public $default_lang;
244
245
	public $ref_facturation; // Reference number of invoice for which it is contact
246
	public $ref_contrat; // Nb de reference contrat pour lequel il est contact
247
	public $ref_commande; // Nb de reference commande pour lequel il est contact
248
	public $ref_propal; // Nb de reference propal pour lequel il est contact
249
250
	public $user_id;
251
	public $user_login;
252
253
	// END MODULEBUILDER PROPERTIES
254
255
256
	/**
257
	 * Old copy
258
	 * @var Contact
259
	 */
260
	public $oldcopy; // To contains a clone of this when we need to save old properties of object
261
262
	public $roles = array();
263
264
	public $cacheprospectstatus = array();
265
	public $fk_prospectlevel;
266
	public $stcomm_id;
267
	public $statut_commercial;
268
	public $stcomm_picto;
269
270
	/**
271
	 *	Constructor
272
	 *
273
	 *  @param		DoliDB		$db      Database handler
274
	 */
275
	public function __construct($db)
276
	{
277
		global $conf, $langs;
278
279
		$this->db = $db;
280
		$this->statut = 1; // By default, status is enabled
281
282
		if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID)) {
283
			$this->fields['rowid']['visible'] = 0;
284
		}
285
		if (empty($conf->mailing->enabled)) {
286
			$this->fields['no_email']['enabled'] = 0;
287
		}
288
		// typical ['s.nom'] is used for third-parties
289
		if (empty($conf->global->SOCIETE_DISABLE_CONTACTS)) {
290
			$this->fields['fk_soc']['enabled'] = 0;
291
			$this->fields['fk_soc']['searchall'] = 0;
292
		}
293
294
		if (empty($conf->global->THIRDPARTY_ENABLE_PROSPECTION_ON_ALTERNATIVE_ADRESSES)) {	// Default behaviour
295
			$this->field['fk_stcommcontact']['enabled'] = 0;
296
			$this->field['fk_prospectcontactlevel']['enabled'] = 0;
297
		}
298
299
		// Unset fields that are disabled
300
		foreach ($this->fields as $key => $val) {
301
			if (isset($val['enabled']) && empty($val['enabled'])) {
302
				unset($this->fields[$key]);
303
			}
304
		}
305
306
		// Translate some data of arrayofkeyval
307
		/*if (is_object($langs))
308
		{
309
			foreach($this->fields as $key => $val)
310
			{
311
				if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval']))
312
				{
313
					foreach($val['arrayofkeyval'] as $key2 => $val2)
314
					{
315
						$this->fields[$key]['arrayofkeyval'][$key2]=$langs->trans($val2);
316
					}
317
				}
318
			}
319
		}*/
320
	}
321
322
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
323
	/**
324
	 *  Load indicators into this->nb for board
325
	 *
326
	 *  @return     int         <0 if KO, >0 if OK
327
	 */
328
	public function load_state_board()
329
	{
330
		// phpcs:enable
331
		global $user;
332
333
		$this->nb = array();
334
		$clause = "WHERE";
335
336
		$sql = "SELECT count(sp.rowid) as nb";
337
		$sql .= " FROM ".MAIN_DB_PREFIX."socpeople as sp";
338
		if (!$user->rights->societe->client->voir && !$user->socid)
339
		{
340
			$sql .= ", ".MAIN_DB_PREFIX."societe as s";
341
			$sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
342
			$sql .= " WHERE sp.fk_soc = s.rowid AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id;
343
			$clause = "AND";
344
		}
345
		$sql .= ' '.$clause.' sp.entity IN ('.getEntity($this->element).')';
346
		$sql .= " AND (sp.priv='0' OR (sp.priv='1' AND sp.fk_user_creat=".$user->id."))";
347
		if ($user->socid > 0) $sql .= " AND sp.fk_soc = ".$user->socid;
348
349
		$resql = $this->db->query($sql);
350
		if ($resql)
351
		{
352
			while ($obj = $this->db->fetch_object($resql))
353
			{
354
				$this->nb["contacts"] = $obj->nb;
355
			}
356
			$this->db->free($resql);
357
			return 1;
358
		} else {
359
			dol_print_error($this->db);
360
			$this->error = $this->db->lasterror();
361
			return -1;
362
		}
363
	}
364
365
	/**
366
	 *  Add a contact into database
367
	 *
368
	 *  @param      User	$user       Object user that create
369
	 *  @return     int      			<0 if KO, >0 if OK
370
	 */
371
	public function create($user)
372
	{
373
		global $conf, $langs;
374
375
		$error = 0;
376
		$now = dol_now();
377
378
		$this->db->begin();
379
380
		// Clean parameters
381
		$this->lastname = $this->lastname ?trim($this->lastname) : trim($this->name);
382
		$this->firstname = trim($this->firstname);
383
		$this->setUpperOrLowerCase();
384
		if (empty($this->socid)) $this->socid = 0;
385
		if (empty($this->priv)) $this->priv = 0;
386
		if (empty($this->statut)) $this->statut = 0; // This is to convert '' into '0' to avoid bad sql request
387
388
		$this->entity = ((isset($this->entity) && is_numeric($this->entity)) ? $this->entity : $conf->entity);
389
390
		$sql = "INSERT INTO ".MAIN_DB_PREFIX."socpeople (";
391
		$sql .= " datec";
392
		$sql .= ", fk_soc";
393
		$sql .= ", lastname";
394
		$sql .= ", firstname";
395
		$sql .= ", fk_user_creat";
396
		$sql .= ", priv";
397
		$sql .= ", fk_stcommcontact";
398
		$sql .= ", statut";
399
		$sql .= ", canvas";
400
		$sql .= ", entity";
401
		$sql .= ", ref_ext";
402
		$sql .= ", import_key";
403
		$sql .= ") VALUES (";
404
		$sql .= "'".$this->db->idate($now)."',";
405
		if ($this->socid > 0) $sql .= " ".$this->db->escape($this->socid).",";
406
		else $sql .= "null,";
407
		$sql .= "'".$this->db->escape($this->lastname)."',";
408
		$sql .= "'".$this->db->escape($this->firstname)."',";
409
		$sql .= " ".($user->id > 0 ? "'".$this->db->escape($user->id)."'" : "null").",";
410
		$sql .= " ".$this->db->escape($this->priv).",";
411
		$sql .= " 0,";
412
		$sql .= " ".$this->db->escape($this->statut).",";
413
		$sql .= " ".(!empty($this->canvas) ? "'".$this->db->escape($this->canvas)."'" : "null").",";
414
		$sql .= " ".$this->db->escape($this->entity).",";
415
		$sql .= "'".$this->db->escape($this->ref_ext)."',";
416
		$sql .= " ".(!empty($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null");
417
		$sql .= ")";
418
419
		dol_syslog(get_class($this)."::create", LOG_DEBUG);
420
		$resql = $this->db->query($sql);
421
		if ($resql)
422
		{
423
			$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."socpeople");
424
425
			if (!$error)
426
			{
427
				$result = $this->update($this->id, $user, 1, 'add'); // This include updateRoles(), ...
428
				if ($result < 0)
429
				{
430
					$error++;
431
					$this->error = $this->db->lasterror();
432
				}
433
			}
434
435
			if (!$error)
436
			{
437
				$result = $this->update_perso($this->id, $user, 1); // TODO Remove function update_perso, should be same than update
438
				if ($result < 0)
439
				{
440
					$error++;
441
					$this->error = $this->db->lasterror();
442
				}
443
			}
444
445
			if (!$error)
446
			{
447
				// Call trigger
448
				$result = $this->call_trigger('CONTACT_CREATE', $user);
449
				if ($result < 0) { $error++; }
450
				// End call triggers
451
			}
452
453
			if (!$error)
454
			{
455
				$this->db->commit();
456
				return $this->id;
457
			} else {
458
				$this->db->rollback();
459
				dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
460
				return -2;
461
			}
462
		} else {
463
			$this->error = $this->db->lasterror();
464
465
			$this->db->rollback();
466
			dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
467
			return -1;
468
		}
469
	}
470
471
	/**
472
	 *      Update informations into database
473
	 *
474
	 *      @param      int		$id          	Id of contact/address to update
475
	 *      @param      User	$user        	Objet user making change
476
	 *      @param      int		$notrigger	    0=no, 1=yes
477
	 *      @param		string	$action			Current action for hookmanager
478
	 *      @param		int		$nosyncuser		No sync linked user (external users and contacts are linked)
479
	 *      @return     int      			   	<0 if KO, >0 if OK
480
	 */
481
	public function update($id, $user = null, $notrigger = 0, $action = 'update', $nosyncuser = 0)
482
	{
483
		global $conf, $langs, $hookmanager;
484
485
		$error = 0;
486
487
		$this->id = $id;
488
489
		$this->entity = ((isset($this->entity) && is_numeric($this->entity)) ? $this->entity : $conf->entity);
490
491
		// Clean parameters
492
		$this->lastname = trim($this->lastname) ?trim($this->lastname) : trim($this->lastname);
493
		$this->firstname = trim($this->firstname);
494
		$this->email = trim($this->email);
495
		$this->phone_pro = trim($this->phone_pro);
496
		$this->phone_perso = trim($this->phone_perso);
497
		$this->phone_mobile = trim($this->phone_mobile);
498
		$this->jabberid = trim($this->jabberid);
1 ignored issue
show
Deprecated Code introduced by
The property Contact::$jabberid has been deprecated. ( Ignorable by Annotation )

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

498
		/** @scrutinizer ignore-deprecated */ $this->jabberid = trim($this->jabberid);
Loading history...
499
		$this->skype = trim($this->skype);
1 ignored issue
show
Deprecated Code introduced by
The property Contact::$skype has been deprecated. ( Ignorable by Annotation )

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

499
		$this->skype = trim(/** @scrutinizer ignore-deprecated */ $this->skype);
Loading history...
500
		$this->photo = trim($this->photo);
501
		$this->fax = trim($this->fax);
502
		$this->zip = (empty($this->zip) ? '' : trim($this->zip));
503
		$this->town = (empty($this->town) ? '' : trim($this->town));
504
		$this->setUpperOrLowerCase();
505
		$this->country_id = ($this->country_id > 0 ? $this->country_id : $this->country_id);
506
		if (empty($this->statut)) $this->statut = 0;
507
		if (empty($this->civility_code) && !is_numeric($this->civility_id)) $this->civility_code = $this->civility_id; // For backward compatibility
508
		$this->db->begin();
509
510
		$sql = "UPDATE ".MAIN_DB_PREFIX."socpeople SET ";
511
		if ($this->socid > 0) $sql .= " fk_soc='".$this->db->escape($this->socid)."',";
512
		elseif ($this->socid == -1) $sql .= " fk_soc=null,";
513
		$sql .= "  civility='".$this->db->escape($this->civility_code)."'";
514
		$sql .= ", lastname='".$this->db->escape($this->lastname)."'";
515
		$sql .= ", firstname='".$this->db->escape($this->firstname)."'";
516
		$sql .= ", address='".$this->db->escape($this->address)."'";
517
		$sql .= ", zip='".$this->db->escape($this->zip)."'";
518
		$sql .= ", town='".$this->db->escape($this->town)."'";
519
		$sql .= ", fk_pays=".($this->country_id > 0 ? $this->country_id : 'NULL');
520
		$sql .= ", fk_departement=".($this->state_id > 0 ? $this->state_id : 'NULL');
521
		$sql .= ", poste='".$this->db->escape($this->poste)."'";
522
		$sql .= ", fax='".$this->db->escape($this->fax)."'";
523
		$sql .= ", email='".$this->db->escape($this->email)."'";
524
		$sql .= ", socialnetworks = '".$this->db->escape(json_encode($this->socialnetworks))."'";
525
		$sql .= ", photo='".$this->db->escape($this->photo)."'";
526
		$sql .= ", birthday=".($this->birthday ? "'".$this->db->idate($this->birthday)."'" : "null");
527
		$sql .= ", note_private = ".(isset($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null");
528
		$sql .= ", note_public = ".(isset($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null");
529
		$sql .= ", phone = ".(isset($this->phone_pro) ? "'".$this->db->escape($this->phone_pro)."'" : "null");
530
		$sql .= ", phone_perso = ".(isset($this->phone_perso) ? "'".$this->db->escape($this->phone_perso)."'" : "null");
531
		$sql .= ", phone_mobile = ".(isset($this->phone_mobile) ? "'".$this->db->escape($this->phone_mobile)."'" : "null");
532
		$sql .= ", priv = '".$this->db->escape($this->priv)."'";
533
		$sql .= ", fk_prospectcontactlevel = '".$this->db->escape($this->fk_prospectlevel)."'";
534
		if (isset($this->stcomm_id))
535
		{
536
			$sql .= ", fk_stcommcontact = ".($this->stcomm_id > 0 || $this->stcomm_id == -1 ? $this->stcomm_id : "0");
537
		}
538
		$sql .= ", statut = ".$this->db->escape($this->statut);
539
		$sql .= ", fk_user_modif=".($user->id > 0 ? "'".$this->db->escape($user->id)."'" : "NULL");
540
		$sql .= ", default_lang=".($this->default_lang ? "'".$this->db->escape($this->default_lang)."'" : "NULL");
541
		$sql .= ", entity = ".$this->db->escape($this->entity);
542
		$sql .= " WHERE rowid=".$this->db->escape($id);
543
544
		dol_syslog(get_class($this)."::update", LOG_DEBUG);
545
		$result = $this->db->query($sql);
546
		if ($result)
547
		{
548
			unset($this->country_code);
549
			unset($this->country);
550
			unset($this->state_code);
551
			unset($this->state);
552
553
			$action = 'update';
554
555
			// Actions on extra fields
556
			if (!$error)
557
			{
558
				$result = $this->insertExtraFields();
559
				if ($result < 0)
560
				{
561
					$error++;
562
				}
563
			}
564
565
			if (!$error) {
566
				$result = $this->updateRoles();
567
				if ($result < 0)
568
				{
569
					$error++;
570
				}
571
			}
572
573
			if (!$error && $this->user_id > 0)
574
			{
575
				// If contact is linked to a user
576
				$tmpobj = new User($this->db);
577
				$tmpobj->fetch($this->user_id);
578
				$usermustbemodified = 0;
579
				if ($tmpobj->office_phone != $this->phone_pro)
580
				{
581
					$tmpobj->office_phone = $this->phone_pro;
582
					$usermustbemodified++;
583
				}
584
				if ($tmpobj->office_fax != $this->fax)
585
				{
586
					$tmpobj->office_fax = $this->fax;
587
					$usermustbemodified++;
588
				}
589
				if ($tmpobj->address != $this->address)
590
				{
591
					$tmpobj->address = $this->address;
592
					$usermustbemodified++;
593
				}
594
				if ($tmpobj->town != $this->town)
595
				{
596
					$tmpobj->town = $this->town;
597
					$usermustbemodified++;
598
				}
599
				if ($tmpobj->zip != $this->zip)
600
				{
601
					$tmpobj->zip = $this->zip;
602
					$usermustbemodified++;
603
				}
604
				if ($tmpobj->zip != $this->zip)
605
				{
606
					$tmpobj->state_id = $this->state_id;
607
					$usermustbemodified++;
608
				}
609
				if ($tmpobj->country_id != $this->country_id)
610
				{
611
					$tmpobj->country_id = $this->country_id;
612
					$usermustbemodified++;
613
				}
614
				if ($tmpobj->email != $this->email)
615
				{
616
					$tmpobj->email = $this->email;
617
					$usermustbemodified++;
618
				}
619
				if (!empty(array_diff($tmpobj->socialnetworks, $this->socialnetworks)))
620
				{
621
					$tmpobj->socialnetworks = $this->socialnetworks;
622
					$usermustbemodified++;
623
				}
624
				// if ($tmpobj->skype != $this->skype)
625
				// {
626
				// 	$tmpobj->skype = $this->skype;
627
				// 	$usermustbemodified++;
628
				// }
629
				// if ($tmpobj->twitter != $this->twitter)
630
				// {
631
				// 	$tmpobj->twitter = $this->twitter;
632
				// 	$usermustbemodified++;
633
				// }
634
				// if ($tmpobj->facebook != $this->facebook)
635
				// {
636
				// 	$tmpobj->facebook = $this->facebook;
637
				// 	$usermustbemodified++;
638
				// }
639
				// if ($tmpobj->linkedin != $this->linkedin)
640
				// {
641
				//     $tmpobj->linkedin = $this->linkedin;
642
				//     $usermustbemodified++;
643
				// }
644
				if ($usermustbemodified)
645
				{
646
					$result = $tmpobj->update($user, 0, 1, 1, 1);
647
					if ($result < 0) { $error++; }
648
				}
649
			}
650
651
			if (!$error && !$notrigger)
652
			{
653
				// Call trigger
654
				$result = $this->call_trigger('CONTACT_MODIFY', $user);
655
				if ($result < 0) { $error++; }
656
				// End call triggers
657
			}
658
659
			if (!$error)
660
			{
661
				$this->db->commit();
662
				return 1;
663
			} else {
664
				dol_syslog(get_class($this)."::update Error ".$this->error, LOG_ERR);
665
				$this->db->rollback();
666
				return -$error;
667
			}
668
		} else {
669
			$this->error = $this->db->lasterror().' sql='.$sql;
670
			$this->db->rollback();
671
			return -1;
672
		}
673
	}
674
675
676
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
677
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
678
	/**
679
	 *	Retourne chaine DN complete dans l'annuaire LDAP pour l'objet
680
	 *
681
	 *	@param		array	$info		Info string loaded by _load_ldap_info
682
	 *	@param		int		$mode		0=Return full DN (uid=qqq,ou=xxx,dc=aaa,dc=bbb)
683
	 *									1=Return DN without key inside (ou=xxx,dc=aaa,dc=bbb)
684
	 *									2=Return key only (uid=qqq)
685
	 *	@return		string				DN
686
	 */
687
	public function _load_ldap_dn($info, $mode = 0)
688
	{
689
		// phpcs:enable
690
		global $conf;
691
		$dn = '';
692
		if ($mode == 0) $dn = $conf->global->LDAP_KEY_CONTACTS."=".$info[$conf->global->LDAP_KEY_CONTACTS].",".$conf->global->LDAP_CONTACT_DN;
693
		elseif ($mode == 1) $dn = $conf->global->LDAP_CONTACT_DN;
694
		elseif ($mode == 2) $dn = $conf->global->LDAP_KEY_CONTACTS."=".$info[$conf->global->LDAP_KEY_CONTACTS];
695
		return $dn;
696
	}
697
698
699
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
700
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
701
	/**
702
	 *	Initialise tableau info (tableau des attributs LDAP)
703
	 *
704
	 *	@return		array		Tableau info des attributs
705
	 */
706
	public function _load_ldap_info()
707
	{
708
		// phpcs:enable
709
		global $conf, $langs;
710
711
		$info = array();
712
713
		// Object classes
714
		$info["objectclass"] = explode(',', $conf->global->LDAP_CONTACT_OBJECT_CLASS);
715
716
		$this->fullname = $this->getFullName($langs);
717
718
		// Fields
719
		if ($this->fullname && !empty($conf->global->LDAP_CONTACT_FIELD_FULLNAME)) $info[$conf->global->LDAP_CONTACT_FIELD_FULLNAME] = $this->fullname;
720
		if ($this->lastname && !empty($conf->global->LDAP_CONTACT_FIELD_NAME)) $info[$conf->global->LDAP_CONTACT_FIELD_NAME] = $this->lastname;
721
		if ($this->firstname && !empty($conf->global->LDAP_CONTACT_FIELD_FIRSTNAME)) $info[$conf->global->LDAP_CONTACT_FIELD_FIRSTNAME] = $this->firstname;
722
723
		if ($this->poste) $info["title"] = $this->poste;
724
		if ($this->socid > 0)
725
		{
726
			$soc = new Societe($this->db);
727
			$soc->fetch($this->socid);
728
729
			$info[$conf->global->LDAP_CONTACT_FIELD_COMPANY] = $soc->name;
730
			if ($soc->client == 1)      $info["businessCategory"] = "Customers";
731
			if ($soc->client == 2)      $info["businessCategory"] = "Prospects";
732
			if ($soc->fournisseur == 1) $info["businessCategory"] = "Suppliers";
733
		}
734
		if ($this->address && !empty($conf->global->LDAP_CONTACT_FIELD_ADDRESS)) $info[$conf->global->LDAP_CONTACT_FIELD_ADDRESS] = $this->address;
735
		if ($this->zip && !empty($conf->global->LDAP_CONTACT_FIELD_ZIP))          $info[$conf->global->LDAP_CONTACT_FIELD_ZIP] = $this->zip;
736
		if ($this->town && !empty($conf->global->LDAP_CONTACT_FIELD_TOWN))      $info[$conf->global->LDAP_CONTACT_FIELD_TOWN] = $this->town;
737
		if ($this->country_code && !empty($conf->global->LDAP_CONTACT_FIELD_COUNTRY))      $info[$conf->global->LDAP_CONTACT_FIELD_COUNTRY] = $this->country_code;
738
		if ($this->phone_pro && !empty($conf->global->LDAP_CONTACT_FIELD_PHONE)) $info[$conf->global->LDAP_CONTACT_FIELD_PHONE] = $this->phone_pro;
739
		if ($this->phone_perso && !empty($conf->global->LDAP_CONTACT_FIELD_HOMEPHONE)) $info[$conf->global->LDAP_CONTACT_FIELD_HOMEPHONE] = $this->phone_perso;
740
		if ($this->phone_mobile && !empty($conf->global->LDAP_CONTACT_FIELD_MOBILE)) $info[$conf->global->LDAP_CONTACT_FIELD_MOBILE] = $this->phone_mobile;
741
		if ($this->fax && !empty($conf->global->LDAP_CONTACT_FIELD_FAX))	    $info[$conf->global->LDAP_CONTACT_FIELD_FAX] = $this->fax;
742
		if ($this->skype && !empty($conf->global->LDAP_CONTACT_FIELD_SKYPE))	    $info[$conf->global->LDAP_CONTACT_FIELD_SKYPE] = $this->skype;
1 ignored issue
show
Deprecated Code introduced by
The property Contact::$skype has been deprecated. ( Ignorable by Annotation )

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

742
		if (/** @scrutinizer ignore-deprecated */ $this->skype && !empty($conf->global->LDAP_CONTACT_FIELD_SKYPE))	    $info[$conf->global->LDAP_CONTACT_FIELD_SKYPE] = $this->skype;
Loading history...
743
		if ($this->note_private && !empty($conf->global->LDAP_CONTACT_FIELD_DESCRIPTION)) $info[$conf->global->LDAP_CONTACT_FIELD_DESCRIPTION] = dol_string_nohtmltag($this->note_private, 2);
744
		if ($this->email && !empty($conf->global->LDAP_CONTACT_FIELD_MAIL))     $info[$conf->global->LDAP_CONTACT_FIELD_MAIL] = $this->email;
745
746
		if ($conf->global->LDAP_SERVER_TYPE == 'egroupware')
747
		{
748
			$info["objectclass"][4] = "phpgwContact"; // compatibilite egroupware
749
750
			$info['uidnumber'] = $this->id;
751
752
			$info['phpgwTz'] = 0;
753
			$info['phpgwMailType'] = 'INTERNET';
754
			$info['phpgwMailHomeType'] = 'INTERNET';
755
756
			$info["phpgwContactTypeId"] = 'n';
757
			$info["phpgwContactCatId"] = 0;
758
			$info["phpgwContactAccess"] = "public";
759
760
			if (dol_strlen($this->egroupware_id) == 0)
761
			{
762
				$this->egroupware_id = 1;
763
			}
764
765
			$info["phpgwContactOwner"] = $this->egroupware_id;
766
767
			if ($this->email) $info["rfc822Mailbox"] = $this->email;
768
			if ($this->phone_mobile) $info["phpgwCellTelephoneNumber"] = $this->phone_mobile;
769
		}
770
771
		return $info;
772
	}
773
774
775
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
776
	/**
777
	 *  Update field alert birthday
778
	 *
779
	 *  @param      int			$id         Id of contact
780
	 *  @param      User		$user		User asking to change alert or birthday
781
	 *  @param      int		    $notrigger	0=no, 1=yes
782
	 *  @return     int         			<0 if KO, >=0 if OK
783
	 */
784
	public function update_perso($id, $user = null, $notrigger = 0)
785
	{
786
		// phpcs:enable
787
		$error = 0;
788
		$result = false;
789
790
		$this->db->begin();
791
792
		// Mis a jour contact
793
		$sql = "UPDATE ".MAIN_DB_PREFIX."socpeople SET";
794
		$sql .= " birthday=".($this->birthday ? "'".$this->db->idate($this->birthday)."'" : "null");
795
		$sql .= ", photo = ".($this->photo ? "'".$this->db->escape($this->photo)."'" : "null");
796
		if ($user) $sql .= ", fk_user_modif=".$user->id;
797
		$sql .= " WHERE rowid=".$this->db->escape($id);
798
799
		dol_syslog(get_class($this)."::update_perso this->birthday=".$this->birthday." -", LOG_DEBUG);
800
		$resql = $this->db->query($sql);
801
		if (!$resql)
802
		{
803
			$error++;
804
			$this->error = $this->db->lasterror();
805
		}
806
807
		// Mis a jour alerte birthday
808
		if (!empty($this->birthday_alert)) {
809
			//check existing
810
			$sql_check = "SELECT rowid FROM ".MAIN_DB_PREFIX."user_alert WHERE type=1 AND fk_contact=".$this->db->escape($id)." AND fk_user=".$user->id;
811
			$result_check = $this->db->query($sql_check);
812
			if (!$result_check || ($this->db->num_rows($result_check) < 1)) {
813
				//insert
814
				$sql = "INSERT INTO ".MAIN_DB_PREFIX."user_alert(type,fk_contact,fk_user) ";
815
				$sql .= "VALUES (1,".$this->db->escape($id).",".$user->id.")";
816
				$result = $this->db->query($sql);
817
				if (!$result) {
818
					$error++;
819
					$this->error = $this->db->lasterror();
820
				}
821
			} else {
822
				$result = true;
823
			}
824
		} else {
825
			$sql = "DELETE FROM ".MAIN_DB_PREFIX."user_alert ";
826
			$sql .= "WHERE type=1 AND fk_contact=".$this->db->escape($id)." AND fk_user=".$user->id;
827
			$result = $this->db->query($sql);
828
			if (!$result) {
829
				$error++;
830
				$this->error = $this->db->lasterror();
831
			}
832
		}
833
834
		if (!$error && !$notrigger) {
835
			// Call trigger
836
			$result = $this->call_trigger('CONTACT_MODIFY', $user);
837
			if ($result < 0) { $error++; }
838
			// End call triggers
839
		}
840
841
		if (!$error) {
842
			$this->db->commit();
843
			return 1;
844
		} else {
845
			dol_syslog(get_class($this)."::update Error ".$this->error, LOG_ERR);
846
			$this->db->rollback();
847
			return -$error;
848
		}
849
	}
850
851
852
	/**
853
	 *  Load object contact.
854
	 *
855
	 *  @param      int		$id         	Id of contact
856
	 *  @param      User	$user       	Load also alerts of this user (subscribing to alerts) that want alerts about this contact
857
	 *  @param      string  $ref_ext    	External reference, not given by Dolibarr
858
	 *  @param		string	$email			Email
859
	 *  @param		int		$loadalsoroles	Load also roles
860
	 *  @return     int     		    	>0 if OK, <0 if KO or if two records found for same ref or idprof, 0 if not found.
861
	 */
862
	public function fetch($id, $user = null, $ref_ext = '', $email = '', $loadalsoroles = 0)
863
	{
864
		global $langs;
865
866
		dol_syslog(get_class($this)."::fetch id=".$id." ref_ext=".$ref_ext." email=".$email, LOG_DEBUG);
867
868
		if (empty($id) && empty($ref_ext) && empty($email))
869
		{
870
			$this->error = 'BadParameter';
871
			return -1;
872
		}
873
874
		$langs->loadLangs(array("dict", "companies"));
875
876
		$sql = "SELECT c.rowid, c.entity, c.fk_soc, c.ref_ext, c.civility as civility_code, c.lastname, c.firstname,";
877
		$sql .= " c.address, c.statut, c.zip, c.town,";
878
		$sql .= " c.fk_pays as country_id,";
879
		$sql .= " c.fk_departement as state_id,";
880
		$sql .= " c.birthday,";
881
		$sql .= " c.poste, c.phone, c.phone_perso, c.phone_mobile, c.fax, c.email,";
882
		$sql .= " c.socialnetworks,";
883
		$sql .= " c.photo,";
884
		$sql .= " c.priv, c.note_private, c.note_public, c.default_lang, c.canvas,";
885
		$sql .= " c.fk_prospectcontactlevel, c.fk_stcommcontact, st.libelle as stcomm, st.picto as stcomm_picto,";
886
		$sql .= " c.import_key,";
887
		$sql .= " c.datec as date_creation, c.tms as date_modification,";
888
		$sql .= " co.label as country, co.code as country_code,";
889
		$sql .= " d.nom as state, d.code_departement as state_code,";
890
		$sql .= " u.rowid as user_id, u.login as user_login,";
891
		$sql .= " s.nom as socname, s.address as socaddress, s.zip as soccp, s.town as soccity, s.default_lang as socdefault_lang";
892
		$sql .= " FROM ".MAIN_DB_PREFIX."socpeople as c";
893
		$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_country as co ON c.fk_pays = co.rowid";
894
		$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_departements as d ON c.fk_departement = d.rowid";
895
		$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as u ON c.rowid = u.fk_socpeople";
896
		$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON c.fk_soc = s.rowid";
897
		$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_stcommcontact as st ON c.fk_stcommcontact = st.id';
898
		if ($id) $sql .= " WHERE c.rowid = ".((int) $id);
899
		else {
900
			$sql .= " WHERE c.entity IN (".getEntity($this->element).")";
901
			if ($ref_ext) {
902
				$sql .= " AND c.ref_ext = '".$this->db->escape($ref_ext)."'";
903
			}
904
			if ($email) {
905
				$sql .= " AND c.email = '".$this->db->escape($email)."'";
906
			}
907
		}
908
909
		$resql = $this->db->query($sql);
910
		if ($resql)
911
		{
912
			$num = $this->db->num_rows($resql);
913
			if ($num > 1)
914
			{
915
				$this->error = 'Fetch found several records. Rename one of contact to avoid duplicate.';
916
				dol_syslog($this->error, LOG_ERR);
917
918
				return 2;
919
			} elseif ($num)   // $num = 1
920
			{
921
				$obj = $this->db->fetch_object($resql);
922
923
				$this->id = $obj->rowid;
924
				$this->entity = $obj->entity;
925
				$this->ref = $obj->rowid;
926
				$this->ref_ext = $obj->ref_ext;
927
928
				$this->civility_code    = $obj->civility_code;
929
				$this->civility	        = $obj->civility_code ? ($langs->trans("Civility".$obj->civility_code) != ("Civility".$obj->civility_code) ? $langs->trans("Civility".$obj->civility_code) : $obj->civility_code) : '';
930
931
				$this->lastname = $obj->lastname;
932
				$this->firstname = $obj->firstname;
933
				$this->address = $obj->address;
934
				$this->zip = $obj->zip;
935
				$this->town = $obj->town;
936
937
				$this->date_creation     = $this->db->jdate($obj->date_creation);
938
				$this->date_modification = $this->db->jdate($obj->date_modification);
939
940
				$this->state_id = $obj->state_id;
941
				$this->state_code = $obj->state_code;
942
				$this->state = $obj->state;
943
944
				$this->country_id = $obj->country_id;
945
				$this->country_code = $obj->country_id ? $obj->country_code : '';
946
				$this->country			= $obj->country_id ? ($langs->trans('Country'.$obj->country_code) != 'Country'.$obj->country_code ? $langs->transnoentities('Country'.$obj->country_code) : $obj->country) : '';
947
948
				$this->socid			= $obj->fk_soc;
949
				$this->socname			= $obj->socname;
950
				$this->poste			= $obj->poste;
951
				$this->statut = $obj->statut;
952
953
				$this->fk_prospectlevel = $obj->fk_prospectcontactlevel;
954
955
				$transcode = $langs->trans('StatusProspect'.$obj->fk_stcommcontact);
956
				$libelle = ($transcode != 'StatusProspect'.$obj->fk_stcommcontact ? $transcode : $obj->stcomm);
957
				$this->stcomm_id = $obj->fk_stcommcontact; // id statut commercial
958
				$this->statut_commercial = $libelle; // libelle statut commercial
959
				$this->stcomm_picto = $obj->stcomm_picto; // Picto statut commercial
960
961
				$this->phone_pro = trim($obj->phone);
962
				$this->fax = trim($obj->fax);
963
				$this->phone_perso = trim($obj->phone_perso);
964
				$this->phone_mobile = trim($obj->phone_mobile);
965
966
				$this->email			= $obj->email;
967
				$this->socialnetworks = (array) json_decode($obj->socialnetworks, true);
968
				$this->photo			= $obj->photo;
969
				$this->priv				= $obj->priv;
970
				$this->mail				= $obj->email;
971
972
				$this->birthday = $this->db->jdate($obj->birthday);
973
				$this->note				= $obj->note_private; // deprecated
974
				$this->note_private		= $obj->note_private;
975
				$this->note_public = $obj->note_public;
976
				$this->default_lang		= $obj->default_lang;
977
				$this->user_id = $obj->user_id;
978
				$this->user_login		= $obj->user_login;
979
				$this->canvas = $obj->canvas;
980
981
				$this->import_key		= $obj->import_key;
982
983
				// Define gender according to civility
984
				$this->setGenderFromCivility();
985
986
				// Search Dolibarr user linked to this contact
987
				$sql = "SELECT u.rowid ";
988
				$sql .= " FROM ".MAIN_DB_PREFIX."user as u";
989
				$sql .= " WHERE u.fk_socpeople = ".$this->id;
990
991
				$resql = $this->db->query($sql);
992
				if ($resql)
993
				{
994
					if ($this->db->num_rows($resql))
995
					{
996
						$uobj = $this->db->fetch_object($resql);
997
998
						$this->user_id = $uobj->rowid;
999
					}
1000
					$this->db->free($resql);
1001
				} else {
1002
					$this->error = $this->db->error();
1003
					return -1;
1004
				}
1005
1006
				// Retrieve all extrafield
1007
				// fetch optionals attributes and labels
1008
				$this->fetch_optionals();
1009
1010
				// Load also alerts of this user
1011
				if ($user)
1012
				{
1013
					$sql = "SELECT fk_user";
1014
					$sql .= " FROM ".MAIN_DB_PREFIX."user_alert";
1015
					$sql .= " WHERE fk_user = ".$user->id." AND fk_contact = ".$this->db->escape($id);
1016
1017
					$resql = $this->db->query($sql);
1018
					if ($resql)
1019
					{
1020
						if ($this->db->num_rows($resql))
1021
						{
1022
							$obj = $this->db->fetch_object($resql);
1023
1024
							$this->birthday_alert = 1;
1025
						}
1026
						$this->db->free($resql);
1027
					} else {
1028
						$this->error = $this->db->error();
1029
						return -1;
1030
					}
1031
				}
1032
1033
				// Load also roles of this address
1034
				if ($loadalsoroles) {
1035
					$resultRole = $this->fetchRoles();
1036
					if ($resultRole < 0) {
1037
						return $resultRole;
1038
					}
1039
				}
1040
1041
				return 1;
1042
			} else {
1043
				$this->error = $langs->trans("RecordNotFound");
1044
				return 0;
1045
			}
1046
		} else {
1047
			$this->error = $this->db->error();
1048
			return -1;
1049
		}
1050
	}
1051
1052
1053
1054
	/**
1055
	 * Set the property "gender" of this class, based on the property "civility_id"
1056
	 * or use property "civility_code" as fallback, when "civility_id" is not available.
1057
	 *
1058
	 * @return void
1059
	 */
1060
	public function setGenderFromCivility()
1061
	{
1062
		unset($this->gender);
1063
1064
		if (in_array($this->civility_id, array('MR')) || in_array($this->civility_code, array('MR')))
1065
		{
1066
			$this->gender = 'man';
1067
		} elseif (in_array($this->civility_id, array('MME', 'MLE')) || in_array($this->civility_code, array('MME', 'MLE')))
1068
		{
1069
			$this->gender = 'woman';
1070
		}
1071
	}
1072
1073
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1074
	/**
1075
	 *  Load number of elements the contact is used as a link for
1076
	 *  ref_facturation
1077
	 *  ref_contrat
1078
	 *  ref_commande (for order and/or shipments)
1079
	 *  ref_propale
1080
	 *
1081
	 *  @return     int             					<0 if KO, >=0 if OK
1082
	 */
1083
	public function load_ref_elements()
1084
	{
1085
		// phpcs:enable
1086
		// Compte les elements pour lesquels il est contact
1087
		$sql = "SELECT tc.element, count(ec.rowid) as nb";
1088
		$sql .= " FROM ".MAIN_DB_PREFIX."element_contact as ec, ".MAIN_DB_PREFIX."c_type_contact as tc";
1089
		$sql .= " WHERE ec.fk_c_type_contact = tc.rowid";
1090
		$sql .= " AND fk_socpeople = ".$this->id;
1091
		$sql .= " AND tc.source = 'external'";
1092
		$sql .= " GROUP BY tc.element";
1093
1094
		dol_syslog(get_class($this)."::load_ref_elements", LOG_DEBUG);
1095
1096
		$resql = $this->db->query($sql);
1097
		if ($resql)
1098
		{
1099
			while ($obj = $this->db->fetch_object($resql))
1100
			{
1101
				if ($obj->nb)
1102
				{
1103
					if ($obj->element == 'facture')  $this->ref_facturation = $obj->nb;
1104
					elseif ($obj->element == 'contrat')  $this->ref_contrat = $obj->nb;
1105
					elseif ($obj->element == 'commande') $this->ref_commande = $obj->nb;
1106
					elseif ($obj->element == 'propal')   $this->ref_propal = $obj->nb;
1107
				}
1108
			}
1109
			$this->db->free($resql);
1110
			return 0;
1111
		} else {
1112
			$this->error = $this->db->lasterror();
1113
			return -1;
1114
		}
1115
	}
1116
1117
	/**
1118
	 *   	Efface le contact de la base
1119
	 *
1120
	 *   	@param		int		$notrigger		Disable all trigger
1121
	 *		@return		int						<0 if KO, >0 if OK
1122
	 */
1123
	public function delete($notrigger = 0)
1124
	{
1125
		global $conf, $langs, $user;
1126
1127
		$error = 0;
1128
1129
		$this->db->begin();
1130
1131
		if (!$error)
1132
		{
1133
			// Get all rowid of element_contact linked to a type that is link to llx_socpeople
1134
			$sql = "SELECT ec.rowid";
1135
			$sql .= " FROM ".MAIN_DB_PREFIX."element_contact ec,";
1136
			$sql .= " ".MAIN_DB_PREFIX."c_type_contact tc";
1137
			$sql .= " WHERE ec.fk_socpeople=".$this->id;
1138
			$sql .= " AND ec.fk_c_type_contact=tc.rowid";
1139
			$sql .= " AND tc.source='external'";
1140
			dol_syslog(__METHOD__, LOG_DEBUG);
1141
			$resql = $this->db->query($sql);
1142
			if ($resql)
1143
			{
1144
				$num = $this->db->num_rows($resql);
1145
1146
				$i = 0;
1147
				while ($i < $num && !$error)
1148
				{
1149
					$obj = $this->db->fetch_object($resql);
1150
1151
					$sqldel = "DELETE FROM ".MAIN_DB_PREFIX."element_contact";
1152
					$sqldel .= " WHERE rowid = ".$obj->rowid;
1153
					dol_syslog(__METHOD__, LOG_DEBUG);
1154
					$result = $this->db->query($sqldel);
1155
					if (!$result)
1156
					{
1157
						$error++;
1158
						$this->error = $this->db->error().' sql='.$sqldel;
1159
					}
1160
1161
					$i++;
1162
				}
1163
			} else {
1164
				$error++;
1165
				$this->error = $this->db->error().' sql='.$sql;
1166
			}
1167
		}
1168
1169
		if (!$error)
1170
		{
1171
			// Remove Roles
1172
			$sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_contacts WHERE fk_socpeople = ".$this->id;
1173
			dol_syslog(__METHOD__, LOG_DEBUG);
1174
			$resql = $this->db->query($sql);
1175
			if (!$resql)
1176
			{
1177
				$error++;
1178
				$this->error .= $this->db->lasterror();
1179
				$errorflag = -1;
1180
			}
1181
		}
1182
1183
		if (!$error)
1184
		{
1185
			// Remove category
1186
			$sql = "DELETE FROM ".MAIN_DB_PREFIX."categorie_contact WHERE fk_socpeople = ".$this->id;
1187
			dol_syslog(__METHOD__, LOG_DEBUG);
1188
			$resql = $this->db->query($sql);
1189
			if (!$resql)
1190
			{
1191
				$error++;
1192
				$this->error .= $this->db->lasterror();
1193
				$errorflag = -1;
1194
			}
1195
		}
1196
1197
		if (!$error)
1198
		{
1199
			$sql = "DELETE FROM ".MAIN_DB_PREFIX."socpeople";
1200
			$sql .= " WHERE rowid=".$this->id;
1201
			dol_syslog(__METHOD__, LOG_DEBUG);
1202
			$result = $this->db->query($sql);
1203
			if (!$result)
1204
			{
1205
				$error++;
1206
				$this->error = $this->db->error().' sql='.$sql;
1207
			}
1208
		}
1209
1210
		// Removed extrafields
1211
		if (!$error) {
1212
			// For avoid conflicts if trigger used
1213
			$result = $this->deleteExtraFields();
1214
			if ($result < 0) $error++;
1215
		}
1216
1217
		if (!$error && !$notrigger)
1218
		{
1219
			// Call trigger
1220
			$result = $this->call_trigger('CONTACT_DELETE', $user);
1221
			if ($result < 0) { $error++; }
1222
			// End call triggers
1223
		}
1224
1225
		if (!$error)
1226
		{
1227
			$this->db->commit();
1228
			return 1;
1229
		} else {
1230
			$this->db->rollback();
1231
			dol_syslog("Error ".$this->error, LOG_ERR);
1232
			return -1;
1233
		}
1234
	}
1235
1236
1237
	/**
1238
	 *  Charge les informations sur le contact, depuis la base
1239
	 *
1240
	 *  @param		int		$id      Id du contact a charger
1241
	 *  @return		void
1242
	 */
1243
	public function info($id)
1244
	{
1245
		$sql = "SELECT c.rowid, c.datec as datec, c.fk_user_creat,";
1246
		$sql .= " c.tms as tms, c.fk_user_modif";
1247
		$sql .= " FROM ".MAIN_DB_PREFIX."socpeople as c";
1248
		$sql .= " WHERE c.rowid = ".$this->db->escape($id);
1249
1250
		$resql = $this->db->query($sql);
1251
		if ($resql)
1252
		{
1253
			if ($this->db->num_rows($resql))
1254
			{
1255
				$obj = $this->db->fetch_object($resql);
1256
1257
				$this->id = $obj->rowid;
1258
1259
				if ($obj->fk_user_creat) {
1260
					$cuser = new User($this->db);
1261
					$cuser->fetch($obj->fk_user_creat);
1262
					$this->user_creation = $cuser;
1263
				}
1264
1265
				if ($obj->fk_user_modif) {
1266
					$muser = new User($this->db);
1267
					$muser->fetch($obj->fk_user_modif);
1268
					$this->user_modification = $muser;
1269
				}
1270
1271
				$this->date_creation     = $this->db->jdate($obj->datec);
1272
				$this->date_modification = $this->db->jdate($obj->tms);
1273
			}
1274
1275
			$this->db->free($resql);
1276
		} else {
1277
			print $this->db->error();
1278
		}
1279
	}
1280
1281
	/**
1282
	 *  Return number of mass Emailing received by this contacts with its email
1283
	 *
1284
	 *  @return       int     Number of EMailings
1285
	 */
1286
	public function getNbOfEMailings()
1287
	{
1288
		$sql = "SELECT count(mc.email) as nb";
1289
		$sql .= " FROM ".MAIN_DB_PREFIX."mailing_cibles as mc, ".MAIN_DB_PREFIX."mailing as m";
1290
		$sql .= " WHERE mc.fk_mailing=m.rowid AND mc.email = '".$this->db->escape($this->email)."' ";
1291
		$sql .= " AND m.entity IN (".getEntity($this->element).") AND mc.statut NOT IN (-1,0)"; // -1 error, 0 not sent, 1 sent with success
1292
1293
		$resql = $this->db->query($sql);
1294
		if ($resql)
1295
		{
1296
			$obj = $this->db->fetch_object($resql);
1297
			$nb = $obj->nb;
1298
1299
			$this->db->free($resql);
1300
			return $nb;
1301
		} else {
1302
			$this->error = $this->db->error();
1303
			return -1;
1304
		}
1305
	}
1306
1307
	/**
1308
	 *  Return name of contact with link (and eventually picto)
1309
	 *	Use $this->id, $this->lastname, $this->firstname, this->civility_id
1310
	 *
1311
	 *	@param		int			$withpicto					Include picto with link
1312
	 *	@param		string		$option						Where the link point to
1313
	 *	@param		int			$maxlen						Max length of
1314
	 *  @param		string		$moreparam					Add more param into URL
1315
	 *  @param      int     	$save_lastsearch_value		-1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
1316
	 *	@param		int			$notooltip					1=Disable tooltip
1317
	 *	@return		string									String with URL
1318
	 */
1319
	public function getNomUrl($withpicto = 0, $option = '', $maxlen = 0, $moreparam = '', $save_lastsearch_value = -1, $notooltip = 0)
1320
	{
1321
		global $conf, $langs, $hookmanager;
1322
1323
		$result = ''; $label = '';
1324
1325
		if (!empty($this->photo) && class_exists('Form'))
1326
		{
1327
			$label .= '<div class="photointooltip">';
1328
			$label .= Form::showphoto('contact', $this, 0, 40, 0, '', 'mini', 0); // Important, we must force height so image will have height tags and if image is inside a tooltip, the tooltip manager can calculate height and position correctly the tooltip.
1329
			$label .= '</div><div style="clear: both;"></div>';
1330
		}
1331
1332
		$label .= img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Contact").'</u>';
1333
		$label .= ' '.$this->getLibStatut(4);
1334
		$label .= '<br><b>'.$langs->trans("Name").':</b> '.$this->getFullName($langs);
1335
		//if ($this->civility_id) $label.= '<br><b>' . $langs->trans("Civility") . ':</b> '.$this->civility_id;		// TODO Translate cibilty_id code
1336
		if (!empty($this->poste)) $label .= '<br><b>'.$langs->trans("Poste").':</b> '.$this->poste;
1337
		$label .= '<br><b>'.$langs->trans("EMail").':</b> '.$this->email;
1338
		$phonelist = array();
1339
		$country_code = empty($this->country_code) ? '': $this->country_code;
1340
		if ($this->phone_pro) $phonelist[] = dol_print_phone($this->phone_pro, $country_code, $this->id, 0, '', '&nbsp;', 'phone');
1341
		if ($this->phone_mobile) $phonelist[] = dol_print_phone($this->phone_mobile, $country_code, $this->id, 0, '', '&nbsp;', 'mobile');
1342
		if ($this->phone_perso) $phonelist[] = dol_print_phone($this->phone_perso, $country_code, $this->id, 0, '', '&nbsp;', 'phone');
1343
		$label .= '<br><b>'.$langs->trans("Phone").':</b> '.implode('&nbsp;', $phonelist);
1344
		$label .= '<br><b>'.$langs->trans("Address").':</b> '.dol_format_address($this, 1, ' ', $langs);
1345
1346
		$url = DOL_URL_ROOT.'/contact/card.php?id='.$this->id;
1347
1348
		if ($option !== 'nolink')
1349
		{
1350
			// Add param to save lastsearch_values or not
1351
			$add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
1352
			if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) $add_save_lastsearch_values = 1;
1353
			if ($add_save_lastsearch_values) $url .= '&save_lastsearch_values=1';
1354
		}
1355
1356
		$url .= $moreparam;
1357
1358
		$linkclose = "";
1359
		if (empty($notooltip)) {
1360
			if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
1361
			{
1362
				$label = $langs->trans("ShowContact");
1363
				$linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
1364
			}
1365
		   	$linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
1366
		   	$linkclose .= ' class="classfortooltip"';
1367
1368
		   	/*
1369
    	   	 $hookmanager->initHooks(array('contactdao'));
1370
    	   	 $parameters=array('id'=>$this->id);
1371
    	   	 $reshook=$hookmanager->executeHooks('getnomurltooltip',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
1372
    	   	 if ($reshook > 0) $linkclose = $hookmanager->resPrint;
1373
    	   	 */
1374
		}
1375
1376
		$linkstart = '<a href="'.$url.'"';
1377
		$linkstart .= $linkclose.'>';
1378
		$linkend = '</a>';
1379
1380
		if ($option == 'xxx')
1381
		{
1382
			$linkstart = '<a href="'.DOL_URL_ROOT.'/contact/card.php?id='.$this->id.$moreparam.'" title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip">';
1383
			$linkend = '</a>';
1384
		}
1385
1386
		$result .= $linkstart;
1387
		if ($withpicto) $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
1388
		if ($withpicto != 2) $result .= ($maxlen ?dol_trunc($this->getFullName($langs), $maxlen) : $this->getFullName($langs));
1389
		$result .= $linkend;
1390
1391
		global $action;
1392
		$hookmanager->initHooks(array('contactdao'));
1393
		$parameters = array('id'=>$this->id, 'getnomurl'=>$result);
1394
		$reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1395
		if ($reshook > 0) $result = $hookmanager->resPrint;
1396
		else $result .= $hookmanager->resPrint;
1397
1398
		return $result;
1399
	}
1400
1401
	/**
1402
	 *    Return civility label of contact
1403
	 *
1404
	 *    @return	string      			Translated name of civility
1405
	 */
1406
	public function getCivilityLabel()
1407
	{
1408
		global $langs;
1409
1410
		$code = ($this->civility_code ? $this->civility_code : (!empty($this->civility_id) ? $this->civility : (!empty($this->civilite) ? $this->civilite : '')));
0 ignored issues
show
Bug introduced by
The property civilite does not exist on Contact. Did you mean civility?
Loading history...
1411
		if (empty($code)) return '';
1412
1413
		$langs->load("dict");
1414
		return $langs->getLabelFromKey($this->db, "Civility".$code, "c_civility", "code", "label", $code);
1415
	}
1416
1417
	/**
1418
	 *	Return label of contact status
1419
	 *
1420
	 *	@param      int			$mode       0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto
1421
	 * 	@return 	string					Label of contact status
1422
	 */
1423
	public function getLibStatut($mode)
1424
	{
1425
		return $this->LibStatut($this->statut, $mode);
1426
	}
1427
1428
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1429
	/**
1430
	 *	Renvoi le libelle d'un statut donne
1431
	 *
1432
	 *  @param      int			$status     Id statut
1433
	 *  @param      int			$mode       0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto
1434
	 *  @return     string					Libelle
1435
	 */
1436
	public function LibStatut($status, $mode)
1437
	{
1438
		// phpcs:enable
1439
		global $langs;
1440
1441
		$labelStatus = array(
1442
			0 => 'ActivityCeased',
1443
			1 => 'InActivity',
1444
			4 => 'InActivity',
1445
			5 => 'ActivityCeased',
1446
		);
1447
		$labelStatusShort = array(
1448
			0 => 'ActivityCeased',
1449
			1 => 'InActivity',
1450
			4 => 'InActivity',
1451
			5 => 'ActivityCeased',
1452
		);
1453
1454
		$statusType = 'status4';
1455
		if ($status == 0 || $status == 5) $statusType = 'status5';
1456
1457
		$label = $langs->trans($labelStatus[$status]);
1458
		$labelshort = $langs->trans($labelStatusShort[$status]);
1459
1460
		return dolGetStatus($label, $labelshort, '', $statusType, $mode);
1461
	}
1462
1463
1464
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1465
	/**
1466
	 *	Return translated label of Public or Private
1467
	 *
1468
	 * 	@param      int			$status		Type (0 = public, 1 = private)
1469
	 *  @return     string					Label translated
1470
	 */
1471
	public function LibPubPriv($status)
1472
	{
1473
		// phpcs:enable
1474
		global $langs;
1475
		if ($status == '1') return $langs->trans('ContactPrivate');
1476
		else return $langs->trans('ContactPublic');
1477
	}
1478
1479
1480
	/**
1481
	 *  Initialise an instance with random values.
1482
	 *  Used to build previews or test instances.
1483
	 *	id must be 0 if object instance is a specimen.
1484
	 *
1485
	 *  @return	int >0 if ok
1486
	 */
1487
	public function initAsSpecimen()
1488
	{
1489
		// Get first id of existing company and save it into $socid
1490
		$socid = 0;
1491
		$sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe ORDER BY rowid LIMIT 1";
1492
		$resql = $this->db->query($sql);
1493
		if ($resql) {
1494
			$obj = $this->db->fetch_object($resql);
1495
			if ($obj) $socid = $obj->rowid;
1496
		}
1497
1498
		// Initialise parameters
1499
		$this->id = 0;
1500
		$this->entity = 1;
1501
		$this->specimen = 1;
1502
		$this->lastname = 'DOLIBARR';
1503
		$this->firstname = 'SPECIMEN';
1504
		$this->address = '21 jump street';
1505
		$this->zip = '99999';
1506
		$this->town = 'MyTown';
1507
		$this->country_id = 1;
1508
		$this->country_code = 'FR';
1509
		$this->country = 'France';
1510
		$this->email = '[email protected]';
1511
		$this->socialnetworks = array(
1512
			'skype' => 'tom.hanson',
1513
		);
1514
		$this->phone_pro = '0909090901';
1515
		$this->phone_perso = '0909090902';
1516
		$this->phone_mobile = '0909090903';
1517
		$this->fax = '0909090909';
1518
1519
		$this->note_public = 'This is a comment (public)';
1520
		$this->note_private = 'This is a comment (private)';
1521
1522
		$this->socid = $socid;
1523
		$this->statut = 1;
1524
		return 1;
1525
	}
1526
1527
	/**
1528
	 *  Change status of a user
1529
	 *
1530
	 *	@param	int		$status		Status to set
1531
	 *  @return int     			<0 if KO, 0 if nothing is done, >0 if OK
1532
	 */
1533
	public function setstatus($status)
1534
	{
1535
		global $conf, $langs, $user;
1536
1537
		$error = 0;
1538
1539
		// Check parameters
1540
		if ($this->statut == $status) return 0;
1541
		else $this->statut = $status;
1542
1543
		$this->db->begin();
1544
1545
		// Desactive utilisateur
1546
		$sql = "UPDATE ".MAIN_DB_PREFIX."socpeople";
1547
		$sql .= " SET statut = ".$this->statut;
1548
		$sql .= " WHERE rowid = ".$this->id;
1549
		$result = $this->db->query($sql);
1550
1551
		dol_syslog(get_class($this)."::setstatus", LOG_DEBUG);
1552
		if ($result)
1553
		{
1554
			// Call trigger
1555
			$result = $this->call_trigger('CONTACT_ENABLEDISABLE', $user);
1556
			if ($result < 0) { $error++; }
1557
			// End call triggers
1558
		}
1559
1560
		if ($error)
1561
		{
1562
			$this->db->rollback();
1563
			return -$error;
1564
		} else {
1565
			$this->db->commit();
1566
			return 1;
1567
		}
1568
	}
1569
1570
	/**
1571
	 * Sets object to supplied categories.
1572
	 *
1573
	 * Deletes object from existing categories not supplied.
1574
	 * Adds it to non existing supplied categories.
1575
	 * Existing categories are left untouch.
1576
	 *
1577
	 * @param int[]|int $categories Category or categories IDs
1578
	 * @return void
1579
	 */
1580
	public function setCategories($categories)
1581
	{
1582
		require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
1583
		return parent::setCategoriesCommon($categories, Categorie::TYPE_CONTACT);
1584
	}
1585
1586
	/**
1587
	 * Function used to replace a thirdparty id with another one.
1588
	 *
1589
	 * @param DoliDB $db Database handler
1590
	 * @param int $origin_id Old thirdparty id
1591
	 * @param int $dest_id New thirdparty id
1592
	 * @return bool
1593
	 */
1594
	public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
1595
	{
1596
		$tables = array(
1597
			'socpeople', 'societe_contacts'
1598
		);
1599
1600
		return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
1601
	}
1602
1603
	/**
1604
	 * Fetch Roles for a contact
1605
	 *
1606
	 * @return float|int
1607
	 * @throws Exception
1608
	 */
1609
	public function fetchRoles()
1610
	{
1611
		global $langs;
1612
		$error = 0;
1613
		$num = 0;
1614
1615
		$sql = "SELECT tc.rowid, tc.element, tc.source, tc.code, tc.libelle, sc.rowid as contactroleid";
1616
		$sql .= " FROM ".MAIN_DB_PREFIX."societe_contacts as sc";
1617
		$sql .= " INNER JOIN ".MAIN_DB_PREFIX."c_type_contact as tc";
1618
		$sql .= " ON tc.rowid = sc.fk_c_type_contact";
1619
		$sql .= " AND sc.fk_socpeople = ".$this->id;
1620
		$sql .= " AND tc.source = 'external' AND tc.active=1";
1621
		$sql .= " AND sc.entity IN (".getEntity('societe').')';
1622
1623
		dol_syslog(__METHOD__, LOG_DEBUG);
1624
1625
		$this->roles = array();
1626
		$resql = $this->db->query($sql);
1627
		if ($resql) {
1628
			$num = $this->db->num_rows($resql);
1629
			if ($num > 0) {
1630
				while ($obj = $this->db->fetch_object($resql)) {
1631
					$transkey = "TypeContact_".$obj->element."_".$obj->source."_".$obj->code;
1632
					$libelle_element = $langs->trans('ContactDefault_'.$obj->element);
1633
					$this->roles[$obj->contactroleid] = array('id'=>$obj->rowid, 'element'=>$obj->element, 'source'=>$obj->source, 'code'=>$obj->code, 'label'=>$libelle_element.' - '.($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle));
1634
				}
1635
			}
1636
		} else {
1637
			$error++;
1638
			$this->error = $this->db->lasterror();
1639
			$this->errors[] = $this->db->lasterror();
1640
		}
1641
1642
		if (empty($error)) {
1643
			return $num;
1644
		} else {
1645
			return $error * -1;
1646
		}
1647
	}
1648
1649
	/**
1650
	 * Get Contact roles for a thirdparty
1651
	 *
1652
	 * @param  string 	$element 	Element type
1653
	 * @return array|int			Array of contact roles or -1
1654
	 * @throws Exception
1655
	 */
1656
	public function getContactRoles($element = '')
1657
	{
1658
		$tab = array();
1659
1660
		if ($element == 'action') {
1661
			$element = 'agenda';
1662
		}
1663
1664
		$sql = "SELECT sc.fk_socpeople as id, sc.fk_c_type_contact";
1665
		$sql .= " FROM ".MAIN_DB_PREFIX."c_type_contact tc";
1666
		$sql .= ", ".MAIN_DB_PREFIX."societe_contacts sc";
1667
		$sql .= " WHERE sc.fk_soc =".$this->socid;
1668
		$sql .= " AND sc.fk_c_type_contact=tc.rowid";
1669
		$sql .= " AND tc.element='".$this->db->escape($element)."'";
1670
		$sql .= " AND tc.active=1";
1671
1672
		dol_syslog(__METHOD__, LOG_DEBUG);
1673
		$resql = $this->db->query($sql);
1674
		if ($resql)
1675
		{
1676
			$num = $this->db->num_rows($resql);
1677
			$i = 0;
1678
			while ($i < $num)
1679
			{
1680
				$obj = $this->db->fetch_object($resql);
1681
				$tab[] = array('fk_socpeople'=>$obj->id, 'type_contact'=>$obj->fk_c_type_contact);
1682
1683
				$i++;
1684
			}
1685
1686
			return $tab;
1687
		} else {
1688
			$this->error = $this->db->error();
1689
			dol_print_error($this->db);
1690
			return -1;
1691
		}
1692
	}
1693
1694
	/**
1695
	 * Updates Roles
1696
	 *
1697
	 * @return float|int
1698
	 * @throws Exception
1699
	 */
1700
	public function updateRoles()
1701
	{
1702
		global $conf;
1703
1704
		$error = 0;
1705
1706
		$this->db->begin();
1707
1708
		$sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_contacts WHERE fk_soc=".$this->socid." AND fk_socpeople=".$this->id; ;
1709
1710
		dol_syslog(__METHOD__, LOG_DEBUG);
1711
		$result = $this->db->query($sql);
1712
		if (!$result) {
1713
			$this->errors[] = $this->db->lasterror().' sql='.$sql;
1714
			$error++;
1715
		} else {
1716
			if (count($this->roles) > 0) {
1717
				foreach ($this->roles as $keyRoles => $valRoles) {
1718
					$sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_contacts";
1719
					$sql .= " (entity,";
1720
					$sql .= "date_creation,";
1721
					$sql .= "fk_soc,";
1722
					$sql .= "fk_c_type_contact,";
1723
					$sql .= "fk_socpeople) ";
1724
					$sql .= " VALUES (".$conf->entity.",";
1725
					$sql .= "'".$this->db->idate(dol_now())."',";
1726
					$sql .= $this->socid.", ";
1727
					$sql .= $valRoles." , ";
1728
					$sql .= $this->id;
1729
					$sql .= ")";
1730
					dol_syslog(__METHOD__, LOG_DEBUG);
1731
1732
					$result = $this->db->query($sql);
1733
					if (!$result)
1734
					{
1735
						$this->errors[] = $this->db->lasterror().' sql='.$sql;
1736
						$error++;
1737
					}
1738
				}
1739
			}
1740
		}
1741
		if (empty($error)) {
1742
			$this->db->commit();
1743
			return 1;
1744
		} else {
1745
			$this->error = implode(' ', $this->errors);
1746
			$this->db->rollback();
1747
			return $error * -1;
1748
		}
1749
	}
1750
1751
	/**
1752
	 *  Load array of prospect status
1753
	 *
1754
	 *  @param	int		$active     1=Active only, 0=Not active only, -1=All
1755
	 *  @return int					<0 if KO, >0 if OK
1756
	 */
1757
	public function loadCacheOfProspStatus($active = 1)
1758
	{
1759
		global $langs;
1760
1761
		$sql = "SELECT id, code, libelle as label, picto FROM ".MAIN_DB_PREFIX."c_stcommcontact";
1762
		if ($active >= 0) $sql .= " WHERE active = ".$active;
1763
		$resql = $this->db->query($sql);
1764
		$num = $this->db->num_rows($resql);
1765
		$i = 0;
1766
		while ($i < $num)
1767
		{
1768
			$obj = $this->db->fetch_object($resql);
1769
			$this->cacheprospectstatus[$obj->id] = array('id' => $obj->id, 'code' => $obj->code, 'label' => ($langs->trans("ST_".strtoupper($obj->code)) == "ST_".strtoupper($obj->code)) ? $obj->label : $langs->trans("ST_".strtoupper($obj->code)), 'picto' => $obj->picto);
1770
			$i++;
1771
		}
1772
		return 1;
1773
	}
1774
1775
	/**
1776
	 *	Return prostect level
1777
	 *
1778
	 *  @return     string        Libelle
1779
	 */
1780
	public function getLibProspLevel()
1781
	{
1782
		return $this->libProspLevel($this->fk_prospectlevel);
1783
	}
1784
1785
	/**
1786
	 *  Return label of prospect level
1787
	 *
1788
	 *  @param	int		$fk_prospectlevel   	Prospect level
1789
	 *  @return string        					label of level
1790
	 */
1791
	public function libProspLevel($fk_prospectlevel)
1792
	{
1793
		global $langs;
1794
1795
		$lib = $langs->trans("ProspectLevel".$fk_prospectlevel);
1796
		// If lib not found in language file, we get label from cache/databse
1797
		if ($lib == $langs->trans("ProspectLevel".$fk_prospectlevel))
1798
		{
1799
			$lib = $langs->getLabelFromKey($this->db, $fk_prospectlevel, 'c_prospectlevel', 'code', 'label');
1800
		}
1801
		return $lib;
1802
	}
1803
1804
1805
	/**
1806
	 *  Set prospect level
1807
	 *
1808
	 *  @param  User	$user		Utilisateur qui definie la remise
1809
	 *	@return	int					<0 if KO, >0 if OK
1810
	 * @deprecated Use update function instead
1811
	 */
1812
	public function setProspectLevel(User $user)
1813
	{
1814
		return $this->update($this->id, $user);
1815
	}
1816
1817
	/**
1818
	 *  Return status of prospect
1819
	 *
1820
	 *  @param	int		$mode       0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long
1821
	 *  @param	string	$label		Label to use for status for added status
1822
	 *  @return string        		Libelle
1823
	 */
1824
	public function getLibProspCommStatut($mode = 0, $label = '')
1825
	{
1826
		return $this->libProspCommStatut($this->stcomm_id, $mode, $label, $this->stcomm_picto);
1827
	}
1828
1829
	/**
1830
	 *  Return label of a given status
1831
	 *
1832
	 *  @param	int|string	$statut        	Id or code for prospection status
1833
	 *  @param  int			$mode          	0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto
1834
	 *  @param	string		$label			Label to use for status for added status
1835
	 *	@param 	string		$picto      	Name of image file to show ('filenew', ...)
1836
	 *                                      If no extension provided, we use '.png'. Image must be stored into theme/xxx/img directory.
1837
	 *                                      Example: picto.png                  if picto.png is stored into htdocs/theme/mytheme/img
1838
	 *                                      Example: picto.png@mymodule         if picto.png is stored into htdocs/mymodule/img
1839
	 *                                      Example: /mydir/mysubdir/picto.png  if picto.png is stored into htdocs/mydir/mysubdir (pictoisfullpath must be set to 1)
1840
	 *  @return string       	 			Libelle du statut
1841
	 */
1842
	public function libProspCommStatut($statut, $mode = 0, $label = '', $picto = '')
1843
	{
1844
		global $langs;
1845
		$langs->load('customers');
1846
1847
		if ($mode == 2)
1848
		{
1849
			if ($statut == '-1' || $statut == 'ST_NO') return img_action($langs->trans("StatusProspect-1"), -1, $picto).' '.$langs->trans("StatusProspect-1");
1850
			elseif ($statut == '0' || $statut == 'ST_NEVER') return img_action($langs->trans("StatusProspect0"), 0, $picto).' '.$langs->trans("StatusProspect0");
1851
			elseif ($statut == '1' || $statut == 'ST_TODO') return img_action($langs->trans("StatusProspect1"), 1, $picto).' '.$langs->trans("StatusProspect1");
1852
			elseif ($statut == '2' || $statut == 'ST_PEND') return img_action($langs->trans("StatusProspect2"), 2, $picto).' '.$langs->trans("StatusProspect2");
1853
			elseif ($statut == '3' || $statut == 'ST_DONE') return img_action($langs->trans("StatusProspect3"), 3, $picto).' '.$langs->trans("StatusProspect3");
1854
			else {
1855
				return img_action(($langs->trans("StatusProspect".$statut) != "StatusProspect".$statut) ? $langs->trans("StatusProspect".$statut) : $label, 0, $picto).' '.(($langs->trans("StatusProspect".$statut) != "StatusProspect".$statut) ? $langs->trans("StatusProspect".$statut) : $label);
1856
			}
1857
		}
1858
		if ($mode == 3)
1859
		{
1860
			if ($statut == '-1' || $statut == 'ST_NO') return img_action($langs->trans("StatusProspect-1"), -1, $picto);
1861
			elseif ($statut == '0' || $statut == 'ST_NEVER') return img_action($langs->trans("StatusProspect0"), 0, $picto);
1862
			elseif ($statut == '1' || $statut == 'ST_TODO') return img_action($langs->trans("StatusProspect1"), 1, $picto);
1863
			elseif ($statut == '2' || $statut == 'ST_PEND') return img_action($langs->trans("StatusProspect2"), 2, $picto);
1864
			elseif ($statut == '3' || $statut == 'ST_DONE') return img_action($langs->trans("StatusProspect3"), 3, $picto);
1865
			else {
1866
				return img_action(($langs->trans("StatusProspect".$statut) != "StatusProspect".$statut) ? $langs->trans("StatusProspect".$statut) : $label, 0, $picto);
1867
			}
1868
		}
1869
		if ($mode == 4)
1870
		{
1871
			if ($statut == '-1' || $statut == 'ST_NO') return img_action($langs->trans("StatusProspect-1"), -1, $picto).' '.$langs->trans("StatusProspect-1");
1872
			elseif ($statut == '0' || $statut == 'ST_NEVER') return img_action($langs->trans("StatusProspect0"), 0, $picto).' '.$langs->trans("StatusProspect0");
1873
			elseif ($statut == '1' || $statut == 'ST_TODO') return img_action($langs->trans("StatusProspect1"), 1, $picto).' '.$langs->trans("StatusProspect1");
1874
			elseif ($statut == '2' || $statut == 'ST_PEND') return img_action($langs->trans("StatusProspect2"), 2, $picto).' '.$langs->trans("StatusProspect2");
1875
			elseif ($statut == '3' || $statut == 'ST_DONE') return img_action($langs->trans("StatusProspect3"), 3, $picto).' '.$langs->trans("StatusProspect3");
1876
			else {
1877
				return img_action(($langs->trans("StatusProspect".$statut) != "StatusProspect".$statut) ? $langs->trans("StatusProspect".$statut) : $label, 0, $picto).' '.(($langs->trans("StatusProspect".$statut) != "StatusProspect".$statut) ? $langs->trans("StatusProspect".$statut) : $label);
1878
			}
1879
		}
1880
1881
		return "Error, mode/status not found";
1882
	}
1883
}
1884