Passed
Push — master ( 3cffbe...0f9140 )
by Alxarafe
23:50
created

AlCommonObject::setValueFrom()   F

Complexity

Conditions 27
Paths > 20000

Size

Total Lines 67
Code Lines 38

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 27
eloc 38
nop 9
dl 0
loc 67
rs 0
c 0
b 0
f 0
nc 35840

How to fix   Long Method    Complexity    Many Parameters   

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:

Many Parameters

Methods with many parameters are not only hard to understand, but their parameters also often become inconsistent when you need more, or different data.

There are several approaches to avoid long parameter lists:

1
<?php
2
/* Copyright (C) 2018       Alxarafe            <[email protected]>
3
 *
4
 * This program is free software; you can redistribute it and/or modify
5
 * it under the terms of the GNU General Public License as published by
6
 * the Free Software Foundation; either version 3 of the License, or
7
 * (at your option) any later version.
8
 *
9
 * This program is distributed in the hope that it will be useful,
10
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
 * GNU General Public License for more details.
13
 *
14
 * You should have received a copy of the GNU General Public License
15
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
16
 */
17
namespace Alixar\Base;
18
19
use Alixar\Helpers\AlDolUtils;
20
use Alixar\Base\AlExtraFields;
21
22
abstract class AlCommonObject
23
{
24
	/**
25
     * @var int The object identifier
26
     */
27
	public $id;
28
29
	/**
30
	 * @var string 		Error string
31
	 * @see             errors
32
	 */
33
	public $error;
34
35
	/**
36
	 * @var string[]	Array of error strings
37
	 */
38
	public $errors=array();
39
40
	/**
41
	 * @var string ID to identify managed object
42
	 */
43
	public $element;
44
45
	/**
46
	 * @var string Name of table without prefix where object is stored
47
	 */
48
	public $table_element;
49
50
	/**
51
	 * @var int    Name of subtable line
52
	 */
53
	public $table_element_line='';
54
55
	/**
56
	 * @var string		Key value used to track if data is coming from import wizard
57
	 */
58
	public $import_key;
59
60
	/**
61
	 * @var mixed		Contains data to manage extrafields
62
	 */
63
	public $array_options=array();
64
65
	/**
66
	 * @var int[][]		Array of linked objects ids. Loaded by ->fetchObjectLinked
67
	 */
68
	public $linkedObjectsIds;
69
70
	/**
71
	 * @var mixed		Array of linked objects. Loaded by ->fetchObjectLinked
72
	 */
73
	public $linkedObjects;
74
75
	/**
76
	 * @var Object      To store a cloned copy of object before to edit it and keep track of old properties
77
	 */
78
	public $oldcopy;
79
80
	/**
81
	 * @var string		Column name of the ref field.
82
	 */
83
	protected $table_ref_field = '';
84
85
86
87
	// Following vars are used by some objects only. We keep this property here in CommonObject to be able to provide common method using them.
88
89
	/**
90
	 * @var array<string,mixed>		Can be used to pass information when only object is provided to method
91
	 */
92
	public $context=array();
93
94
	/**
95
	 * @var string		Contains canvas name if record is an alternative canvas record
96
	 */
97
	public $canvas;
98
99
	/**
100
	 * @var Project The related project
0 ignored issues
show
Bug introduced by alxarafe
The type Alixar\Base\Project was not found. Did you mean Project? If so, make sure to prefix the type with \.
Loading history...
101
	 * @see fetch_projet()
102
	 */
103
	public $project;
104
105
	/**
106
	 * @var int The related project ID
107
	 * @see setProject(), project
108
	 */
109
	public $fk_project;
110
111
	/**
112
	 * @deprecated
113
	 * @see project
114
	 */
115
	public $projet;
116
117
	/**
118
	 * @var Contact a related contact
0 ignored issues
show
Bug introduced by alxarafe
The type Alixar\Base\Contact was not found. Did you mean Contact? If so, make sure to prefix the type with \.
Loading history...
119
	 * @see fetch_contact()
120
	 */
121
	public $contact;
122
123
	/**
124
	 * @var int The related contact ID
125
	 * @see fetch_contact()
126
	 */
127
	public $contact_id;
128
129
	/**
130
	 * @var Societe A related thirdparty
0 ignored issues
show
Bug introduced by alxarafe
The type Alixar\Base\Societe was not found. Did you mean Societe? If so, make sure to prefix the type with \.
Loading history...
131
	 * @see fetch_thirdparty()
132
	 */
133
	public $thirdparty;
134
135
	/**
136
	 * @var User A related user
137
	 * @see fetch_user()
138
	 */
139
	public $user;
140
141
	/**
142
	 * @var string 	The type of originating object ('commande', 'facture', ...)
143
	 * @see fetch_origin()
144
	 */
145
	public $origin;
146
147
	/**
148
	 * @var int 	The id of originating object
149
	 * @see fetch_origin()
150
	 */
151
	public $origin_id;
152
153
	/**
154
	 * @var string The object's reference
155
	 */
156
	public $ref;
157
158
	/**
159
	 * @var string The object's previous reference
160
	 */
161
	public $ref_previous;
162
163
	/**
164
	 * @var string The object's next reference
165
	 */
166
	public $ref_next;
167
168
	/**
169
	 * @var string An external reference for the object
170
	 */
171
	public $ref_ext;
172
173
	/**
174
	 * @var int The object's status
175
	 * @see setStatut()
176
	 */
177
	public $statut;
178
179
	/**
180
	 * @var string
181
	 * @see getFullAddress()
182
	 */
183
	public $country;
184
185
	/**
186
	 * @var int
187
	 * @see getFullAddress(), country
188
	 */
189
	public $country_id;
190
191
	/**
192
	 * @var string
193
	 * @see getFullAddress(), isInEEC(), country
194
	 */
195
    public $country_code;
196
197
    /**
198
	 * @var string
199
	 * @see getFullAddress()
200
	 */
201
	public $state;
202
203
	/**
204
	 * @var int
205
	 * @see getFullAddress(), state
206
	 */
207
	public $state_id;
208
209
	/**
210
	 * @var string
211
	 * @see getFullAddress(), state
212
	 */
213
    public $state_code;
214
215
    /**
216
	 * @var string
217
	 * @see getFullAddress(), region
218
	 */
219
	public $region;
220
221
	/**
222
	 * @var string
223
	 * @see getFullAddress(), region
224
	 */
225
    public $region_code;
226
227
	/**
228
	 * @var int
229
	 * @see fetch_barcode()
230
	 */
231
	public $barcode_type;
232
233
	/**
234
	 * @var string
235
	 * @see fetch_barcode(), barcode_type
236
	 */
237
	public $barcode_type_code;
238
239
	/**
240
	 * @var string
241
	 * @see fetch_barcode(), barcode_type
242
	 */
243
	public $barcode_type_label;
244
245
	/**
246
	 * @var string
247
	 * @see fetch_barcode(), barcode_type
248
	 */
249
	public $barcode_type_coder;
250
251
	/**
252
	 * @var int Payment method ID (cheque, cash, ...)
253
	 * @see setPaymentMethods()
254
	 */
255
	public $mode_reglement_id;
256
257
	/**
258
	 * @var int Payment terms ID
259
	 * @see setPaymentTerms()
260
	 */
261
	public $cond_reglement_id;
262
263
	/**
264
	 * @var int Payment terms ID
265
	 * @deprecated Kept for compatibility
266
	 * @see cond_reglement_id;
267
	 */
268
	public $cond_reglement;
269
270
	/**
271
	 * @var int Delivery address ID
272
	 * @deprecated
273
	 * @see setDeliveryAddress()
274
	 */
275
	public $fk_delivery_address;
276
277
	/**
278
	 * @var int Shipping method ID
279
	 * @see setShippingMethod()
280
	 */
281
	public $shipping_method_id;
282
283
	/**
284
	 * @var string
285
	 * @see SetDocModel()
286
	 */
287
	public $modelpdf;
288
289
	/**
290
	 * @var int Bank account ID
291
	 * @see SetBankAccount()
292
	 */
293
	public $fk_account;
294
295
	/**
296
	 * @var string Public note
297
	 * @see update_note()
298
	 */
299
	public $note_public;
300
301
	/**
302
	 * @var string Private note
303
	 * @see update_note()
304
	 */
305
	public $note_private;
306
307
	/**
308
	 * @deprecated
309
	 * @see note_public
310
	 */
311
	public $note;
312
313
	/**
314
	 * @var float Total amount before taxes
315
	 * @see update_price()
316
	 */
317
	public $total_ht;
318
319
	/**
320
	 * @var float Total VAT amount
321
	 * @see update_price()
322
	 */
323
	public $total_tva;
324
325
	/**
326
	 * @var float Total local tax 1 amount
327
	 * @see update_price()
328
	 */
329
	public $total_localtax1;
330
331
	/**
332
	 * @var float Total local tax 2 amount
333
	 * @see update_price()
334
	 */
335
	public $total_localtax2;
336
337
	/**
338
	 * @var float Total amount with taxes
339
	 * @see update_price()
340
	 */
341
	public $total_ttc;
342
343
	/**
344
	 * @var CommonObjectLine[]
345
	 */
346
	public $lines;
347
348
	/**
349
	 * @var mixed		Contains comments
350
	 * @see fetchComments()
351
	 */
352
	public $comments=array();
353
354
	/**
355
	 * @var int
356
	 * @see setIncoterms()
357
	 */
358
	public $fk_incoterms;
359
360
	/**
361
	 * @var string
362
	 * @see SetIncoterms()
363
	 */
364
	public $libelle_incoterms;
365
366
	/**
367
	 * @var string
368
	 * @see display_incoterms()
369
	 */
370
	public $location_incoterms;
371
372
	public $name;
373
	public $lastname;
374
	public $firstname;
375
	public $civility_id;
376
377
	// Dates
378
	public $date_creation;			// Date creation
379
	public $date_validation;		// Date validation
380
	public $date_modification;		// Date last change (tms field)
381
382
383
384
	// No constructor as it is an abstract class
385
386
	/**
387
	 * Check an object id/ref exists
388
	 * If you don't need/want to instantiate object and just need to know if object exists, use this method instead of fetch
389
	 *
390
	 *  @param	string	$element   	String of element ('product', 'facture', ...)
391
	 *  @param	int		$id      	Id of object
392
	 *  @param  string	$ref     	Ref of object to check
393
	 *  @param	string	$ref_ext	Ref ext of object to check
394
	 *  @return int     			<0 if KO, 0 if OK but not found, >0 if OK and exists
395
	 */
396
	static function isExistingObject($element, $id, $ref='', $ref_ext='')
397
	{
398
		global $db,$conf;
399
400
		$sql = "SELECT rowid, ref, ref_ext";
401
		$sql.= " FROM ".MAIN_DB_PREFIX.$element;
402
		$sql.= " WHERE entity IN (".getEntity($element).")" ;
403
404
		if ($id > 0) $sql.= " AND rowid = ".$db->escape($id);
405
		else if ($ref) $sql.= " AND ref = '".$db->escape($ref)."'";
406
		else if ($ref_ext) $sql.= " AND ref_ext = '".$db->escape($ref_ext)."'";
407
		else {
408
			$error='ErrorWrongParameters';
409
			dol_print_error(get_class()."::isExistingObject ".$error, LOG_ERR);
410
			return -1;
411
		}
412
		if ($ref || $ref_ext)
413
            $sql .= " AND entity = " . Globals::$conf->entity;
414
415
        dol_syslog(get_class()."::isExistingObject", LOG_DEBUG);
416
		$resql = $db->query($sql);
417
		if ($resql)
418
		{
419
			$num=$db->num_rows($resql);
420
			if ($num > 0) return 1;
421
			else return 0;
422
		}
423
		return -1;
424
	}
425
426
	/**
427
	 * Method to output saved errors
428
	 *
429
	 * @return	string		String with errors
430
	 */
431
	function errorsToString()
432
	{
433
		return $this->error.(is_array($this->errors)?(($this->error!=''?', ':'').join(', ',$this->errors)):'');
434
	}
435
436
	/**
437
	 *	Return full name (civility+' '+name+' '+lastname)
438
	 *
439
	 *	@param	Translate	$langs			Language object for translation of civility (used only if option is 1)
0 ignored issues
show
Bug introduced by alxarafe
The type Alixar\Base\Translate was not found. Did you mean Translate? If so, make sure to prefix the type with \.
Loading history...
440
	 *	@param	int			$option			0=No option, 1=Add civility
441
	 * 	@param	int			$nameorder		-1=Auto, 0=Lastname+Firstname, 1=Firstname+Lastname, 2=Firstname
442
	 * 	@param	int			$maxlen			Maximum length
443
	 * 	@return	string						String with full name
444
	 */
445
	function getFullName($langs,$option=0,$nameorder=-1,$maxlen=0)
446
	{
447
		//print "lastname=".$this->lastname." name=".$this->name." nom=".$this->nom."<br>\n";
448
		$lastname=$this->lastname;
449
		$firstname=$this->firstname;
450
		if (empty($lastname))  $lastname=(isset($this->lastname)?$this->lastname:(isset($this->name)?$this->name:(isset($this->nom)?$this->nom:(isset($this->societe)?$this->societe:(isset($this->company)?$this->company:'')))));
451
452
		$ret='';
453
		if ($option && $this->civility_id)
454
		{
455
			if ($langs->transnoentitiesnoconv("Civility".$this->civility_id)!="Civility".$this->civility_id) $ret.=$langs->transnoentitiesnoconv("Civility".$this->civility_id).' ';
456
			else $ret.=$this->civility_id.' ';
457
		}
458
459
		$ret .= AlDolUtils::dolGetFirstLastname($firstname, $lastname, $nameorder);
460
461
        return AlDolUtils::dol_trunc($ret, $maxlen);
462
    }
463
464
	/**
465
	 * 	Return full address of contact
466
	 *
467
	 * 	@param		int			$withcountry		1=Add country into address string
468
	 *  @param		string		$sep				Separator to use to build string
469
	 *  @param		int		    $withregion			1=Add region into address string
470
	 *	@return		string							Full address string
471
	 */
472
	function getFullAddress($withcountry=0, $sep="\n", $withregion=0)
473
	{
474
		if ($withcountry && $this->country_id && (empty($this->country_code) || empty($this->country)))
475
		{
476
			require_once DOL_DOCUMENT_ROOT .'/core/lib/company.lib.php';
477
			$tmparray=getCountry($this->country_id,'all');
478
			$this->country_code=$tmparray['code'];
479
			$this->country     =$tmparray['label'];
480
		}
481
482
        if ($withregion && $this->state_id && (empty($this->state_code) || empty($this->state) || empty($this->region) || empty($this->region_cpde)))
0 ignored issues
show
Bug introduced by alxarafe
The property region_cpde does not exist on Alixar\Base\AlCommonObject. Did you mean region?
Loading history...
483
    	{
484
    		require_once DOL_DOCUMENT_ROOT .'/core/lib/company.lib.php';
485
    		$tmparray=getState($this->state_id,'all',0,1);
486
			$this->state_code   =$tmparray['code'];
487
			$this->state        =$tmparray['label'];
488
			$this->region_code  =$tmparray['region_code'];
489
			$this->region       =$tmparray['region'];
490
        }
491
492
		return dol_format_address($this, $withcountry, $sep);
493
	}
494
495
496
	/**
497
	 * 	Return full address for banner
498
	 *
499
	 * 	@param		string		$htmlkey            HTML id to make banner content unique
500
	 *  @param      Object      $object				Object (thirdparty, thirdparty of contact for contact, null for a member)
501
	 *	@return		string							Full address string
502
	 */
503
	function getBannerAddress($htmlkey, $object)
504
	{
505
		global $conf, $langs;
506
507
		$countriesusingstate=array('AU','US','IN','GB','ES','UK','TR');    // See also option MAIN_FORCE_STATE_INTO_ADDRESS
508
509
		$contactid=0;
510
		$thirdpartyid=0;
511
		if ($this->element == 'societe')
512
		{
513
			$thirdpartyid=$this->id;
514
		}
515
		if ($this->element == 'contact')
516
		{
517
			$contactid=$this->id;
518
			$thirdpartyid=$object->fk_soc;
519
		}
520
		if ($this->element == 'user')
521
		{
522
			$contactid=$this->contact_id;
523
			$thirdpartyid=$object->fk_soc;
524
		}
525
526
		$out='<!-- BEGIN part to show address block -->';
527
528
		$outdone=0;
529
		$coords = $this->getFullAddress(1, ', ', Globals::$conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT);
530
        if ($coords)
531
		{
532
			if (!empty(Globals::$conf->use_javascript_ajax)) {
533
				$namecoords = $this->getFullName($langs,1).'<br>'.$coords;
534
				// hideonsmatphone because copyToClipboard call jquery dialog that does not work with jmobile
535
				$out.='<a href="#" class="hideonsmartphone" onclick="return copyToClipboard(\''.dol_escape_js($namecoords).'\',\''.dol_escape_js($langs->trans("HelpCopyToClipboard")).'\');">';
536
				$out.=img_picto($langs->trans("Address"), 'object_address.png');
537
				$out.='</a> ';
538
			}
539
			$out.=dol_print_address($coords, 'address_'.$htmlkey.'_'.$this->id, $this->element, $this->id, 1, ', '); $outdone++;
540
			$outdone++;
541
		}
542
543
		if (!in_array($this->country_code, $countriesusingstate) && empty(Globals::$conf->global->MAIN_FORCE_STATE_INTO_ADDRESS)   // If MAIN_FORCE_STATE_INTO_ADDRESS is on, state is already returned previously with getFullAddress
544
            && empty(Globals::$conf->global->SOCIETE_DISABLE_STATE) && $this->state) {
545
            if (!empty(Globals::$conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) && Globals::$conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 1 && $this->region) {
546
                $out.=($outdone?' - ':'').$this->region.' - '.$this->state;
547
            }
548
            else {
549
                $out.=($outdone?' - ':'').$this->state;
550
            }
551
			$outdone++;
552
		}
553
554
		if (! empty($this->phone) || ! empty($this->phone_pro) || ! empty($this->phone_mobile) || ! empty($this->phone_perso) || ! empty($this->fax) || ! empty($this->office_phone) || ! empty($this->user_mobile) || ! empty($this->office_fax)) $out.=($outdone?'<br>':'');
555
		if (! empty($this->phone) && empty($this->phone_pro)) {		// For objects that store pro phone into ->phone
556
			$out.=dol_print_phone($this->phone,$this->country_code,$contactid,$thirdpartyid,'AC_TEL','&nbsp;','phone',$langs->trans("PhonePro")); $outdone++;
557
		}
558
		if (! empty($this->phone_pro)) {
559
			$out.=dol_print_phone($this->phone_pro,$this->country_code,$contactid,$thirdpartyid,'AC_TEL','&nbsp;','phone',$langs->trans("PhonePro")); $outdone++;
560
		}
561
		if (! empty($this->phone_mobile)) {
562
			$out.=dol_print_phone($this->phone_mobile,$this->country_code,$contactid,$thirdpartyid,'AC_TEL','&nbsp;','mobile',$langs->trans("PhoneMobile")); $outdone++;
563
		}
564
		if (! empty($this->phone_perso)) {
565
			$out.=dol_print_phone($this->phone_perso,$this->country_code,$contactid,$thirdpartyid,'AC_TEL','&nbsp;','phone',$langs->trans("PhonePerso")); $outdone++;
0 ignored issues
show
Bug Best Practice introduced by alxarafe
The property phone_perso does not exist on Alixar\Base\AlCommonObject. Did you maybe forget to declare it?
Loading history...
566
		}
567
		if (! empty($this->office_phone)) {
568
			$out.=dol_print_phone($this->office_phone,$this->country_code,$contactid,$thirdpartyid,'AC_TEL','&nbsp;','phone',$langs->trans("PhonePro")); $outdone++;
569
		}
570
		if (! empty($this->user_mobile)) {
571
			$out.=dol_print_phone($this->user_mobile,$this->country_code,$contactid,$thirdpartyid,'AC_TEL','&nbsp;','mobile',$langs->trans("PhoneMobile")); $outdone++;
572
		}
573
		if (! empty($this->fax)) {
574
			$out.=dol_print_phone($this->fax,$this->country_code,$contactid,$thirdpartyid,'AC_FAX','&nbsp;','fax',$langs->trans("Fax")); $outdone++;
575
		}
576
		if (! empty($this->office_fax)) {
577
			$out.=dol_print_phone($this->office_fax,$this->country_code,$contactid,$thirdpartyid,'AC_FAX','&nbsp;','fax',$langs->trans("Fax")); $outdone++;
578
		}
579
580
		$out.='<div style="clear: both;"></div>';
581
		$outdone=0;
582
		if (! empty($this->email))
583
		{
584
			$out.=dol_print_email($this->email,$this->id,$object->id,'AC_EMAIL',0,0,1);
585
			$outdone++;
586
		}
587
		if (! empty($this->url))
588
		{
589
			$out.=dol_print_url($this->url,'_goout',0,1);
0 ignored issues
show
Bug Best Practice introduced by alxarafe
The property url does not exist on Alixar\Base\AlCommonObject. Did you maybe forget to declare it?
Loading history...
590
			$outdone++;
591
		}
592
		$out.='<div style="clear: both;">';
593
		if (!empty(Globals::$conf->socialnetworks->enabled)) {
594
			if ($this->skype) $out.=dol_print_socialnetworks($this->skype,$this->id,$object->id,'skype');
595
			$outdone++;
596
			if ($this->jabberid) $out.=dol_print_socialnetworks($this->jabberid,$this->id,$object->id,'jabber');
0 ignored issues
show
Bug Best Practice introduced by alxarafe
The property jabberid does not exist on Alixar\Base\AlCommonObject. Did you maybe forget to declare it?
Loading history...
597
			$outdone++;
598
			if ($this->twitter) $out.=dol_print_socialnetworks($this->twitter,$this->id,$object->id,'twitter');
599
			$outdone++;
600
			if ($this->facebook) $out.=dol_print_socialnetworks($this->facebook,$this->id,$object->id,'facebook');
601
			$outdone++;
602
		}
603
		$out.='</div>';
604
605
		$out.='<!-- END Part to show address block -->';
606
607
		return $out;
608
	}
609
610
	/**
611
	 * Return the link of last main doc file for direct public download.
612
	 *
613
	 * @param	string	$modulepart			Module related to document
614
	 * @param	int		$initsharekey		Init the share key if it was not yet defined
615
	 * @param	int		$relativelink		0=Return full external link, 1=Return link relative to root of file
616
	 * @return	string						Link or empty string if there is no download link
617
	 */
618
	function getLastMainDocLink($modulepart, $initsharekey=0, $relativelink=0)
619
	{
620
		global $user, $dolibarr_main_url_root;
621
622
		if (empty($this->last_main_doc))
623
		{
624
			return '';		// No way to known which document name to use
625
		}
626
627
		include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
628
		$ecmfile=new EcmFiles($this->db);
0 ignored issues
show
Bug Best Practice introduced by alxarafe
The property db does not exist on Alixar\Base\AlCommonObject. Did you maybe forget to declare it?
Loading history...
Bug introduced by alxarafe
The type Alixar\Base\EcmFiles was not found. Did you mean EcmFiles? If so, make sure to prefix the type with \.
Loading history...
629
		$result = $ecmfile->fetch(0, '', $this->last_main_doc);
0 ignored issues
show
Bug Best Practice introduced by alxarafe
The property last_main_doc does not exist on Alixar\Base\AlCommonObject. Did you maybe forget to declare it?
Loading history...
630
		if ($result < 0)
631
		{
632
			$this->error = $ecmfile->error;
633
			$this->errors = $ecmfile->errors;
634
			return -1;
635
		}
636
637
		if (empty($ecmfile->id))
638
		{
639
			// Add entry into index
640
			if ($initsharekey)
641
			{
642
				require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
643
				// TODO We can't, we dont' have full path of file, only last_main_doc adn ->element, so we must rebuild full path first
644
				/*
645
				$ecmfile->filepath = $rel_dir;
646
				$ecmfile->filename = $filename;
647
				$ecmfile->label = md5_file(dol_osencode($destfull));	// hash of file content
648
				$ecmfile->fullpath_orig = '';
649
				$ecmfile->gen_or_uploaded = 'generated';
650
				$ecmfile->description = '';    // indexed content
651
				$ecmfile->keyword = '';        // keyword content
652
				$ecmfile->share = getRandomPassword(true);
653
				$result = $ecmfile->create($user);
654
				if ($result < 0)
655
				{
656
					$this->error = $ecmfile->error;
657
					$this->errors = $ecmfile->errors;
658
				}
659
				*/
660
			}
661
			else return '';
662
		}
663
		elseif (empty($ecmfile->share))
664
		{
665
			// Add entry into index
666
			if ($initsharekey)
667
			{
668
				require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
669
				$ecmfile->share = getRandomPassword(true);
670
				$ecmfile->update($user);
671
			}
672
			else return '';
673
		}
674
675
		// Define $urlwithroot
676
		$urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT,'/').'$/i','',trim($dolibarr_main_url_root));
