Passed
Branch develop (f6c1a1)
by
unknown
28:54
created

Contact::LibPubPriv()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 3
c 0
b 0
f 0
nc 2
nop 1
dl 0
loc 6
rs 10
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
	// BEGIN MODULEBUILDER PROPERTIES
65
	/**
66
	 * @var array  Array with all fields and their property. Do not use it as a static var. It may be modified by constructor.
67
	 */
68
	public $fields = array(
69
		'rowid' =>array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>10),
70
		'datec' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-1, 'position'=>15),
71
		'tms' =>array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>20),
72
		'fk_soc' =>array('type'=>'integer', 'label'=>'ThirdParty', 'enabled'=>1, 'visible'=>-1, 'position'=>25),
73
		'entity' =>array('type'=>'integer', 'label'=>'Entity', 'default'=>1, 'enabled'=>1, 'visible'=>0, 'notnull'=>1, 'position'=>30, 'index'=>1),
74
		'ref_ext' =>array('type'=>'varchar(255)', 'label'=>'Ref ext', 'enabled'=>1, 'visible'=>0, 'position'=>35),
75
		'civility' =>array('type'=>'varchar(6)', 'label'=>'Civility', 'enabled'=>1, 'visible'=>-1, 'position'=>40),
76
		'lastname' =>array('type'=>'varchar(50)', 'label'=>'Lastname', 'enabled'=>1, 'visible'=>-1, 'position'=>45, 'showoncombobox'=>1),
77
		'firstname' =>array('type'=>'varchar(50)', 'label'=>'Firstname', 'enabled'=>1, 'visible'=>-1, 'position'=>50, 'showoncombobox'=>1),
78
		'address' =>array('type'=>'varchar(255)', 'label'=>'Address', 'enabled'=>1, 'visible'=>-1, 'position'=>55),
79
		'zip' =>array('type'=>'varchar(25)', 'label'=>'Zip', 'enabled'=>1, 'visible'=>-1, 'position'=>60),
80
		'town' =>array('type'=>'text', 'label'=>'Town', 'enabled'=>1, 'visible'=>-1, 'position'=>65),
81
		'fk_departement' =>array('type'=>'integer', 'label'=>'Fk departement', 'enabled'=>1, 'visible'=>-1, 'position'=>70),
82
		'fk_pays' =>array('type'=>'integer', 'label'=>'Fk pays', 'enabled'=>1, 'visible'=>-1, 'position'=>75),
83
		'birthday' =>array('type'=>'date', 'label'=>'Birthday', 'enabled'=>1, 'visible'=>-1, 'position'=>80),
84
		'poste' =>array('type'=>'varchar(80)', 'label'=>'PostOrFunction', 'enabled'=>1, 'visible'=>-1, 'position'=>85),
85
		'phone' =>array('type'=>'varchar(30)', 'label'=>'Phone', 'enabled'=>1, 'visible'=>-1, 'position'=>90),
86
		'phone_perso' =>array('type'=>'varchar(30)', 'label'=>'Phone perso', 'enabled'=>1, 'visible'=>-1, 'position'=>95),
87
		'phone_mobile' =>array('type'=>'varchar(30)', 'label'=>'Phone mobile', 'enabled'=>1, 'visible'=>-1, 'position'=>100),
88
		'fax' =>array('type'=>'varchar(30)', 'label'=>'Fax', 'enabled'=>1, 'visible'=>-1, 'position'=>105),
89
		'email' =>array('type'=>'varchar(255)', 'label'=>'Email', 'enabled'=>1, 'visible'=>-1, 'position'=>110),
90
		'socialnetworks' =>array('type'=>'text', 'label'=>'SocialNetworks', 'enabled'=>1, 'visible'=>-1, 'position'=>115),
91
		'photo' =>array('type'=>'varchar(255)', 'label'=>'Photo', 'enabled'=>1, 'visible'=>-1, 'position'=>170),
92
		'priv' =>array('type'=>'smallint(6)', 'label'=>'Private', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>175),
93
		'fk_stcomm' =>array('type'=>'integer', 'label'=>'Fk stcommcontact', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>220),
94
		'fk_prospectlevel' =>array('type'=>'varchar(12)', 'label'=>'ProspectLevel', 'enabled'=>1, 'visible'=>-1, 'position'=>255),
95
		'no_email' =>array('type'=>'smallint(6)', 'label'=>'No email', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>180),
96
		'fk_user_creat' =>array('type'=>'integer', 'label'=>'UserAuthor', 'enabled'=>1, 'visible'=>-1, 'position'=>185),
97
		'fk_user_modif' =>array('type'=>'integer', 'label'=>'UserModif', 'enabled'=>1, 'visible'=>-1, 'position'=>190),
98
		'note_private' =>array('type'=>'text', 'label'=>'NotePrivate', 'enabled'=>1, 'visible'=>0, 'position'=>195),
99
		'note_public' =>array('type'=>'text', 'label'=>'NotePublic', 'enabled'=>1, 'visible'=>0, 'position'=>200),
100
		'default_lang' =>array('type'=>'varchar(6)', 'label'=>'Default lang', 'enabled'=>1, 'visible'=>-1, 'position'=>205),
101
		'canvas' =>array('type'=>'varchar(32)', 'label'=>'Canvas', 'enabled'=>1, 'visible'=>-1, 'position'=>210),
102
		'statut' =>array('type'=>'tinyint(4)', 'label'=>'Statut', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>500),
103
		'import_key' =>array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-2, 'position'=>1000),
104
	);
105
106
	public $civility_id; // In fact we store civility_code
107
	public $civility_code;
108
	public $civility;
109
110
	/**
111
	 * Address
112
	 * @var string
113
	 */
114
	public $address;
115
	public $zip;
116
	public $town;
117
118
	public $state_id; // Id of department
119
	public $state_code; // Code of department
120
	public $state; // Label of department
121
122
    public $poste; // Position
123
124
	public $socid; // fk_soc
125
	public $statut; // 0=inactif, 1=actif
126
127
	public $code;
128
129
    /**
130
     * Email
131
     * @var string
132
     */
133
	public $email;
134
135
    /**
136
     * Unsuscribe all : 1 = contact has globaly unsubscribe of all mass emailings
137
	 * @var int
138
     */
139
	public $no_email;
140
141
    /**
142
     * @var array array of socialnetworks
143
     */
144
    public $socialnetworks;
145
146
    /**
147
     * Skype username
148
     * @var string
149
     * @deprecated
150
     */
151
	public $skype;
152
153
	/**
154
     * Twitter username
155
     * @var string
156
     * @deprecated
157
     */
158
	public $twitter;
159
160
	 /**
161
     * Facebook username
162
     * @var string
163
     * @deprecated
164
     */
165
	public $facebook;
166
167
	 /**
168
     * Linkedin username
169
     * @var string
170
     * @deprecated
171
     */
172
    public $linkedin;
173
174
    /**
175
     * Jabber username
176
     * @var string
177
     * @deprecated
178
     */
179
	public $jabberid;
180
181
	public $photo;
182
	public $phone_pro;
183
	public $phone_perso;
184
	public $phone_mobile;
185
	public $fax;
186
187
	/**
188
	 * Private or public
189
	 * @var int
190
	 */
191
	public $priv;
192
193
	public $birthday;
194
	public $default_lang;
195
196
	public $ref_facturation; // Reference number of invoice for which it is contact
197
	public $ref_contrat; // Nb de reference contrat pour lequel il est contact
198
	public $ref_commande; // Nb de reference commande pour lequel il est contact
199
	public $ref_propal; // Nb de reference propal pour lequel il est contact
200
201
	public $user_id;
202
	public $user_login;
203
204
	// END MODULEBUILDER PROPERTIES
205
206
207
    /**
208
     * Old copy
209
     * @var Contact
210
     */
211
	public $oldcopy; // To contains a clone of this when we need to save old properties of object
212
213
	public $roles = array();
214
215
	public $cacheprospectstatus = array();
216
	public $fk_prospectlevel;
217
	public $stcomm_id;
218
	public $statut_commercial;
219
	public $stcomm_picto;
220
221
	/**
222
	 *	Constructor
223
	 *
224
	 *  @param		DoliDB		$db      Database handler
225
	 */
226
	public function __construct($db)
227
	{
228
		global $conf, $langs;
229
230
		$this->db = $db;
231
232
		if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid'])) $this->fields['rowid']['visible'] = 0;
233
		if (empty($conf->mailing->enabled)) $this->fields['no_email']['enabled'] = 0;
234
		if (!empty($conf->global->SOCIETE_DISABLE_CONTACTS)) $this->fields['thirdparty']['enabled'] = 0;
235
		if (empty($conf->global->THIRDPARTY_ENABLE_PROSPECTION_ON_ALTERNATIVE_ADRESSES)) {	// Default behaviour
236
			$this->field['fk_stcomm']['enabled'] = 0;
237
			$this->field['fk_prospectlevel']['enabled'] = 0;
238
		}
239
		$this->statut = 1; // By default, status is enabled
240
241
		// Unset fields that are disabled
242
		foreach ($this->fields as $key => $val)
243
		{
244
			if (isset($val['enabled']) && empty($val['enabled']))
245
			{
246
				unset($this->fields[$key]);
247
			}
248
		}
249
250
		// Translate some data of arrayofkeyval
251
		/*if (is_object($langs))
252
		{
253
			foreach($this->fields as $key => $val)
254
			{
255
				if (is_array($val['arrayofkeyval']))
256
				{
257
					foreach($val['arrayofkeyval'] as $key2 => $val2)
258
					{
259
						$this->fields[$key]['arrayofkeyval'][$key2]=$langs->trans($val2);
260
					}
261
				}
262
			}
263
		}*/
264
	}
