Passed
Branch develop (5e8dc3)
by
unknown
25:58
created

Don   F

Complexity

Total Complexity 132

Size/Duplication

Total Lines 1058
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 514
dl 0
loc 1058
rs 2
c 1
b 0
f 0
wmc 132

19 Methods

Rating   Name   Duplication   Size   Complexity  
B fetch() 0 78 5
B delete() 0 59 11
F check() 0 78 14
F update() 0 75 18
A initAsSpecimen() 0 50 3
A set_paid() 0 22 4
A set_cancel() 0 17 3
A __construct() 0 3 1
A getLibStatut() 0 3 1
A LibStatut() 0 22 5
A valid_promesse() 0 36 6
F create() 0 105 20
A setValid() 0 3 1
A load_state_board() 0 25 3
A reopen() 0 16 2
A sum_donations() 0 20 2
F getNomUrl() 0 32 16
A info() 0 34 5
D generateDocument() 0 89 12

How to fix   Complexity   

Complex Class

Complex classes like Don often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Don, and based on these observations, apply Extract Interface, too.

1
<?php
2
/* Copyright (C) 2002      Rodolphe Quiedeville <[email protected]>
3
 * Copyright (C) 2004-2008 Laurent Destailleur  <[email protected]>
4
 * Copyright (C) 2009      Regis Houssin        <[email protected]>
5
 * Copyright (C) 2014      Florian Henry        <[email protected]>
6
 * Copyright (C) 2015-2017 Alexandre Spangaro   <[email protected]>
7
 * Copyright (C) 2016      Juanjo Menent        <[email protected]>
8
 * Copyright (C) 2019      Thibault FOUCART     <[email protected]>
9
 * Copyright (C) 2019-2020 Frédéric France      <[email protected]>
10
 *
11
 * This program is free software; you can redistribute it and/or modify
12
 * it under the terms of the GNU General Public License as published by
13
 * the Free Software Foundation; either version 3 of the License, or
14
 * (at your option) any later version.
15
 *
16
 * This program is distributed in the hope that it will be useful,
17
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19
 * GNU General Public License for more details.
20
 *
21
 * You should have received a copy of the GNU General Public License
22
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
23
 */
24
25
/**
26
 *   	\file       htdocs/don/class/don.class.php
27
 *		\ingroup    Donation
28
 *		\brief      File of class to manage donations
29
 */
30
31
require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
32
33
34
/**
35
 *		Class to manage donations
36
 */