677
		$urlwithroot=$urlwithouturlroot.DOL_URL_ROOT;		// This is to use external domain name found into config file
678
		//$urlwithroot=DOL_MAIN_URL_ROOT;					// This is to use same domain name than current
679
680
		$forcedownload=0;
681
682
		$paramlink='';
683
		//if (! empty($modulepart)) $paramlink.=($paramlink?'&':'').'modulepart='.$modulepart;		// For sharing with hash (so public files), modulepart is not required.
684
		//if (! empty($ecmfile->entity)) $paramlink.='&entity='.$ecmfile->entity; 					// For sharing with hash (so public files), entity is not required.
685
		//$paramlink.=($paramlink?'&':'').'file='.urlencode($filepath);								// No need of name of file for public link, we will use the hash
686
		if (! empty($ecmfile->share)) $paramlink.=($paramlink?'&':'').'hashp='.$ecmfile->share;			// Hash for public share
687
		if ($forcedownload) $paramlink.=($paramlink?'&':'').'attachment=1';
688
689
		if ($relativelink)
690
		{
691
			$linktoreturn='document.php'.($paramlink?'?'.$paramlink:'');
692
		}
693
		else
694
		{
695
			$linktoreturn=$urlwithroot.'/document.php'.($paramlink?'?'.$paramlink:'');
696
		}