265
266
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
267
	/**
268
	 *  Load indicators into this->nb for board
269
	 *
270
	 *  @return     int         <0 if KO, >0 if OK
271
	 */
272
	public function load_state_board()
273
	{
274
        // phpcs:enable
275
		global $user;
276
277
		$this->nb = array();
278
		$clause = "WHERE";
279
280
		$sql = "SELECT count(sp.rowid) as nb";
281
		$sql .= " FROM ".MAIN_DB_PREFIX."socpeople as sp";
282
		if (!$user->rights->societe->client->voir && !$user->socid)
283
		{
284
		    $sql .= ", ".MAIN_DB_PREFIX."societe as s";
285
		    $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
286
			$sql .= " WHERE sp.fk_soc = s.rowid AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id;
287
			$clause = "AND";
288
		}
289
		$sql .= ' '.$clause.' sp.entity IN ('.getEntity($this->element).')';
290
		$sql .= " AND (sp.priv='0' OR (sp.priv='1' AND sp.fk_user_creat=".$user->id."))";
291
        if ($user->socid > 0) $sql .= " AND sp.fk_soc = ".$user->socid;
292
293
		$resql = $this->db->query($sql);
294
		if ($resql)
295
		{
296
			while ($obj = $this->db->fetch_object($resql))
297
			{
298
				$this->nb["contacts"] = $obj->nb;
299
			}
300
			$this->db->free($resql);
301
			return 1;
302
		} else {
303
			dol_print_error($this->db);
304
			$this->error = $this->db->lasterror();
305
			return -1;
306
		}
307
	}
308
309
	/**
310
	 *  Add a contact into database
311
	 *
312
	 *  @param      User	$user       Object user that create
313
	 *  @return     int      			<0 if KO, >0 if OK
314
	 */
315
	public function create($user)