37
class Don extends CommonObject
38
{
39
	/**
40
	 * @var string ID to identify managed object
41
	 */
42
	public $element = 'don';
43
44
	/**
45
	 * @var string Name of table without prefix where object is stored
46
	 */
47
	public $table_element = 'don';
48
49
	/**
50
	 * @var int Field with ID of parent key if this field has a parent
51
	 */
52
	public $fk_element = 'fk_donation';
53
54
	/**
55
	 * 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
56
	 * @var int
57
	 */
58
	public $ismultientitymanaged = 1;
59
60
	/**
61
	 * @var string String with name of icon for object don. Must be the part after the 'object_' into object_myobject.png
62
	 */
63
	public $picto = 'donation';
64
65
	/**
66
	 * @var string Date of the donation
67
	 */
68
	public $date;
69
70
	/**
71
	 * amount of donation
72
	 * @var double
73
	 */
74
	public $amount;
75
76
	/**
77
	 * @var string Thirdparty name
78
	 */
79
	public $societe;
80
81
	/**
82
	 * @var string Address
83
	 */
84
	public $address;
85
86
	/**
87
	 * @var string Zipcode
88
	 */
89
	public $zip;
90
91
	/**
92
	 * @var string Town
93
	 */
94
	public $town;
95
96
	/**
97
	 * @var string Email
98
	 */
99
	public $email;
100
101
	/**
102
	 * @var int 0 or 1
103
	 */
104
	public $public;
105
106
	/**
107
	 * @var int project ID
108
	 */
109
	public $fk_project;
110
111
	/**
112
	 * @var int type payment ID
113
	 */
114
	public $fk_typepayment;
115
116
	public $num_payment;
117
	public $date_valid;
118
119
	/**
120
	 * @var int payment mode id
121
	 */
122
	public $modepaymentid = 0;
123
124
	/**
125
	 * @var array Array of status label
126
	 */
127
	public $labelStatus;
128
129
	/**
130
	 * @var array Array of status label short
131
	 */
132
	public $labelStatusShort;
133
134
135
	const STATUS_DRAFT = 0;
136
	const STATUS_VALIDATED = 1;
137
	const STATUS_PAID = 2;
138
	const STATUS_CANCELED = -1;
139
140
141
	/**
142
	 *  Constructor
143
	 *
144
	 *  @param	DoliDB	$db 	Database handler
145
	 */
146
	public function __construct($db)
147
	{
148
		 $this->db = $db;
149
	}
150
151
152
	/**
153
	 * 	Returns the donation status label (draft, valid, abandoned, paid)
154
	 *
155
	 *  @param  int		$mode          	0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto
156
	 *  @return string        			Label of status
157
	 */
158
	public function getLibStatut($mode = 0)
159
	{
160
		return $this->LibStatut($this->statut, $mode);
161
	}
162
163
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
164
	/**
165
	 *  Return the label of a given status
166
	 *
167
	 *  @param	int		$status        Id statut
168
	 *  @param  int		$mode          0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto
169
	 *  @return string 			       Label of status
170
	 */
171
	public function LibStatut($status, $mode = 0)
172
	{
173
		// phpcs:enable
174
		if (empty($this->labelStatus) || empty($this->labelStatusShort))
175
		{
176
			global $langs;
177
			$langs->load("donations");
178
			$this->labelStatus[-1] = $langs->transnoentitiesnoconv("Canceled");
179
			$this->labelStatus[0] = $langs->transnoentitiesnoconv("DonationStatusPromiseNotValidated");
180
			$this->labelStatus[1] = $langs->transnoentitiesnoconv("DonationStatusPromiseValidated");
181
			$this->labelStatus[2] = $langs->transnoentitiesnoconv("DonationStatusPaid");
182
			$this->labelStatusShort[-1] = $langs->transnoentitiesnoconv("Canceled");
183
			$this->labelStatusShort[0] = $langs->transnoentitiesnoconv("DonationStatusPromiseNotValidatedShort");
184
			$this->labelStatusShort[1] = $langs->transnoentitiesnoconv("DonationStatusPromiseValidatedShort");
185
			$this->labelStatusShort[2] = $langs->transnoentitiesnoconv("DonationStatusPaidShort");
186
		}
187
188
		$statusType = 'status'.$status;
189
		if ($status == self::STATUS_CANCELED) $statusType = 'status9';
190
		if ($status == self::STATUS_PAID) $statusType = 'status6';
191
192
		return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
193
	}
194
195
196
	/**
197
	 *  Initialise an instance with random values.
198
	 *  Used to build previews or test instances.
199
	 *	id must be 0 if object instance is a specimen.
200
	 *
201
	 *  @return	void
202
	 */
203
	public function initAsSpecimen()
204
	{
205
		global $conf, $user, $langs;
206
207
		$now = dol_now();
208
209
		// Charge tableau des id de societe socids
210
		$socids = array();
211
212
		$sql = "SELECT rowid";
213
		$sql .= " FROM ".MAIN_DB_PREFIX."societe";
214
		$sql .= " WHERE client IN (1, 3)";
215
		$sql .= " AND entity = ".$conf->entity;
216
		$sql .= " LIMIT 10";
217
218
		$resql = $this->db->query($sql);
219
		if ($resql)
220
		{
221
			$num_socs = $this->db->num_rows($resql);
222
			$i = 0;
223
			while ($i < $num_socs)
224
			{
225
				$i++;
226
227
				$row = $this->db->fetch_row($resql);
228
				$socids[$i] = $row[0];
229
			}
230
		}
231
232
		// Initialise parametres
233
		$this->id = 0;
234
		$this->ref = 'SPECIMEN';
235
		$this->specimen = 1;
236
		$this->lastname = 'Doe';
237
		$this->firstname = 'John';
238
		$this->socid = 1;
239
		$this->date = $now;
240
		$this->date_valid = $now;
241
		$this->amount = 100.90;
242
		$this->public = 1;
243
		$this->societe = 'The Company';
244
		$this->address = 'Twist road';
245
		$this->zip = '99999';
246
		$this->town = 'Town';
247
		$this->note_private = 'Private note';
248
		$this->note_public = 'Public note';
249
		$this->email = '[email protected]';
250
		$this->phone = '0123456789';
251
		$this->phone_mobile = '0606060606';
252
		$this->statut = 1;
253
	}
254
255
256
	/**
257
	 *	Check params and init ->errors array.
258
	 *  TODO This function seems to not be used by core code.
259
	 *
260
	 *	@param	int	$minimum	Minimum
261
	 *	@return	int				0 if KO, >0 if OK
262
	 */
263
	public function check($minimum = 0)
264
	{
265
		global $langs;
266
		$langs->load('main');
267
		$langs->load('companies');
268
269
		$error_string = array();
270
		$err = 0;
271
272
		if (dol_strlen(trim($this->societe)) == 0)
273
		{
274
			if ((dol_strlen(trim($this->lastname)) + dol_strlen(trim($this->firstname))) == 0)
275
			{
276
				$error_string[] = $langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Company').'/'.$langs->transnoentitiesnoconv('Firstname').'-'.$langs->transnoentitiesnoconv('Lastname'));
277
				$err++;
278
			}
279
		}
280
281
		if (dol_strlen(trim($this->address)) == 0)
282
		{
283
			$error_string[] = $langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Address'));
284
			$err++;
285
		}
286
287
		if (dol_strlen(trim($this->zip)) == 0)
288
		{
289
			$error_string[] = $langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Zip'));
290
			$err++;
291
		}
292
293
		if (dol_strlen(trim($this->town)) == 0)
294
		{
295
			$error_string[] = $langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Town'));
296
			$err++;
297
		}
298
299
		if (dol_strlen(trim($this->email)) == 0)
300
		{
301
			$error_string[] = $langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('EMail'));
302
			$err++;
303
		}
304
305
		$this->amount = trim($this->amount);
306
307
		$map = range(0, 9);
308
		$len = dol_strlen($this->amount);
309
		for ($i = 0; $i < $len; $i++)
310
		{
311
			if (!isset($map[substr($this->amount, $i, 1)]))
312
			{
313
				$error_string[] = $langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Amount'));
314
				$err++;
315
				$amount_invalid = 1;
316
				break;
317
			}
318
		}
319
320
		if (!$amount_invalid)
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $amount_invalid does not seem to be defined for all execution paths leading up to this point.
Loading history...
321
		{
322
			if ($this->amount == 0)
323
			{
324
				$error_string[] = $langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Amount'));
325
				$err++;
326
			} else {
327
				if ($this->amount < $minimum && $minimum > 0)
328
				{
329
					$error_string[] = $langs->trans('MinimumAmount', $langs->transnoentitiesnoconv('$minimum'));
330
					$err++;
331
				}
332
			}
333
		}
334
335
		if ($err)
336
		{
337
			$this->errors = $error_string;
338
			return 0;
339
		} else {
340
			return 1;
341
		}
342
	}