697
698
		// Here $ecmfile->share is defined
699
		return $linktoreturn;
700
	}
701
702
703
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
704
	/**
705
	 *  Add a link between element $this->element and a contact
706
	 *
707
	 *  @param	int		$fk_socpeople       Id of thirdparty contact (if source = 'external') or id of user (if souce = 'internal') to link
708
	 *  @param 	int		$type_contact 		Type of contact (code or id). Must be id or code found into table llx_c_type_contact. For example: SALESREPFOLL
709
	 *  @param  string	$source             external=Contact extern (llx_socpeople), internal=Contact intern (llx_user)
710
	 *  @param  int		$notrigger			Disable all triggers
711
	 *  @return int                 		<0 if KO, >0 if OK
712
	 */
713
	function add_contact($fk_socpeople, $type_contact, $source='external',$notrigger=0)
714
	{
715
        // phpcs:enable
716
		global $user,$langs;
717
718
719
		dol_syslog(get_class($this)."::add_contact $fk_socpeople, $type_contact, $source, $notrigger");
720
721
		// Check parameters
722
		if ($fk_socpeople <= 0)
723
		{
724
			$langs->load("errors");
725
			$this->error=$langs->trans("ErrorWrongValueForParameterX","1");
726
			dol_syslog(get_class($this)."::add_contact ".$this->error,LOG_ERR);
727
			return -1;
728
		}
729
		if (! $type_contact)
730
		{
731
			$langs->load("errors");
732
			$this->error=$langs->trans("ErrorWrongValueForParameterX","2");
733
			dol_syslog(get_class($this)."::add_contact ".$this->error,LOG_ERR);
734
			return -2;
735
		}
736
737
		$id_type_contact=0;
738
		if (is_numeric($type_contact))
739
		{
740
			$id_type_contact=$type_contact;
741
		}
742
		else
743
		{
744
			// We look for id type_contact
745
			$sql = "SELECT tc.rowid";
746
			$sql.= " FROM ".MAIN_DB_PREFIX."c_type_contact as tc";
747
			$sql.= " WHERE tc.element='".$this->db->escape($this->element)."'";
748
			$sql.= " AND tc.source='".$this->db->escape($source)."'";
749
			$sql.= " AND tc.code='".$this->db->escape($type_contact)."' AND tc.active=1";
750
			//print $sql;
751
			$resql=$this->db->query($sql);
752
			if ($resql)
753
			{
754
				$obj = $this->db->fetch_object($resql);
755
				if ($obj) $id_type_contact=$obj->rowid;
756
			}
757
		}
758
759
		if ($id_type_contact == 0)
760
		{
761
			$this->error='CODE_NOT_VALID_FOR_THIS_ELEMENT';
762
			dol_syslog("CODE_NOT_VALID_FOR_THIS_ELEMENT: Code type of contact '".$type_contact."' does not exists or is not active for element ".$this->element.", we can ignore it");
763
			return -3;
764
		}
765
766
		$datecreate = dol_now();
767
768
		// Socpeople must have already been added by some trigger, then we have to check it to avoid DB_ERROR_RECORD_ALREADY_EXISTS error
769
		$TListeContacts=$this->liste_contact(-1, $source);
770
		$already_added=false;
771
		if(!empty($TListeContacts)) {
772
			foreach($TListeContacts as $array_contact) {
773
				if($array_contact['status'] == 4 && $array_contact['id'] == $fk_socpeople && $array_contact['fk_c_type_contact'] == $id_type_contact) {
774
					$already_added=true;
775
					break;
776
				}
777
			}
778
		}
779
780
		if(!$already_added) {
781
782
			$this->db->begin();
0 ignored issues
show
Bug Best Practice introduced by alxarafe
The property db does not exist on Alixar\Base\AlCommonObject. Did you maybe forget to declare it?
Loading history...
783
784
			// Insert into database
785
			$sql = "INSERT INTO ".MAIN_DB_PREFIX."element_contact";
786
			$sql.= " (element_id, fk_socpeople, datecreate, statut, fk_c_type_contact) ";
787
			$sql.= " VALUES (".$this->id.", ".$fk_socpeople." , " ;
788
			$sql.= "'".$this->db->idate($datecreate)."'";
789
			$sql.= ", 4, ". $id_type_contact;
790
			$sql.= ")";
791
792
			$resql=$this->db->query($sql);
793
			if ($resql)
794
			{
795
				if (! $notrigger)
796
				{
797
					$result=$this->call_trigger(strtoupper($this->element).'_ADD_CONTACT', $user);
798
					if ($result < 0)
799
					{
800
						$this->db->rollback();
801
						return -1;
802
					}
803
				}
804
805
				$this->db->commit();
806
				return 1;
807
			}
808
			else
809
			{
810
				if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS')
811
				{
812
					$this->error=$this->db->errno();
813
					$this->db->rollback();
814
					echo 'err rollback';
815
					return -2;
816
				}
817
				else
818
				{
819
					$this->error=$this->db->error();
820
					$this->db->rollback();
821
					return -1;
822
				}
823
			}
824
		} else return 0;
825
	}