316
	{
317
		global $conf, $langs;
318
319
		$error = 0;
320
		$now = dol_now();
321
322
		$this->db->begin();
323
324
		// Clean parameters
325
		$this->lastname = $this->lastname ?trim($this->lastname) : trim($this->name);
326
        $this->firstname = trim($this->firstname);
327
        if (!empty($conf->global->MAIN_FIRST_TO_UPPER)) $this->lastname = ucwords(strtolower($this->lastname));
328
		if (!empty($conf->global->MAIN_ALL_TO_UPPER)) $this->lastname = strtoupper($this->lastname);
329
        if (!empty($conf->global->MAIN_FIRST_TO_UPPER)) $this->firstname = ucwords(strtolower($this->firstname));
330
        if (empty($this->socid)) $this->socid = 0;
331
		if (empty($this->priv)) $this->priv = 0;
332
		if (empty($this->statut)) $this->statut = 0; // This is to convert '' into '0' to avoid bad sql request
333
334
		$this->entity = ((isset($this->entity) && is_numeric($this->entity)) ? $this->entity : $conf->entity);
335
336
		$sql = "INSERT INTO ".MAIN_DB_PREFIX."socpeople (";
337
		$sql .= " datec";
338
		$sql .= ", fk_soc";
339
        $sql .= ", lastname";
340
        $sql .= ", firstname";
341
        $sql .= ", fk_user_creat";
342
		$sql .= ", priv";
343
		$sql.= ", fk_stcommcontact";
344
		$sql .= ", statut";
345
		$sql .= ", canvas";
346
		$sql .= ", entity";
347
		$sql .= ", ref_ext";
348
		$sql .= ", import_key";
349
		$sql .= ") VALUES (";
350
		$sql .= "'".$this->db->idate($now)."',";
351
		if ($this->socid > 0) $sql .= " ".$this->db->escape($this->socid).",";
352
		else $sql .= "null,";
353
		$sql .= "'".$this->db->escape($this->lastname)."',";
354
        $sql .= "'".$this->db->escape($this->firstname)."',";
355
        $sql .= " ".($user->id > 0 ? "'".$this->db->escape($user->id)."'" : "null").",";
356
		$sql .= " ".$this->db->escape($this->priv).",";
357
		$sql.= " 0,";
358
		$sql .= " ".$this->db->escape($this->statut).",";
359
        $sql .= " ".(!empty($this->canvas) ? "'".$this->db->escape($this->canvas)."'" : "null").",";
360
        $sql .= " ".$this->db->escape($this->entity).",";
361
        $sql .= "'".$this->db->escape($this->ref_ext)."',";
362
        $sql .= " ".(!empty($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null");
363
		$sql .= ")";
364
365
		dol_syslog(get_class($this)."::create", LOG_DEBUG);
366
		$resql = $this->db->query($sql);
367
		if ($resql)
368
		{
369
			$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."socpeople");
370
371
			if (!$error)
372
			{
373
                $result = $this->update($this->id, $user, 1, 'add'); // This include updateRoles(), ...
374
                if ($result < 0)
375
                {
376
                    $error++;
377
				    $this->error = $this->db->lasterror();
378
                }
379
			}
380
381
			if (!$error)
382
            {
383
                $result = $this->update_perso($this->id, $user, 1); // TODO Remove function update_perso, should be same than update
384
                if ($result < 0)
385
                {
386
                    $error++;
387
                    $this->error = $this->db->lasterror();
388
                }
389
            }
390
391
            if (!$error)
392
            {
393
                // Call trigger
394
                $result = $this->call_trigger('CONTACT_CREATE', $user);
395
                if ($result < 0) { $error++; }
396
                // End call triggers
397
            }
398
399
            if (!$error)
400
            {
401
                $this->db->commit();
402
                return $this->id;
403
            } else {
404
                $this->db->rollback();
405
                dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
406
                return -2;
407
            }
408
		} else {
409
			$this->error = $this->db->lasterror();
410
411
			$this->db->rollback();
412
			dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
413
			return -1;
414
		}
415
	}
416
417
	/**
418
	 *      Update informations into database
419
	 *
420
	 *      @param      int		$id          	Id of contact/address to update
421
	 *      @param      User	$user        	Objet user making change
422
	 *      @param      int		$notrigger	    0=no, 1=yes
423
	 *      @param		string	$action			Current action for hookmanager
424
	 *      @param		int		$nosyncuser		No sync linked user (external users and contacts are linked)
425
	 *      @return     int      			   	<0 if KO, >0 if OK
426
	 */
427
	public function update($id, $user = null, $notrigger = 0, $action = 'update', $nosyncuser = 0)
428
	{
429
		global $conf, $langs, $hookmanager;
430
431
		$error = 0;
432
433
		$this->id = $id;
434
435
		$this->entity = ((isset($this->entity) && is_numeric($this->entity)) ? $this->entity : $conf->entity);
436
437
		// Clean parameters
438
		if (!empty($conf->global->MAIN_FIRST_TO_UPPER)) $this->lastname = ucwords(strtolower($this->lastname));
439
		if (!empty($conf->global->MAIN_ALL_TO_UPPER)) $this->lastname = strtoupper($this->lastname);
440
        if (!empty($conf->global->MAIN_FIRST_TO_UPPER)) $this->firstname = ucwords(strtolower($this->firstname));
441
442
		$this->lastname = trim($this->lastname) ?trim($this->lastname) : trim($this->lastname);
443
		$this->firstname = trim($this->firstname);
444
		$this->email = trim($this->email);
445
		$this->phone_pro = trim($this->phone_pro);
446
		$this->phone_perso = trim($this->phone_perso);
447
		$this->phone_mobile = trim($this->phone_mobile);
448
		$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

448
		$this->jabberid = trim(/** @scrutinizer ignore-deprecated */ $this->jabberid);
Loading history...
449
		$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

449
		$this->skype = trim(/** @scrutinizer ignore-deprecated */ $this->skype);
Loading history...
450
		$this->photo = trim($this->photo);
451
		$this->fax = trim($this->fax);
452
		$this->zip = (empty($this->zip) ? '' : $this->zip);
453
		$this->town = (empty($this->town) ? '' : $this->town);
454
		$this->country_id = ($this->country_id > 0 ? $this->country_id : $this->country_id);
455
		if (empty($this->statut)) $this->statut = 0;
456
		if (empty($this->civility_code) && !is_numeric($this->civility_id)) $this->civility_code = $this->civility_id; // For backward compatibility
457
		$this->db->begin();
458
459
		$sql = "UPDATE ".MAIN_DB_PREFIX."socpeople SET ";
460
		if ($this->socid > 0) $sql .= " fk_soc='".$this->db->escape($this->socid)."',";
461
		elseif ($this->socid == -1) $sql .= " fk_soc=null,";
462
		$sql .= "  civility='".$this->db->escape($this->civility_code)."'";
463
		$sql .= ", lastname='".$this->db->escape($this->lastname)."'";
464
		$sql .= ", firstname='".$this->db->escape($this->firstname)."'";
465
		$sql .= ", address='".$this->db->escape($this->address)."'";
466
		$sql .= ", zip='".$this->db->escape($this->zip)."'";
467
		$sql .= ", town='".$this->db->escape($this->town)."'";
468
		$sql .= ", fk_pays=".($this->country_id > 0 ? $this->country_id : 'NULL');
469
		$sql .= ", fk_departement=".($this->state_id > 0 ? $this->state_id : 'NULL');
470
		$sql .= ", poste='".$this->db->escape($this->poste)."'";
471
		$sql .= ", fax='".$this->db->escape($this->fax)."'";
472
		$sql .= ", email='".$this->db->escape($this->email)."'";
473
        $sql .= ", socialnetworks = '".$this->db->escape(json_encode($this->socialnetworks))."'";
474
		$sql .= ", photo='".$this->db->escape($this->photo)."'";
475
		$sql .= ", birthday=".($this->birthday ? "'".$this->db->idate($this->birthday)."'" : "null");
476
		$sql .= ", note_private = ".(isset($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null");
477
		$sql .= ", note_public = ".(isset($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null");
478
		$sql .= ", phone = ".(isset($this->phone_pro) ? "'".$this->db->escape($this->phone_pro)."'" : "null");
479
		$sql .= ", phone_perso = ".(isset($this->phone_perso) ? "'".$this->db->escape($this->phone_perso)."'" : "null");
480
		$sql .= ", phone_mobile = ".(isset($this->phone_mobile) ? "'".$this->db->escape($this->phone_mobile)."'" : "null");
481
		$sql .= ", priv = '".$this->db->escape($this->priv)."'";
482
		$sql .= ", fk_prospectcontactlevel = '".$this->db->escape($this->fk_prospectlevel)."'";
483
		if (isset($this->stcomm_id))
484
		{
485
			$sql .= ", fk_stcommcontact = ".($this->stcomm_id > 0 || $this->stcomm_id == -1 ? $this->stcomm_id : "0");
486
		}
487
		$sql .= ", statut = ".$this->db->escape($this->statut);
488
		$sql .= ", fk_user_modif=".($user->id > 0 ? "'".$this->db->escape($user->id)."'" : "NULL");
489
		$sql .= ", default_lang=".($this->default_lang ? "'".$this->db->escape($this->default_lang)."'" : "NULL");
490
		$sql .= ", entity = ".$this->db->escape($this->entity);
491
		$sql .= " WHERE rowid=".$this->db->escape($id);
492
493
		dol_syslog(get_class($this)."::update", LOG_DEBUG);
494
		$result = $this->db->query($sql);
495
		if ($result)
496
		{
497
		    unset($this->country_code);
498
		    unset($this->country);
499
		    unset($this->state_code);
500
		    unset($this->state);
501
502
		    $action = 'update';
503
504
		    // Actions on extra fields
505
		    if (!$error)
506
		    {
507
		    	$result = $this->insertExtraFields();
508
		    	if ($result < 0)
509
		    	{
510
		    		$error++;
511
		    	}
512
		    }
513
514
			if (!$error) {
515
				$result = $this->updateRoles();
516
				if ($result < 0)
517
				{
518
					$error++;
519
				}
520
			}
521
522
			if (!$error && $this->user_id > 0)
523
			{
524
				// If contact is linked to a user
525
				$tmpobj = new User($this->db);
526
				$tmpobj->fetch($this->user_id);
527
				$usermustbemodified = 0;
528
				if ($tmpobj->office_phone != $this->phone_pro)
529
				{
530
					$tmpobj->office_phone = $this->phone_pro;
531
					$usermustbemodified++;
532
				}
533
				if ($tmpobj->office_fax != $this->fax)
534
				{
535
					$tmpobj->office_fax = $this->fax;
536
					$usermustbemodified++;
537
				}
538
				if ($tmpobj->address != $this->address)
539
				{
540
					$tmpobj->address = $this->address;
541
					$usermustbemodified++;
542
				}
543
				if ($tmpobj->town != $this->town)
544
				{
545
					$tmpobj->town = $this->town;
546
					$usermustbemodified++;
547
				}
548
				if ($tmpobj->zip != $this->zip)
549
				{
550
					$tmpobj->zip = $this->zip;
551
					$usermustbemodified++;
552
				}
553
				if ($tmpobj->zip != $this->zip)
554
				{
555
					$tmpobj->state_id = $this->state_id;
556
					$usermustbemodified++;
557
				}
558
				if ($tmpobj->country_id != $this->country_id)
559
				{
560
					$tmpobj->country_id = $this->country_id;
561
					$usermustbemodified++;
562
				}
563
				if ($tmpobj->email != $this->email)
564
				{
565
					$tmpobj->email = $this->email;
566
					$usermustbemodified++;
567
				}
568
				if (!empty(array_diff($tmpobj->socialnetworks, $this->socialnetworks)))
569
				{
570
					$tmpobj->socialnetworks = $this->socialnetworks;
571
					$usermustbemodified++;
572
				}
573
				// if ($tmpobj->skype != $this->skype)
574
				// {
575
				// 	$tmpobj->skype = $this->skype;
576
				// 	$usermustbemodified++;
577
				// }
578
				// if ($tmpobj->twitter != $this->twitter)
579
				// {
580
				// 	$tmpobj->twitter = $this->twitter;
581
				// 	$usermustbemodified++;
582
				// }
583
				// if ($tmpobj->facebook != $this->facebook)
584
				// {
585
				// 	$tmpobj->facebook = $this->facebook;
586
				// 	$usermustbemodified++;
587
				// }
588
				// if ($tmpobj->linkedin != $this->linkedin)
589
				// {
590
				//     $tmpobj->linkedin = $this->linkedin;
591
				//     $usermustbemodified++;
592
				// }
593
				if ($usermustbemodified)
594
				{
595
					$result = $tmpobj->update($user, 0, 1, 1, 1);
596
					if ($result < 0) { $error++; }
597
				}
598
			}
599
600
			if (!$error && !$notrigger)
601
			{
602
				// Call trigger
603
				$result = $this->call_trigger('CONTACT_MODIFY', $user);
604
				if ($result < 0) { $error++; }
605
				// End call triggers
606
			}
607
608
			if (!$error)
609
			{
610
				$this->db->commit();
611
				return 1;
612
			} else {
613
				dol_syslog(get_class($this)."::update Error ".$this->error, LOG_ERR);
614
				$this->db->rollback();
615
				return -$error;
616
			}
617
		} else {
618
			$this->error = $this->db->lasterror().' sql='.$sql;
619
            $this->db->rollback();
620
			return -1;
621
		}
622
	}
623
624
625
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
626
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
627
	/**
628
	 *	Retourne chaine DN complete dans l'annuaire LDAP pour l'objet
629
	 *
630
	 *	@param		array	$info		Info string loaded by _load_ldap_info
631
	 *	@param		int		$mode		0=Return full DN (uid=qqq,ou=xxx,dc=aaa,dc=bbb)
632
	 *									1=Return DN without key inside (ou=xxx,dc=aaa,dc=bbb)
633
	 *									2=Return key only (uid=qqq)
634
	 *	@return		string				DN
635
	 */
636
	public function _load_ldap_dn($info, $mode = 0)
637
	{
638
        // phpcs:enable
639
		global $conf;
640
		$dn = '';
641
		if ($mode == 0) $dn = $conf->global->LDAP_KEY_CONTACTS."=".$info[$conf->global->LDAP_KEY_CONTACTS].",".$conf->global->LDAP_CONTACT_DN;
642
		elseif ($mode == 1) $dn = $conf->global->LDAP_CONTACT_DN;
643
		elseif ($mode == 2) $dn = $conf->global->LDAP_KEY_CONTACTS."=".$info[$conf->global->LDAP_KEY_CONTACTS];
644
		return $dn;
645
	}
646
647
648
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
649
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
650
	/**
651
	 *	Initialise tableau info (tableau des attributs LDAP)
652
	 *
653
	 *	@return		array		Tableau info des attributs
654
	 */
655
	public function _load_ldap_info()
656
	{
657
        // phpcs:enable
658
		global $conf, $langs;
659
660
        $info = array();
661
662
        // Object classes
663
		$info["objectclass"] = explode(',', $conf->global->LDAP_CONTACT_OBJECT_CLASS);
664
665
		$this->fullname = $this->getFullName($langs);
666
667
		// Fields
668
		if ($this->fullname && !empty($conf->global->LDAP_CONTACT_FIELD_FULLNAME)) $info[$conf->global->LDAP_CONTACT_FIELD_FULLNAME] = $this->fullname;
669
		if ($this->lastname && !empty($conf->global->LDAP_CONTACT_FIELD_NAME)) $info[$conf->global->LDAP_CONTACT_FIELD_NAME] = $this->lastname;
670
		if ($this->firstname && !empty($conf->global->LDAP_CONTACT_FIELD_FIRSTNAME)) $info[$conf->global->LDAP_CONTACT_FIELD_FIRSTNAME] = $this->firstname;
671
672
		if ($this->poste) $info["title"] = $this->poste;
673
		if ($this->socid > 0)
674
		{
675
			$soc = new Societe($this->db);
676
			$soc->fetch($this->socid);
677
678
			$info[$conf->global->LDAP_CONTACT_FIELD_COMPANY] = $soc->name;
679
			if ($soc->client == 1)      $info["businessCategory"] = "Customers";
680
			if ($soc->client == 2)      $info["businessCategory"] = "Prospects";
681
			if ($soc->fournisseur == 1) $info["businessCategory"] = "Suppliers";
682
		}
683
		if ($this->address && !empty($conf->global->LDAP_CONTACT_FIELD_ADDRESS)) $info[$conf->global->LDAP_CONTACT_FIELD_ADDRESS] = $this->address;
684
		if ($this->zip && !empty($conf->global->LDAP_CONTACT_FIELD_ZIP))          $info[$conf->global->LDAP_CONTACT_FIELD_ZIP] = $this->zip;
685
		if ($this->town && !empty($conf->global->LDAP_CONTACT_FIELD_TOWN))      $info[$conf->global->LDAP_CONTACT_FIELD_TOWN] = $this->town;
686
		if ($this->country_code && !empty($conf->global->LDAP_CONTACT_FIELD_COUNTRY))      $info[$conf->global->LDAP_CONTACT_FIELD_COUNTRY] = $this->country_code;
687
		if ($this->phone_pro && !empty($conf->global->LDAP_CONTACT_FIELD_PHONE)) $info[$conf->global->LDAP_CONTACT_FIELD_PHONE] = $this->phone_pro;
688
		if ($this->phone_perso && !empty($conf->global->LDAP_CONTACT_FIELD_HOMEPHONE)) $info[$conf->global->LDAP_CONTACT_FIELD_HOMEPHONE] = $this->phone_perso;
689
		if ($this->phone_mobile && !empty($conf->global->LDAP_CONTACT_FIELD_MOBILE)) $info[$conf->global->LDAP_CONTACT_FIELD_MOBILE] = $this->phone_mobile;
690
		if ($this->fax && !empty($conf->global->LDAP_CONTACT_FIELD_FAX))	    $info[$conf->global->LDAP_CONTACT_FIELD_FAX] = $this->fax;
691
        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

691
        if ($this->skype && !empty($conf->global->LDAP_CONTACT_FIELD_SKYPE))	    $info[$conf->global->LDAP_CONTACT_FIELD_SKYPE] = /** @scrutinizer ignore-deprecated */ $this->skype;
Loading history...
692
        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);
693
		if ($this->email && !empty($conf->global->LDAP_CONTACT_FIELD_MAIL))     $info[$conf->global->LDAP_CONTACT_FIELD_MAIL] = $this->email;
694
695
		if ($conf->global->LDAP_SERVER_TYPE == 'egroupware')
696
		{
697
			$info["objectclass"][4] = "phpgwContact"; // compatibilite egroupware
698
699
			$info['uidnumber'] = $this->id;
700
701
			$info['phpgwTz'] = 0;
702
			$info['phpgwMailType'] = 'INTERNET';
703
			$info['phpgwMailHomeType'] = 'INTERNET';
704
705
			$info["phpgwContactTypeId"] = 'n';
706
			$info["phpgwContactCatId"] = 0;
707
			$info["phpgwContactAccess"] = "public";
708
709
			if (dol_strlen($this->egroupware_id) == 0)
710
			{
711
				$this->egroupware_id = 1;
712
			}
713
714
			$info["phpgwContactOwner"] = $this->egroupware_id;
715
716
			if ($this->email) $info["rfc822Mailbox"] = $this->email;
717
			if ($this->phone_mobile) $info["phpgwCellTelephoneNumber"] = $this->phone_mobile;
718
		}
719
720
		return $info;
721
	}
722
723
724
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
725
	/**
726
	 *  Update field alert birthday
727
	 *
728
	 *  @param      int			$id         Id of contact
729
	 *  @param      User		$user		User asking to change alert or birthday
730
	 *  @param      int		    $notrigger	0=no, 1=yes
731
     *  @return     int         			<0 if KO, >=0 if OK
732
	 */
733
	public function update_perso($id, $user = null, $notrigger = 0)
734
	{
735
        // phpcs:enable
736
	    $error = 0;
737
	    $result = false;
738
739
	    $this->db->begin();
740
741
		// Mis a jour contact
742
		$sql = "UPDATE ".MAIN_DB_PREFIX."socpeople SET";
743
		$sql .= " birthday=".($this->birthday ? "'".$this->db->idate($this->birthday)."'" : "null");
744
		$sql .= ", photo = ".($this->photo ? "'".$this->db->escape($this->photo)."'" : "null");
745
		if ($user) $sql .= ", fk_user_modif=".$user->id;
746
		$sql .= " WHERE rowid=".$this->db->escape($id);
747
748
		dol_syslog(get_class($this)."::update_perso this->birthday=".$this->birthday." -", LOG_DEBUG);
749
		$resql = $this->db->query($sql);
750
		if (!$resql)
751
		{
752
			$error++;
753
			$this->error = $this->db->lasterror();
754
		}
755
756
		// Mis a jour alerte birthday
757
		if ($this->birthday_alert)
758
		{
759
			//check existing
760
			$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;
761
			$result_check = $this->db->query($sql_check);
762
			if (!$result_check || ($this->db->num_rows($result_check) < 1))
763
			{
764
				//insert
765
				$sql = "INSERT INTO ".MAIN_DB_PREFIX."user_alert(type,fk_contact,fk_user) ";
766
				$sql .= "VALUES (1,".$this->db->escape($id).",".$user->id.")";
767
				$result = $this->db->query($sql);
768
				if (!$result)
769
				{
770
                    $error++;
771
                    $this->error = $this->db->lasterror();
772
				}
773
			} else {
774
				$result = true;
775
			}
776
		} else {
777
			$sql = "DELETE FROM ".MAIN_DB_PREFIX."user_alert ";
778
			$sql .= "WHERE type=1 AND fk_contact=".$this->db->escape($id)." AND fk_user=".$user->id;
779
			$result = $this->db->query($sql);
780
			if (!$result)
781
			{
782
                $error++;
783
                $this->error = $this->db->lasterror();
784
			}
785
		}
786
787
		if (!$error && !$notrigger)
788
		{
789
		    // Call trigger
790
		    $result = $this->call_trigger('CONTACT_MODIFY', $user);
791
		    if ($result < 0) { $error++; }
792
		    // End call triggers
793
		}
794
795
		if (!$error)
796
		{
797
		    $this->db->commit();
798
		    return 1;
799
		} else {
800
		    dol_syslog(get_class($this)."::update Error ".$this->error, LOG_ERR);
801
		    $this->db->rollback();
802
		    return -$error;
803
		}
804
	}
805
806
807
	/**
808
	 *  Load object contact.
809
	 *
810
	 *  @param      int		$id         	Id of contact
811
	 *  @param      User	$user       	Load also alerts of this user (subscribing to alerts) that want alerts about this contact
812
     *  @param      string  $ref_ext    	External reference, not given by Dolibarr
813
     *  @param		string	$email			Email
814
     *  @param		int		$loadalsoroles	Load also roles
815
	 *  @return     int     		    	>0 if OK, <0 if KO or if two records found for same ref or idprof, 0 if not found.
816
	 */
817
	public function fetch($id, $user = null, $ref_ext = '', $email = '', $loadalsoroles = 0)
818
	{
819
		global $langs;
820
821
		dol_syslog(get_class($this)."::fetch id=".$id." ref_ext=".$ref_ext." email=".$email, LOG_DEBUG);
822
823
		if (empty($id) && empty($ref_ext) && empty($email))
824
		{
825
			$this->error = 'BadParameter';
826
			return -1;
827
		}
828
829
		$langs->loadLangs(array("dict", "companies"));
830
831
		$sql = "SELECT c.rowid, c.entity, c.fk_soc, c.ref_ext, c.civility as civility_code, c.lastname, c.firstname,";
832
		$sql .= " c.address, c.statut, c.zip, c.town,";
833
		$sql .= " c.fk_pays as country_id,";
834
		$sql .= " c.fk_departement as state_id,";
835
		$sql .= " c.birthday,";
836
		$sql .= " c.poste, c.phone, c.phone_perso, c.phone_mobile, c.fax, c.email,";
837
		$sql .= " c.socialnetworks,";
838
        $sql .= " c.photo,";
839
		$sql .= " c.priv, c.note_private, c.note_public, c.default_lang, c.canvas,";
840
		$sql.= " c.fk_prospectcontactlevel, c.fk_stcommcontact, st.libelle as stcomm, st.picto as stcomm_picto,";
841
		$sql .= " c.import_key,";
842
		$sql .= " c.datec as date_creation, c.tms as date_modification,";
843
		$sql .= " co.label as country, co.code as country_code,";
844
		$sql .= " d.nom as state, d.code_departement as state_code,";
845
		$sql .= " u.rowid as user_id, u.login as user_login,";
846
		$sql .= " s.nom as socname, s.address as socaddress, s.zip as soccp, s.town as soccity, s.default_lang as socdefault_lang";
847
		$sql .= " FROM ".MAIN_DB_PREFIX."socpeople as c";
848
		$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_country as co ON c.fk_pays = co.rowid";
849
		$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_departements as d ON c.fk_departement = d.rowid";
850
		$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as u ON c.rowid = u.fk_socpeople";
851
		$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON c.fk_soc = s.rowid";
852
		$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_stcommcontact as st ON c.fk_stcommcontact = st.id';
853
		if ($id) $sql .= " WHERE c.rowid = ".$id;
854
		else {
855
			$sql .= " WHERE c.entity IN (".getEntity($this->element).")";
856
			if ($ref_ext) {
857
				$sql .= " AND c.ref_ext = '".$this->db->escape($ref_ext)."'";
858
			}
859
			if ($email) {
860
				$sql .= " AND c.email = '".$this->db->escape($email)."'";
861
			}
862
		}
863
864
		$resql = $this->db->query($sql);
865
		if ($resql)
866
		{
867
			$num = $this->db->num_rows($resql);
868
			if ($num > 1)
869
			{
870
				$this->error = 'Fetch found several records. Rename one of contact to avoid duplicate.';
871
				dol_syslog($this->error, LOG_ERR);
872
873
				return 2;
874
			} elseif ($num)   // $num = 1
875
			{
876
				$obj = $this->db->fetch_object($resql);
877
878
				$this->id = $obj->rowid;
879
				$this->entity = $obj->entity;
880
				$this->ref = $obj->rowid;
881
				$this->ref_ext = $obj->ref_ext;
882
883
				$this->civility_code    = $obj->civility_code;
884
				$this->civility	        = $obj->civility_code ? ($langs->trans("Civility".$obj->civility_code) != ("Civility".$obj->civility_code) ? $langs->trans("Civility".$obj->civility_code) : $obj->civility_code) : '';
885
886
                $this->lastname = $obj->lastname;
887
				$this->firstname = $obj->firstname;
888
				$this->address = $obj->address;
889
				$this->zip = $obj->zip;
890
				$this->town = $obj->town;
891
892
				$this->date_creation     = $this->db->jdate($obj->date_creation);
893
				$this->date_modification = $this->db->jdate($obj->date_modification);
894
895
				$this->state_id = $obj->state_id;
896
				$this->state_code = $obj->state_code;
897
				$this->state = $obj->state;
898
899
				$this->country_id = $obj->country_id;
900
				$this->country_code = $obj->country_id ? $obj->country_code : '';
901
				$this->country			= $obj->country_id ? ($langs->trans('Country'.$obj->country_code) != 'Country'.$obj->country_code ? $langs->transnoentities('Country'.$obj->country_code) : $obj->country) : '';
902
903
				$this->socid			= $obj->fk_soc;
904
				$this->socname			= $obj->socname;
905
				$this->poste			= $obj->poste;
906
				$this->statut = $obj->statut;
907
908
				$this->fk_prospectlevel = $obj->fk_prospectcontactlevel;
909
910
				$transcode=$langs->trans('StatusProspect'.$obj->fk_stcommcontact);
911
				$libelle=($transcode!='StatusProspect'.$obj->fk_stcommcontact?$transcode:$obj->stcomm);
912
				$this->stcomm_id = $obj->fk_stcommcontact;  // id statut commercial
913
				$this->statut_commercial = $libelle;    	// libelle statut commercial
914
				$this->stcomm_picto = $obj->stcomm_picto; 	// Picto statut commercial
915
916
				$this->phone_pro = trim($obj->phone);
917
				$this->fax = trim($obj->fax);
918
				$this->phone_perso = trim($obj->phone_perso);
919
				$this->phone_mobile = trim($obj->phone_mobile);
920
921
				$this->email			= $obj->email;
922
				$this->socialnetworks = (array) json_decode($obj->socialnetworks, true);
923
				$this->photo			= $obj->photo;
924
				$this->priv				= $obj->priv;
925
				$this->mail				= $obj->email;
926
927
				$this->birthday = $this->db->jdate($obj->birthday);
928
				$this->note				= $obj->note_private; // deprecated
929
				$this->note_private		= $obj->note_private;
930
				$this->note_public = $obj->note_public;
931
				$this->default_lang		= $obj->default_lang;
932
				$this->user_id = $obj->user_id;
933
				$this->user_login		= $obj->user_login;
934
				$this->canvas = $obj->canvas;
935
936
				$this->import_key		= $obj->import_key;
937
938
				// Define gender according to civility
939
				$this->setGenderFromCivility();
940
941
				// Search Dolibarr user linked to this contact
942
				$sql = "SELECT u.rowid ";
943
				$sql .= " FROM ".MAIN_DB_PREFIX."user as u";
944
				$sql .= " WHERE u.fk_socpeople = ".$this->id;
945
946
				$resql = $this->db->query($sql);
947
				if ($resql)
948
				{
949
					if ($this->db->num_rows($resql))
950
					{
951
						$uobj = $this->db->fetch_object($resql);
952
953
						$this->user_id = $uobj->rowid;
954
					}
955
					$this->db->free($resql);
956
				} else {
957
					$this->error = $this->db->error();
958
					return -1;
959
				}
960
961
				// Retreive all extrafield
962
				// fetch optionals attributes and labels
963
				$this->fetch_optionals();
964
965
				// Load also alerts of this user
966
				if ($user)
967
				{
968
					$sql = "SELECT fk_user";
969
					$sql .= " FROM ".MAIN_DB_PREFIX."user_alert";
970
					$sql .= " WHERE fk_user = ".$user->id." AND fk_contact = ".$this->db->escape($id);
971
972
					$resql = $this->db->query($sql);
973
					if ($resql)
974
					{
975
						if ($this->db->num_rows($resql))
976
						{
977
							$obj = $this->db->fetch_object($resql);
978
979
							$this->birthday_alert = 1;
980
						}
981
						$this->db->free($resql);
982
					} else {
983
						$this->error = $this->db->error();
984
						return -1;
985
					}
986
				}
987
988
				// Load also roles of this address
989
				if ($loadalsoroles) {
990
					$resultRole = $this->fetchRoles();
991
					if ($resultRole < 0) {
992
						return $resultRole;
993
					}
994
				}
995
996
				return 1;
997
			} else {
998
				$this->error = $langs->trans("RecordNotFound");
999
				return 0;
1000
			}
1001
		} else {
1002
			$this->error = $this->db->error();
1003
			return -1;
1004
		}
1005
	}
1006
1007
1008
1009
	/**
1010
	 * Set the property "gender" of this class, based on the property "civility_id"
1011
	 * or use property "civility_code" as fallback, when "civility_id" is not available.
1012
	 *
1013
	 * @return void
1014
	 */
1015
	public function setGenderFromCivility()
1016
	{
1017
		unset($this->gender);
1018
1019
		if (in_array($this->civility_id, array('MR')) || in_array($this->civility_code, array('MR')))
1020
		{
1021
			$this->gender = 'man';
1022
		} elseif (in_array($this->civility_id, array('MME', 'MLE')) || in_array($this->civility_code, array('MME', 'MLE')))
1023
		{
1024
			$this->gender = 'woman';
1025
		}
1026
	}
1027
1028
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1029
	/**
1030
	 *  Load number of elements the contact is used as a link for
1031
	 *  ref_facturation
1032
	 *  ref_contrat
1033
	 *  ref_commande (for order and/or shipments)
1034
	 *  ref_propale
1035
	 *
1036
     *  @return     int             					<0 if KO, >=0 if OK
1037
	 */
1038
	public function load_ref_elements()
1039
	{
1040
        // phpcs:enable
1041
		// Compte les elements pour lesquels il est contact
1042
		$sql = "SELECT tc.element, count(ec.rowid) as nb";
1043
		$sql .= " FROM ".MAIN_DB_PREFIX."element_contact as ec, ".MAIN_DB_PREFIX."c_type_contact as tc";
1044
		$sql .= " WHERE ec.fk_c_type_contact = tc.rowid";
1045
		$sql .= " AND fk_socpeople = ".$this->id;
1046
		$sql .= " AND tc.source = 'external'";
1047
		$sql .= " GROUP BY tc.element";
1048
1049
		dol_syslog(get_class($this)."::load_ref_elements", LOG_DEBUG);
1050
1051
		$resql = $this->db->query($sql);
1052
		if ($resql)
1053
		{
1054
			while ($obj = $this->db->fetch_object($resql))
1055
			{
1056
				if ($obj->nb)
1057
				{
1058
					if ($obj->element == 'facture')  $this->ref_facturation = $obj->nb;
1059
					elseif ($obj->element == 'contrat')  $this->ref_contrat = $obj->nb;
1060
					elseif ($obj->element == 'commande') $this->ref_commande = $obj->nb;
1061
					elseif ($obj->element == 'propal')   $this->ref_propal = $obj->nb;
1062
				}
1063
			}
1064
			$this->db->free($resql);
1065
			return 0;
1066
		} else {
1067
			$this->error = $this->db->lasterror();
1068
			return -1;
1069
		}
1070
	}
1071
1072
	/**
1073
	 *   	Efface le contact de la base
1074
	 *
1075
	 *   	@param		int		$notrigger		Disable all trigger
1076
	 *		@return		int						<0 if KO, >0 if OK
1077
	 */
1078
	public function delete($notrigger = 0)
1079
	{
1080
		global $conf, $langs, $user;
1081
1082
		$error = 0;
1083
1084
		$this->db->begin();
1085
1086
		if (!$error)
1087
		{
1088
			// Get all rowid of element_contact linked to a type that is link to llx_socpeople
1089
			$sql = "SELECT ec.rowid";
1090
			$sql .= " FROM ".MAIN_DB_PREFIX."element_contact ec,";
1091
			$sql .= " ".MAIN_DB_PREFIX."c_type_contact tc";
1092
			$sql .= " WHERE ec.fk_socpeople=".$this->id;
1093
			$sql .= " AND ec.fk_c_type_contact=tc.rowid";
1094
			$sql .= " AND tc.source='external'";
1095
			dol_syslog(__METHOD__, LOG_DEBUG);
1096
			$resql = $this->db->query($sql);
1097
			if ($resql)
1098
			{
1099
				$num = $this->db->num_rows($resql);
1100
1101
				$i = 0;
1102
				while ($i < $num && !$error)
1103
				{
1104
					$obj = $this->db->fetch_object($resql);
1105
1106
					$sqldel = "DELETE FROM ".MAIN_DB_PREFIX."element_contact";
1107
					$sqldel .= " WHERE rowid = ".$obj->rowid;
1108
					dol_syslog(__METHOD__, LOG_DEBUG);
1109
					$result = $this->db->query($sqldel);
1110
					if (!$result)
1111
					{
1112
						$error++;
1113
						$this->error = $this->db->error().' sql='.$sqldel;
1114
					}
1115
1116
					$i++;
1117
				}
1118
			} else {
1119
				$error++;
1120
				$this->error = $this->db->error().' sql='.$sql;
1121
			}
1122
		}
1123
1124
		if (!$error)
1125
		{
1126
			// Remove Roles
1127
			$sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_contacts WHERE fk_socpeople = ".$this->id;
1128
			dol_syslog(__METHOD__, LOG_DEBUG);
1129
			$resql = $this->db->query($sql);
1130
			if (!$resql)
1131
			{
1132
				$error++;
1133
				$this->error .= $this->db->lasterror();
1134
				$errorflag = -1;
1135
			}
1136
		}
1137
1138
		if (!$error)
1139
		{
1140
			// Remove category
1141
			$sql = "DELETE FROM ".MAIN_DB_PREFIX."categorie_contact WHERE fk_socpeople = ".$this->id;
1142
			dol_syslog(__METHOD__, LOG_DEBUG);
1143
			$resql = $this->db->query($sql);
1144
			if (!$resql)
1145
			{
1146
				$error++;
1147
				$this->error .= $this->db->lasterror();
1148
				$errorflag = -1;
1149
			}
1150
		}
1151
1152
		if (!$error)
1153
		{
1154
			$sql = "DELETE FROM ".MAIN_DB_PREFIX."socpeople";
1155
			$sql .= " WHERE rowid=".$this->id;
1156
			dol_syslog(__METHOD__, LOG_DEBUG);
1157
			$result = $this->db->query($sql);
1158
			if (!$result)
1159
			{
1160
				$error++;
1161
				$this->error = $this->db->error().' sql='.$sql;
1162
			}
1163
		}
1164
1165
		// Removed extrafields
1166
        if (!$error) {
1167
            // For avoid conflicts if trigger used
1168
			$result = $this->deleteExtraFields();
1169
			if ($result < 0) $error++;
1170
		}
1171
1172
		if (!$error && !$notrigger)
1173
		{
1174
            // Call trigger
1175
            $result = $this->call_trigger('CONTACT_DELETE', $user);
1176
            if ($result < 0) { $error++; }
1177
            // End call triggers
1178
		}
1179
1180
		if (!$error)
1181
		{
1182
			$this->db->commit();
1183
			return 1;
1184
		} else {
1185
			$this->db->rollback();
1186
			dol_syslog("Error ".$this->error, LOG_ERR);
1187
			return -1;
1188
		}
1189
	}
1190
1191
1192
	/**
1193
	 *  Charge les informations sur le contact, depuis la base
1194
	 *
1195
	 *  @param		int		$id      Id du contact a charger
1196
	 *  @return		void
1197
	 */
1198
	public function info($id)
1199
	{
1200
		$sql = "SELECT c.rowid, c.datec as datec, c.fk_user_creat,";
1201
		$sql .= " c.tms as tms, c.fk_user_modif";
1202
		$sql .= " FROM ".MAIN_DB_PREFIX."socpeople as c";
1203
		$sql .= " WHERE c.rowid = ".$this->db->escape($id);
1204
1205
		$resql = $this->db->query($sql);
1206
		if ($resql)
1207
		{
1208
			if ($this->db->num_rows($resql))
1209
			{
1210
				$obj = $this->db->fetch_object($resql);
1211
1212
				$this->id = $obj->rowid;
1213
1214
				if ($obj->fk_user_creat) {
1215
					$cuser = new User($this->db);
1216
					$cuser->fetch($obj->fk_user_creat);
1217
					$this->user_creation = $cuser;
1218
				}
1219
1220
				if ($obj->fk_user_modif) {
1221
					$muser = new User($this->db);
1222
					$muser->fetch($obj->fk_user_modif);
1223
					$this->user_modification = $muser;
1224
				}
1225
1226
				$this->date_creation     = $this->db->jdate($obj->datec);
1227
				$this->date_modification = $this->db->jdate($obj->tms);
1228
			}
1229
1230
			$this->db->free($resql);
1231
		} else {
1232
			print $this->db->error();
1233
		}
1234
	}
1235
1236
	/**
1237
	 *  Return number of mass Emailing received by this contacts with its email
1238
	 *
1239
	 *  @return       int     Number of EMailings
1240
	 */
1241
	public function getNbOfEMailings()
1242
	{
1243
		$sql = "SELECT count(mc.email) as nb";
1244
		$sql .= " FROM ".MAIN_DB_PREFIX."mailing_cibles as mc, ".MAIN_DB_PREFIX."mailing as m";
1245
		$sql .= " WHERE mc.fk_mailing=m.rowid AND mc.email = '".$this->db->escape($this->email)."' ";
1246
		$sql .= " AND m.entity IN (".getEntity($this->element).") AND mc.statut NOT IN (-1,0)"; // -1 error, 0 not sent, 1 sent with success
1247
1248
		$resql = $this->db->query($sql);
1249
		if ($resql)
1250
		{
1251
			$obj = $this->db->fetch_object($resql);
1252
			$nb = $obj->nb;
1253
1254
			$this->db->free($resql);
1255
			return $nb;
1256
		} else {
1257
			$this->error = $this->db->error();
1258
			return -1;
1259
		}
1260
	}
1261
1262
	/**
1263
	 *  Return name of contact with link (and eventually picto)
1264
	 *	Use $this->id, $this->lastname, $this->firstname, this->civility_id
1265
	 *
1266
	 *	@param		int			$withpicto					Include picto with link
1267
	 *	@param		string		$option						Where the link point to
1268
	 *	@param		int			$maxlen						Max length of
1269
	 *  @param		string		$moreparam					Add more param into URL
1270
     *  @param      int     	$save_lastsearch_value		-1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
1271
	 *	@param		int			$notooltip					1=Disable tooltip
1272
	 *	@return		string									String with URL
1273
	 */
1274
	public function getNomUrl($withpicto = 0, $option = '', $maxlen = 0, $moreparam = '', $save_lastsearch_value = -1, $notooltip = 0)
1275
	{
1276
		global $conf, $langs, $hookmanager;
1277
1278
		$result = ''; $label = '';
1279
1280
		if (!empty($this->photo) && class_exists('Form'))
1281
		{
1282
			$label .= '<div class="photointooltip">';
1283
			$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.
1284
			$label .= '</div><div style="clear: both;"></div>';
1285
		}
1286
1287
        $label .= '<u>'.$langs->trans("Contact").'</u>';
1288
        $label .= '<br><b>'.$langs->trans("Name").':</b> '.$this->getFullName($langs);
1289
        //if ($this->civility_id) $label.= '<br><b>' . $langs->trans("Civility") . ':</b> '.$this->civility_id;		// TODO Translate cibilty_id code
1290
        if (!empty($this->poste)) $label .= '<br><b>'.$langs->trans("Poste").':</b> '.$this->poste;
1291
        $label .= '<br><b>'.$langs->trans("EMail").':</b> '.$this->email;
1292
        $phonelist = array();
1293
        if ($this->phone_pro) $phonelist[] = dol_print_phone($this->phone_pro, $this->country_code, $this->id, 0, '', '&nbsp;', 'phone');
1294
        if ($this->phone_mobile) $phonelist[] = dol_print_phone($this->phone_mobile, $this->country_code, $this->id, 0, '', '&nbsp;', 'mobile');
1295
        if ($this->phone_perso) $phonelist[] = dol_print_phone($this->phone_perso, $this->country_code, $this->id, 0, '', '&nbsp;', 'phone');
1296
        $label .= '<br><b>'.$langs->trans("Phone").':</b> '.implode('&nbsp;', $phonelist);
1297
        $label .= '<br><b>'.$langs->trans("Address").':</b> '.dol_format_address($this, 1, ' ', $langs);
1298
1299
        $url = DOL_URL_ROOT.'/contact/card.php?id='.$this->id;
1300
1301
        if ($option !== 'nolink')
1302
        {
1303
        	// Add param to save lastsearch_values or not
1304
        	$add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
1305
        	if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) $add_save_lastsearch_values = 1;
1306
        	if ($add_save_lastsearch_values) $url .= '&save_lastsearch_values=1';
1307
        }
1308
1309
        $url .= $moreparam;
1310
1311
        $linkclose = "";
1312
		if (empty($notooltip)) {
1313
	    	if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
1314
    	    {
1315
        	    $label = $langs->trans("ShowContact");
1316
            	$linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
1317
        	}
1318
	       	$linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
1319
    	   	$linkclose .= ' class="classfortooltip"';
1320
1321
    	   	/*
1322
    	   	 $hookmanager->initHooks(array('contactdao'));
1323
    	   	 $parameters=array('id'=>$this->id);
1324
    	   	 $reshook=$hookmanager->executeHooks('getnomurltooltip',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
1325
    	   	 if ($reshook > 0) $linkclose = $hookmanager->resPrint;
1326
    	   	 */
1327
		}
1328
1329
		$linkstart = '<a href="'.$url.'"';
1330
		$linkstart .= $linkclose.'>';
1331
		$linkend = '</a>';
1332
1333
		if ($option == 'xxx')
1334
		{
1335
			$linkstart = '<a href="'.DOL_URL_ROOT.'/contact/card.php?id='.$this->id.$moreparam.'" title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip">';
1336
			$linkend = '</a>';
1337
		}
1338
1339
		$result .= $linkstart;
1340
		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);
1341
		if ($withpicto != 2) $result .= ($maxlen ?dol_trunc($this->getFullName($langs), $maxlen) : $this->getFullName($langs));
1342
		$result .= $linkend;
1343
1344
		global $action;
1345
		$hookmanager->initHooks(array('contactdao'));
1346
		$parameters = array('id'=>$this->id, 'getnomurl'=>$result);
1347
		$reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1348
		if ($reshook > 0) $result = $hookmanager->resPrint;
1349
		else $result .= $hookmanager->resPrint;
1350
1351
		return $result;
1352
	}
1353
1354
	/**
1355
	 *    Return civility label of contact
1356
	 *
1357
	 *    @return	string      			Translated name of civility
1358
	 */
1359
	public function getCivilityLabel()
1360
	{
1361
		global $langs;
1362
1363
		$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...
1364
		if (empty($code)) return '';
1365
1366
		$langs->load("dict");
1367
		return $langs->getLabelFromKey($this->db, "Civility".$code, "c_civility", "code", "label", $code);
1368
	}
1369
1370
	/**
1371
	 *	Return label of contact status
1372
	 *
1373
	 *	@param      int			$mode       0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto
1374
	 * 	@return 	string					Label of contact status
1375
	 */
1376
	public function getLibStatut($mode)
1377
	{
1378
		return $this->LibStatut($this->statut, $mode);
1379
	}
1380
1381
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1382
	/**
1383
	 *	Renvoi le libelle d'un statut donne
1384
	 *
1385
	 *  @param      int			$status     Id statut
1386
	 *  @param      int			$mode       0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto
1387
	 *  @return     string					Libelle
1388
	 */
1389
	public function LibStatut($status, $mode)
1390
	{
1391
        // phpcs:enable
1392
		global $langs;
1393
1394
		$labelStatus = array(
1395
			0 => 'ActivityCeased',
1396
			1 => 'InActivity',
1397
			4 => 'InActivity',
1398
			5 => 'ActivityCeased',
1399
		);
1400
		$labelStatusShort = array(
1401
			0 => 'ActivityCeased',
1402
			1 => 'InActivity',
1403
			4 => 'InActivity',
1404
			5 => 'ActivityCeased',
1405
		);
1406
1407
		$statusType = 'status4';
1408
		if ($status == 0 || $status == 5) $statusType = 'status5';
1409
1410
		$label = $langs->trans($labelStatus[$status]);
1411
		$labelshort = $langs->trans($labelStatusShort[$status]);
1412
1413
		return dolGetStatus($label, $labelshort, '', $statusType, $mode);
1414
	}
1415
1416
1417
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1418
	/**
1419
	 *	Return translated label of Public or Private
1420
	 *
1421
	 * 	@param      int			$status		Type (0 = public, 1 = private)
1422
	 *  @return     string					Label translated
1423
	 */
1424
	public function LibPubPriv($status)
1425
	{
1426
        // phpcs:enable
1427
		global $langs;
1428
		if ($status == '1') return $langs->trans('ContactPrivate');
1429
		else return $langs->trans('ContactPublic');
1430
	}
1431
1432
1433
	/**
1434
     *  Initialise an instance with random values.
1435
     *  Used to build previews or test instances.
1436
     *	id must be 0 if object instance is a specimen.
1437
     *
1438
     *  @return	int >0 if ok
1439
	 */
1440
	public function initAsSpecimen()
1441
	{
1442
		// Get first id of existing company and save it into $socid
1443
		$socid = 0;
1444
		$sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe ORDER BY rowid LIMIT 1";
1445
		$resql = $this->db->query($sql);
1446
		if ($resql) {
1447
			$obj = $this->db->fetch_object($resql);
1448
			if ($obj) $socid = $obj->rowid;
1449
		}
1450
1451
		// Initialise parameters
1452
		$this->id = 0;
1453
		$this->specimen = 1;
1454
		$this->lastname = 'DOLIBARR';
1455
		$this->firstname = 'SPECIMEN';
1456
		$this->address = '21 jump street';
1457
		$this->zip = '99999';
1458
		$this->town = 'MyTown';
1459
		$this->country_id = 1;
1460
		$this->country_code = 'FR';
1461
		$this->country = 'France';
1462
		$this->email = '[email protected]';
1463
		$this->skype = 'tom.hanson';
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

1463
		/** @scrutinizer ignore-deprecated */ $this->skype = 'tom.hanson';
Loading history...
1464
		$this->socialnetworks = array(
1465
			'skype' => 'tom.hanson',
1466
		);
1467
		$this->phone_pro = '0909090901';
1468
		$this->phone_perso = '0909090902';
1469
		$this->phone_mobile = '0909090903';
1470
		$this->fax = '0909090909';
1471
1472
		$this->note_public = 'This is a comment (public)';
1473
		$this->note_private = 'This is a comment (private)';
1474
1475
		$this->socid = $socid;
1476
		$this->statut = 1;
1477
		return 1;
1478
	}
1479
1480
	/**
1481
	 *  Change status of a user
1482
	 *
1483
	 *	@param	int		$status		Status to set
1484
	 *  @return int     			<0 if KO, 0 if nothing is done, >0 if OK
1485
	 */
1486
	public function setstatus($status)
1487
	{
1488
		global $conf, $langs, $user;
1489
1490
		$error = 0;
1491
1492
		// Check parameters
1493
		if ($this->statut == $status) return 0;
1494
		else $this->statut = $status;
1495
1496
		$this->db->begin();
1497
1498
		// Desactive utilisateur
1499
		$sql = "UPDATE ".MAIN_DB_PREFIX."socpeople";
1500
		$sql .= " SET statut = ".$this->statut;
1501
		$sql .= " WHERE rowid = ".$this->id;
1502
		$result = $this->db->query($sql);
1503
1504
		dol_syslog(get_class($this)."::setstatus", LOG_DEBUG);
1505
		if ($result)
1506
		{
1507
            // Call trigger
1508
            $result = $this->call_trigger('CONTACT_ENABLEDISABLE', $user);
1509
            if ($result < 0) { $error++; }
1510
            // End call triggers
1511
		}
1512
1513
		if ($error)
1514
		{
1515
			$this->db->rollback();
1516
			return -$error;
1517
		} else {
1518
			$this->db->commit();
1519
			return 1;
1520
		}
1521
	}
1522
1523
	/**
1524
	 * Sets object to supplied categories.
1525
	 *
1526
	 * Deletes object from existing categories not supplied.
1527
	 * Adds it to non existing supplied categories.
1528
	 * Existing categories are left untouch.
1529
	 *
1530
	 * @param int[]|int $categories Category or categories IDs
1531
     * @return void
1532
	 */
1533
	public function setCategories($categories)
1534
	{
1535
		// Handle single category
1536
		if (!is_array($categories)) {
1537
			$categories = array($categories);
1538
		}
1539
1540
		// Get current categories
1541
		require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
1542
		$c = new Categorie($this->db);
1543
		$existing = $c->containing($this->id, Categorie::TYPE_CONTACT, 'id');
1544
1545
		// Diff
1546
		if (is_array($existing)) {
0 ignored issues
show
introduced by
The condition is_array($existing) is always false.
Loading history...
1547
			$to_del = array_diff($existing, $categories);
1548
			$to_add = array_diff($categories, $existing);
1549
		} else {
1550
			$to_del = array(); // Nothing to delete
1551
			$to_add = $categories;
1552
		}
1553
1554
		// Process
1555
		foreach ($to_del as $del) {
1556
			if ($c->fetch($del) > 0) {
1557
				$c->del_type($this, Categorie::TYPE_CONTACT);
1558
			}
1559
		}
1560
		foreach ($to_add as $add) {
1561
			if ($c->fetch($add) > 0) {
1562
				$c->add_type($this, Categorie::TYPE_CONTACT);
1563
			}
1564
		}
1565
1566
		return;
1567
	}
1568
1569
	/**
1570
	 * Function used to replace a thirdparty id with another one.
1571
	 *
1572
	 * @param DoliDB $db Database handler
1573
	 * @param int $origin_id Old thirdparty id
1574
	 * @param int $dest_id New thirdparty id
1575
	 * @return bool
1576
	 */
1577
	public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
1578
	{
1579
		$tables = array(
1580
			'socpeople', 'societe_contacts'
1581
		);
1582
1583
		return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
1584
	}
1585
1586
	/**
1587
	 * Fetch Roles for a contact
1588
	 *
1589
	 * @return float|int
1590
	 * @throws Exception
1591
	 */
1592
	public function fetchRoles()
1593
	{
1594
		global $langs;
1595
		$error = 0;
1596
		$num = 0;
1597
1598
		$sql = "SELECT tc.rowid, tc.element, tc.source, tc.code, tc.libelle, sc.rowid as contactroleid";
1599
		$sql .= " FROM ".MAIN_DB_PREFIX."societe_contacts as sc";
1600
		$sql .= " INNER JOIN ".MAIN_DB_PREFIX."c_type_contact as tc";
1601
		$sql .= " ON tc.rowid = sc.fk_c_type_contact";
1602
		$sql .= " AND sc.fk_socpeople = ".$this->id;
1603
		$sql .= " AND tc.source = 'external' AND tc.active=1";
1604
		$sql .= " AND sc.entity IN (".getEntity('societe').')';
1605
1606
		dol_syslog(__METHOD__, LOG_DEBUG);
1607
1608
		$this->roles = array();
1609
		$resql = $this->db->query($sql);
1610
		if ($resql) {
1611
			$num = $this->db->num_rows($resql);
1612
			if ($num > 0) {
1613
				while ($obj = $this->db->fetch_object($resql)) {
1614
					$transkey = "TypeContact_".$obj->element."_".$obj->source."_".$obj->code;
1615
					$libelle_element = $langs->trans('ContactDefault_'.$obj->element);
1616
					$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));
1617
				}
1618
			}
1619
		} else {
1620
			$error++;
1621
			$this->error = $this->db->lasterror();
1622
			$this->errors[] = $this->db->lasterror();
1623
		}
1624
1625
		if (empty($error)) {
1626
			return $num;
1627
		} else {
1628
			return $error * -1;
1629
		}
1630
	}