343
344
	/**
345
	 * Create donation record into database
346
	 *
347
	 * @param	User	$user		User who created the donation
348
	 * @param	int		$notrigger	Disable triggers
349
	 * @return  int  		        <0 if KO, id of created donation if OK
350
	 * TODO    add numbering module for Ref
351
	 */
352
	public function create($user, $notrigger = 0)
353
	{
354
		global $conf, $langs;
355
356
		$error = 0;
357
		$ret = 0;
358
		$now = dol_now();
359
360
		// Clean parameters
361
		$this->address = ($this->address > 0 ? $this->address : $this->address);
362
		$this->zip = ($this->zip > 0 ? $this->zip : $this->zip);
363
		$this->town = ($this->town > 0 ? $this->town : $this->town);
364
		$this->country_id = ($this->country_id > 0 ? $this->country_id : $this->country_id);
365
		$this->country = ($this->country ? $this->country : $this->country);
366
367
		$this->db->begin();
368
369
		$sql = "INSERT INTO ".MAIN_DB_PREFIX."don (";
370
		$sql .= "datec";
371
		$sql .= ", entity";
372
		$sql .= ", amount";
373
		$sql .= ", fk_payment";
374
		$sql .= ", fk_soc";
375
		$sql .= ", firstname";
376
		$sql .= ", lastname";
377
		$sql .= ", societe";
378
		$sql .= ", address";
379
		$sql .= ", zip";
380
		$sql .= ", town";
381
		$sql .= ", fk_country";
382
		$sql .= ", public";
383
		$sql .= ", fk_projet";
384
		$sql .= ", note_private";
385
		$sql .= ", note_public";
386
		$sql .= ", fk_user_author";
387
		$sql .= ", fk_user_valid";
388
		$sql .= ", datedon";
389
		$sql .= ", email";
390
		$sql .= ", phone";
391
		$sql .= ", phone_mobile";
392
		$sql .= ") VALUES (";
393
		$sql .= "'".$this->db->idate($now)."'";
394
		$sql .= ", ".$conf->entity;
395
		$sql .= ", ".price2num($this->amount);
396
		$sql .= ", ".($this->modepaymentid ? $this->modepaymentid : "null");
397
		$sql .= ", ".($this->socid > 0 ? $this->socid : "null");
398
		$sql .= ", '".$this->db->escape($this->firstname)."'";
399
		$sql .= ", '".$this->db->escape($this->lastname)."'";
400
		$sql .= ", '".$this->db->escape($this->societe)."'";
401
		$sql .= ", '".$this->db->escape($this->address)."'";
402
		$sql .= ", '".$this->db->escape($this->zip)."'";
403
		$sql .= ", '".$this->db->escape($this->town)."'";
404
		$sql .= ", ".(int) ($this->country_id > 0 ? $this->country_id : 0);
405
		$sql .= ", ".(int) $this->public;
406
		$sql .= ", ".($this->fk_project > 0 ? (int) $this->fk_project : "null");
407
	   	$sql .= ", ".(!empty($this->note_private) ? ("'".$this->db->escape($this->note_private)."'") : "NULL");
408
		$sql .= ", ".(!empty($this->note_public) ? ("'".$this->db->escape($this->note_public)."'") : "NULL");
409
		$sql .= ", ".$user->id;
410
		$sql .= ", null";
411
		$sql .= ", '".$this->db->idate($this->date)."'";
412
		$sql .= ", '".$this->db->escape(trim($this->email))."'";
413
		$sql .= ", '".$this->db->escape(trim($this->phone))."'";
414
		$sql .= ", '".$this->db->escape(trim($this->phone_mobile))."'";
415
		$sql .= ")";
416
417
		$resql = $this->db->query($sql);
418
		if ($resql)
419
		{
420
			$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."don");
421
			$ret = $this->id;
422
423
			if (!$notrigger)
424
			{
425
				// Call trigger
426
				$result = $this->call_trigger('DON_CREATE', $user);
427
				if ($result < 0) { $error++; }
428
				// End call triggers
429
			}
430
		} else {
431
			$this->error = $this->db->lasterror();
432
			$this->errno = $this->db->lasterrno();
433
			$error++;
434
		}