826
827
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
828
	/**
829
	 *    Copy contact from one element to current
830
	 *
831
	 *    @param    CommonObject    $objFrom    Source element
0 ignored issues
show
Bug introduced by alxarafe
The type Alixar\Base\CommonObject was not found. Did you mean CommonObject? If so, make sure to prefix the type with \.
Loading history...
832
	 *    @param    string          $source     Nature of contact ('internal' or 'external')
833
	 *    @return   int                         >0 if OK, <0 if KO
834
	 */
835
	function copy_linked_contact($objFrom, $source='internal')
836
	{
837
        // phpcs:enable
838
		$contacts = $objFrom->liste_contact(-1, $source);
839
		foreach($contacts as $contact)
840
		{
841
			if ($this->add_contact($contact['id'], $contact['fk_c_type_contact'], $contact['source']) < 0)
842
			{
843
				$this->error=$this->db->lasterror();
0 ignored issues
show
Bug Best Practice introduced by alxarafe
The property db does not exist on Alixar\Base\AlCommonObject. Did you maybe forget to declare it?
Loading history...
844
				return -1;
845
			}
846
		}
847
		return 1;
848
	}
849
850
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
851
	/**
852
	 *      Update a link to contact line
853
	 *
854
	 *      @param	int		$rowid              Id of line contact-element
855
	 * 		@param	int		$statut	            New status of link
856
	 *      @param  int		$type_contact_id    Id of contact type (not modified if 0)
857
	 *      @param  int		$fk_socpeople	    Id of soc_people to update (not modified if 0)
858
	 *      @return int                 		<0 if KO, >= 0 if OK
859
	 */