1631
1632
	/**
1633
	 * Get Contact roles for a thirdparty
1634
	 *
1635
	 * @param  string 	$element 	Element type
1636
	 * @return array|int			Array of contact roles or -1
1637
	 * @throws Exception
1638
	 */
1639
	public function getContactRoles($element = '')
1640
	{
1641
		$tab = array();
1642
1643
		if ($element == 'action') {
1644
			$element = 'agenda';
1645
		}
1646
1647
		$sql = "SELECT sc.fk_socpeople as id, sc.fk_c_type_contact";
1648
		$sql .= " FROM ".MAIN_DB_PREFIX."c_type_contact tc";
1649
		$sql .= ", ".MAIN_DB_PREFIX."societe_contacts sc";
1650
		$sql .= " WHERE sc.fk_soc =".$this->socid;
1651
		$sql .= " AND sc.fk_c_type_contact=tc.rowid";
1652
		$sql .= " AND tc.element='".$element."'";
1653
		$sql .= " AND tc.active=1";
1654
1655
		dol_syslog(__METHOD__, LOG_DEBUG);
1656
		$resql = $this->db->query($sql);
1657
		if ($resql)
1658
		{
1659
			$num = $this->db->num_rows($resql);
1660
			$i = 0;
1661
			while ($i < $num)
1662
			{
1663
				$obj = $this->db->fetch_object($resql);
1664
				$tab[] = array('fk_socpeople'=>$obj->id, 'type_contact'=>$obj->fk_c_type_contact);
1665
1666
				$i++;
1667
			}
1668
1669
			return $tab;
1670
		} else {
1671
			$this->error = $this->db->error();
1672
			dol_print_error($this->db);
1673
			return -1;
1674
		}
1675
	}