435
436
		// Update extrafield
437
		if (!$error) {
438
			$result = $this->insertExtraFields();
439
			if ($result < 0) {
440
				$error++;
441
			}
442
		}
443
444
		if (!$error && !empty($conf->global->MAIN_DISABLEDRAFTSTATUS))
445
		{
446
			//$res = $this->setValid($user);
447
			//if ($res < 0) $error++;
448
		}
449
450
		if (!$error)
451
		{
452
			$this->db->commit();
453
			return $ret;
454
		} else {
455
			$this->db->rollback();
456
			return -1;
457
		}
458
	}
459
460
	/**
461
	 *  Update a donation record
462
	 *
463
	 *  @param 		User	$user   Objet utilisateur qui met a jour le don
464
	 *  @param      int		$notrigger	Disable triggers
465
	 *  @return     int      		>0 if OK, <0 if KO
466
	 */
467
	public function update($user, $notrigger = 0)
468
	{
469
		global $langs, $conf;
470
471
		$error = 0;
472
473
		// Clean parameters
474
		$this->address = ($this->address > 0 ? $this->address : $this->address);
475
		$this->zip = ($this->zip > 0 ? $this->zip : $this->zip);
476
		$this->town = ($this->town > 0 ? $this->town : $this->town);
477
		$this->country_id = ($this->country_id > 0 ? $this->country_id : $this->country_id);
478
		$this->country = ($this->country ? $this->country : $this->country);
479
480
		$this->db->begin();
481
482
		$sql = "UPDATE ".MAIN_DB_PREFIX."don SET ";
483
		$sql .= "amount = ".price2num($this->amount);
484
		$sql .= ",fk_payment = ".($this->modepaymentid ? $this->modepaymentid : "null");
485
		$sql .= ",firstname = '".$this->db->escape($this->firstname)."'";
486
		$sql .= ",lastname='".$this->db->escape($this->lastname)."'";
487
		$sql .= ",societe='".$this->db->escape($this->societe)."'";
488
		$sql .= ",address='".$this->db->escape($this->address)."'";
489
		$sql .= ",zip='".$this->db->escape($this->zip)."'";
490
		$sql .= ",town='".$this->db->escape($this->town)."'";
491
		$sql .= ",fk_country = ".($this->country_id > 0 ? $this->country_id : '0');
492
		$sql .= ",public=".$this->public;
493
		$sql .= ",fk_projet=".($this->fk_project > 0 ? $this->fk_project : 'null');
494
		$sql .= ",note_private=".(!empty($this->note_private) ? ("'".$this->db->escape($this->note_private)."'") : "NULL");
495
		$sql .= ",note_public=".(!empty($this->note_public) ? ("'".$this->db->escape($this->note_public)."'") : "NULL");
496
		$sql .= ",datedon='".$this->db->idate($this->date)."'";
497
		$sql .= ",date_valid=".($this->date_valid ? "'".$this->db->idate($this->date)."'" : "null");
498
		$sql .= ",email='".$this->db->escape(trim($this->email))."'";
499
		$sql .= ",phone='".$this->db->escape(trim($this->phone))."'";
500
		$sql .= ",phone_mobile='".$this->db->escape(trim($this->phone_mobile))."'";
501
		$sql .= ",fk_statut=".$this->statut;
502
		$sql .= " WHERE rowid = ".$this->id;
503
504
		dol_syslog(get_class($this)."::Update", LOG_DEBUG);
505
		$resql = $this->db->query($sql);
506
		if ($resql)
507
		{
508
			if (!$notrigger)
509
			{
510
				// Call trigger
511
				$result = $this->call_trigger('DON_MODIFY', $user);
512
				if ($result < 0) { $error++; }
513
				// End call triggers
514
			}
515
516
			// Update extrafield
517
			if (!$error)
518
			{
519
			   	$result = $this->insertExtraFields();
520
			   	if ($result < 0)
521
			   	{
522
			   		$error++;
523
			   	}
524
			}
525
526
			if (!$error)
527
			{
528
				$this->db->commit();
529
				$result = 1;
530
			} else {
531
				$this->db->rollback();
532
				$result = -1;
533
			}
534
		} else {
535
			$this->error = $this->db->lasterror();
536
			$this->errors[] = $this->error;
537
			$this->db->rollback();
538
			dol_syslog(get_class($this)."::Update error -2 ".$this->error, LOG_ERR);
539
			$result = -2;
540
		}
541
		return $result;
542
	}