860
	function update_contact($rowid, $statut, $type_contact_id=0, $fk_socpeople=0)
861
	{
862
        // phpcs:enable
863
		// Insert into database
864
		$sql = "UPDATE ".MAIN_DB_PREFIX."element_contact set";
865
		$sql.= " statut = ".$statut;
866
		if ($type_contact_id) $sql.= ", fk_c_type_contact = '".$type_contact_id ."'";
867
		if ($fk_socpeople) $sql.= ", fk_socpeople = '".$fk_socpeople ."'";
868
		$sql.= " where rowid = ".$rowid;
869
		$resql=$this->db->query($sql);
0 ignored issues
show
Bug Best Practice introduced by alxarafe
The property db does not exist on Alixar\Base\AlCommonObject. Did you maybe forget to declare it?
Loading history...
870
		if ($resql)
871
		{
872
			return 0;
873
		}
874
		else
875
		{
876
			$this->error=$this->db->lasterror();
877
			return -1;
878
		}
879
	}
880
881
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
882
	/**
883
	 *    Delete a link to contact line
884
	 *
885
	 *    @param	int		$rowid			Id of contact link line to delete
886
	 *    @param	int		$notrigger		Disable all triggers
887
	 *    @return   int						>0 if OK, <0 if KO
888
	 */