1676
1677
	/**
1678
	 * Updates Roles
1679
	 *
1680
	 * @return float|int
1681
	 * @throws Exception
1682
	 */
1683
	public function updateRoles()
1684
	{
1685
		global $conf;
1686
1687
		$error = 0;
1688
1689
		$this->db->begin();
1690
1691
		$sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_contacts WHERE fk_soc=".$this->socid." AND fk_socpeople=".$this->id; ;
1692
1693
		dol_syslog(__METHOD__, LOG_DEBUG);
1694
		$result = $this->db->query($sql);
1695
		if (!$result) {
1696
			$this->errors[] = $this->db->lasterror().' sql='.$sql;
1697
			$error++;
1698
		} else {
1699
			if (count($this->roles) > 0) {
1700
				foreach ($this->roles as $keyRoles => $valRoles) {
1701
					$sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_contacts";
1702
					$sql .= " (entity,";
1703
					$sql .= "date_creation,";
1704
					$sql .= "fk_soc,";
1705
					$sql .= "fk_c_type_contact,";
1706
					$sql .= "fk_socpeople) ";
1707
					$sql .= " VALUES (".$conf->entity.",";
1708
					$sql .= "'".$this->db->idate(dol_now())."',";
1709
					$sql .= $this->socid.", ";
1710
					$sql .= $valRoles." , ";
1711
					$sql .= $this->id;
1712
					$sql .= ")";
1713
					dol_syslog(__METHOD__, LOG_DEBUG);
1714
1715
					$result = $this->db->query($sql);
1716
					if (!$result)
1717
					{
1718
						$this->errors[] = $this->db->lasterror().' sql='.$sql;
1719
						$error++;
1720
					}
1721
				}
1722
			}
1723
		}
1724
		if (empty($error)) {
1725
			$this->db->commit();
1726
			return 1;
1727
		} else {
1728
			$this->error = implode(' ', $this->errors);
1729
			$this->db->rollback();
1730
			return $error * -1;
1731
		}
1732
	}