543
544
	/**
545
	 *    Delete a donation from database
546
	 *
547
	 *    @param       User		$user            User
548
	 *    @param       int		$notrigger       Disable triggers
549
	 *    @return      int       			      <0 if KO, 0 if not possible, >0 if OK
550
	 */
551
	public function delete($user, $notrigger = 0)
552
	{
553
		global $user, $conf, $langs;
554
		require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
555
556
		$error = 0;
557
558
		$this->db->begin();
559
560
   		if (!$error && !$notrigger) {
561
			// Call trigger
562
			$result = $this->call_trigger('DON_DELETE', $user);
563
564
			if ($result < 0) {
565
				$error++;
566
			}
567
			// End call triggers
568
		}
569
570
		// Delete donation
571
		if (!$error)
572
		{
573
			$sql = "DELETE FROM ".MAIN_DB_PREFIX."don_extrafields";
574
			$sql .= " WHERE fk_object=".$this->id;
575
576
			$resql = $this->db->query($sql);
577
			if (!$resql)
578
			{
579
				$this->errors[] = $this->db->lasterror();
580
				$error++;
581
			}
582
		}
583
584
		if (!$error)
585
		{
586
			$sql = "DELETE FROM ".MAIN_DB_PREFIX."don";
587
			$sql .= " WHERE rowid=".$this->id;
588
589
			$resql = $this->db->query($sql);
590
			if (!$resql)
591
			{
592
				$this->errors[] = $this->db->lasterror();
593
				$error++;
594
			}
595
		}
596
597
		if (!$error)
598
		{
599
			$this->db->commit();
600
			return 1;
601
		} else {
602
			foreach ($this->errors as $errmsg)
603
			{
604
				dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
605
				$this->error .= ($this->error ? ', '.$errmsg : $errmsg);
606
			}
607
			dol_syslog(get_class($this)."::delete ".$this->error, LOG_ERR);
608
			$this->db->rollback();
609
			return -1;
610
		}
611
	}
612
613
	/**
614
	 *      Load donation from database
615
	 *
616
	 *      @param      int		$id      Id of donation to load
617
	 *      @param      string	$ref        Ref of donation to load
618
	 *      @return     int      			<0 if KO, >0 if OK
619
	 */
620
	public function fetch($id, $ref = '')
621
	{
622
		global $conf;
623
624
		$sql = "SELECT d.rowid, d.datec, d.date_valid, d.tms as datem, d.datedon,";
625
		$sql .= " d.fk_soc as socid,d.firstname, d.lastname, d.societe, d.amount, d.fk_statut, d.address, d.zip, d.town, ";
626
		$sql .= " d.fk_country, d.country as country_olddata, d.public, d.amount, d.fk_payment, d.paid, d.note_private, d.note_public, d.email, d.phone, ";
627
		$sql .= " d.phone_mobile, d.fk_projet as fk_project, d.model_pdf,";
628
		$sql .= " p.ref as project_ref,";
629
		$sql .= " cp.libelle as payment_label, cp.code as payment_code,";
630
		$sql .= " c.code as country_code, c.label as country";
631
		$sql .= " FROM ".MAIN_DB_PREFIX."don as d";
632
		$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."projet as p ON p.rowid = d.fk_projet";
633
		$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as cp ON cp.id = d.fk_payment";
634
		$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_country as c ON d.fk_country = c.rowid";
635
		$sql .= " WHERE d.entity IN (".getEntity('donation').")";
636
		if (!empty($id))
637
		{
638
			$sql .= " AND d.rowid=".$id;
639
		} elseif (!empty($ref))
640
		{
641
			$sql .= " AND d.ref='".$this->db->escape($ref)."'";
642
		}
643
644
		dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
645
		$resql = $this->db->query($sql);
646
		if ($resql)
647
		{
648
			if ($this->db->num_rows($resql))
649
			{
650
				$obj = $this->db->fetch_object($resql);
651
652
				$this->id                 = $obj->rowid;
653
				$this->ref                = $obj->rowid;
654
				$this->date_creation      = $this->db->jdate($obj->datec);
655
				$this->datec              = $this->db->jdate($obj->datec);
656
				$this->date_validation    = $this->db->jdate($obj->date_valid);
657
				$this->date_valid = $this->db->jdate($obj->date_valid);
658
				$this->date_modification  = $this->db->jdate($obj->datem);
659
				$this->datem              = $this->db->jdate($obj->datem);
660
				$this->date               = $this->db->jdate($obj->datedon);
661
				$this->socid              = $obj->socid;
662
				$this->firstname          = $obj->firstname;
663
				$this->lastname           = $obj->lastname;
664
				$this->societe            = $obj->societe;
665
				$this->statut             = $obj->fk_statut;
666
				$this->address            = $obj->address;
667
				$this->zip                = $obj->zip;
668
				$this->town               = $obj->town;
669
				$this->country_id         = $obj->fk_country;
670
				$this->country_code       = $obj->country_code;
671
				$this->country            = $obj->country;
672
				$this->country_olddata    = $obj->country_olddata; // deprecated
673
				$this->email              = $obj->email;
674
				$this->phone              = $obj->phone;
675
				$this->phone_mobile       = $obj->phone_mobile;
676
				$this->project            = $obj->project_ref;
677
				$this->fk_projet          = $obj->fk_project; // deprecated
678
				$this->fk_project         = $obj->fk_project;
679
				$this->public             = $obj->public;
680
				$this->mode_reglement_id  = $obj->fk_payment;
681
				$this->mode_reglement_code = $obj->payment_code;
682
				$this->mode_reglement     = $obj->payment_label;
683
				$this->paid = $obj->paid;
684
				$this->amount             = $obj->amount;
685
				$this->note_private	      = $obj->note_private;
686
				$this->note_public = $obj->note_public;
687
				$this->model_pdf          = $obj->model_pdf;
688
				$this->modelpdf           = $obj->model_pdf; // deprecated
689
690
				// Retrieve all extrafield
691
				// fetch optionals attributes and labels
692
				$this->fetch_optionals();
693
			}
694
			return 1;
695
		} else {
696
			dol_print_error($this->db);
697
			return -1;
698
		}
699
	}