889
	function delete_contact($rowid, $notrigger=0)
890
	{
891
        // phpcs:enable
892
		global $user;
893
894
895
		$this->db->begin();
0 ignored issues
show
Bug Best Practice introduced by alxarafe
The property db does not exist on Alixar\Base\AlCommonObject. Did you maybe forget to declare it?
Loading history...
896
897
		$sql = "DELETE FROM ".MAIN_DB_PREFIX."element_contact";
898
		$sql.= " WHERE rowid =".$rowid;
899
900
		dol_syslog(get_class($this)."::delete_contact", LOG_DEBUG);
901
		if ($this->db->query($sql))
902
		{
903
			if (! $notrigger)
904
			{
905
				$result=$this->call_trigger(strtoupper($this->element).'_DELETE_CONTACT', $user);
906
				if ($result < 0) { $this->db->rollback(); return -1; }
907
			}
908
909
			$this->db->commit();
910
			return 1;
911
		}
912
		else
913
		{
914
			$this->error=$this->db->lasterror();
915
			$this->db->rollback();
916
			return -1;
917
		}
918
	}
919
920
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
921
	/**
922
	 *    Delete all links between an object $this and all its contacts
923
	 *
924
	 *	  @param	string	$source		'' or 'internal' or 'external'
925
	 *	  @param	string	$code		Type of contact (code or id)
926
	 *    @return   int					>0 if OK, <0 if KO
927
	 */