1733
1734
	/**
1735
	 *  Load array of prospect status
1736
	 *
1737
	 *  @param	int		$active     1=Active only, 0=Not active only, -1=All
1738
	 *  @return int					<0 if KO, >0 if OK
1739
	 */
1740
	public function loadCacheOfProspStatus($active = 1)
1741
	{
1742
		global $langs;
1743
1744
		$sql = "SELECT id, code, libelle as label, picto FROM " . MAIN_DB_PREFIX . "c_stcommcontact";
1745
		if ($active >= 0) $sql .= " WHERE active = " . $active;
1746
		$resql = $this->db->query($sql);
1747
		$num = $this->db->num_rows($resql);
1748
		$i = 0;
1749
		while ($i < $num)
1750
		{
1751
			$obj = $this->db->fetch_object($resql);
1752
			$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);
1753
			$i++;
1754
		}
1755
		return 1;
1756
	}
1757
1758
	/**
1759
	 *	Return prostect level
1760
	 *
1761
	 *  @return     string        Libelle
1762
	 */
1763
	public function getLibProspLevel()
1764
	{
1765
		return $this->libProspLevel($this->fk_prospectlevel);
1766
	}
1767
1768
	/**
1769
	 *  Return label of prospect level
1770
	 *
1771
	 *  @param	int		$fk_prospectlevel   	Prospect level
1772
	 *  @return string        					label of level
1773
	 */