700
701
	/**
702
	 *	Validate a intervention
703
	 *
704
	 *	@param		User		$user		User that validate
705
	 *  @param		int			$notrigger	1=Does not execute triggers, 0= execute triggers
706
	 *	@return		int						<0 if KO, >0 if OK
707
	 */
708
	public function setValid($user, $notrigger = 0)
709
	{
710
		return $this->valid_promesse($this->id, $user->id, $notrigger);
711
	}
712
713
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
714
	/**
715
	 *    Validate a promise of donation
716
	 *
717
	 *    @param	int		$id   		id of donation
718
	 *    @param  	int		$userid  	User who validate the donation/promise
719
	 *    @param	int		$notrigger	Disable triggers
720
	 *    @return   int     			<0 if KO, >0 if OK
721
	 */
722
	public function valid_promesse($id, $userid, $notrigger = 0)
723
	{
724
		// phpcs:enable
725
		global $langs, $user;
726
727
		$error = 0;
728
729
		$this->db->begin();
730
731
		$sql = "UPDATE ".MAIN_DB_PREFIX."don SET fk_statut = 1, fk_user_valid = ".$userid." WHERE rowid = ".$id." AND fk_statut = 0";
732
733
		$resql = $this->db->query($sql);
734
		if ($resql)
735
		{
736
			if ($this->db->affected_rows($resql))
737
			{
738
				if (!$notrigger)
739
				{
740
					// Call trigger
741
					$result = $this->call_trigger('DON_VALIDATE', $user);
742
					if ($result < 0) { $error++; }
743
					// End call triggers
744
				}
745
			}
746
		} else {
747
			$error++;
748
			$this->error = $this->db->lasterror();
749
		}
750
751
		if (!$error)
752
		{
753
			$this->db->commit();
754
			return 1;
755
		} else {
756
			$this->db->rollback();
757
			return -1;
758
		}
759
	}
760
761
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
762
	/**
763
	 *    Classify the donation as paid, the donation was received
764
	 *
765
	 *    @param	int		$id           	    id of donation
766
	 *    @param    int		$modepayment   	    mode of payment
767
	 *    @return   int      					<0 if KO, >0 if OK
768
	 */
769
	public function set_paid($id, $modepayment = 0)
770
	{
771
		// phpcs:enable
772
		$sql = "UPDATE ".MAIN_DB_PREFIX."don SET fk_statut = 2";
773
		if ($modepayment)
774
		{
775
			$sql .= ", fk_payment=".$modepayment;
776
		}
777
		$sql .= " WHERE rowid = ".$id." AND fk_statut = 1";
778
779
		$resql = $this->db->query($sql);
780
		if ($resql)
781
		{
782
			if ($this->db->affected_rows($resql))
783
			{
784
				return 1;
785
			} else {
786
				return 0;
787
			}
788
		} else {
789
			dol_print_error($this->db);
790
			return -1;
791
		}
792
	}
793
794
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
795
	/**
796
	 *    Set donation to status cancelled
797
	 *
798
	 *    @param	int		$id   	    id of donation
799
	 *    @return   int     			<0 if KO, >0 if OK
800
	 */
801
	public function set_cancel($id)
802
	{
803
		// phpcs:enable
804
		$sql = "UPDATE ".MAIN_DB_PREFIX."don SET fk_statut = -1 WHERE rowid = ".$id;
805
806
		$resql = $this->db->query($sql);
807
		if ($resql)
808
		{
809
			if ($this->db->affected_rows($resql))
810
			{
811
				return 1;
812
			} else {
813
				return 0;
814
			}
815
		} else {
816
			dol_print_error($this->db);
817
			return -1;
818
		}
819
	}