928
	function delete_linked_contact($source='',$code='')
929
	{
930
        // phpcs:enable
931
		$temp = array();
932
		$typeContact = $this->liste_type_contact($source,'',0,0,$code);
933
934
		foreach($typeContact as $key => $value)
935
		{
936
			array_push($temp,$key);
937
		}
938
		$listId = implode(",", $temp);
939
940
		$sql = "DELETE FROM ".MAIN_DB_PREFIX."element_contact";
941
		$sql.= " WHERE element_id = ".$this->id;
942
		if ($listId)
943
			$sql.= " AND fk_c_type_contact IN (".$listId.")";
944
945
		dol_syslog(get_class($this)."::delete_linked_contact", LOG_DEBUG);
946
		if ($this->db->query($sql))
0 ignored issues
show
Bug Best Practice introduced by alxarafe
The property db does not exist on Alixar\Base\AlCommonObject. Did you maybe forget to declare it?
Loading history...
947
		{
948
			return 1;
949
		}
950
		else
951
		{
952
			$this->error=$this->db->lasterror();
953
			return -1;
954
		}
955
	}
956
957
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
958
	/**
959
	 *    Get array of all contacts for an object
960
	 *
961
	 *    @param	int			$statut		Status of links to get (-1=all)
962
	 *    @param	string		$source		Source of contact: external or thirdparty (llx_socpeople) or internal (llx_user)
963
	 *    @param	int         $list       0:Return array contains all properties, 1:Return array contains just id
964
	 *    @param    string      $code       Filter on this code of contact type ('SHIPPING', 'BILLING', ...)
965
	 *    @return	array|int		        Array of contacts, -1 if error
966
	 */
967
	function liste_contact($statut=-1,$source='external',$list=0,$code='')