1774
	public function libProspLevel($fk_prospectlevel)
1775
	{
1776
		global $langs;
1777
1778
		$lib = $langs->trans("ProspectLevel" . $fk_prospectlevel);
1779
		// If lib not found in language file, we get label from cache/databse
1780
		if ($lib == $langs->trans("ProspectLevel" . $fk_prospectlevel))
1781
		{
1782
			$lib = $langs->getLabelFromKey($this->db, $fk_prospectlevel, 'c_prospectlevel', 'code', 'label');
1783
		}
1784
		return $lib;
1785
	}
1786
1787
1788
	/**
1789
	 *  Set prospect level
1790
	 *
1791
	 *  @param  User	$user		Utilisateur qui definie la remise
1792
	 *	@return	int					<0 if KO, >0 if OK
1793
	 * @deprecated Use update function instead
1794
	 */
1795
	public function setProspectLevel(User $user)
1796
	{
1797
		return $this->update($this->id, $user);
1798
	}
1799
1800
	/**
1801
	 *  Return status of prospect
1802
	 *
1803
	 *  @param	int		$mode       0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long
1804
	 *  @param	string	$label		Label to use for status for added status
1805
	 *  @return string        		Libelle
1806
	 */
1807
	public function getLibProspCommStatut($mode = 0, $label = '')