820
821
	/**
822
	 *	Set cancel status
823
	 *
824
	 *	@param	User	$user			Object user that modify
825
	 *  @param	int		$notrigger		1=Does not execute triggers, 0=Execute triggers
826
	 *	@return	int						<0 if KO, 0=Nothing done, >0 if OK
827
	 */
828
	public function reopen($user, $notrigger = 0)
829
	{
830
		// Protection
831
		if ($this->statut != self::STATUS_CANCELED)
832
		{
833
			return 0;
834
		}
835
836
		/*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->bom->write))
837
		 || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->bom->bom_advance->validate))))
838
		 {
839
		 $this->error='Permission denied';
840
		 return -1;
841
		 }*/
842
843
		return $this->setStatusCommon($user, self::STATUS_VALIDATED, $notrigger, 'DON_REOPEN');
844
	}
845
846
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
847
	/**
848
	 *  Sum of donations
849
	 *
850
	 *	@param	string	$param	1=promesses de dons validees , 2=xxx, 3=encaisses
851
	 *	@return	int				Summ of donations
852
	 */
853
	public function sum_donations($param)
854
	{
855
		// phpcs:enable
856
		global $conf;
857
858
		$result = 0;
859
860
		$sql = "SELECT sum(amount) as total";
861
		$sql .= " FROM ".MAIN_DB_PREFIX."don";
862
		$sql .= " WHERE fk_statut = ".$param;
863
		$sql .= " AND entity = ".$conf->entity;
864
865
		$resql = $this->db->query($sql);
866
		if ($resql)
867
		{
868
			$obj = $this->db->fetch_object($resql);
869
			$result = $obj->total;
870
		}
871
872
		return $result;
873
	}
874
875
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
876
	/**
877
	 *	Charge indicateurs this->nb pour le tableau de bord
878
	 *
879
	 *	@return     int         <0 if KO, >0 if OK
880
	 */
881
	public function load_state_board()
882
	{
883
		// phpcs:enable
884
		global $conf;
885
886
		$this->nb = array();
887
888
		$sql = "SELECT count(d.rowid) as nb";
889
		$sql .= " FROM ".MAIN_DB_PREFIX."don as d";
890
		$sql .= " WHERE d.fk_statut > 0";
891
		$sql .= " AND d.entity IN (".getEntity('donation').")";
892
893
		$resql = $this->db->query($sql);
894
		if ($resql)
895
		{
896
			while ($obj = $this->db->fetch_object($resql))
897
			{
898
				$this->nb["donations"] = $obj->nb;
899
			}
900
			$this->db->free($resql);
901
			return 1;
902
		} else {
903
			dol_print_error($this->db);
904
			$this->error = $this->db->error();
905
			return -1;
906
		}
907
	}
908
909
	/**
910
	 *	Return clicable name (with picto eventually)
911
	 *
912
	 *	@param	int		$withpicto					0=No picto, 1=Include picto into link, 2=Only picto
913
	 *	@param	int  	$notooltip					1=Disable tooltip
914
	 *	@param	string	$moretitle					Add more text to title tooltip
915
	 *  @param  int     $save_lastsearch_value    	-1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
916
	 *	@return	string								Chaine avec URL
917
	 */
918
	public function getNomUrl($withpicto = 0, $notooltip = 0, $moretitle = '', $save_lastsearch_value = -1)
919
	{
920
		global $conf, $langs;
921
922
		if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips
923
924
		$result = '';
925
		$label = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Donation").'</u>';
926
		if (isset($this->status)) {
927
			$label .= ' '.$this->getLibStatut(5);
928
		}
929
		if (!empty($this->id)) {
930
			$label .= '<br><b>'.$langs->trans('Ref').':</b> '.$this->id;
931
			$label .= '<br><b>'.$langs->trans('Date').':</b> '.dol_print_date($this->date, 'day');
932
		}
933
		if ($moretitle) $label .= ' - '.$moretitle;
934
935
		$url = DOL_URL_ROOT.'/don/card.php?id='.$this->id;
936
937
	   	$add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
938
	   	if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) $add_save_lastsearch_values = 1;
939
	   	if ($add_save_lastsearch_values) $url .= '&save_lastsearch_values=1';
940
941
		$linkstart = '<a href="'.$url.'" title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip">';
942
		$linkend = '</a>';
943
944
		$result .= $linkstart;
945
		if ($withpicto) $result .= img_object(($notooltip ? '' : $label), $this->picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
946
		if ($withpicto != 2) $result .= $this->ref;
947
		$result .= $linkend;
948
949
		return $result;
950
	}
951
952
	/**
953
	 * Information on record
954
	 *
955
	 * @param	int		$id      Id of record
956
	 * @return	void
957
	 */
958
	public function info($id)