968
	{
969
        // phpcs:enable
970
		global $langs;
971
972
		$tab=array();
973
974
		$sql = "SELECT ec.rowid, ec.statut as statuslink, ec.fk_socpeople as id, ec.fk_c_type_contact";    // This field contains id of llx_socpeople or id of llx_user
975
		if ($source == 'internal') $sql.=", '-1' as socid, t.statut as statuscontact, t.login, t.photo";
976
		if ($source == 'external' || $source == 'thirdparty') $sql.=", t.fk_soc as socid, t.statut as statuscontact";
977
		$sql.= ", t.civility as civility, t.lastname as lastname, t.firstname, t.email";
978
		$sql.= ", tc.source, tc.element, tc.code, tc.libelle";
979
		$sql.= " FROM ".MAIN_DB_PREFIX."c_type_contact tc";
980
		$sql.= ", ".MAIN_DB_PREFIX."element_contact ec";
981
		if ($source == 'internal') $sql.=" LEFT JOIN ".MAIN_DB_PREFIX."user t on ec.fk_socpeople = t.rowid";
982
		if ($source == 'external'|| $source == 'thirdparty') $sql.=" LEFT JOIN ".MAIN_DB_PREFIX."socpeople t on ec.fk_socpeople = t.rowid";
983
		$sql.= " WHERE ec.element_id =".$this->id;
984
		$sql.= " AND ec.fk_c_type_contact=tc.rowid";
985
		$sql.= " AND tc.element='".$this->db->escape($this->element)."'";
0 ignored issues
show
Bug Best Practice introduced by alxarafe
The property db does not exist on Alixar\Base\AlCommonObject. Did you maybe forget to declare it?
Loading history...
986
		if ($code) $sql.= " AND tc.code = '".$this->db->escape($code)."'";
987
		if ($source == 'internal') $sql.= " AND tc.source = 'internal'";
988
		if ($source == 'external' || $source == 'thirdparty') $sql.= " AND tc.source = 'external'";
989
		$sql.= " AND tc.active=1";
990
		if ($statut >= 0) $sql.= " AND ec.statut = '".$statut."'";
991
		$sql.=" ORDER BY t.lastname ASC";
992
993
		dol_syslog(get_class($this)."::liste_contact", LOG_DEBUG);
994
		$resql=$this->db->query($sql);
995
		if ($resql)
996
		{
997
			$num=$this->db->num_rows($resql);
998
			$i=0;
999
			while ($i < $num)
1000
			{
1001
				$obj = $this->db->fetch_object($resql);
1002
1003
				if (! $list)
1004
				{
1005
					$transkey="TypeContact_".$obj->element."_".$obj->source."_".$obj->code;
1006
					$libelle_type=($langs->trans($transkey)!=$transkey ? $langs->trans($transkey) : $obj->libelle);
1007
					$tab[$i]=array('source'=>$obj->source,'socid'=>$obj->socid,'id'=>$obj->id,
1008
								   'nom'=>$obj->lastname,      // For backward compatibility
1009
								   'civility'=>$obj->civility, 'lastname'=>$obj->lastname, 'firstname'=>$obj->firstname, 'email'=>$obj->email, 'login'=>$obj->login, 'photo'=>$obj->photo, 'statuscontact'=>$obj->statuscontact,
1010
								   'rowid'=>$obj->rowid, 'code'=>$obj->code, 'libelle'=>$libelle_type, 'status'=>$obj->statuslink, 'fk_c_type_contact'=>$obj->fk_c_type_contact);
1011
				}
1012
				else
1013
				{
1014
					$tab[$i]=$obj->id;
1015
				}
1016
1017
				$i++;
1018
			}
1019
1020
			return $tab;
1021
		}
1022
		else
1023
		{
1024
			$this->error=$this->db->lasterror();
1025
			dol_print_error($this->db);
1026
			return -1;
1027
		}
1028
	}
1029
1030
1031
	/**
1032
	 * 		Update status of a contact linked to object
1033
	 *
1034
	 * 		@param	int		$rowid		Id of link between object and contact
1035
	 * 		@return	int					<0 if KO, >=0 if OK
1036
	 */
1037
	function swapContactStatus($rowid)
1038
	{
1039
		$sql = "SELECT ec.datecreate, ec.statut, ec.fk_socpeople, ec.fk_c_type_contact,";
1040
		$sql.= " tc.code, tc.libelle";
1041
		//$sql.= ", s.fk_soc";
1042
		$sql.= " FROM (".MAIN_DB_PREFIX."element_contact as ec, ".MAIN_DB_PREFIX."c_type_contact as tc)";
1043
		//$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."socpeople as s ON ec.fk_socpeople=s.rowid";	// Si contact de type external, alors il est lie a une societe
1044
		$sql.= " WHERE ec.rowid =".$rowid;
1045
		$sql.= " AND ec.fk_c_type_contact=tc.rowid";
1046
		$sql.= " AND tc.element = '".$this->db->escape($this->element)."'";
0 ignored issues
show
Bug Best Practice introduced by alxarafe
The property db does not exist on Alixar\Base\AlCommonObject. Did you maybe forget to declare it?
Loading history...
1047
1048
		dol_syslog(get_class($this)."::swapContactStatus", LOG_DEBUG);
1049
		$resql=$this->db->query($sql);
1050
		if ($resql)
1051
		{
1052
			$obj = $this->db->fetch_object($resql);
1053
			$newstatut = ($obj->statut == 4) ? 5 : 4;
1054
			$result = $this->update_contact($rowid, $newstatut);
1055
			$this->db->free($resql);
1056
			return $result;
1057
		}
1058
		else
1059
		{
1060
			$this->error=$this->db->error();
1061
			dol_print_error($this->db);
1062
			return -1;