1808
	{
1809
		return $this->libProspCommStatut($this->stcomm_id, $mode, $label, $this->stcomm_picto);
1810
	}
1811
1812
	/**
1813
	 *  Return label of a given status
1814
	 *
1815
	 *  @param	int|string	$statut        	Id or code for prospection status
1816
	 *  @param  int			$mode          	0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto
1817
	 *  @param	string		$label			Label to use for status for added status
1818
	 *	@param 	string		$picto      	Name of image file to show ('filenew', ...)
1819
	 *                                      If no extension provided, we use '.png'. Image must be stored into theme/xxx/img directory.
1820
	 *                                      Example: picto.png                  if picto.png is stored into htdocs/theme/mytheme/img
1821
	 *                                      Example: picto.png@mymodule         if picto.png is stored into htdocs/mymodule/img
1822
	 *                                      Example: /mydir/mysubdir/picto.png  if picto.png is stored into htdocs/mydir/mysubdir (pictoisfullpath must be set to 1)
1823
	 *  @return string       	 			Libelle du statut
1824
	 */
1825
	public function libProspCommStatut($statut, $mode = 0, $label = '', $picto = '')
1826
	{
1827
		global $langs;
1828
		$langs->load('customers');
1829
1830
		if ($mode == 2)
1831
		{
1832
			if ($statut == '-1' || $statut == 'ST_NO') return img_action($langs->trans("StatusProspect-1"), -1, $picto) . ' ' . $langs->trans("StatusProspect-1");
1833
			elseif ($statut == '0' || $statut == 'ST_NEVER') return img_action($langs->trans("StatusProspect0"), 0, $picto) . ' ' . $langs->trans("StatusProspect0");
1834
			elseif ($statut == '1' || $statut == 'ST_TODO') return img_action($langs->trans("StatusProspect1"), 1, $picto) . ' ' . $langs->trans("StatusProspect1");
1835
			elseif ($statut == '2' || $statut == 'ST_PEND') return img_action($langs->trans("StatusProspect2"), 2, $picto) . ' ' . $langs->trans("StatusProspect2");
1836
			elseif ($statut == '3' || $statut == 'ST_DONE') return img_action($langs->trans("StatusProspect3"), 3, $picto) . ' ' . $langs->trans("StatusProspect3");
1837
			else {
1838
				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);
1839
			}
1840
		}
1841
		if ($mode == 3)
1842
		{
1843
			if ($statut == '-1' || $statut == 'ST_NO') return img_action($langs->trans("StatusProspect-1"), -1, $picto);
1844
			elseif ($statut == '0' || $statut == 'ST_NEVER') return img_action($langs->trans("StatusProspect0"), 0, $picto);
1845
			elseif ($statut == '1' || $statut == 'ST_TODO') return img_action($langs->trans("StatusProspect1"), 1, $picto);
1846
			elseif ($statut == '2' || $statut == 'ST_PEND') return img_action($langs->trans("StatusProspect2"), 2, $picto);
1847
			elseif ($statut == '3' || $statut == 'ST_DONE') return img_action($langs->trans("StatusProspect3"), 3, $picto);
1848
			else {
1849
				return img_action(($langs->trans("StatusProspect" . $statut) != "StatusProspect" . $statut) ? $langs->trans("StatusProspect" . $statut) : $label, 0, $picto);
1850
			}
1851
		}
1852
		if ($mode == 4)
1853
		{
1854
			if ($statut == '-1' || $statut == 'ST_NO') return img_action($langs->trans("StatusProspect-1"), -1, $picto) . ' ' . $langs->trans("StatusProspect-1");
1855
			elseif ($statut == '0' || $statut == 'ST_NEVER') return img_action($langs->trans("StatusProspect0"), 0, $picto) . ' ' . $langs->trans("StatusProspect0");
1856
			elseif ($statut == '1' || $statut == 'ST_TODO') return img_action($langs->trans("StatusProspect1"), 1, $picto) . ' ' . $langs->trans("StatusProspect1");
1857
			elseif ($statut == '2' || $statut == 'ST_PEND') return img_action($langs->trans("StatusProspect2"), 2, $picto) . ' ' . $langs->trans("StatusProspect2");
1858
			elseif ($statut == '3' || $statut == 'ST_DONE') return img_action($langs->trans("StatusProspect3"), 3, $picto) . ' ' . $langs->trans("StatusProspect3");
1859
			else {
1860
				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);
1861
			}
1862
		}
1863
1864
		return "Error, mode/status not found";
1865
	}
1866
}
1867