959
	{
960
		$sql = 'SELECT d.rowid, d.datec, d.fk_user_author, d.fk_user_valid,';
961
		$sql .= ' d.tms';
962
		$sql .= ' FROM '.MAIN_DB_PREFIX.'don as d';
963
		$sql .= ' WHERE d.rowid = '.$id;
964
965
		dol_syslog(get_class($this).'::info', LOG_DEBUG);
966
		$result = $this->db->query($sql);
967
968
		if ($result)
969
		{
970
			if ($this->db->num_rows($result))
971
			{
972
				$obj = $this->db->fetch_object($result);
973
				$this->id = $obj->rowid;
974
				if ($obj->fk_user_author)
975
				{
976
					$cuser = new User($this->db);
977
					$cuser->fetch($obj->fk_user_author);
978
					$this->user_creation = $cuser;
979
				}
980
				if ($obj->fk_user_valid)
981
				{
982
					$vuser = new User($this->db);
983
					$vuser->fetch($obj->fk_user_valid);
984
					$this->user_modification = $vuser;
985
				}
986
				$this->date_creation     = $this->db->jdate($obj->datec);
987
				$this->date_modification = $this->db->jdate($obj->tms);
988
			}
989
			$this->db->free($result);
990
		} else {
991
			dol_print_error($this->db);
992
		}
993
	}
994
995
996
	/**
997
	 *  Create a document onto disk according to template module.
998
	 *
999
	 *  @param	    string		$modele			Force template to use ('' to not force)
1000
	 *  @param		Translate	$outputlangs	objet lang a utiliser pour traduction
1001
	 *  @param      int			$hidedetails    Hide details of lines
1002
	 *  @param      int			$hidedesc       Hide description
1003
	 *  @param      int			$hideref        Hide ref
1004
	 *  @return     int         				0 if KO, 1 if OK
1005
	 */
1006
	public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0)
1007
	{
1008
		global $conf, $langs;
1009
1010
		$langs->load("bills");
1011
1012
		if (!dol_strlen($modele)) {
1013
			$modele = 'html_cerfafr';
1014
1015
			if ($this->model_pdf) {
1016
				$modele = $this->model_pdf;
1017
			} elseif (!empty($conf->global->DON_ADDON_MODEL)) {
1018
				$modele = $conf->global->DON_ADDON_MODEL;
1019
			}
1020
		}
1021
1022
		$modelpath = "core/modules/dons/";
1023
1024
		// TODO Restore use of commonGenerateDocument instead of dedicated code here
1025
		//return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref);
1026
1027
		// Increase limit for PDF build
1028
		$err = error_reporting();
1029
		error_reporting(0);
1030
		@set_time_limit(120);
1031
		error_reporting($err);
1032
1033
		$srctemplatepath = '';
1034
1035
		// If selected modele is a filename template (then $modele="modelname:filename")
1036
		$tmp = explode(':', $modele, 2);
1037
		if (!empty($tmp[1]))
1038
		{
1039
			$modele = $tmp[0];
1040
			$srctemplatepath = $tmp[1];
1041
		}
1042
1043
		// Search template files
1044
		$file = ''; $classname = ''; $filefound = 0;
1045
		$dirmodels = array('/');
1046
		if (is_array($conf->modules_parts['models'])) $dirmodels = array_merge($dirmodels, $conf->modules_parts['models']);
1047
		foreach ($dirmodels as $reldir)
1048
		{
1049
			foreach (array('html', 'doc', 'pdf') as $prefix)
1050
			{
1051
				$file = $prefix."_".preg_replace('/^html_/', '', $modele).".modules.php";
1052
1053
				// On verifie l'emplacement du modele
1054
				$file = dol_buildpath($reldir."core/modules/dons/".$file, 0);
1055
				if (file_exists($file))
1056
				{
1057
					$filefound = 1;
1058
					$classname = $prefix.'_'.$modele;
1059
					break;
1060
				}
1061
			}
1062
			if ($filefound) break;
1063
		}
1064
1065
		// Charge le modele
1066
		if ($filefound)
1067
		{
1068
			require_once $file;
1069
1070
			$object = $this;
1071
1072
			$classname = $modele;
1073
			$obj = new $classname($this->db);
1074
1075
			// We save charset_output to restore it because write_file can change it if needed for
1076
			// output format that does not support UTF8.
1077
			$sav_charset_output = $outputlangs->charset_output;
1078
			if ($obj->write_file($object, $outputlangs, $srctemplatepath, $hidedetails, $hidedesc, $hideref) > 0)
1079
			{
1080
				$outputlangs->charset_output = $sav_charset_output;
1081
1082
				// we delete preview files
1083
				require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1084
				dol_delete_preview($object);
1085
				return 1;
1086
			} else {
1087
				$outputlangs->charset_output = $sav_charset_output;
1088
				dol_syslog("Erreur dans don_create");
1089
				dol_print_error($this->db, $obj->error);
1090
				return 0;
1091
			}
1092
		} else {
1093
			print $langs->trans("Error")." ".$langs->trans("ErrorFileDoesNotExists", $file);
1094
			return 0;
1095
		}
1096
	}
1097
}
1098