Passed
Push — EXTRACT_CLASSES ( 231cec...0382f2 )
by Rafael
65:54 queued 05:18
created

Adherent   F

Complexity

Total Complexity 507

Size/Duplication

Total Lines 3245
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 1739
dl 0
loc 3245
rs 0.8
c 0
b 0
f 0
wmc 507

42 Methods

Rating   Name   Duplication   Size   Complexity  
F fetch() 0 137 17
A hasDelay() 0 15 3
A fetch_name() 0 18 3
A fetch_subscriptions() 0 55 4
D makeSubstitution() 0 64 37
F delete() 0 80 14
A loadStateBoard() 0 22 3
A send_an_email() 0 6 1
A resiliate() 0 38 4
A fetch_login() 0 17 3
C setPassword() 0 87 14
A getLibStatut() 0 3 1
A fetchPartnerships() 0 10 1
A _load_ldap_dn() 0 15 4
A getNbOfEMailings() 0 17 2
A setThirdPartyId() 0 28 4
F getNomUrl() 0 115 41
C getKanbanView() 0 33 10
B subscription() 0 57 6
A getCivilityLabel() 0 10 3
B add_to_abo() 0 42 11
F create() 0 117 20
B del_to_abo() 0 42 10
F sendReminderForExpiredSubscription() 0 243 33
B sendEmail() 0 36 6
A update_end_date() 0 40 4
F update() 0 259 68
B load_board() 0 70 9
A setUserId() 0 32 4
C getTooltipContentArray() 0 50 12
A exclude() 0 36 4
F subscriptionComplementaryActions() 0 247 51
A validate() 0 43 4
A setCategories() 0 4 1
F _load_ldap_info() 0 142 66
B LibStatut() 0 43 8
A initAsSpecimen() 0 59 1
A __construct() 0 11 1
B getmorphylib() 0 42 11
A info() 0 28 3
A generateDocument() 0 19 4
A replaceThirdparty() 0 5 1

How to fix   Complexity   

Complex Class

Complex classes like Adherent 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 Adherent, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
/* Copyright (C) 2002-2003  Rodolphe Quiedeville        <[email protected]>
4
 * Copyright (C) 2002-2003	Jean-Louis Bergamo		    <[email protected]>
5
 * Copyright (C) 2004-2012	Laurent Destailleur		    <[email protected]>
6
 * Copyright (C) 2004		Sebastien Di Cintio		    <[email protected]>
7
 * Copyright (C) 2004		Benoit Mortier			    <[email protected]>
8
 * Copyright (C) 2009-2017	Regis Houssin			    <[email protected]>
9
 * Copyright (C) 2014-2018	Alexandre Spangaro		    <[email protected]>
10
 * Copyright (C) 2015		Marcos García			    <[email protected]>
11
 * Copyright (C) 2015-2024	Frédéric France			    <[email protected]>
12
 * Copyright (C) 2015		Raphaël Doursenaud		    <[email protected]>
13
 * Copyright (C) 2016		Juanjo Menent			    <[email protected]>
14
 * Copyright (C) 2018-2019	Thibault FOUCART		    <[email protected]>
15
 * Copyright (C) 2019		Nicolas ZABOURI 		    <[email protected]>
16
 * Copyright (C) 2020		Josep Lluís Amador 		    <[email protected]>
17
 * Copyright (C) 2021		Waël Almoman                <[email protected]>
18
 * Copyright (C) 2021		Philippe Grand              <[email protected]>
19
 * Copyright (C) 2024		MDW							<[email protected]>
20
 * Copyright (C) 2024       Rafael San José             <[email protected]>
21
 *
22
 * This program is free software; you can redistribute it and/or modify
23
 * it under the terms of the GNU General Public License as published by
24
 * the Free Software Foundation; either version 3 of the License, or
25
 * (at your option) any later version.
26
 *
27
 * This program is distributed in the hope that it will be useful,
28
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
29
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
30
 * GNU General Public License for more details.
31
 *
32
 * You should have received a copy of the GNU General Public License
33
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
34
 */
35
36
namespace Dolibarr\Code\Adherents\Classes;
37
38
/**
39
 *  \file       htdocs/adherents/class/adherent.class.php
40
 *  \ingroup    member
41
 *  \brief      File of class to manage members of a foundation
42
 */
43
44
use Dolibarr\Core\Base\CommonObject;
45
require_once constant('DOL_DOCUMENT_ROOT') . '/core/lib/date.lib.php';
46
require_once constant('DOL_DOCUMENT_ROOT') . '/categories/class/categorie.class.php';
47
require_once constant('DOL_DOCUMENT_ROOT') . '/core/class/commonpeople.class.php';
48
49
50
/**
51
 *      Class to manage members of a foundation
52
 */
53
class Adherent extends CommonObject
54
{
55
    use CommonPeople;
0 ignored issues
show
Bug introduced by
The type Dolibarr\Code\Adherents\Classes\CommonPeople was not found. Did you mean CommonPeople? If so, make sure to prefix the type with \.
Loading history...
56
57
    /**
58
     * @var string ID to identify managed object
59
     */
60
    public $element = 'member';
61
62
    /**
63
     * @var string Name of table without prefix where object is stored
64
     */
65
    public $table_element = 'adherent';
66
67
    /**
68
     * @var string picto
69
     */
70
    public $picto = 'member';
71
72
    /**
73
     * @var string[] array of messages
74
     */
75
    public $mesgs;
76
77
    /**
78
     * @var string login of member
79
     */
80
    public $login;
81
82
    /**
83
     * @var string Clear password in memory
84
     */
85
    public $pass;
86
87
    /**
88
     * @var string Clear password in database (defined if DATABASE_PWD_ENCRYPTED=0)
89
     */
90
    public $pass_indatabase;
91
92
    /**
93
     * @var string Encrypted password in database (always defined)
94
     */
95
    public $pass_indatabase_crypted;
96
97
    /**
98
     * @var string fullname
99
     */
100
    public $fullname;
101
102
    /**
103
     * @var string
104
     * @deprecated
105
     * @see $civility_code
106
     */
107
    public $civility_id;
108
109
    /**
110
     * @var string The civility code, not an integer (ex: 'MR', 'MME', 'MLE', etc.)
111
     */
112
    public $civility_code;
113
114
    public $civility;
115
116
    /**
117
     * @var string company name
118
     * @deprecated
119
     * @see $company
120
     */
121
    public $societe;
122
123
    /**
124
     * @var string company name
125
     */
126
    public $company;
127
128
    /**
129
     * @var int Thirdparty ID
130
     * @deprecated
131
     * @see $socid
132
     */
133
    public $fk_soc;
134
135
    /**
136
     * @var int socid
137
     */
138
    public $socid;
139
140
    /**
141
     * @var array array of socialnetworks
142
     */
143
    public $socialnetworks;
144
145
    /**
146
     * @var string Phone number
147
     */
148
    public $phone;
149
150
    /**
151
     * @var string Private Phone number
152
     */
153
    public $phone_perso;
154
155
    /**
156
     * @var string Professional Phone number
157
     */
158
    public $phone_pro;
159
160
    /**
161
     * @var string Mobile phone number
162
     */
163
    public $phone_mobile;
164
165
    /**
166
     * @var string Fax number
167
     */
168
    public $fax;
169
170
    /**
171
     * @var string Function
172
     */
173
    public $poste;
174
175
    /**
176
     * @var string mor or phy
177
     */
178
    public $morphy;
179
180
    /**
181
     * @var int Info can be public
182
     */
183
    public $public;
184
185
    /**
186
     * Default language code of member (en_US, ...)
187
     * @var string
188
     */
189
    public $default_lang;
190
191
    /**
192
     * @var string photo of member
193
     */
194
    public $photo;
195
196
    /**
197
     * Date creation record (datec)
198
     *
199
     * @var integer
200
     */
201
    public $datec;
202
203
    /**
204
     * Date modification record (tms)
205
     *
206
     * @var integer
207
     */
208
    public $datem;
209
210
    public $datevalid;
211
212
    /**
213
     * @var string gender
214
     */
215
    public $gender;
216
217
    /**
218
     * @var int|string date of birth
219
     */
220
    public $birth;
221
222
    /**
223
     * @var int id type member
224
     */
225
    public $typeid;
226
227
    /**
228
     * @var string label type member
229
     */
230
    public $type;
231
232
    /**
233
     * @var int need_subscription
234
     */
235
    public $need_subscription;
236
237
    /**
238
     * @var int user_id
239
     */
240
    public $user_id;
241
242
    /**
243
     * @var string user_login
244
     */
245
    public $user_login;
246
247
    public $datefin;
248
249
250
    // Fields loaded by fetch_subscriptions() from member table
251
252
    /**
253
     * @var int|string date
254
     */
255
    public $first_subscription_date;
256
257
    /**
258
     * @var int|string date
259
     */
260
    public $first_subscription_date_start;
261
262
    /**
263
     * @var int|string date
264
     */
265
    public $first_subscription_date_end;
266
267
    /**
268
     * @var int|string date
269
     */
270
    public $first_subscription_amount;
271
272
    /**
273
     * @var int|string date
274
     */
275
    public $last_subscription_date;
276
277
    /**
278
     * @var int|string date
279
     */
280
    public $last_subscription_date_start;
281
282
    /**
283
     * @var int|string date
284
     */
285
    public $last_subscription_date_end;
286
287
    /**
288
     * @var int|string date
289
     */
290
    public $last_subscription_amount;
291
292
    /**
293
     * @var array
294
     */
295
    public $subscriptions = array();
296
297
    /**
298
     * @var string ip
299
     */
300
    public $ip;
301
302
    // Fields loaded by fetchPartnerships() from partnership table
303
304
    public $partnerships = array();
305
306
    /**
307
     * @var Facture|null        To store the created invoice into subscriptionComplementaryActions()
0 ignored issues
show
Bug introduced by
The type Dolibarr\Code\Adherents\Classes\Facture was not found. Did you mean Facture? If so, make sure to prefix the type with \.
Loading history...
308
     */
309
    public $invoice;
310
311
312
    /**
313
     * @var array<string,array{type:string,label:string,enabled:int<0,2>|string,position:int,notnull?:int,visible:int,noteditable?:int,default?:string,index?:int,foreignkey?:string,searchall?:int,isameasure?:int,css?:string,csslist?:string,help?:string,showoncombobox?:int,disabled?:int,arrayofkeyval?:array<int,string>,comment?:string}>  Array with all fields and their property. Do not use it as a static var. It may be modified by constructor.
0 ignored issues
show
Documentation Bug introduced by
The doc comment array<string,array{type:...ring>,comment?:string}> at position 16 could not be parsed: Expected '}' at position 16, but found 'int'.
Loading history...
314
     */
315
    public $fields = array(
316
        'rowid' => array('type' => 'integer', 'label' => 'TechnicalID', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 10),
317
        'ref' => array('type' => 'varchar(30)', 'label' => 'Ref', 'default' => '1', 'enabled' => 1, 'visible' => 1, 'notnull' => 1, 'position' => 12, 'index' => 1),
318
        'entity' => array('type' => 'integer', 'label' => 'Entity', 'default' => '1', 'enabled' => 1, 'visible' => -2, 'notnull' => 1, 'position' => 15, 'index' => 1),
319
        'ref_ext' => array('type' => 'varchar(128)', 'label' => 'Ref ext', 'enabled' => 1, 'visible' => 0, 'position' => 20),
320
        'civility' => array('type' => 'varchar(6)', 'label' => 'Civility', 'enabled' => 1, 'visible' => -1, 'position' => 25),
321
        'lastname' => array('type' => 'varchar(50)', 'label' => 'Lastname', 'enabled' => 1, 'visible' => 1, 'position' => 30, 'showoncombobox' => 1),
322
        'firstname' => array('type' => 'varchar(50)', 'label' => 'Firstname', 'enabled' => 1, 'visible' => 1, 'position' => 35, 'showoncombobox' => 1),
323
        'login' => array('type' => 'varchar(50)', 'label' => 'Login', 'enabled' => 1, 'visible' => 1, 'position' => 40),
324
        'pass' => array('type' => 'varchar(50)', 'label' => 'Pass', 'enabled' => 1, 'visible' => -1, 'position' => 45),
325
        'pass_crypted' => array('type' => 'varchar(128)', 'label' => 'Pass crypted', 'enabled' => 1, 'visible' => -1, 'position' => 50),
326
        'morphy' => array('type' => 'varchar(3)', 'label' => 'MemberNature', 'enabled' => 1, 'visible' => 1, 'notnull' => 1, 'position' => 55),
327
        'fk_adherent_type' => array('type' => 'integer', 'label' => 'Fk adherent type', 'enabled' => 1, 'visible' => 1, 'notnull' => 1, 'position' => 60),
328
        'societe' => array('type' => 'varchar(128)', 'label' => 'Societe', 'enabled' => 1, 'visible' => 1, 'position' => 65, 'showoncombobox' => 2),
329
        'fk_soc' => array('type' => 'integer:Societe:societe/class/societe.class.php', 'label' => 'ThirdParty', 'enabled' => 1, 'visible' => 1, 'position' => 70),
330
        'address' => array('type' => 'text', 'label' => 'Address', 'enabled' => 1, 'visible' => -1, 'position' => 75),
331
        'zip' => array('type' => 'varchar(10)', 'label' => 'Zip', 'enabled' => 1, 'visible' => -1, 'position' => 80),
332
        'town' => array('type' => 'varchar(50)', 'label' => 'Town', 'enabled' => 1, 'visible' => -1, 'position' => 85),
333
        'state_id' => array('type' => 'integer', 'label' => 'State id', 'enabled' => 1, 'visible' => -1, 'position' => 90),
334
        'country' => array('type' => 'integer:Ccountry:core/class/ccountry.class.php', 'label' => 'Country', 'enabled' => 1, 'visible' => 1, 'position' => 95),
335
        'phone' => array('type' => 'varchar(30)', 'label' => 'Phone', 'enabled' => 1, 'visible' => -1, 'position' => 115),
336
        'phone_perso' => array('type' => 'varchar(30)', 'label' => 'Phone perso', 'enabled' => 1, 'visible' => -1, 'position' => 120),
337
        'phone_mobile' => array('type' => 'varchar(30)', 'label' => 'Phone mobile', 'enabled' => 1, 'visible' => -1, 'position' => 125),
338
        'email' => array('type' => 'varchar(255)', 'label' => 'Email', 'enabled' => 1, 'visible' => 1, 'position' => 126),
339
        'url' => array('type' => 'varchar(255)', 'label' => 'Url', 'enabled' => 1, 'visible' => -1, 'position' => 127),
340
        'socialnetworks' => array('type' => 'text', 'label' => 'Socialnetworks', 'enabled' => 1, 'visible' => -1, 'position' => 128),
341
        'birth' => array('type' => 'date', 'label' => 'DateOfBirth', 'enabled' => 1, 'visible' => -1, 'position' => 130),
342
        'gender' => array('type' => 'varchar(10)', 'label' => 'Gender', 'enabled' => 1, 'visible' => -1, 'position' => 132),
343
        'photo' => array('type' => 'varchar(255)', 'label' => 'Photo', 'enabled' => 1, 'visible' => -1, 'position' => 135),
344
        'public' => array('type' => 'smallint(6)', 'label' => 'Public', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 145),
345
        'datefin' => array('type' => 'datetime', 'label' => 'DateEnd', 'enabled' => 1, 'visible' => 1, 'position' => 150),
346
        'default_lang' => array('type' => 'varchar(6)', 'label' => 'Default lang', 'enabled' => 1, 'visible' => -1, 'position' => 153),
347
        'note_public' => array('type' => 'text', 'label' => 'NotePublic', 'enabled' => 1, 'visible' => 0, 'position' => 155),
348
        'note_private' => array('type' => 'text', 'label' => 'NotePrivate', 'enabled' => 1, 'visible' => 0, 'position' => 160),
349
        'datevalid' => array('type' => 'datetime', 'label' => 'DateValidation', 'enabled' => 1, 'visible' => -1, 'position' => 165),
350
        'datec' => array('type' => 'datetime', 'label' => 'DateCreation', 'enabled' => 1, 'visible' => -1, 'position' => 170),
351
        'tms' => array('type' => 'timestamp', 'label' => 'DateModification', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 175),
352
        'fk_user_author' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'Fk user author', 'enabled' => 1, 'visible' => -1, 'position' => 180),
353
        'fk_user_mod' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'Fk user mod', 'enabled' => 1, 'visible' => -1, 'position' => 185),
354
        'fk_user_valid' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserValidation', 'enabled' => 1, 'visible' => -1, 'position' => 190),
355
        'canvas' => array('type' => 'varchar(32)', 'label' => 'Canvas', 'enabled' => 1, 'visible' => -1, 'position' => 195),
356
        'statut' => array('type' => 'smallint(6)', 'label' => 'Statut', 'enabled' => 1, 'visible' => 1, 'notnull' => 1, 'position' => 500, 'arrayofkeyval' => array(-1 => 'Draft', 1 => 'Validated', 0 => 'MemberStatusResiliatedShort', -2 => 'MemberStatusExcludedShort')),
357
        'model_pdf' => array('type' => 'varchar(255)', 'label' => 'Model pdf', 'enabled' => 1, 'visible' => 0, 'position' => 800),
358
        'import_key' => array('type' => 'varchar(14)', 'label' => 'ImportId', 'enabled' => 1, 'visible' => -2, 'position' => 805)
359
    );
360
361
    /**
362
     * Draft status
363
     */
364
    const STATUS_DRAFT = -1;
365
    /**
366
     * Validated status
367
     */
368
    const STATUS_VALIDATED = 1;
369
    /**
370
     * Resiliated
371
     */
372
    const STATUS_RESILIATED = 0;
373
    /**
374
     * Excluded
375
     */
376
    const STATUS_EXCLUDED = -2;
377
378
379
    /**
380
     *  Constructor
381
     *
382
     *  @param      DoliDB      $db     Database handler
0 ignored issues
show
Bug introduced by
The type Dolibarr\Code\Adherents\Classes\DoliDB was not found. Did you mean DoliDB? If so, make sure to prefix the type with \.
Loading history...
383
     */
384
    public function __construct($db)
385
    {
386
        $this->db = $db;
387
        $this->statut = self::STATUS_DRAFT;
0 ignored issues
show
Deprecated Code introduced by
The property Dolibarr\Core\Base\CommonObject::$statut has been deprecated: Use $status instead. ( Ignorable by Annotation )

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

387
        /** @scrutinizer ignore-deprecated */ $this->statut = self::STATUS_DRAFT;

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
388
        $this->status = self::STATUS_DRAFT;
389
        // l'adherent n'est pas public par default
390
        $this->public = 0;
391
        $this->ismultientitymanaged = 1;
392
        $this->isextrafieldmanaged = 1;
393
        // les champs optionnels sont vides
394
        $this->array_options = array();
395
    }
396
397
398
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
399
    /**
400
     *  Function sending an email to the current member with the text supplied in parameter.
401
     *
402
     *  @param  string  $text               Content of message (not html entities encoded)
403
     *  @param  string  $subject            Subject of message
404
     *  @param  array   $filename_list      Array of attached files
405
     *  @param  array   $mimetype_list      Array of mime types of attached files
406
     *  @param  array   $mimefilename_list  Array of public names of attached files
407
     *  @param  string  $addr_cc            Email cc
408
     *  @param  string  $addr_bcc           Email bcc
409
     *  @param  int     $deliveryreceipt    Ask a delivery receipt
410
     *  @param  int     $msgishtml          1=String IS already html, 0=String IS NOT html, -1=Unknown need autodetection
411
     *  @param  string  $errors_to          errors to
412
     *  @param  string  $moreinheader       Add more html headers
413
     *  @deprecated since V18
414
     *  @see sendEmail()
415
     *  @return int                         Return integer <0 if KO, >0 if OK
416
     */
417
    public function send_an_email($text, $subject, $filename_list = array(), $mimetype_list = array(), $mimefilename_list = array(), $addr_cc = "", $addr_bcc = "", $deliveryreceipt = 0, $msgishtml = -1, $errors_to = '', $moreinheader = '')
418
    {
419
		// phpcs:enable
420
        dol_syslog('Warning using deprecated Adherent::send_an_email', LOG_WARNING);
421
422
        return $this->sendEmail($text, $subject, $filename_list, $mimetype_list, $mimefilename_list, $addr_cc, $addr_bcc, $deliveryreceipt, $msgishtml, $errors_to, $moreinheader);
423
    }
424
425
    /**
426
     *  Function sending an email to the current member with the text supplied in parameter.
427
     *
428
     *  @param  string  $text               Content of message (not html entities encoded)
429
     *  @param  string  $subject            Subject of message
430
     *  @param  array   $filename_list      Array of attached files
431
     *  @param  array   $mimetype_list      Array of mime types of attached files
432
     *  @param  array   $mimefilename_list  Array of public names of attached files
433
     *  @param  string  $addr_cc            Email cc
434
     *  @param  string  $addr_bcc           Email bcc
435
     *  @param  int     $deliveryreceipt    Ask a delivery receipt
436
     *  @param  int     $msgishtml          1=String IS already html, 0=String IS NOT html, -1=Unknown need autodetection
437
     *  @param  string  $errors_to          errors to
438
     *  @param  string  $moreinheader       Add more html headers
439
     *  @since V18
440
     *  @return int                         Return integer <0 if KO, >0 if OK
441
     */
442
    public function sendEmail($text, $subject, $filename_list = array(), $mimetype_list = array(), $mimefilename_list = array(), $addr_cc = "", $addr_bcc = "", $deliveryreceipt = 0, $msgishtml = -1, $errors_to = '', $moreinheader = '')
443
    {
444
        global $conf, $langs;
445
446
        // Detect if message is HTML
447
        if ($msgishtml == -1) {
448
            $msgishtml = 0;
449
            if (dol_textishtml($text, 0)) {
450
                $msgishtml = 1;
451
            }
452
        }
453
454
        dol_syslog('sendEmail msgishtml=' . $msgishtml);
455
456
        $texttosend = $this->makeSubstitution($text);
457
        $subjecttosend = $this->makeSubstitution($subject);
458
        if ($msgishtml) {
459
            $texttosend = dol_htmlentitiesbr($texttosend);
460
        }
461
462
        // Envoi mail confirmation
463
        $from = $conf->email_from;
464
        if (getDolGlobalString('ADHERENT_MAIL_FROM')) {
465
            $from = getDolGlobalString('ADHERENT_MAIL_FROM');
466
        }
467
468
        $trackid = 'mem' . $this->id;
469
470
        // Send email (substitutionarray must be done just before this)
471
        include_once DOL_DOCUMENT_ROOT . '/core/class/CMailFile.class.php';
472
        $mailfile = new CMailFile($subjecttosend, $this->email, $from, $texttosend, $filename_list, $mimetype_list, $mimefilename_list, $addr_cc, $addr_bcc, $deliveryreceipt, $msgishtml, '', '', $trackid, $moreinheader);
0 ignored issues
show
Bug introduced by
The type Dolibarr\Code\Adherents\Classes\CMailFile was not found. Did you mean CMailFile? If so, make sure to prefix the type with \.
Loading history...
473
        if ($mailfile->sendfile()) {
474
            return 1;
475
        } else {
476
            $this->error = $langs->trans("ErrorFailedToSendMail", $from, $this->email) . '. ' . $mailfile->error;
477
            return -1;
478
        }
479
    }
480
481
482
    /**
483
     * Make substitution of tags into text with value of current object.
484
     *
485
     * @param   string  $text       Text to make substitution to
486
     * @return  string              Value of input text string with substitutions done
487
     */
488
    public function makeSubstitution($text)
489
    {
490
        global $langs;
491
492
        $birthday = dol_print_date($this->birth, 'day');
493
494
        $msgishtml = 0;
495
        if (dol_textishtml($text, 1)) {
496
            $msgishtml = 1;
497
        }
498
499
        $infos = '';
500
        if ($this->civility_id) {
501
            $infos .= $langs->transnoentities("UserTitle") . ": " . $this->getCivilityLabel() . "\n";
502
        }
503
        $infos .= $langs->transnoentities("id") . ": " . $this->id . "\n";
504
        $infos .= $langs->transnoentities("ref") . ": " . $this->ref . "\n";
505
        $infos .= $langs->transnoentities("Lastname") . ": " . $this->lastname . "\n";
506
        $infos .= $langs->transnoentities("Firstname") . ": " . $this->firstname . "\n";
507
        $infos .= $langs->transnoentities("Company") . ": " . $this->company . "\n";
508
        $infos .= $langs->transnoentities("Address") . ": " . $this->address . "\n";
509
        $infos .= $langs->transnoentities("Zip") . ": " . $this->zip . "\n";
510
        $infos .= $langs->transnoentities("Town") . ": " . $this->town . "\n";
511
        $infos .= $langs->transnoentities("Country") . ": " . $this->country . "\n";
512
        $infos .= $langs->transnoentities("EMail") . ": " . $this->email . "\n";
513
        $infos .= $langs->transnoentities("PhonePro") . ": " . $this->phone . "\n";
514
        $infos .= $langs->transnoentities("PhonePerso") . ": " . $this->phone_perso . "\n";
515
        $infos .= $langs->transnoentities("PhoneMobile") . ": " . $this->phone_mobile . "\n";
516
        if (!getDolGlobalString('ADHERENT_LOGIN_NOT_REQUIRED')) {
517
            $infos .= $langs->transnoentities("Login") . ": " . $this->login . "\n";
518
            $infos .= $langs->transnoentities("Password") . ": " . $this->pass . "\n";
519
        }
520
        $infos .= $langs->transnoentities("Birthday") . ": " . $birthday . "\n";
521
        $infos .= $langs->transnoentities("Photo") . ": " . $this->photo . "\n";
522
        $infos .= $langs->transnoentities("Public") . ": " . yn($this->public);
523
524
        // Substitutions
525
        $substitutionarray = array(
526
            '__ID__' => $this->id,
527
            '__REF__' => $this->ref,
528
            '__MEMBER_ID__' => $this->id,
529
            '__CIVILITY__' => $this->getCivilityLabel(),
530
            '__FIRSTNAME__' => $msgishtml ? dol_htmlentitiesbr($this->firstname) : ($this->firstname ? $this->firstname : ''),
531
            '__LASTNAME__' => $msgishtml ? dol_htmlentitiesbr($this->lastname) : ($this->lastname ? $this->lastname : ''),
532
            '__FULLNAME__' => $msgishtml ? dol_htmlentitiesbr($this->getFullName($langs)) : $this->getFullName($langs),
533
            '__COMPANY__' => $msgishtml ? dol_htmlentitiesbr($this->company) : ($this->company ? $this->company : ''),
534
            '__ADDRESS__' => $msgishtml ? dol_htmlentitiesbr($this->address) : ($this->address ? $this->address : ''),
535
            '__ZIP__' => $msgishtml ? dol_htmlentitiesbr($this->zip) : ($this->zip ? $this->zip : ''),
536
            '__TOWN__' => $msgishtml ? dol_htmlentitiesbr($this->town) : ($this->town ? $this->town : ''),
537
            '__COUNTRY__' => $msgishtml ? dol_htmlentitiesbr($this->country) : ($this->country ? $this->country : ''),
538
            '__EMAIL__' => $msgishtml ? dol_htmlentitiesbr($this->email) : ($this->email ? $this->email : ''),
539
            '__BIRTH__' => $msgishtml ? dol_htmlentitiesbr($birthday) : ($birthday ? $birthday : ''),
540
            '__PHOTO__' => $msgishtml ? dol_htmlentitiesbr($this->photo) : ($this->photo ? $this->photo : ''),
541
            '__LOGIN__' => $msgishtml ? dol_htmlentitiesbr($this->login) : ($this->login ? $this->login : ''),
542
            '__PASSWORD__' => $msgishtml ? dol_htmlentitiesbr($this->pass) : ($this->pass ? $this->pass : ''),
543
            '__PHONE__' => $msgishtml ? dol_htmlentitiesbr($this->phone) : ($this->phone ? $this->phone : ''),
544
            '__PHONEPRO__' => $msgishtml ? dol_htmlentitiesbr($this->phone_perso) : ($this->phone_perso ? $this->phone_perso : ''),
545
            '__PHONEMOBILE__' => $msgishtml ? dol_htmlentitiesbr($this->phone_mobile) : ($this->phone_mobile ? $this->phone_mobile : ''),
546
            '__TYPE__' => $msgishtml ? dol_htmlentitiesbr($this->type) : ($this->type ? $this->type : '')
547
        );
548
549
        complete_substitutions_array($substitutionarray, $langs, $this);
550
551
        return make_substitutions($text, $substitutionarray, $langs);
552
    }
553
554
555
    /**
556
     *  Return translated label by the nature of a adherent (physical or moral)
557
     *
558
     *  @param  string      $morphy     Nature of the adherent (physical or moral)
559
     *  @param  int<0,2>    $addbadge   Add badge (1=Full label, 2=First letters only)
560
     *  @return string                  Label
561
     */
562
    public function getmorphylib($morphy = '', $addbadge = 0)
563
    {
564
        global $langs;
565
        $s = '';
566
567
        // Clean var
568
        if (!$morphy) {
569
            $morphy = $this->morphy;
570
        }
571
572
        if ($addbadge) {
573
            $labeltoshowm = $langs->trans("Moral");
574
            $labeltoshowp = $langs->trans("Physical");
575
            if ($morphy == 'phy') {
576
                $labeltoshow = $labeltoshowp;
577
                if ($addbadge == 2) {
578
                    $labeltoshow = dol_strtoupper(dolGetFirstLetters($labeltoshowp));
579
                    if ($labeltoshow == dol_strtoupper(dolGetFirstLetters($labeltoshowm))) {
580
                        $labeltoshow = dol_strtoupper(dolGetFirstLetters($labeltoshowp, 2));
581
                    }
582
                }
583
                $s .= '<span class="member-individual-back paddingleftimp paddingrightimp" title="' . $langs->trans("Physical") . '">' . $labeltoshow . '</span>';
584
            }
585
            if ($morphy == 'mor') {
586
                $labeltoshow = $labeltoshowm;
587
                if ($addbadge == 2) {
588
                    $labeltoshow = dol_strtoupper(dolGetFirstLetters($labeltoshowm));
589
                    if ($labeltoshow == dol_strtoupper(dolGetFirstLetters($labeltoshowp))) {
590
                        $labeltoshow = dol_strtoupper(dolGetFirstLetters($labeltoshowm, 2));
591
                    }
592
                }
593
                $s .= '<span class="member-company-back paddingleftimp paddingrightimp" title="' . $langs->trans("Moral") . '">' . $labeltoshow . '</span>';
594
            }
595
        } else {
596
            if ($morphy == 'phy') {
597
                $s = $langs->trans("Physical");
598
            } elseif ($morphy == 'mor') {
599
                $s = $langs->trans("Moral");
600
            }
601
        }
602
603
        return $s;
604
    }
605
606
    /**
607
     *  Create a member into database
608
     *
609
     *  @param  User    $user           Object user qui demande la creation
0 ignored issues
show
Bug introduced by
The type Dolibarr\Code\Adherents\Classes\User was not found. Did you mean User? If so, make sure to prefix the type with \.
Loading history...
610
     *  @param  int     $notrigger      1 ne declenche pas les triggers, 0 sinon
611
     *  @return int                     Return integer <0 if KO, >0 if OK
612
     */
613
    public function create($user, $notrigger = 0)
614
    {
615
        global $conf, $langs, $mysoc;
616
617
        $error = 0;
618
619
        $now = dol_now();
620
621
        // Clean parameters
622
        $this->import_key = trim($this->import_key);
623
624
        // Check parameters
625
        if (getDolGlobalString('ADHERENT_MAIL_REQUIRED') && !isValidEmail($this->email)) {
626
            $langs->load("errors");
627
            $this->error = $langs->trans("ErrorBadEMail", $this->email);
628
            return -1;
629
        }
630
        if (!$this->datec) {
631
            $this->datec = $now;
632
        }
633
        if (!getDolGlobalString('ADHERENT_LOGIN_NOT_REQUIRED')) {
634
            if (empty($this->login)) {
635
                $this->error = $langs->trans("ErrorWrongValueForParameterX", "Login");
636
                return -1;
637
            }
638
        }
639
640
        $this->db->begin();
641
642
        // Insert member
643
        $sql = "INSERT INTO " . MAIN_DB_PREFIX . "adherent";
644
        $sql .= " (ref, datec,login,fk_user_author,fk_user_mod,fk_user_valid,morphy,fk_adherent_type,entity,import_key, ip)";
645
        $sql .= " VALUES (";
646
        $sql .= " '(PROV)'";
647
        $sql .= ", '" . $this->db->idate($this->datec) . "'";
648
        $sql .= ", " . ($this->login ? "'" . $this->db->escape($this->login) . "'" : "null");
649
        $sql .= ", " . ($user->id > 0 ? $user->id : "null"); // Can be null because member can be created by a guest or a script
650
        $sql .= ", null, null, '" . $this->db->escape($this->morphy) . "'";
651
        $sql .= ", " . ((int) $this->typeid);
652
        $sql .= ", " . $conf->entity;
653
        $sql .= ", " . (!empty($this->import_key) ? "'" . $this->db->escape($this->import_key) . "'" : "null");
654
        $sql .= ", " . (!empty($this->ip) ? "'" . $this->db->escape($this->ip) . "'" : "null");
655
        $sql .= ")";
656
657
        dol_syslog(get_class($this) . "::create", LOG_DEBUG);
658
        $result = $this->db->query($sql);
659
        if ($result) {
660
            $id = $this->db->last_insert_id(MAIN_DB_PREFIX . "adherent");
661
            if ($id > 0) {
662
                $this->id = $id;
663
                if (getDolGlobalString('MEMBER_CODEMEMBER_ADDON') == '') {
664
                    // keep old numbering
665
                    $this->ref = (string) $id;
666
                } else {
667
                    // auto code
668
                    $modfile = dol_buildpath('core/modules/member/' . getDolGlobalString('MEMBER_CODEMEMBER_ADDON') . '.php', 0);
669
                    try {
670
                        require_once $modfile;
671
                        $modname = getDolGlobalString('MEMBER_CODEMEMBER_ADDON');
672
                        $modCodeMember = new $modname();
673
                        '@phan-var-force ModeleNumRefMembers $modCodeMember';
674
                        $this->ref = $modCodeMember->getNextValue($mysoc, $this);
675
                    } catch (Exception $e) {
0 ignored issues
show
Bug introduced by
The type Dolibarr\Code\Adherents\Classes\Exception was not found. Did you mean Exception? If so, make sure to prefix the type with \.
Loading history...
676
                        dol_syslog($e->getMessage(), LOG_ERR);
677
                        $error++;
678
                    }
679
                }
680
681
                // Update minor fields
682
                $result = $this->update($user, 1, 1, 0, 0, 'add'); // nosync is 1 to avoid update data of user
683
                if ($result < 0) {
684
                    $this->db->rollback();
685
                    return -1;
686
                }
687
688
                // Add link to user
689
                if ($this->user_id) {
690
                    // Add link to user
691
                    $sql = "UPDATE " . MAIN_DB_PREFIX . "user SET";
692
                    $sql .= " fk_member = " . ((int) $this->id);
693
                    $sql .= " WHERE rowid = " . ((int) $this->user_id);
694
                    dol_syslog(get_class($this) . "::create", LOG_DEBUG);
695
                    $resql = $this->db->query($sql);
696
                    if (!$resql) {
697
                        $this->error = 'Failed to update user to make link with member';
698
                        $this->db->rollback();
699
                        return -4;
700
                    }
701
                }
702
703
                if (!$notrigger) {
704
                    // Call trigger
705
                    $result = $this->call_trigger('MEMBER_CREATE', $user);
706
                    if ($result < 0) {
707
                        $error++;
708
                    }
709
                    // End call triggers
710
                }
711
712
                if (count($this->errors)) {
713
                    dol_syslog(get_class($this) . "::create " . implode(',', $this->errors), LOG_ERR);
714
                    $this->db->rollback();
715
                    return -3;
716
                } else {
717
                    $this->db->commit();
718
                    return $this->id;
719
                }
720
            } else {
721
                $this->error = 'Failed to get last insert id';
722
                dol_syslog(get_class($this) . "::create " . $this->error, LOG_ERR);
723
                $this->db->rollback();
724
                return -2;
725
            }
726
        } else {
727
            $this->error = $this->db->error();
728
            $this->db->rollback();
729
            return -1;
730
        }
731
    }
732
733
734
    /**
735
     *  Update a member in database (standard information and password)
736
     *
737
     *  @param  User    $user               User making update
738
     *  @param  int     $notrigger          1=disable trigger UPDATE (when called by create)
739
     *  @param  int     $nosyncuser         0=Synchronize linked user (standard info), 1=Do not synchronize linked user
740
     *  @param  int     $nosyncuserpass     0=Synchronize linked user (password), 1=Do not synchronize linked user
741
     *  @param  int     $nosyncthirdparty   0=Synchronize linked thirdparty (standard info), 1=Do not synchronize linked thirdparty
742
     *  @param  string  $action             Current action for hookmanager
743
     *  @return int                         Return integer <0 if KO, >0 if OK
744
     */
745
    public function update($user, $notrigger = 0, $nosyncuser = 0, $nosyncuserpass = 0, $nosyncthirdparty = 0, $action = 'update')
746
    {
747
        global $langs, $hookmanager;
748
749
        require_once constant('DOL_DOCUMENT_ROOT') . '/core/lib/functions2.lib.php';
750
751
        $nbrowsaffected = 0;
752
        $error = 0;
753
754
        dol_syslog(get_class($this) . "::update notrigger=" . $notrigger . ", nosyncuser=" . $nosyncuser . ", nosyncuserpass=" . $nosyncuserpass . " nosyncthirdparty=" . $nosyncthirdparty . ", email=" . $this->email);
755
756
        // Clean parameters
757
        $this->lastname = trim($this->lastname) ? trim($this->lastname) : trim($this->lastname);
758
        $this->firstname = trim($this->firstname) ? trim($this->firstname) : trim($this->firstname);
759
        $this->gender = trim($this->gender);
760
        // $this->address = ($this->address ? $this->address : $this->address);
761
        // $this->zip = ($this->zip ? $this->zip : $this->zip);
762
        // $this->town = ($this->town ? $this->town : $this->town);
763
        // $this->country_id = ($this->country_id > 0 ? $this->country_id : $this->country_id);
764
        // $this->state_id = ($this->state_id > 0 ? $this->state_id : $this->state_id);
765
        // $this->note_public = ($this->note_public ? $this->note_public : $this->note_public);
766
        // $this->note_private = ($this->note_private ? $this->note_private : $this->note_private);
767
        $this->url = $this->url ? clean_url($this->url, 0) : '';
768
        $this->setUpperOrLowerCase();
769
        // Check parameters
770
        if (getDolGlobalString('ADHERENT_MAIL_REQUIRED') && !isValidEmail($this->email)) {
771
            $langs->load("errors");
772
            $this->error = $langs->trans("ErrorBadEMail", $this->email);
773
            return -1;
774
        }
775
776
        $this->db->begin();
777
778
        $sql = "UPDATE " . MAIN_DB_PREFIX . "adherent SET";
779
        $sql .= " ref = '" . $this->db->escape($this->ref) . "'";
780
        $sql .= ", civility = " . ($this->civility_id ? "'" . $this->db->escape($this->civility_id) . "'" : "null");
781
        $sql .= ", firstname = " . ($this->firstname ? "'" . $this->db->escape($this->firstname) . "'" : "null");
782
        $sql .= ", lastname = " . ($this->lastname ? "'" . $this->db->escape($this->lastname) . "'" : "null");
783
        $sql .= ", gender = " . ($this->gender != -1 ? "'" . $this->db->escape($this->gender) . "'" : "null"); // 'man' or 'woman'
784
        $sql .= ", login = " . ($this->login ? "'" . $this->db->escape($this->login) . "'" : "null");
785
        $sql .= ", societe = " . ($this->company ? "'" . $this->db->escape($this->company) . "'" : ($this->societe ? "'" . $this->db->escape($this->societe) . "'" : "null"));
786
        if ($this->socid) {
787
            $sql .= ", fk_soc = " . ($this->socid > 0 ? (int) $this->socid : "null");  // Must be modified only when creating from a third-party
788
        }
789
        $sql .= ", address = " . ($this->address ? "'" . $this->db->escape($this->address) . "'" : "null");
790
        $sql .= ", zip = " . ($this->zip ? "'" . $this->db->escape($this->zip) . "'" : "null");
791
        $sql .= ", town = " . ($this->town ? "'" . $this->db->escape($this->town) . "'" : "null");
792
        $sql .= ", country = " . ($this->country_id > 0 ? (int) $this->country_id : "null");
793
        $sql .= ", state_id = " . ($this->state_id > 0 ? (int) $this->state_id : "null");
794
        $sql .= ", email = '" . $this->db->escape($this->email) . "'";
795
        $sql .= ", url = " . (!empty($this->url) ? "'" . $this->db->escape($this->url) . "'" : "null");
796
        $sql .= ", socialnetworks = " . ($this->socialnetworks ? "'" . $this->db->escape(json_encode($this->socialnetworks)) . "'" : "null");
797
        $sql .= ", phone = " . ($this->phone ? "'" . $this->db->escape($this->phone) . "'" : "null");
798
        $sql .= ", phone_perso = " . ($this->phone_perso ? "'" . $this->db->escape($this->phone_perso) . "'" : "null");
799
        $sql .= ", phone_mobile = " . ($this->phone_mobile ? "'" . $this->db->escape($this->phone_mobile) . "'" : "null");
800
        $sql .= ", note_private = " . ($this->note_private ? "'" . $this->db->escape($this->note_private) . "'" : "null");
801
        $sql .= ", note_public = " . ($this->note_public ? "'" . $this->db->escape($this->note_public) . "'" : "null");
802
        $sql .= ", photo = " . ($this->photo ? "'" . $this->db->escape($this->photo) . "'" : "null");
803
        $sql .= ", public = '" . $this->db->escape($this->public) . "'";
804
        $sql .= ", statut = " . (int) $this->statut;
0 ignored issues
show
Deprecated Code introduced by
The property Dolibarr\Core\Base\CommonObject::$statut has been deprecated: Use $status instead. ( Ignorable by Annotation )

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

804
        $sql .= ", statut = " . (int) /** @scrutinizer ignore-deprecated */ $this->statut;

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
805
        $sql .= ", default_lang = " . (!empty($this->default_lang) ? "'" . $this->db->escape($this->default_lang) . "'" : "null");
806
        $sql .= ", fk_adherent_type = " . (int) $this->typeid;
807
        $sql .= ", morphy = '" . $this->db->escape($this->morphy) . "'";
808
        $sql .= ", birth = " . ($this->birth ? "'" . $this->db->idate($this->birth) . "'" : "null");
809
810
        if ($this->datefin) {
811
            $sql .= ", datefin = '" . $this->db->idate($this->datefin) . "'"; // Must be modified only when deleting a subscription
812
        }
813
        if ($this->datevalid) {
814
            $sql .= ", datevalid = '" . $this->db->idate($this->datevalid) . "'"; // Must be modified only when validating a member
815
        }
816
        $sql .= ", fk_user_mod = " . ($user->id > 0 ? $user->id : 'null'); // Can be null because member can be create by a guest
817
        $sql .= " WHERE rowid = " . ((int) $this->id);
818
819
        // If we change the type of membership, we set also label of new type
820
        if (!empty($this->oldcopy) && $this->typeid != $this->oldcopy->typeid) {
0 ignored issues
show
Bug Best Practice introduced by
The property typeid does not exist on Dolibarr\Core\Base\CommonObject. Since you implemented __get, consider adding a @property annotation.
Loading history...
821
            $sql2 = "SELECT libelle as label";
822
            $sql2 .= " FROM " . MAIN_DB_PREFIX . "adherent_type";
823
            $sql2 .= " WHERE rowid = " . ((int) $this->typeid);
824
            $resql2 = $this->db->query($sql2);
825
            if ($resql2) {
826
                while ($obj = $this->db->fetch_object($resql2)) {
827
                    $this->type = $obj->label;
828
                }
829
            }
830
        }
831
832
        dol_syslog(get_class($this) . "::update update member", LOG_DEBUG);
833
        $resql = $this->db->query($sql);
834
        if ($resql) {
835
            unset($this->country_code);
836
            unset($this->country);
837
            unset($this->state_code);
838
            unset($this->state);
839
840
            $nbrowsaffected += $this->db->affected_rows($resql);
841
842
            $action = 'update';
843
844
            // Actions on extra fields
845
            if (!$error) {
846
                $result = $this->insertExtraFields();
847
                if ($result < 0) {
848
                    $error++;
849
                }
850
            }
851
852
            // Update password
853
            if (!$error && $this->pass) {
854
                dol_syslog(get_class($this) . "::update update password");
855
                if ($this->pass != $this->pass_indatabase && $this->pass != $this->pass_indatabase_crypted) {
856
                    $isencrypted = getDolGlobalString('DATABASE_PWD_ENCRYPTED') ? 1 : 0;
857
858
                    // If password to set differs from the one found into database
859
                    $result = $this->setPassword($user, $this->pass, $isencrypted, $notrigger, $nosyncuserpass);
860
                    if (!$nbrowsaffected) {
861
                        $nbrowsaffected++;
862
                    }
863
                }
864
            }
865
866
            // Remove links to user and replace with new one
867
            if (!$error) {
868
                dol_syslog(get_class($this) . "::update update link to user");
869
                $sql = "UPDATE " . MAIN_DB_PREFIX . "user SET fk_member = NULL WHERE fk_member = " . ((int) $this->id);
870
                dol_syslog(get_class($this) . "::update", LOG_DEBUG);
871
                $resql = $this->db->query($sql);
872
                if (!$resql) {
873
                    $this->error = $this->db->error();
874
                    $this->db->rollback();
875
                    return -5;
876
                }
877
                // If there is a user linked to this member
878
                if ($this->user_id > 0) {
879
                    $sql = "UPDATE " . MAIN_DB_PREFIX . "user SET fk_member = " . ((int) $this->id) . " WHERE rowid = " . ((int) $this->user_id);
880
                    dol_syslog(get_class($this) . "::update", LOG_DEBUG);
881
                    $resql = $this->db->query($sql);
882
                    if (!$resql) {
883
                        $this->error = $this->db->error();
884
                        $this->db->rollback();
885
                        return -5;
886
                    }
887
                }
888
            }
889
890
            if (!$error && $nbrowsaffected) { // If something has change in main data
891
                // Update information on linked user if it is an update
892
                if (!$error && $this->user_id > 0 && !$nosyncuser) {
893
                    require_once constant('DOL_DOCUMENT_ROOT') . '/user/class/user.class.php';
894
895
                    dol_syslog(get_class($this) . "::update update linked user");
896
897
                    $luser = new User($this->db);
898
                    $result = $luser->fetch($this->user_id);
899
900
                    if ($result >= 0) {
901
                        //var_dump($this->user_login);exit;
902
                        //var_dump($this->login);exit;
903
904
                        // If option ADHERENT_LOGIN_NOT_REQUIRED is on, there is no login of member, so we do not overwrite user login to keep existing one.
905
                        if (!getDolGlobalString('ADHERENT_LOGIN_NOT_REQUIRED')) {
906
                            $luser->login = $this->login;
907
                        }
908
909
                        $luser->ref = $this->ref;
910
                        $luser->civility_id = $this->civility_id;
911
                        $luser->firstname = $this->firstname;
912
                        $luser->lastname = $this->lastname;
913
                        $luser->gender = $this->gender;
914
                        $luser->pass = $this->pass;
915
                        //$luser->socid=$this->fk_soc;      // We do not enable this. This may transform a user into an external user.
916
917
                        $luser->birth = $this->birth;
918
919
                        $luser->address = $this->address;
920
                        $luser->zip = $this->zip;
921
                        $luser->town = $this->town;
922
                        $luser->country_id = $this->country_id;
923
                        $luser->state_id = $this->state_id;
924
925
                        $luser->email = $this->email;
926
                        $luser->socialnetworks = $this->socialnetworks;
927
                        $luser->office_phone = $this->phone;
928
                        $luser->user_mobile = $this->phone_mobile;
929
930
                        $luser->lang = $this->default_lang;
931
932
                        $luser->fk_member = $this->id;
933
934
                        $result = $luser->update($user, 0, 1, 1); // Use nosync to 1 to avoid cyclic updates
935
                        if ($result < 0) {
936
                            $this->error = $luser->error;
937
                            dol_syslog(get_class($this) . "::update " . $this->error, LOG_ERR);
938
                            $error++;
939
                        }
940
                    } else {
941
                        $this->error = $luser->error;
942
                        $error++;
943
                    }
944
                }
945
946
                // Update information on linked thirdparty if it is an update
947
                if (!$error && $this->fk_soc > 0 && !$nosyncthirdparty) {
948
                    require_once constant('DOL_DOCUMENT_ROOT') . '/societe/class/societe.class.php';
949
950
                    dol_syslog(get_class($this) . "::update update linked thirdparty");
951
952
                    // This member is linked with a thirdparty, so we also update thirdparty information
953
                    // if this is an update.
954
                    $lthirdparty = new Societe($this->db);
0 ignored issues
show
Bug introduced by
The type Dolibarr\Code\Adherents\Classes\Societe was not found. Did you mean Societe? If so, make sure to prefix the type with \.
Loading history...
955
                    $result = $lthirdparty->fetch($this->fk_soc);
956
957
                    if ($result > 0) {
958
                        $lthirdparty->address = $this->address;
959
                        $lthirdparty->zip = $this->zip;
960
                        $lthirdparty->town = $this->town;
961
                        $lthirdparty->email = $this->email;
962
                        $lthirdparty->socialnetworks = $this->socialnetworks;
963
                        $lthirdparty->phone = $this->phone;
964
                        $lthirdparty->state_id = $this->state_id;
965
                        $lthirdparty->country_id = $this->country_id;
966
                        //$lthirdparty->phone_mobile=$this->phone_mobile;
967
                        $lthirdparty->default_lang = $this->default_lang;
968
969
                        $result = $lthirdparty->update($this->fk_soc, $user, 0, 1, 1, 'update'); // Use sync to 0 to avoid cyclic updates
970
971
                        if ($result < 0) {
972
                            $this->error = $lthirdparty->error;
973
                            $this->errors = $lthirdparty->errors;
974
                            dol_syslog(get_class($this) . "::update " . $this->error, LOG_ERR);
975
                            $error++;
976
                        }
977
                    } elseif ($result < 0) {
978
                        $this->error = $lthirdparty->error;
979
                        $error++;
980
                    }
981
                }
982
            }
983
984
            if (!$error && !$notrigger) {
985
                // Call trigger
986
                $result = $this->call_trigger('MEMBER_MODIFY', $user);
987
                if ($result < 0) {
988
                    $error++;
989
                }
990
                // End call triggers
991
            }
992
993
            if (!$error) {
994
                $this->db->commit();
995
                return $nbrowsaffected;
996
            } else {
997
                $this->db->rollback();
998
                return -1;
999
            }
1000
        } else {
1001
            $this->db->rollback();
1002
            $this->error = $this->db->lasterror();
1003
            return -2;
1004
        }
1005
    }
1006
1007
1008
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1009
    /**
1010
     *  Update denormalized last subscription date.
1011
     *  This function is called when we delete a subscription for example.
1012
     *
1013
     *  @param  User    $user           User making change
1014
     *  @return int                     Return integer <0 if KO, >0 if OK
1015
     */
1016
    public function update_end_date($user)
1017
    {
1018
		// phpcs:enable
1019
        $this->db->begin();
1020
1021
        // Search for last subscription id and end date
1022
        $sql = "SELECT rowid, datec as dateop, dateadh as datedeb, datef as datefin";
1023
        $sql .= " FROM " . MAIN_DB_PREFIX . "subscription";
1024
        $sql .= " WHERE fk_adherent = " . ((int) $this->id);
1025
        $sql .= " ORDER by dateadh DESC"; // Sort by start subscription date
1026
1027
        dol_syslog(get_class($this) . "::update_end_date", LOG_DEBUG);
1028
        $resql = $this->db->query($sql);
1029
        if ($resql) {
1030
            $obj = $this->db->fetch_object($resql);
1031
            $dateop = $this->db->jdate($obj->dateop);
1032
            $datedeb = $this->db->jdate($obj->datedeb);
1033
            $datefin = $this->db->jdate($obj->datefin);
1034
1035
            $sql = "UPDATE " . MAIN_DB_PREFIX . "adherent SET";
1036
            $sql .= " datefin=" . ($datefin != '' ? "'" . $this->db->idate($datefin) . "'" : "null");
1037
            $sql .= " WHERE rowid = " . ((int) $this->id);
1038
1039
            dol_syslog(get_class($this) . "::update_end_date", LOG_DEBUG);
1040
            $resql = $this->db->query($sql);
1041
            if ($resql) {
1042
                $this->last_subscription_date = $dateop;
1043
                $this->last_subscription_date_start = $datedeb;
1044
                $this->last_subscription_date_end = $datefin;
1045
                $this->datefin = $datefin;
1046
                $this->db->commit();
1047
                return 1;
1048
            } else {
1049
                $this->db->rollback();
1050
                return -1;
1051
            }
1052
        } else {
1053
            $this->error = $this->db->lasterror();
1054
            $this->db->rollback();
1055
            return -1;
1056
        }
1057
    }
1058
1059
    /**
1060
     *  Fonction to delete a member and its data
1061
     *
1062
     *  @param  User    $user       User object
1063
     *  @param  int     $notrigger  1=Does not execute triggers, 0= execute triggers
1064
     *  @return int                 Return integer <0 if KO, 0=nothing to do, >0 if OK
1065
     */
1066
    public function delete($user, $notrigger = 0)
1067
    {
1068
        $result = 0;
1069
        $error = 0;
1070
        $errorflag = 0;
1071
1072
        // Check parameters
1073
        $rowid = $this->id;
1074
1075
        $this->db->begin();
1076
1077
        if (!$error && !$notrigger) {
1078
            // Call trigger
1079
            $result = $this->call_trigger('MEMBER_DELETE', $user);
1080
            if ($result < 0) {
1081
                $error++;
1082
            }
1083
            // End call triggers
1084
        }
1085
1086
        // Remove category
1087
        $sql = "DELETE FROM " . MAIN_DB_PREFIX . "categorie_member WHERE fk_member = " . ((int) $rowid);
1088
        dol_syslog(get_class($this) . "::delete", LOG_DEBUG);
1089
        $resql = $this->db->query($sql);
1090
        if (!$resql) {
1091
            $error++;
1092
            $this->error .= $this->db->lasterror();
1093
            $errorflag = -1;
1094
        }
1095
1096
        // Remove subscription
1097
        if (!$error) {
1098
            $sql = "DELETE FROM " . MAIN_DB_PREFIX . "subscription WHERE fk_adherent = " . ((int) $rowid);
1099
            dol_syslog(get_class($this) . "::delete", LOG_DEBUG);
1100
            $resql = $this->db->query($sql);
1101
            if (!$resql) {
1102
                $error++;
1103
                $this->error .= $this->db->lasterror();
1104
                $errorflag = -2;
1105
            }
1106
        }
1107
1108
        // Remove linked user
1109
        if (!$error) {
1110
            $ret = $this->setUserId(0);
1111
            if ($ret < 0) {
1112
                $error++;
1113
                $this->error .= $this->db->lasterror();
1114
                $errorflag = -3;
1115
            }
1116
        }
1117
1118
        // Removed extrafields
1119
        if (!$error) {
1120
            $result = $this->deleteExtraFields();
1121
            if ($result < 0) {
1122
                $error++;
1123
                $errorflag = -4;
1124
                dol_syslog(get_class($this) . "::delete erreur " . $errorflag . " " . $this->error, LOG_ERR);
1125
            }
1126
        }
1127
1128
        // Remove adherent
1129
        if (!$error) {
1130
            $sql = "DELETE FROM " . MAIN_DB_PREFIX . "adherent WHERE rowid = " . ((int) $rowid);
1131
            dol_syslog(get_class($this) . "::delete", LOG_DEBUG);
1132
            $resql = $this->db->query($sql);
1133
            if (!$resql) {
1134
                $error++;
1135
                $this->error .= $this->db->lasterror();
1136
                $errorflag = -5;
1137
            }
1138
        }
1139
1140
        if (!$error) {
1141
            $this->db->commit();
1142
            return 1;
1143
        } else {
1144
            $this->db->rollback();
1145
            return $errorflag;
1146
        }
1147
    }
1148
1149
1150
    /**
1151
     *    Change password of a user
1152
     *
1153
     *    @param    User    $user           Object user de l'utilisateur qui fait la modification
1154
     *    @param    string  $password       New password (to generate if empty)
1155
     *    @param    int     $isencrypted    0 ou 1 if the password needs to be encrypted in the DB (default: 0)
1156
     *    @param    int     $notrigger      1=Does not raise the triggers
1157
     *    @param    int     $nosyncuser     Do not synchronize linked user
1158
     *    @return   string|int              Clear password if change ok, 0 if no change, <0 if error
1159
     */
1160
    public function setPassword($user, $password = '', $isencrypted = 0, $notrigger = 0, $nosyncuser = 0)
1161
    {
1162
        global $conf, $langs;
1163
1164
        $error = 0;
1165
1166
        dol_syslog(get_class($this) . "::setPassword user=" . $user->id . " password=" . preg_replace('/./i', '*', $password) . " isencrypted=" . $isencrypted);
1167
1168
        // If new password not provided, we generate one
1169
        if (!$password) {
1170
            require_once constant('DOL_DOCUMENT_ROOT') . '/core/lib/security2.lib.php';
1171
            $password = getRandomPassword(false);
1172
        }
1173
1174
        // Crypt password
1175
        $password_crypted = dol_hash($password);
1176
1177
        $password_indatabase = '';
1178
        if (!$isencrypted) {
1179
            $password_indatabase = $password;
1180
        }
1181
1182
        $this->db->begin();
1183
1184
        // Mise a jour
1185
        $sql = "UPDATE " . MAIN_DB_PREFIX . "adherent";
1186
        $sql .= " SET pass_crypted = '" . $this->db->escape($password_crypted) . "'";
1187
        if ($isencrypted) {
1188
            $sql .= ", pass = null";
1189
        } else {
1190
            $sql .= ", pass = '" . $this->db->escape($password_indatabase) . "'";
1191
        }
1192
        $sql .= " WHERE rowid = " . ((int) $this->id);
1193
1194
        //dol_syslog("Adherent::Password sql=hidden");
1195
        dol_syslog(get_class($this) . "::setPassword", LOG_DEBUG);
1196
        $result = $this->db->query($sql);
1197
        if ($result) {
1198
            $nbaffectedrows = $this->db->affected_rows($result);
1199
1200
            if ($nbaffectedrows) {
1201
                $this->pass = $password;
1202
                $this->pass_indatabase = $password_indatabase;
1203
                $this->pass_indatabase_crypted = $password_crypted;
1204
1205
                if ($this->user_id && !$nosyncuser) {
1206
                    require_once constant('DOL_DOCUMENT_ROOT') . '/user/class/user.class.php';
1207
1208
                    // This member is linked with a user, so we also update users information
1209
                    // if this is an update.
1210
                    $luser = new User($this->db);
1211
                    $result = $luser->fetch($this->user_id);
1212
1213
                    if ($result >= 0) {
1214
                        $result = $luser->setPassword($user, $this->pass, 0, 0, 1);
1215
                        if (is_int($result) && $result < 0) {
1216
                            $this->error = $luser->error;
1217
                            dol_syslog(get_class($this) . "::setPassword " . $this->error, LOG_ERR);
1218
                            $error++;
1219
                        }
1220
                    } else {
1221
                        $this->error = $luser->error;
1222
                        $error++;
1223
                    }
1224
                }
1225
1226
                if (!$error && !$notrigger) {
1227
                    // Call trigger
1228
                    $result = $this->call_trigger('MEMBER_NEW_PASSWORD', $user);
1229
                    if ($result < 0) {
1230
                        $error++;
1231
                        $this->db->rollback();
1232
                        return -1;
1233
                    }
1234
                    // End call triggers
1235
                }
1236
1237
                $this->db->commit();
1238
                return $this->pass;
1239
            } else {
1240
                $this->db->rollback();
1241
                return 0;
1242
            }
1243
        } else {
1244
            $this->db->rollback();
1245
            dol_print_error($this->db);
1246
            return -1;
1247
        }
1248
    }
1249
1250
1251
    /**
1252
     *    Set link to a user
1253
     *
1254
     *    @param     int    $userid         Id of user to link to
1255
     *    @return    int                    1=OK, -1=KO
1256
     */
1257
    public function setUserId($userid)
1258
    {
1259
        global $conf, $langs;
1260
1261
        $this->db->begin();
1262
1263
        // If user is linked to this member, remove old link to this member
1264
        $sql = "UPDATE " . MAIN_DB_PREFIX . "user SET fk_member = NULL WHERE fk_member = " . ((int) $this->id);
1265
        dol_syslog(get_class($this) . "::setUserId", LOG_DEBUG);
1266
        $resql = $this->db->query($sql);
1267
        if (!$resql) {
1268
            $this->error = $this->db->error();
1269
            $this->db->rollback();
1270
            return -1;
1271
        }
1272
1273
        // Set link to user
1274
        if ($userid > 0) {
1275
            $sql = "UPDATE " . MAIN_DB_PREFIX . "user SET fk_member = " . ((int) $this->id);
1276
            $sql .= " WHERE rowid = " . ((int) $userid);
1277
            dol_syslog(get_class($this) . "::setUserId", LOG_DEBUG);
1278
            $resql = $this->db->query($sql);
1279
            if (!$resql) {
1280
                $this->error = $this->db->error();
1281
                $this->db->rollback();
1282
                return -2;
1283
            }
1284
        }
1285
1286
        $this->db->commit();
1287
1288
        return 1;
1289
    }
1290
1291
1292
    /**
1293
     *    Set link to a third party
1294
     *
1295
     *    @param     int    $thirdpartyid       Id of user to link to
1296
     *    @return    int                        1=OK, -1=KO
1297
     */
1298
    public function setThirdPartyId($thirdpartyid)
1299
    {
1300
        global $conf, $langs;
1301
1302
        $this->db->begin();
1303
1304
        // Remove link to third party onto any other members
1305
        if ($thirdpartyid > 0) {
1306
            $sql = "UPDATE " . MAIN_DB_PREFIX . "adherent SET fk_soc = null";
1307
            $sql .= " WHERE fk_soc = " . ((int) $thirdpartyid);
1308
            $sql .= " AND entity = " . $conf->entity;
1309
            dol_syslog(get_class($this) . "::setThirdPartyId", LOG_DEBUG);
1310
            $resql = $this->db->query($sql);
1311
        }
1312
1313
        // Add link to third party for current member
1314
        $sql = "UPDATE " . MAIN_DB_PREFIX . "adherent SET fk_soc = " . ($thirdpartyid > 0 ? (int) $thirdpartyid : 'null');
1315
        $sql .= " WHERE rowid = " . ((int) $this->id);
1316
1317
        dol_syslog(get_class($this) . "::setThirdPartyId", LOG_DEBUG);
1318
        $resql = $this->db->query($sql);
1319
        if ($resql) {
1320
            $this->db->commit();
1321
            return 1;
1322
        } else {
1323
            $this->error = $this->db->error();
1324
            $this->db->rollback();
1325
            return -1;
1326
        }
1327
    }
1328
1329
1330
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1331
    /**
1332
     *  Method to load member from its login
1333
     *
1334
     *  @param  string  $login      login of member
1335
     *  @return void
1336
     */
1337
    public function fetch_login($login)
1338
    {
1339
		// phpcs:enable
1340
        global $conf;
1341
1342
        $sql = "SELECT rowid FROM " . MAIN_DB_PREFIX . "adherent";
1343
        $sql .= " WHERE login='" . $this->db->escape($login) . "'";
1344
        $sql .= " AND entity = " . $conf->entity;
1345
1346
        $resql = $this->db->query($sql);
1347
        if ($resql) {
1348
            if ($this->db->num_rows($resql)) {
1349
                $obj = $this->db->fetch_object($resql);
1350
                $this->fetch($obj->rowid);
1351
            }
1352
        } else {
1353
            dol_print_error($this->db);
1354
        }
1355
    }
1356
1357
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1358
    /**
1359
     *  Method to load member from its name
1360
     *
1361
     *  @param  string  $firstname  Firstname
1362
     *  @param  string  $lastname   Lastname
1363
     *  @return void
1364
     */
1365
    public function fetch_name($firstname, $lastname)
1366
    {
1367
		// phpcs:enable
1368
        global $conf;
1369
1370
        $sql = "SELECT rowid FROM " . MAIN_DB_PREFIX . "adherent";
1371
        $sql .= " WHERE firstname='" . $this->db->escape($firstname) . "'";
1372
        $sql .= " AND lastname='" . $this->db->escape($lastname) . "'";
1373
        $sql .= " AND entity = " . $conf->entity;
1374
1375
        $resql = $this->db->query($sql);
1376
        if ($resql) {
1377
            if ($this->db->num_rows($resql)) {
1378
                $obj = $this->db->fetch_object($resql);
1379
                $this->fetch($obj->rowid);
1380
            }
1381
        } else {
1382
            dol_print_error($this->db);
1383
        }
1384
    }
1385
1386
    /**
1387
     *  Load member from database
1388
     *
1389
     *  @param  int     $rowid                  Id of object to load
1390
     *  @param  string  $ref                    To load member from its ref
1391
     *  @param  int     $fk_soc                 To load member from its link to third party
1392
     *  @param  string  $ref_ext                External reference
1393
     *  @param  bool    $fetch_optionals        To load optionals (extrafields)
1394
     *  @param  bool    $fetch_subscriptions    To load member subscriptions
1395
     *  @return int                             >0 if OK, 0 if not found, <0 if KO
1396
     */
1397
    public function fetch($rowid, $ref = '', $fk_soc = 0, $ref_ext = '', $fetch_optionals = true, $fetch_subscriptions = true)
1398
    {
1399
        global $langs;
1400
1401
        $sql = "SELECT d.rowid, d.ref, d.ref_ext, d.civility as civility_code, d.gender, d.firstname, d.lastname,";
1402
        $sql .= " d.societe as company, d.fk_soc, d.statut, d.public, d.address, d.zip, d.town, d.note_private,";
1403
        $sql .= " d.note_public,";
1404
        $sql .= " d.email, d.url, d.socialnetworks, d.phone, d.phone_perso, d.phone_mobile, d.login, d.pass, d.pass_crypted,";
1405
        $sql .= " d.photo, d.fk_adherent_type, d.morphy, d.entity,";
1406
        $sql .= " d.datec as datec,";
1407
        $sql .= " d.tms as datem,";
1408
        $sql .= " d.datefin as datefin, d.default_lang,";
1409
        $sql .= " d.birth as birthday,";
1410
        $sql .= " d.datevalid as datev,";
1411
        $sql .= " d.country,";
1412
        $sql .= " d.state_id,";
1413
        $sql .= " d.model_pdf,";
1414
        $sql .= " c.rowid as country_id, c.code as country_code, c.label as country,";
1415
        $sql .= " dep.nom as state, dep.code_departement as state_code,";
1416
        $sql .= " t.libelle as type, t.subscription as subscription,";
1417
        $sql .= " u.rowid as user_id, u.login as user_login";
1418
        $sql .= " FROM " . MAIN_DB_PREFIX . "adherent_type as t, " . MAIN_DB_PREFIX . "adherent as d";
1419
        $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "c_country as c ON d.country = c.rowid";
1420
        $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "c_departements as dep ON d.state_id = dep.rowid";
1421
        $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "user as u ON d.rowid = u.fk_member";
1422
        $sql .= " WHERE d.fk_adherent_type = t.rowid";
1423
        if ($rowid) {
1424
            $sql .= " AND d.rowid=" . ((int) $rowid);
1425
        } elseif ($ref || $fk_soc) {
1426
            $sql .= " AND d.entity IN (" . getEntity('adherent') . ")";
1427
            if ($ref) {
1428
                $sql .= " AND d.ref='" . $this->db->escape($ref) . "'";
1429
            } elseif ($fk_soc > 0) {
1430
                $sql .= " AND d.fk_soc=" . ((int) $fk_soc);
1431
            }
1432
        } elseif ($ref_ext) {
1433
            $sql .= " AND d.ref_ext='" . $this->db->escape($ref_ext) . "'";
1434
        }
1435
1436
        dol_syslog(get_class($this) . "::fetch", LOG_DEBUG);
1437
        $resql = $this->db->query($sql);
1438
        if ($resql) {
1439
            if ($this->db->num_rows($resql)) {
1440
                $obj = $this->db->fetch_object($resql);
1441
1442
                $this->entity = $obj->entity;
1443
                $this->id = $obj->rowid;
1444
                $this->ref = $obj->ref;
1445
                $this->ref_ext = $obj->ref_ext;
1446
1447
                $this->civility_id = $obj->civility_code; // Bad. Kept for backward compatibility
1448
                $this->civility_code = $obj->civility_code;
1449
                $this->civility = $obj->civility_code ? ($langs->trans("Civility" . $obj->civility_code) != "Civility" . $obj->civility_code ? $langs->trans("Civility" . $obj->civility_code) : $obj->civility_code) : '';
1450
1451
                $this->firstname = $obj->firstname;
1452
                $this->lastname = $obj->lastname;
1453
                $this->gender = $obj->gender;
1454
                $this->login = $obj->login;
1455
                $this->societe = $obj->company;
1456
                $this->company = $obj->company;
1457
                $this->socid = $obj->fk_soc;
1458
                $this->fk_soc = $obj->fk_soc; // For backward compatibility
1459
                $this->address = $obj->address;
1460
                $this->zip = $obj->zip;
1461
                $this->town = $obj->town;
1462
1463
                $this->pass = $obj->pass;
1464
                $this->pass_indatabase = $obj->pass;
1465
                $this->pass_indatabase_crypted = $obj->pass_crypted;
1466
1467
                $this->state_id = $obj->state_id;
1468
                $this->state_code = $obj->state_id ? $obj->state_code : '';
1469
                $this->state = $obj->state_id ? $obj->state : '';
1470
1471
                $this->country_id = $obj->country_id;
1472
                $this->country_code = $obj->country_code;
1473
                if ($langs->trans("Country" . $obj->country_code) != "Country" . $obj->country_code) {
1474
                    $this->country = $langs->transnoentitiesnoconv("Country" . $obj->country_code);
1475
                } else {
1476
                    $this->country = $obj->country;
1477
                }
1478
1479
                $this->phone = $obj->phone;
1480
                $this->phone_perso = $obj->phone_perso;
1481
                $this->phone_mobile = $obj->phone_mobile;
1482
                $this->email = $obj->email;
1483
                $this->url = $obj->url;
1484
1485
                $this->socialnetworks = ($obj->socialnetworks ? (array) json_decode($obj->socialnetworks, true) : array());
1486
1487
                $this->photo = $obj->photo;
1488
                $this->statut = $obj->statut;
0 ignored issues
show
Deprecated Code introduced by
The property Dolibarr\Core\Base\CommonObject::$statut has been deprecated: Use $status instead. ( Ignorable by Annotation )

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

1488
                /** @scrutinizer ignore-deprecated */ $this->statut = $obj->statut;

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
1489
                $this->status = $obj->statut;
1490
                $this->public = $obj->public;
1491
1492
                $this->datec = $this->db->jdate($obj->datec);
1493
                $this->date_creation = $this->db->jdate($obj->datec);
1494
                $this->datem = $this->db->jdate($obj->datem);
1495
                $this->date_modification = $this->db->jdate($obj->datem);
1496
                $this->datefin = $this->db->jdate($obj->datefin);
1497
                $this->datevalid = $this->db->jdate($obj->datev);
1498
                $this->date_validation = $this->db->jdate($obj->datev);
1499
                $this->birth = $this->db->jdate($obj->birthday);
1500
1501
                $this->default_lang = $obj->default_lang;
1502
1503
                $this->note_private = $obj->note_private;
1504
                $this->note_public = $obj->note_public;
1505
                $this->morphy = $obj->morphy;
1506
1507
                $this->typeid = $obj->fk_adherent_type;
1508
                $this->type = $obj->type;
1509
                $this->need_subscription = $obj->subscription;
1510
1511
                $this->user_id = $obj->user_id;
1512
                $this->user_login = $obj->user_login;
1513
1514
                $this->model_pdf = $obj->model_pdf;
1515
1516
                // Retrieve all extrafield
1517
                // fetch optionals attributes and labels
1518
                if ($fetch_optionals) {
1519
                    $this->fetch_optionals();
1520
                }
1521
1522
                // Load other properties
1523
                if ($fetch_subscriptions) {
1524
                    $result = $this->fetch_subscriptions();
1525
                }
1526
1527
                return $this->id;
1528
            } else {
1529
                return 0;
1530
            }
1531
        } else {
1532
            $this->error = $this->db->lasterror();
1533
            return -1;
1534
        }
1535
    }
1536
1537
1538
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1539
    /**
1540
     *  Function to get member subscriptions data:
1541
     *  subscriptions,
1542
     *  first_subscription_date, first_subscription_date_start, first_subscription_date_end, first_subscription_amount
1543
     *  last_subscription_date, last_subscription_date_start, last_subscription_date_end, last_subscription_amount
1544
     *
1545
     *  @return     int         Return integer <0 if KO, >0 if OK
1546
     */
1547
    public function fetch_subscriptions()
1548
    {
1549
		// phpcs:enable
1550
        global $langs;
1551
1552
        require_once constant('DOL_DOCUMENT_ROOT') . '/adherents/class/subscription.class.php';
1553
1554
        $sql = "SELECT c.rowid, c.fk_adherent, c.fk_type, c.subscription, c.note as note_public, c.fk_bank,";
1555
        $sql .= " c.tms as datem,";
1556
        $sql .= " c.datec as datec,";
1557
        $sql .= " c.dateadh as dateh,";
1558
        $sql .= " c.datef as datef";
1559
        $sql .= " FROM " . MAIN_DB_PREFIX . "subscription as c";
1560
        $sql .= " WHERE c.fk_adherent = " . ((int) $this->id);
1561
        $sql .= " ORDER BY c.dateadh";
1562
        dol_syslog(get_class($this) . "::fetch_subscriptions", LOG_DEBUG);
1563
1564
        $resql = $this->db->query($sql);
1565
        if ($resql) {
1566
            $this->subscriptions = array();
1567
1568
            $i = 0;
1569
            while ($obj = $this->db->fetch_object($resql)) {
1570
                if ($i == 0) {
1571
                    $this->first_subscription_date = $this->db->jdate($obj->datec);
1572
                    $this->first_subscription_date_start = $this->db->jdate($obj->dateh);
1573
                    $this->first_subscription_date_end = $this->db->jdate($obj->datef);
1574
                    $this->first_subscription_amount = $obj->subscription;
1575
                }
1576
                $this->last_subscription_date = $this->db->jdate($obj->datec);
1577
                $this->last_subscription_date_start = $this->db->jdate($obj->dateh);
1578
                $this->last_subscription_date_end = $this->db->jdate($obj->datef);
1579
                $this->last_subscription_amount = $obj->subscription;
1580
1581
                $subscription = new Subscription($this->db);
1582
                $subscription->id = $obj->rowid;
1583
                $subscription->fk_adherent = $obj->fk_adherent;
1584
                $subscription->fk_type = $obj->fk_type;
1585
                $subscription->amount = $obj->subscription;
1586
                $subscription->note = $obj->note_public;
0 ignored issues
show
Deprecated Code introduced by
The property Dolibarr\Core\Base\CommonObject::$note has been deprecated: Use $note_private instead. ( Ignorable by Annotation )

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

1586
                /** @scrutinizer ignore-deprecated */ $subscription->note = $obj->note_public;

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
1587
                $subscription->note_public = $obj->note_public;
1588
                $subscription->fk_bank = $obj->fk_bank;
1589
                $subscription->datem = $this->db->jdate($obj->datem);
1590
                $subscription->datec = $this->db->jdate($obj->datec);
1591
                $subscription->dateh = $this->db->jdate($obj->dateh);
1592
                $subscription->datef = $this->db->jdate($obj->datef);
1593
1594
                $this->subscriptions[] = $subscription;
1595
1596
                $i++;
1597
            }
1598
            return 1;
1599
        } else {
1600
            $this->error = $this->db->error() . ' sql=' . $sql;
1601
            return -1;
1602
        }
1603
    }
1604
1605
1606
    /**
1607
     *  Function to get partnerships array
1608
     *
1609
     *  @param      string      $mode       'member' or 'thirdparty'
1610
     *  @return     int                     Return integer <0 if KO, >0 if OK
1611
     */
1612
    public function fetchPartnerships($mode)
1613
    {
1614
        global $langs;
1615
1616
        require_once constant('DOL_DOCUMENT_ROOT') . '/partnership/class/partnership.class.php';
1617
1618
1619
        $this->partnerships[] = array();
1620
1621
        return 1;
1622
    }
1623
1624
1625
    /**
1626
     *  Insert subscription into database and eventually add links to banks, mailman, etc...
1627
     *
1628
     *  @param  int         $date               Date of effect of subscription
1629
     *  @param  double      $amount             Amount of subscription (0 accepted for some members)
1630
     *  @param  int         $accountid          Id bank account. NOT USED.
1631
     *  @param  string      $operation          Code of payment mode (if Id bank account provided). Example: 'CB', ... NOT USED.
1632
     *  @param  string      $label              Label operation (if Id bank account provided).
1633
     *  @param  string      $num_chq            Numero cheque (if Id bank account provided)
1634
     *  @param  string      $emetteur_nom       Name of cheque writer
1635
     *  @param  string      $emetteur_banque    Name of bank of cheque
1636
     *  @param  int         $datesubend         Date end subscription
1637
     *  @param  int         $fk_type            Member type id
1638
     *  @return int                             rowid of record added, <0 if KO
1639
     */
1640
    public function subscription($date, $amount, $accountid = 0, $operation = '', $label = '', $num_chq = '', $emetteur_nom = '', $emetteur_banque = '', $datesubend = 0, $fk_type = null)
1641
    {
1642
        global $conf, $langs, $user;
1643
1644
        require_once constant('DOL_DOCUMENT_ROOT') . '/adherents/class/subscription.class.php';
1645
1646
        $error = 0;
1647
1648
        // Clean parameters
1649
        if (!$amount) {
1650
            $amount = 0;
1651
        }
1652
1653
        $this->db->begin();
1654
1655
        if ($datesubend) {
1656
            $datefin = $datesubend;
1657
        } else {
1658
            // If no end date, end date = date + 1 year - 1 day
1659
            $datefin = dol_time_plus_duree($date, 1, 'y');
1660
            $datefin = dol_time_plus_duree($datefin, -1, 'd');
1661
        }
1662
1663
        // Create subscription
1664
        $subscription = new Subscription($this->db);
1665
        $subscription->fk_adherent = $this->id;
1666
        $subscription->dateh = $date; // Date of new subscription
1667
        $subscription->datef = $datefin; // End data of new subscription
1668
        $subscription->amount = $amount;
1669
        $subscription->note = $label; // deprecated
0 ignored issues
show
Deprecated Code introduced by
The property Dolibarr\Core\Base\CommonObject::$note has been deprecated: Use $note_private instead. ( Ignorable by Annotation )

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

1669
        /** @scrutinizer ignore-deprecated */ $subscription->note = $label; // deprecated

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
1670
        $subscription->note_public = $label;
1671
        $subscription->fk_type = $fk_type;
1672
1673
        $rowid = $subscription->create($user);
1674
        if ($rowid > 0) {
1675
            // Update denormalized subscription end date (read database subscription to find values)
1676
            // This will also update this->datefin
1677
            $result = $this->update_end_date($user);
1678
            if ($result > 0) {
1679
                // Change properties of object (used by triggers)
1680
                $this->last_subscription_date = dol_now();
1681
                $this->last_subscription_date_start = $date;
1682
                $this->last_subscription_date_end = $datefin;
1683
                $this->last_subscription_amount = $amount;
1684
            }
1685
1686
            if (!$error) {
1687
                $this->db->commit();
1688
                return $rowid;
1689
            } else {
1690
                $this->db->rollback();
1691
                return -2;
1692
            }
1693
        } else {
1694
            $this->setErrorsFromObject($subscription);
1695
            $this->db->rollback();
1696
            return -1;
1697
        }
1698
    }
1699
1700
1701
    /**
1702
     *  Do complementary actions after subscription recording.
1703
     *
1704
     *  @param  int         $subscriptionid         Id of created subscription
1705
     *  @param  string      $option                 Which action ('bankdirect', 'bankviainvoice', 'invoiceonly', ...)
1706
     *  @param  int         $accountid              Id bank account
1707
     *  @param  int         $datesubscription       Date of subscription
1708
     *  @param  int         $paymentdate            Date of payment
1709
     *  @param  string      $operation              Code of type of operation (if Id bank account provided). Example 'CB', ...
1710
     *  @param  string      $label                  Label operation (if Id bank account provided)
1711
     *  @param  double      $amount                 Amount of subscription (0 accepted for some members)
1712
     *  @param  string      $num_chq                Numero cheque (if Id bank account provided)
1713
     *  @param  string      $emetteur_nom           Name of cheque writer
1714
     *  @param  string      $emetteur_banque        Name of bank of cheque
1715
     *  @param  int         $autocreatethirdparty   Auto create new thirdparty if member not yet linked to a thirdparty and we request an option that generate invoice.
1716
     *  @param  string      $ext_payment_id         External id of payment (for example Stripe charge id)
1717
     *  @param  string      $ext_payment_site       Name of external paymentmode (for example 'stripe')
1718
     *  @return int                                 Return integer <0 if KO, >0 if OK
1719
     */
1720
    public function subscriptionComplementaryActions($subscriptionid, $option, $accountid, $datesubscription, $paymentdate, $operation, $label, $amount, $num_chq, $emetteur_nom = '', $emetteur_banque = '', $autocreatethirdparty = 0, $ext_payment_id = '', $ext_payment_site = '')
1721
    {
1722
        global $conf, $langs, $user, $mysoc;
1723
1724
        $error = 0;
1725
1726
        $this->invoice = null; // This will contains invoice if an invoice is created
1727
1728
        dol_syslog("subscriptionComplementaryActions subscriptionid=" . $subscriptionid . " option=" . $option . " accountid=" . $accountid . " datesubscription=" . $datesubscription . " paymentdate=" .
1729
            $paymentdate . " label=" . $label . " amount=" . $amount . " num_chq=" . $num_chq . " autocreatethirdparty=" . $autocreatethirdparty);
1730
1731
        // Insert into bank account directlty (if option chosen for) + link to llx_subscription if option is 'bankdirect'
1732
        if ($option == 'bankdirect' && $accountid) {
1733
            require_once constant('DOL_DOCUMENT_ROOT') . '/compta/bank/class/account.class.php';
1734
1735
            $acct = new Account($this->db);
0 ignored issues
show
Bug introduced by
The type Dolibarr\Code\Adherents\Classes\Account was not found. Did you mean Account? If so, make sure to prefix the type with \.
Loading history...
1736
            $result = $acct->fetch($accountid);
1737
1738
            $dateop = $paymentdate;
1739
1740
            $insertid = $acct->addline($dateop, $operation, $label, $amount, $num_chq, '', $user, $emetteur_nom, $emetteur_banque);
1741
            if ($insertid > 0) {
1742
                $inserturlid = $acct->add_url_line($insertid, $this->id, constant('BASE_URL') . '/adherents/card.php?rowid=', $this->getFullName($langs), 'member');
1743
                if ($inserturlid > 0) {
1744
                    // Update table subscription
1745
                    $sql = "UPDATE " . MAIN_DB_PREFIX . "subscription SET fk_bank=" . ((int) $insertid);
1746
                    $sql .= " WHERE rowid=" . ((int) $subscriptionid);
1747
1748
                    dol_syslog("subscription::subscription", LOG_DEBUG);
1749
                    $resql = $this->db->query($sql);
1750
                    if (!$resql) {
1751
                        $error++;
1752
                        $this->error = $this->db->lasterror();
1753
                        $this->errors[] = $this->error;
1754
                    }
1755
                } else {
1756
                    $error++;
1757
                    $this->setErrorsFromObject($acct);
1758
                }
1759
            } else {
1760
                $error++;
1761
                $this->setErrorsFromObject($acct);
1762
            }
1763
        }
1764
1765
        // If option chosen, we create invoice
1766
        if (($option == 'bankviainvoice' && $accountid) || $option == 'invoiceonly') {
1767
            require_once constant('DOL_DOCUMENT_ROOT') . '/compta/facture/class/facture.class.php';
1768
            require_once constant('DOL_DOCUMENT_ROOT') . '/compta/facture/class/paymentterm.class.php';
1769
1770
            $invoice = new Facture($this->db);
1771
            $customer = new Societe($this->db);
1772
1773
            if (!$error) {
1774
                if (!($this->fk_soc > 0)) { // If not yet linked to a company
1775
                    if ($autocreatethirdparty) {
1776
                        // Create a linked thirdparty to member
1777
                        $companyalias = '';
1778
                        $fullname = $this->getFullName($langs);
1779
1780
                        if ($this->morphy == 'mor') {
1781
                            $companyname = $this->company;
1782
                            if (!empty($fullname)) {
1783
                                $companyalias = $fullname;
1784
                            }
1785
                        } else {
1786
                            $companyname = $fullname;
1787
                            if (!empty($this->company)) {
1788
                                $companyalias = $this->company;
1789
                            }
1790
                        }
1791
1792
                        $result = $customer->create_from_member($this, $companyname, $companyalias);
1793
                        if ($result < 0) {
1794
                            $this->error = $customer->error;
1795
                            $this->errors = $customer->errors;
1796
                            $error++;
1797
                        } else {
1798
                            $this->fk_soc = $result;
1799
                        }
1800
                    } else {
1801
                        $langs->load("errors");
1802
                        $this->error = $langs->trans("ErrorMemberNotLinkedToAThirpartyLinkOrCreateFirst");
1803
                        $this->errors[] = $this->error;
1804
                        $error++;
1805
                    }
1806
                }
1807
            }
1808
            if (!$error) {
1809
                $result = $customer->fetch($this->fk_soc);
1810
                if ($result <= 0) {
1811
                    $this->error = $customer->error;
1812
                    $this->errors = $customer->errors;
1813
                    $error++;
1814
                }
1815
            }
1816
1817
            if (!$error) {
1818
                // Create draft invoice
1819
                $invoice->type = Facture::TYPE_STANDARD;
1820
                $invoice->cond_reglement_id = $customer->cond_reglement_id;
1821
                if (empty($invoice->cond_reglement_id)) {
1822
                    $paymenttermstatic = new PaymentTerm($this->db);
0 ignored issues
show
Bug introduced by
The type Dolibarr\Code\Adherents\Classes\PaymentTerm was not found. Did you mean PaymentTerm? If so, make sure to prefix the type with \.
Loading history...
1823
                    $invoice->cond_reglement_id = $paymenttermstatic->getDefaultId();
1824
                    if (empty($invoice->cond_reglement_id)) {
1825
                        $error++;
1826
                        $this->error = 'ErrorNoPaymentTermRECEPFound';
1827
                        $this->errors[] = $this->error;
1828
                    }
1829
                }
1830
                $invoice->socid = $this->fk_soc;
1831
                //$invoice->date = $datesubscription;
1832
                $invoice->date = dol_now();
1833
1834
                // Possibility to add external linked objects with hooks
1835
                $invoice->linked_objects['subscription'] = $subscriptionid;
1836
                if (GETPOSTISARRAY('other_linked_objects')) {
1837
                    $invoice->linked_objects = array_merge($invoice->linked_objects, GETPOST('other_linked_objects', 'array:int'));
1838
                }
1839
1840
                $result = $invoice->create($user);
1841
                if ($result <= 0) {
1842
                    $this->error = $invoice->error;
1843
                    $this->errors = $invoice->errors;
1844
                    $error++;
1845
                } else {
1846
                    $this->invoice = $invoice;
1847
                }
1848
            }
1849
1850
            if (!$error) {
1851
                // Add line to draft invoice
1852
                $idprodsubscription = 0;
1853
                if (getDolGlobalString('ADHERENT_PRODUCT_ID_FOR_SUBSCRIPTIONS') && (isModEnabled("product") || isModEnabled("service"))) {
1854
                    $idprodsubscription = getDolGlobalString('ADHERENT_PRODUCT_ID_FOR_SUBSCRIPTIONS');
1855
                }
1856
1857
                $vattouse = 0;
1858
                if (getDolGlobalString('ADHERENT_VAT_FOR_SUBSCRIPTIONS') == 'defaultforfoundationcountry') {
1859
                    $vattouse = get_default_tva($mysoc, $mysoc, $idprodsubscription);
1860
                }
1861
                //print xx".$vattouse." - ".$mysoc." - ".$customer;exit;
1862
                // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
1863
                $result = $invoice->addline($label, 0, 1, $vattouse, 0, 0, $idprodsubscription, 0, $datesubscription, '', 0, 0, '', 'TTC', $amount, 1);
1864
                if ($result <= 0) {
1865
                    $this->error = $invoice->error;
1866
                    $this->errors = $invoice->errors;
1867
                    $error++;
1868
                }
1869
            }
1870
1871
            if (!$error) {
1872
                // Validate invoice
1873
                $result = $invoice->validate($user);
1874
                if ($result <= 0) {
1875
                    $this->error = $invoice->error;
1876
                    $this->errors = $invoice->errors;
1877
                    $error++;
1878
                }
1879
            }
1880
1881
            if (!$error) {
1882
                // TODO Link invoice with subscription ?
1883
            }
1884
1885
            // Add payment onto invoice
1886
            if (!$error && $option == 'bankviainvoice' && $accountid) {
1887
                require_once constant('DOL_DOCUMENT_ROOT') . '/compta/paiement/class/paiement.class.php';
1888
                require_once constant('DOL_DOCUMENT_ROOT') . '/compta/bank/class/account.class.php';
1889
                require_once constant('DOL_DOCUMENT_ROOT') . '/core/lib/functions.lib.php';
1890
1891
                $amounts = array();
1892
                $amounts[$invoice->id] = (float) price2num($amount);
1893
1894
                $paiement = new Paiement($this->db);
0 ignored issues
show
Bug introduced by
The type Dolibarr\Code\Adherents\Classes\Paiement was not found. Did you mean Paiement? If so, make sure to prefix the type with \.
Loading history...
1895
                $paiement->datepaye = $paymentdate;
1896
                $paiement->amounts = $amounts;
1897
                $paiement->paiementcode = $operation;
1898
                $paiement->paiementid = dol_getIdFromCode($this->db, $operation, 'c_paiement', 'code', 'id', 1);
1899
                $paiement->num_payment = $num_chq;
1900
                $paiement->note_public = $label;
1901
                $paiement->ext_payment_id = $ext_payment_id;
1902
                $paiement->ext_payment_site = $ext_payment_site;
1903
1904
                if (!$error) {
1905
                    // Create payment line for invoice
1906
                    $paiement_id = $paiement->create($user);
1907
                    if (!($paiement_id > 0)) {
1908
                        $this->error = $paiement->error;
1909
                        $this->errors = $paiement->errors;
1910
                        $error++;
1911
                    }
1912
                }
1913
1914
                if (!$error) {
1915
                    // Add transaction into bank account
1916
                    $bank_line_id = $paiement->addPaymentToBank($user, 'payment', '(SubscriptionPayment)', $accountid, $emetteur_nom, $emetteur_banque);
1917
                    if (!($bank_line_id > 0)) {
1918
                        $this->error = $paiement->error;
1919
                        $this->errors = $paiement->errors;
1920
                        $error++;
1921
                    }
1922
                }
1923
1924
                if (!$error && !empty($bank_line_id)) {
1925
                    // Update fk_bank into subscription table
1926
                    $sql = 'UPDATE ' . MAIN_DB_PREFIX . 'subscription SET fk_bank=' . ((int) $bank_line_id);
1927
                    $sql .= ' WHERE rowid=' . ((int) $subscriptionid);
1928
1929
                    $result = $this->db->query($sql);
1930
                    if (!$result) {
1931
                        $error++;
1932
                    }
1933
                }
1934
1935
                if (!$error) {
1936
                    // Set invoice as paid
1937
                    $invoice->setPaid($user);
1938
                }
1939
            }
1940
1941
            if (!$error) {
1942
                // Define output language
1943
                $outputlangs = $langs;
1944
                $newlang = '';
1945
                $lang_id = GETPOST('lang_id');
1946
                if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && !empty($lang_id)) {
1947
                    $newlang = $lang_id;
1948
                }
1949
                if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
1950
                    $newlang = $customer->default_lang;
1951
                }
1952
                if (!empty($newlang)) {
1953
                    $outputlangs = new Translate("", $conf);
0 ignored issues
show
Bug introduced by
The type Dolibarr\Code\Adherents\Classes\Translate was not found. Did you mean Translate? If so, make sure to prefix the type with \.
Loading history...
1954
                    $outputlangs->setDefaultLang($newlang);
1955
                }
1956
                // Generate PDF (whatever is option MAIN_DISABLE_PDF_AUTOUPDATE) so we can include it into email
1957
                //if (!getDolGlobalString('MAIN_DISABLE_PDF_AUTOUPDATE'))
1958
1959
                $invoice->generateDocument($invoice->model_pdf, $outputlangs);
1960
            }
1961
        }
1962
1963
        if ($error) {
1964
            return -1;
1965
        } else {
1966
            return 1;
1967
        }
1968
    }
1969
1970
1971
    /**
1972
     *      Function that validate a member
1973
     *
1974
     *      @param  User    $user       user adherent qui valide
1975
     *      @return int                 Return integer <0 if KO, 0 if nothing done, >0 if OK
1976
     */
1977
    public function validate($user)
1978
    {
1979
        global $langs, $conf;
1980
1981
        $error = 0;
1982
        $now = dol_now();
1983
1984
        // Check parameters
1985
        if ($this->statut == self::STATUS_VALIDATED) {
0 ignored issues
show
Deprecated Code introduced by
The property Dolibarr\Core\Base\CommonObject::$statut has been deprecated: Use $status instead. ( Ignorable by Annotation )

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

1985
        if (/** @scrutinizer ignore-deprecated */ $this->statut == self::STATUS_VALIDATED) {

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
1986
            dol_syslog(get_class($this) . "::validate statut of member does not allow this", LOG_WARNING);
1987
            return 0;
1988
        }
1989
1990
        $this->db->begin();
1991
1992
        $sql = "UPDATE " . MAIN_DB_PREFIX . "adherent SET";
1993
        $sql .= " statut = " . self::STATUS_VALIDATED;
1994
        $sql .= ", datevalid = '" . $this->db->idate($now) . "'";
1995
        $sql .= ", fk_user_valid = " . ((int) $user->id);
1996
        $sql .= " WHERE rowid = " . ((int) $this->id);
1997
1998
        dol_syslog(get_class($this) . "::validate", LOG_DEBUG);
1999
        $result = $this->db->query($sql);
2000
        if ($result) {
2001
            $this->statut = self::STATUS_VALIDATED;
0 ignored issues
show
Deprecated Code introduced by
The property Dolibarr\Core\Base\CommonObject::$statut has been deprecated: Use $status instead. ( Ignorable by Annotation )

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

2001
            /** @scrutinizer ignore-deprecated */ $this->statut = self::STATUS_VALIDATED;

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
2002
2003
            // Call trigger
2004
            $result = $this->call_trigger('MEMBER_VALIDATE', $user);
2005
            if ($result < 0) {
2006
                $error++;
2007
                $this->db->rollback();
2008
                return -1;
2009
            }
2010
            // End call triggers
2011
2012
            $this->datevalid = $now;
2013
2014
            $this->db->commit();
2015
            return 1;
2016
        } else {
2017
            $this->error = $this->db->error();
2018
            $this->db->rollback();
2019
            return -1;
2020
        }
2021
    }
2022
2023
2024
    /**
2025
     *      Fonction qui resilie un adherent
2026
     *
2027
     *      @param  User    $user       User making change
2028
     *      @return int                 Return integer <0 if KO, >0 if OK
2029
     */
2030
    public function resiliate($user)
2031
    {
2032
        global $langs, $conf;
2033
2034
        $error = 0;
2035
2036
        // Check parameters
2037
        if ($this->statut == self::STATUS_RESILIATED) {
0 ignored issues
show
Deprecated Code introduced by
The property Dolibarr\Core\Base\CommonObject::$statut has been deprecated: Use $status instead. ( Ignorable by Annotation )

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

2037
        if (/** @scrutinizer ignore-deprecated */ $this->statut == self::STATUS_RESILIATED) {

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
2038
            dol_syslog(get_class($this) . "::resiliate statut of member does not allow this", LOG_WARNING);
2039
            return 0;
2040
        }
2041
2042
        $this->db->begin();
2043
2044
        $sql = "UPDATE " . MAIN_DB_PREFIX . "adherent SET";
2045
        $sql .= " statut = " . self::STATUS_RESILIATED;
2046
        $sql .= ", fk_user_valid=" . $user->id;
2047
        $sql .= " WHERE rowid = " . ((int) $this->id);
2048
2049
        $result = $this->db->query($sql);
2050
        if ($result) {
2051
            $this->statut = self::STATUS_RESILIATED;
0 ignored issues
show
Deprecated Code introduced by
The property Dolibarr\Core\Base\CommonObject::$statut has been deprecated: Use $status instead. ( Ignorable by Annotation )

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

2051
            /** @scrutinizer ignore-deprecated */ $this->statut = self::STATUS_RESILIATED;

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
2052
2053
            // Call trigger
2054
            $result = $this->call_trigger('MEMBER_RESILIATE', $user);
2055
            if ($result < 0) {
2056
                $error++;
2057
                $this->db->rollback();
2058
                return -1;
2059
            }
2060
            // End call triggers
2061
2062
            $this->db->commit();
2063
            return 1;
2064
        } else {
2065
            $this->error = $this->db->error();
2066
            $this->db->rollback();
2067
            return -1;
2068
        }
2069
    }
2070
2071
    /**
2072
     *      Functiun to exclude (set adherent.status to -2) a member
2073
     *      TODO
2074
     *      A private note should be added to know why the member has been excluded
2075
     *      For historical purpose it add an "extra-subscription" type excluded
2076
     *
2077
     *      @param  User    $user       User making change
2078
     *      @return int                 Return integer <0 if KO, >0 if OK
2079
     */
2080
    public function exclude($user)
2081
    {
2082
        $error = 0;
2083
2084
        // Check parameters
2085
        if ($this->statut == self::STATUS_EXCLUDED) {
0 ignored issues
show
Deprecated Code introduced by
The property Dolibarr\Core\Base\CommonObject::$statut has been deprecated: Use $status instead. ( Ignorable by Annotation )

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

2085
        if (/** @scrutinizer ignore-deprecated */ $this->statut == self::STATUS_EXCLUDED) {

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
2086
            dol_syslog(get_class($this) . "::resiliate statut of member does not allow this", LOG_WARNING);
2087
            return 0;
2088
        }
2089
2090
        $this->db->begin();
2091
2092
        $sql = "UPDATE " . MAIN_DB_PREFIX . "adherent SET";
2093
        $sql .= " statut = " . self::STATUS_EXCLUDED;
2094
        $sql .= ", fk_user_valid=" . $user->id;
2095
        $sql .= " WHERE rowid = " . ((int) $this->id);
2096
2097
        $result = $this->db->query($sql);
2098
        if ($result) {
2099
            $this->statut = self::STATUS_EXCLUDED;
0 ignored issues
show
Deprecated Code introduced by
The property Dolibarr\Core\Base\CommonObject::$statut has been deprecated: Use $status instead. ( Ignorable by Annotation )

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

2099
            /** @scrutinizer ignore-deprecated */ $this->statut = self::STATUS_EXCLUDED;

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
2100
2101
            // Call trigger
2102
            $result = $this->call_trigger('MEMBER_EXCLUDE', $user);
2103
            if ($result < 0) {
2104
                $error++;
2105
                $this->db->rollback();
2106
                return -1;
2107
            }
2108
            // End call triggers
2109
2110
            $this->db->commit();
2111
            return 1;
2112
        } else {
2113
            $this->error = $this->db->error();
2114
            $this->db->rollback();
2115
            return -1;
2116
        }
2117
    }
2118
2119
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2120
    /**
2121
     *  Function to add member into external tools mailing-list, spip, etc.
2122
     *
2123
     *  @return     int     Return integer <0 if KO, >0 if OK
2124
     */
2125
    public function add_to_abo()
2126
    {
2127
		// phpcs:enable
2128
        global $langs;
2129
2130
        include_once DOL_DOCUMENT_ROOT . '/mailmanspip/class/mailmanspip.class.php';
2131
        $mailmanspip = new MailmanSpip($this->db);
0 ignored issues
show
Bug introduced by
The type Dolibarr\Code\Adherents\Classes\MailmanSpip was not found. Did you mean MailmanSpip? If so, make sure to prefix the type with \.
Loading history...
2132
2133
        $err = 0;
2134
2135
        // mailman
2136
        if (getDolGlobalString('ADHERENT_USE_MAILMAN') && isModEnabled('mailmanspip')) {
2137
            $result = $mailmanspip->add_to_mailman($this);
2138
2139
            if ($result < 0) {
2140
                if (!empty($mailmanspip->error)) {
2141
                    $this->errors[] = $mailmanspip->error;
2142
                }
2143
                $err += 1;
2144
            }
2145
            foreach ($mailmanspip->mladded_ko as $tmplist => $tmpemail) {
2146
                $langs->load("errors");
2147
                $this->errors[] = $langs->trans("ErrorFailedToAddToMailmanList", $tmpemail, $tmplist);
2148
            }
2149
            foreach ($mailmanspip->mladded_ok as $tmplist => $tmpemail) {
2150
                $langs->load("mailmanspip");
2151
                $this->mesgs[] = $langs->trans("SuccessToAddToMailmanList", $tmpemail, $tmplist);
2152
            }
2153
        }
2154
2155
        // spip
2156
        if (getDolGlobalString('ADHERENT_USE_SPIP') && isModEnabled('mailmanspip')) {
2157
            $result = $mailmanspip->add_to_spip($this);
2158
            if ($result < 0) {
2159
                $this->errors[] = $mailmanspip->error;
2160
                $err += 1;
2161
            }
2162
        }
2163
        if ($err) {
2164
            return -$err;
2165
        } else {
2166
            return 1;
2167
        }
2168
    }
2169
2170
2171
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2172
    /**
2173
     *  Function to delete a member from external tools like mailing-list, spip, etc.
2174
     *
2175
     *  @return     int     Return integer <0 if KO, >0 if OK
2176
     */
2177
    public function del_to_abo()
2178
    {
2179
		// phpcs:enable
2180
        global $conf, $langs;
2181
2182
        include_once DOL_DOCUMENT_ROOT . '/mailmanspip/class/mailmanspip.class.php';
2183
        $mailmanspip = new MailmanSpip($this->db);
2184
2185
        $err = 0;
2186
2187
        // mailman
2188
        if (getDolGlobalString('ADHERENT_USE_MAILMAN')) {
2189
            $result = $mailmanspip->del_to_mailman($this);
2190
            if ($result < 0) {
2191
                if (!empty($mailmanspip->error)) {
2192
                    $this->errors[] = $mailmanspip->error;
2193
                }
2194
                $err += 1;
2195
            }
2196
2197
            foreach ($mailmanspip->mlremoved_ko as $tmplist => $tmpemail) {
2198
                $langs->load("errors");
2199
                $this->errors[] = $langs->trans("ErrorFailedToRemoveToMailmanList", $tmpemail, $tmplist);
2200
            }
2201
            foreach ($mailmanspip->mlremoved_ok as $tmplist => $tmpemail) {
2202
                $langs->load("mailmanspip");
2203
                $this->mesgs[] = $langs->trans("SuccessToRemoveToMailmanList", $tmpemail, $tmplist);
2204
            }
2205
        }
2206
2207
        if (getDolGlobalString('ADHERENT_USE_SPIP') && isModEnabled('mailmanspip')) {
2208
            $result = $mailmanspip->del_to_spip($this);
2209
            if ($result < 0) {
2210
                $this->errors[] = $mailmanspip->error;
2211
                $err += 1;
2212
            }
2213
        }
2214
        if ($err) {
2215
            // error
2216
            return -$err;
2217
        } else {
2218
            return 1;
2219
        }
2220
    }
2221
2222
2223
    /**
2224
     *    Return civility label of a member
2225
     *
2226
     *    @return   string                  Translated name of civility (translated with transnoentitiesnoconv)
2227
     */
2228
    public function getCivilityLabel()
2229
    {
2230
        global $langs;
2231
        $langs->load("dict");
2232
2233
        $code = (empty($this->civility_id) ? '' : $this->civility_id);
2234
        if (empty($code)) {
2235
            return '';
2236
        }
2237
        return $langs->getLabelFromKey($this->db, "Civility" . $code, "c_civility", "code", "label", $code);
2238
    }
2239
2240
    /**
2241
     * getTooltipContentArray
2242
     * @param array $params params to construct tooltip data
2243
     * @since v18
2244
     * @return array
2245
     */
2246
    public function getTooltipContentArray($params)
2247
    {
2248
        global $langs;
2249
2250
        $langs->loadLangs(['members', 'companies']);
2251
        $nofetch = !empty($params['nofetch']);
2252
2253
        $datas = array();
2254
2255
        if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
2256
            $langs->load("users");
2257
            return ['optimize' => $langs->trans("ShowUser")];
2258
        }
2259
        if (!empty($this->photo)) {
2260
            $photo = '<div class="photointooltip floatright">';
2261
            $photo .= Form::showphoto('memberphoto', $this, 80, 0, 0, 'photoref photowithmargin photologintooltip', 'small', 0, 1);
0 ignored issues
show
Bug introduced by
The type Dolibarr\Code\Adherents\Classes\Form was not found. Did you mean Form? If so, make sure to prefix the type with \.
Loading history...
2262
            $photo .= '</div>';
2263
            $datas['photo'] = $photo;
2264
        }
2265
2266
        $datas['divopen'] = '<div class="centpercent">';
2267
        $datas['picto'] = img_picto('', $this->picto) . ' <u class="paddingrightonly">' . $langs->trans("Member") . '</u> ' . $this->getLibStatut(4);
2268
        if (!empty($this->morphy)) {
2269
            $datas['picto'] .= '&nbsp;' . $this->getmorphylib('', 1);
2270
        }
2271
        if (!empty($this->ref)) {
2272
            $datas['ref'] = '<br><b>' . $langs->trans('Ref') . ':</b> ' . $this->ref;
2273
        }
2274
        if (!empty($this->login)) {
2275
            $datas['login'] = '<br><b>' . $langs->trans('Login') . ':</b> ' . $this->login;
2276
        }
2277
        if (!empty($this->firstname) || !empty($this->lastname)) {
2278
            $datas['name'] = '<br><b>' . $langs->trans('Name') . ':</b> ' . $this->getFullName($langs);
2279
        }
2280
        if (!empty($this->company)) {
2281
            $datas['company'] = '<br><b>' . $langs->trans('Company') . ':</b> ' . $this->company;
2282
        }
2283
        if (!empty($this->email)) {
2284
            $datas['email'] = '<br><b>' . $langs->trans("EMail") . ':</b> ' . $this->email;
2285
        }
2286
        $datas['address'] = '<br><b>' . $langs->trans("Address") . ':</b> ' . dol_format_address($this, 1, ' ', $langs);
2287
        // show categories for this record only in ajax to not overload lists
2288
        if (isModEnabled('category') && !$nofetch) {
2289
            require_once constant('DOL_DOCUMENT_ROOT') . '/categories/class/categorie.class.php';
2290
            $form = new Form($this->db);
2291
            $datas['categories'] = '<br>' . $form->showCategories($this->id, Categorie::TYPE_MEMBER, 1);
0 ignored issues
show
Bug introduced by
The type Dolibarr\Code\Adherents\Classes\Categorie was not found. Did you mean Categorie? If so, make sure to prefix the type with \.
Loading history...
2292
        }
2293
        $datas['divclose'] = '</div>';
2294
2295
        return $datas;
2296
    }
2297
2298
    /**
2299
     *  Return clicable name (with picto eventually)
2300
     *
2301
     *  @param  int     $withpictoimg               0=No picto, 1=Include picto into link, 2=Only picto, -1=Include photo into link, -2=Only picto photo, -3=Only photo very small, -4=???)
2302
     *  @param  int     $maxlen                     length max label
2303
     *  @param  string  $option                     Page for link ('card', 'category', 'subscription', ...)
2304
     *  @param  string  $mode                       ''=Show firstname+lastname as label (using default order), 'firstname'=Show only firstname, 'lastname'=Show only lastname, 'login'=Show login, 'ref'=Show ref
2305
     *  @param  string  $morecss                    Add more css on link
2306
     *  @param  int     $save_lastsearch_value      -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
2307
     *  @param  int     $notooltip                  1=Disable tooltip
2308
     *  @param  int     $addlinktonotes             1=Add link to notes
2309
     *  @return string                              Chaine avec URL
2310
     */
2311
    public function getNomUrl($withpictoimg = 0, $maxlen = 0, $option = 'card', $mode = '', $morecss = '', $save_lastsearch_value = -1, $notooltip = 0, $addlinktonotes = 0)
2312
    {
2313
        global $conf, $langs, $hookmanager;
2314
2315
        if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER') && $withpictoimg) {
2316
            $withpictoimg = 0;
2317
        }
2318
2319
        $result = '';
2320
        $linkstart = '';
2321
        $linkend = '';
2322
        $classfortooltip = 'classfortooltip';
2323
        $dataparams = '';
2324
        $params = [
2325
            'id' => $this->id,
2326
            'objecttype' => $this->element,
2327
            'option' => $option,
2328
            'nofetch' => 1,
2329
        ];
2330
        if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
2331
            $classfortooltip = 'classforajaxtooltip';
2332
            $dataparams = ' data-params="' . dol_escape_htmltag(json_encode($params)) . '"';
2333
            $label = '';
2334
        } else {
2335
            $label = implode($this->getTooltipContentArray($params));
2336
        }
2337
2338
        $url = constant('BASE_URL') . '/adherents/card.php?rowid=' . ((int) $this->id);
2339
        if ($option == 'subscription') {
2340
            $url = constant('BASE_URL') . '/adherents/subscription.php?rowid=' . ((int) $this->id);
2341
        }
2342
2343
        if ($option != 'nolink') {
2344
            // Add param to save lastsearch_values or not
2345
            $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
2346
            if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
2347
                $add_save_lastsearch_values = 1;
2348
            }
2349
            if ($add_save_lastsearch_values) {
2350
                $url .= '&save_lastsearch_values=1';
2351
            }
2352
        }
2353
2354
        $linkstart .= '<a href="' . $url . '"';
2355
        $linkclose = "";
2356
        if (empty($notooltip)) {
2357
            if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
2358
                $langs->load("users");
2359
                $label = $langs->trans("ShowUser");
2360
                $linkclose .= ' alt="' . dol_escape_htmltag($label, 1) . '"';
2361
            }
2362
            $linkclose .= ($label ? ' title="' . dol_escape_htmltag($label, 1) . '"' : ' title="tocomplete"');
2363
            $linkclose .= $dataparams . ' class="' . $classfortooltip . ($morecss ? ' ' . $morecss : '') . '"';
2364
        }
2365
2366
        $linkstart .= $linkclose . '>';
2367
        $linkend = '</a>';
2368
2369
        $result .= $linkstart;
2370
2371
        if ($withpictoimg) {
2372
            $paddafterimage = '';
2373
            if (abs($withpictoimg) == 1 || abs($withpictoimg) == 4) {
2374
                $morecss .= ' paddingrightonly';
2375
            }
2376
            // Only picto
2377
            if ($withpictoimg > 0) {
2378
                $picto = '<span class="nopadding' . ($morecss ? ' userimg' . $morecss : '') . '">' . img_object('', 'user', $paddafterimage . ' ' . ($notooltip ? '' : $dataparams), 0, 0, $notooltip ? 0 : 1) . '</span>';
2379
            } else {
2380
                // Picto must be a photo
2381
                $picto = '<span class="nopadding' . ($morecss ? ' userimg' . $morecss : '') . '"' . ($paddafterimage ? ' ' . $paddafterimage : '') . '>';
2382
                $picto .= Form::showphoto('memberphoto', $this, 0, 0, 0, 'userphoto' . (($withpictoimg == -3 || $withpictoimg == -4) ? 'small' : ''), 'mini', 0, 1);
2383
                $picto .= '</span>';
2384
            }
2385
            $result .= $picto;
2386
        }
2387
        if (($withpictoimg > -2 && $withpictoimg != 2) || $withpictoimg == -4) {
2388
            if (!getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
2389
                $result .= '<span class="nopadding valignmiddle' . ((!isset($this->statut) || $this->statut) ? '' : ' strikefordisabled') .
0 ignored issues
show
Deprecated Code introduced by
The property Dolibarr\Core\Base\CommonObject::$statut has been deprecated: Use $status instead. ( Ignorable by Annotation )

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

2389
                $result .= '<span class="nopadding valignmiddle' . ((!isset(/** @scrutinizer ignore-deprecated */ $this->statut) || $this->statut) ? '' : ' strikefordisabled') .

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
2390
                ($morecss ? ' usertext' . $morecss : '') . '">';
2391
            }
2392
            if ($mode == 'login') {
2393
                $result .= dol_trunc($this->login, $maxlen);
2394
            } elseif ($mode == 'ref') {
2395
                $result .= $this->ref;
2396
            } else {
2397
                $result .= $this->getFullName($langs, '', ($mode == 'firstname' ? 2 : ($mode == 'lastname' ? 4 : -1)), $maxlen);
2398
            }
2399
            if (!getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
2400
                $result .= '</span>';
2401
            }
2402
        }
2403
2404
        $result .= $linkend;
2405
2406
        if ($addlinktonotes) {
2407
            if ($this->note_private) {
2408
                $notetoshow = $langs->trans("ViewPrivateNote") . ':<br>' . dol_string_nohtmltag($this->note_private, 1);
2409
                $result .= ' <span class="note inline-block">';
2410
                $result .= '<a href="' . constant('BASE_URL') . '/adherents/note.php?id=' . $this->id . '" class="classfortooltip" title="' . dol_escape_htmltag($notetoshow) . '">';
2411
                $result .= img_picto('', 'note');
2412
                $result .= '</a>';
2413
                $result .= '</span>';
2414
            }
2415
        }
2416
        global $action;
2417
        $hookmanager->initHooks(array($this->element . 'dao'));
2418
        $parameters = array('id' => $this->id, 'getnomurl' => &$result);
2419
        $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
2420
        if ($reshook > 0) {
2421
            $result = $hookmanager->resPrint;
2422
        } else {
2423
            $result .= $hookmanager->resPrint;
2424
        }
2425
        return $result;
2426
    }
2427
2428
    /**
2429
     *  Retourne le libelle du statut d'un adherent (brouillon, valide, resilie, exclu)
2430
     *
2431
     *  @param  int     $mode       0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto
2432
     *  @return string              Label
2433
     */
2434
    public function getLibStatut($mode = 0)
2435
    {
2436
        return $this->LibStatut($this->statut, $this->need_subscription, $this->datefin, $mode);
0 ignored issues
show
Deprecated Code introduced by
The property Dolibarr\Core\Base\CommonObject::$statut has been deprecated: Use $status instead. ( Ignorable by Annotation )

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

2436
        return $this->LibStatut(/** @scrutinizer ignore-deprecated */ $this->statut, $this->need_subscription, $this->datefin, $mode);

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
2437
    }
2438
2439
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2440
    /**
2441
     *  Renvoi le libelle d'un statut donne
2442
     *
2443
     *  @param  int         $status                 Id status
2444
     *  @param  int         $need_subscription      1 if member type need subscription, 0 otherwise
2445
     *  @param  int         $date_end_subscription  Date fin adhesion
2446
     *  @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
2447
     *  @return string                              Label
2448
     */
2449
    public function LibStatut($status, $need_subscription, $date_end_subscription, $mode = 0)
2450
    {
2451
		// phpcs:enable
2452
        global $langs;
2453
        $langs->load("members");
2454
2455
        $statusType = '';
2456
        $labelStatus = '';
2457
        $labelStatusShort = '';
2458
2459
        if ($status == self::STATUS_DRAFT) {
2460
            $statusType = 'status0';
2461
            $labelStatus = $langs->trans("MemberStatusDraft");
2462
            $labelStatusShort = $langs->trans("MemberStatusDraftShort");
2463
        } elseif ($status >= self::STATUS_VALIDATED) {
2464
            if ($need_subscription === 0) {
2465
                $statusType = 'status4';
2466
                $labelStatus = $langs->trans("Validated") . ' - ' . $langs->trans("MemberStatusNoSubscription");
2467
                $labelStatusShort = $langs->trans("MemberStatusNoSubscriptionShort");
2468
            } elseif (!$date_end_subscription) {
2469
                $statusType = 'status1';
2470
                $labelStatus = $langs->trans("Validated") . ' - ' . $langs->trans("WaitingSubscription");
2471
                $labelStatusShort = $langs->trans("WaitingSubscriptionShort");
2472
            } elseif ($date_end_subscription < dol_now()) { // expired
2473
                $statusType = 'status8';
2474
                $labelStatus = $langs->trans("Validated") . ' - ' . $langs->trans("MemberStatusActiveLate");
2475
                $labelStatusShort = $langs->trans("MemberStatusActiveLateShort");
2476
            } else {
2477
                $statusType = 'status4';
2478
                $labelStatus = $langs->trans("Validated") . ' - ' . $langs->trans("MemberStatusPaid");
2479
                $labelStatusShort = $langs->trans("MemberStatusPaidShort");
2480
            }
2481
        } elseif ($status == self::STATUS_RESILIATED) {
2482
            $statusType = 'status6';
2483
            $labelStatus = $langs->transnoentitiesnoconv("MemberStatusResiliated");
2484
            $labelStatusShort = $langs->transnoentitiesnoconv("MemberStatusResiliatedShort");
2485
        } elseif ($status == self::STATUS_EXCLUDED) {
2486
            $statusType = 'status10';
2487
            $labelStatus = $langs->transnoentitiesnoconv("MemberStatusExcluded");
2488
            $labelStatusShort = $langs->transnoentitiesnoconv("MemberStatusExcludedShort");
2489
        }
2490
2491
        return dolGetStatus($labelStatus, $labelStatusShort, '', $statusType, $mode);
2492
    }
2493
2494
2495
    /**
2496
     *      Load indicators this->nb in state board
2497
     *
2498
     *      @return     int         Return integer <0 if KO, >0 if OK
2499
     */
2500
    public function loadStateBoard()
2501
    {
2502
        global $conf;
2503
2504
        $this->nb = array();
2505
2506
        $sql = "SELECT count(a.rowid) as nb";
2507
        $sql .= " FROM " . MAIN_DB_PREFIX . "adherent as a";
2508
        $sql .= " WHERE a.statut > 0";
2509
        $sql .= " AND a.entity IN (" . getEntity('adherent') . ")";
2510
2511
        $resql = $this->db->query($sql);
2512
        if ($resql) {
2513
            while ($obj = $this->db->fetch_object($resql)) {
2514
                $this->nb["members"] = $obj->nb;
2515
            }
2516
            $this->db->free($resql);
2517
            return 1;
2518
        } else {
2519
            dol_print_error($this->db);
2520
            $this->error = $this->db->error();
2521
            return -1;
2522
        }
2523
    }
2524
2525
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2526
    /**
2527
     *      Load indicators for dashboard (this->nbtodo and this->nbtodolate)
2528
     *
2529
     *      @param  User    $user           Object user
2530
     *      @param  string  $mode           "expired" for membership to renew, "shift" for member to validate
2531
     *      @return WorkboardResponse|int   Return integer <0 if KO, WorkboardResponse if OK
2532
     */
2533
    public function load_board($user, $mode)
2534
    {
2535
		// phpcs:enable
2536
        global $conf, $langs;
2537
2538
        if ($user->socid) {
2539
            return -1; // protection pour eviter appel par utilisateur externe
2540
        }
2541
2542
        $now = dol_now();
2543
2544
        $sql = "SELECT a.rowid, a.datefin, a.statut";
2545
        $sql .= " FROM " . MAIN_DB_PREFIX . "adherent as a";
2546
        $sql .= ", " . MAIN_DB_PREFIX . "adherent_type as t";
2547
        $sql .= " WHERE a.fk_adherent_type = t.rowid";
2548
        if ($mode == 'expired') {
2549
            $sql .= " AND a.statut = " . self::STATUS_VALIDATED;
2550
            $sql .= " AND a.entity IN (" . getEntity('adherent') . ")";
2551
            $sql .= " AND ((a.datefin IS NULL or a.datefin < '" . $this->db->idate($now) . "') AND t.subscription = '1')";
2552
        } elseif ($mode == 'shift') {
2553
            $sql .= " AND a.statut = " . self::STATUS_DRAFT;
2554
            $sql .= " AND a.entity IN (" . getEntity('adherent') . ")";
2555
        }
2556
2557
        $resql = $this->db->query($sql);
2558
        if ($resql) {
2559
            $langs->load("members");
2560
2561
            $warning_delay = 0;
2562
            $url = '';
2563
            $label = '';
2564
            $labelShort = '';
2565
2566
            if ($mode == 'expired') {
2567
                $warning_delay = $conf->adherent->subscription->warning_delay / 60 / 60 / 24;
2568
                $label = $langs->trans("MembersWithSubscriptionToReceive");
2569
                $labelShort = $langs->trans("MembersWithSubscriptionToReceiveShort");
2570
                $url = constant('BASE_URL') . '/adherents/list.php?mainmenu=members&amp;statut=' . self::STATUS_VALIDATED . '&amp;filter=outofdate';
2571
            } elseif ($mode == 'shift') {
2572
                $warning_delay = $conf->adherent->subscription->warning_delay / 60 / 60 / 24;
2573
                $url = constant('BASE_URL') . '/adherents/list.php?mainmenu=members&amp;statut=' . self::STATUS_DRAFT;
2574
                $label = $langs->trans("MembersListToValid");
2575
                $labelShort = $langs->trans("ToValidate");
2576
            }
2577
2578
            $response = new WorkboardResponse();
0 ignored issues
show
Bug introduced by
The type Dolibarr\Code\Adherents\Classes\WorkboardResponse was not found. Did you mean WorkboardResponse? If so, make sure to prefix the type with \.
Loading history...
2579
            $response->warning_delay = $warning_delay;
2580
            $response->label = $label;
2581
            $response->labelShort = $labelShort;
2582
            $response->url = $url;
2583
            $response->img = img_object('', "user");
2584
2585
            $adherentstatic = new Adherent($this->db);
2586
2587
            while ($obj = $this->db->fetch_object($resql)) {
2588
                $response->nbtodo++;
2589
2590
                $adherentstatic->datefin = $this->db->jdate($obj->datefin);
2591
                $adherentstatic->statut = $obj->statut;
0 ignored issues
show
Deprecated Code introduced by
The property Dolibarr\Core\Base\CommonObject::$statut has been deprecated: Use $status instead. ( Ignorable by Annotation )

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

2591
                /** @scrutinizer ignore-deprecated */ $adherentstatic->statut = $obj->statut;

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
2592
2593
                if ($adherentstatic->hasDelay()) {
2594
                    $response->nbtodolate++;
2595
                }
2596
            }
2597
2598
            return $response;
2599
        } else {
2600
            dol_print_error($this->db);
2601
            $this->error = $this->db->error();
2602
            return -1;
2603
        }
2604
    }
2605
2606
2607
    /**
2608
     *  Create a document onto disk according to template module.
2609
     *
2610
     *  @param      string      $modele         Force template to use ('' to not force)
2611
     *  @param      Translate   $outputlangs    object lang a utiliser pour traduction
2612
     *  @param      int         $hidedetails    Hide details of lines
2613
     *  @param      int         $hidedesc       Hide description
2614
     *  @param      int         $hideref        Hide ref
2615
     *  @param   null|array  $moreparams     Array to provide more information
2616
     *  @return     int                         0 if KO, 1 if OK
2617
     */
2618
    public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
2619
    {
2620
        global $conf, $langs;
2621
2622
        $langs->load("orders");
2623
2624
        if (!dol_strlen($modele)) {
2625
            $modele = 'standard';
2626
2627
            if ($this->model_pdf) {
2628
                $modele = $this->model_pdf;
2629
            } elseif (getDolGlobalString('ADHERENT_ADDON_PDF')) {
2630
                $modele = getDolGlobalString('ADHERENT_ADDON_PDF');
2631
            }
2632
        }
2633
2634
        $modelpath = "core/modules/member/doc/";
2635
2636
        return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
2637
    }
2638
2639
2640
    /**
2641
     *  Initialise an instance with random values.
2642
     *  Used to build previews or test instances.
2643
     *  id must be 0 if object instance is a specimen.
2644
     *
2645
     *  @return int
2646
     */
2647
    public function initAsSpecimen()
2648
    {
2649
        global $user, $langs;
2650
        $now = dol_now();
2651
2652
        // Initialise parameters
2653
        $this->id = 0;
2654
        $this->ref = 'ABC001';
2655
        $this->entity = 1;
2656
        $this->specimen = 1;
2657
        $this->civility_id = 'MR';
2658
        $this->lastname = 'DOLIBARR';
2659
        $this->firstname = 'SPECIMEN';
2660
        $this->gender = 'man';
2661
        $this->login = 'dolibspec';
2662
        $this->pass = 'dolibspec';
2663
        $this->company = 'Societe ABC';
2664
        $this->address = '61 jump street';
2665
        $this->zip = '75000';
2666
        $this->town = 'Paris';
2667
        $this->country_id = 1;
2668
        $this->country_code = 'FR';
2669
        $this->country = 'France';
2670
        $this->morphy = 'mor';
2671
        $this->email = '[email protected]';
2672
        $this->socialnetworks = array(
2673
            'skype' => 'skypepseudo',
2674
            'twitter' => 'twitterpseudo',
2675
            'facebook' => 'facebookpseudo',
2676
            'linkedin' => 'linkedinpseudo',
2677
        );
2678
        $this->phone = '0999999999';
2679
        $this->phone_perso = '0999999998';
2680
        $this->phone_mobile = '0999999997';
2681
        $this->note_public = 'This is a public note';
2682
        $this->note_private = 'This is a private note';
2683
        $this->birth = $now;
2684
        $this->photo = '';
2685
        $this->public = 1;
2686
        $this->statut = self::STATUS_DRAFT;
0 ignored issues
show
Deprecated Code introduced by
The property Dolibarr\Core\Base\CommonObject::$statut has been deprecated: Use $status instead. ( Ignorable by Annotation )

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

2686
        /** @scrutinizer ignore-deprecated */ $this->statut = self::STATUS_DRAFT;

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
2687
2688
        $this->datefin = $now;
2689
        $this->datevalid = $now;
2690
        $this->default_lang = '';
2691
2692
        $this->typeid = 1; // Id type adherent
2693
        $this->type = 'Type adherent'; // Libelle type adherent
2694
        $this->need_subscription = 0;
2695
2696
        $this->first_subscription_date = $now;
2697
        $this->first_subscription_date_start = $this->first_subscription_date;
2698
        $this->first_subscription_date_end = dol_time_plus_duree($this->first_subscription_date_start, 1, 'y');
2699
        $this->first_subscription_amount = 10;
2700
2701
        $this->last_subscription_date = $this->first_subscription_date;
2702
        $this->last_subscription_date_start = $this->first_subscription_date;
2703
        $this->last_subscription_date_end = dol_time_plus_duree($this->last_subscription_date_start, 1, 'y');
2704
        $this->last_subscription_amount = 10;
2705
        return 1;
2706
    }
2707
2708
2709
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2710
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
2711
    /**
2712
     *  Retourne chaine DN complete dans l'annuaire LDAP pour l'objet
2713
     *
2714
     *  @param  array   $info       Info array loaded by _load_ldap_info
2715
     *  @param  int     $mode       0=Return full DN (uid=qqq,ou=xxx,dc=aaa,dc=bbb)
2716
     *                              1=Return DN without key inside (ou=xxx,dc=aaa,dc=bbb)
2717
     *                              2=Return key only (uid=qqq)
2718
     *  @return string              DN
2719
     */
2720
    public function _load_ldap_dn($info, $mode = 0)
2721
    {
2722
		// phpcs:enable
2723
        global $conf;
2724
        $dn = '';
2725
        if ($mode == 0) {
2726
            $dn = getDolGlobalString('LDAP_KEY_MEMBERS') . "=" . $info[getDolGlobalString('LDAP_KEY_MEMBERS')] . "," . getDolGlobalString('LDAP_MEMBER_DN');
2727
        }
2728
        if ($mode == 1) {
2729
            $dn = getDolGlobalString('LDAP_MEMBER_DN');
2730
        }
2731
        if ($mode == 2) {
2732
            $dn = getDolGlobalString('LDAP_KEY_MEMBERS') . "=" . $info[getDolGlobalString('LDAP_KEY_MEMBERS')];
2733
        }
2734
        return $dn;
2735
    }
2736
2737
2738
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2739
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
2740
    /**
2741
     *  Initialise tableau info (tableau des attributes LDAP)
2742
     *
2743
     *  @return     array       Tableau info des attributes
2744
     */
2745
    public function _load_ldap_info()
2746
    {
2747
		// phpcs:enable
2748
        global $conf, $langs;
2749
2750
        $info = array();
2751
        $socialnetworks = getArrayOfSocialNetworks();
2752
        $keymodified = false;
2753
2754
        // Object classes
2755
        $info["objectclass"] = explode(',', getDolGlobalString('LDAP_MEMBER_OBJECT_CLASS'));
2756
2757
        $this->fullname = $this->getFullName($langs);
2758
2759
        // For avoid ldap error when firstname and lastname are empty
2760
        if ($this->morphy == 'mor' && (empty($this->fullname) || $this->fullname == $this->company)) {
2761
            $this->fullname = $this->company;
2762
            $this->lastname = $this->company;
2763
        }
2764
2765
        // Possible LDAP KEY (constname => varname)
2766
        $ldapkey = array(
2767
            'LDAP_MEMBER_FIELD_FULLNAME' => 'fullname',
2768
            'LDAP_MEMBER_FIELD_NAME' => 'lastname',
2769
            'LDAP_MEMBER_FIELD_LOGIN' => 'login',
2770
            'LDAP_MEMBER_FIELD_LOGIN_SAMBA' => 'login',
2771
            'LDAP_MEMBER_FIELD_MAIL' => 'email'
2772
        );
2773
2774
        // Member
2775
        foreach ($ldapkey as $constname => $varname) {
2776
            if (!empty($this->$varname) && getDolGlobalString($constname)) {
2777
                $info[getDolGlobalString($constname)] = $this->$varname;
2778
2779
                // Check if it is the LDAP key and if its value has been changed
2780
                if (getDolGlobalString('LDAP_KEY_MEMBERS') && getDolGlobalString('LDAP_KEY_MEMBERS') == getDolGlobalString($constname)) {
2781
                    if (!empty($this->oldcopy) && $this->$varname != $this->oldcopy->$varname) {
2782
                        $keymodified = true; // For check if LDAP key has been modified
2783
                    }
2784
                }
2785
            }
2786
        }
2787
        if ($this->firstname && getDolGlobalString('LDAP_MEMBER_FIELD_FIRSTNAME')) {
2788
            $info[getDolGlobalString('LDAP_MEMBER_FIELD_FIRSTNAME')] = $this->firstname;
2789
        }
2790
        if ($this->poste && getDolGlobalString('LDAP_MEMBER_FIELD_TITLE')) {
2791
            $info[getDolGlobalString('LDAP_MEMBER_FIELD_TITLE')] = $this->poste;
2792
        }
2793
        if ($this->company && getDolGlobalString('LDAP_MEMBER_FIELD_COMPANY')) {
2794
            $info[getDolGlobalString('LDAP_MEMBER_FIELD_COMPANY')] = $this->company;
2795
        }
2796
        if ($this->address && getDolGlobalString('LDAP_MEMBER_FIELD_ADDRESS')) {
2797
            $info[getDolGlobalString('LDAP_MEMBER_FIELD_ADDRESS')] = $this->address;
2798
        }
2799
        if ($this->zip && getDolGlobalString('LDAP_MEMBER_FIELD_ZIP')) {
2800
            $info[getDolGlobalString('LDAP_MEMBER_FIELD_ZIP')] = $this->zip;
2801
        }
2802
        if ($this->town && getDolGlobalString('LDAP_MEMBER_FIELD_TOWN')) {
2803
            $info[getDolGlobalString('LDAP_MEMBER_FIELD_TOWN')] = $this->town;
2804
        }
2805
        if ($this->country_code && getDolGlobalString('LDAP_MEMBER_FIELD_COUNTRY')) {
2806
            $info[getDolGlobalString('LDAP_MEMBER_FIELD_COUNTRY')] = $this->country_code;
2807
        }
2808
        foreach ($socialnetworks as $key => $value) {
2809
            if ($this->socialnetworks[$value['label']] && getDolGlobalString('LDAP_MEMBER_FIELD_' . strtoupper($value['label']))) {
2810
                $info[getDolGlobalString('LDAP_MEMBER_FIELD_' . strtoupper($value['label']))] = $this->socialnetworks[$value['label']];
2811
            }
2812
        }
2813
        if ($this->phone && getDolGlobalString('LDAP_MEMBER_FIELD_PHONE')) {
2814
            $info[getDolGlobalString('LDAP_MEMBER_FIELD_PHONE')] = $this->phone;
2815
        }
2816
        if ($this->phone_perso && getDolGlobalString('LDAP_MEMBER_FIELD_PHONE_PERSO')) {
2817
            $info[getDolGlobalString('LDAP_MEMBER_FIELD_PHONE_PERSO')] = $this->phone_perso;
2818
        }
2819
        if ($this->phone_mobile && getDolGlobalString('LDAP_MEMBER_FIELD_MOBILE')) {
2820
            $info[getDolGlobalString('LDAP_MEMBER_FIELD_MOBILE')] = $this->phone_mobile;
2821
        }
2822
        if ($this->fax && getDolGlobalString('LDAP_MEMBER_FIELD_FAX')) {
2823
            $info[getDolGlobalString('LDAP_MEMBER_FIELD_FAX')] = $this->fax;
2824
        }
2825
        if ($this->note_private && getDolGlobalString('LDAP_MEMBER_FIELD_DESCRIPTION')) {
2826
            $info[getDolGlobalString('LDAP_MEMBER_FIELD_DESCRIPTION')] = dol_string_nohtmltag($this->note_private, 2);
2827
        }
2828
        if ($this->note_public && getDolGlobalString('LDAP_MEMBER_FIELD_NOTE_PUBLIC')) {
2829
            $info[getDolGlobalString('LDAP_MEMBER_FIELD_NOTE_PUBLIC')] = dol_string_nohtmltag($this->note_public, 2);
2830
        }
2831
        if ($this->birth && getDolGlobalString('LDAP_MEMBER_FIELD_BIRTHDATE')) {
2832
            $info[getDolGlobalString('LDAP_MEMBER_FIELD_BIRTHDATE')] = dol_print_date($this->birth, 'dayhourldap');
2833
        }
2834
        if (isset($this->statut) && getDolGlobalString('LDAP_FIELD_MEMBER_STATUS')) {
0 ignored issues
show
Deprecated Code introduced by
The property Dolibarr\Core\Base\CommonObject::$statut has been deprecated: Use $status instead. ( Ignorable by Annotation )

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

2834
        if (isset(/** @scrutinizer ignore-deprecated */ $this->statut) && getDolGlobalString('LDAP_FIELD_MEMBER_STATUS')) {

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
2835
            $info[getDolGlobalString('LDAP_FIELD_MEMBER_STATUS')] = $this->statut;
2836
        }
2837
        if ($this->datefin && getDolGlobalString('LDAP_FIELD_MEMBER_END_LASTSUBSCRIPTION')) {
2838
            $info[getDolGlobalString('LDAP_FIELD_MEMBER_END_LASTSUBSCRIPTION')] = dol_print_date($this->datefin, 'dayhourldap');
2839
        }
2840
2841
        // When password is modified
2842
        if (!empty($this->pass)) {
2843
            if (getDolGlobalString('LDAP_MEMBER_FIELD_PASSWORD')) {
2844
                $info[getDolGlobalString('LDAP_MEMBER_FIELD_PASSWORD')] = $this->pass; // this->pass = Unencrypted password
2845
            }
2846
            if (getDolGlobalString('LDAP_MEMBER_FIELD_PASSWORD_CRYPTED')) {
2847
                $info[getDolGlobalString('LDAP_MEMBER_FIELD_PASSWORD_CRYPTED')] = dol_hash($this->pass, 'openldap'); // Create OpenLDAP password (see LDAP_PASSWORD_HASH_TYPE)
2848
            }
2849
        } elseif (getDolGlobalString('LDAP_SERVER_PROTOCOLVERSION') !== '3') {
2850
            // Set LDAP password if possible
2851
            // If ldap key is modified and LDAPv3 we use ldap_rename function for avoid lose encrypt password
2852
            if (getDolGlobalString('DATABASE_PWD_ENCRYPTED')) { // This should be on on default installation
2853
                // Just for the case we use old md5 encryption (deprecated, no more used, kept for compatibility)
2854
                if (!getDolGlobalString('MAIN_SECURITY_HASH_ALGO') || getDolGlobalString('MAIN_SECURITY_HASH_ALGO') == 'md5') {
2855
                    if ($this->pass_indatabase_crypted && getDolGlobalString('LDAP_MEMBER_FIELD_PASSWORD_CRYPTED')) {
2856
                        // Create OpenLDAP MD5 password from Dolibarr MD5 password
2857
                        // Note: This suppose that "pass_indatabase_crypted" is a md5 (this should not happen anymore)"
2858
                        $info[getDolGlobalString('LDAP_MEMBER_FIELD_PASSWORD_CRYPTED')] = dolGetLdapPasswordHash($this->pass_indatabase_crypted, 'md5frommd5');
2859
                    }
2860
                }
2861
            } elseif (!empty($this->pass_indatabase)) {
2862
                // Use $this->pass_indatabase value if exists
2863
                if (getDolGlobalString('LDAP_MEMBER_FIELD_PASSWORD')) {
2864
                    $info[getDolGlobalString('LDAP_MEMBER_FIELD_PASSWORD')] = $this->pass_indatabase; // $this->pass_indatabase = Unencrypted password
2865
                }
2866
                if (getDolGlobalString('LDAP_MEMBER_FIELD_PASSWORD_CRYPTED')) {
2867
                    $info[getDolGlobalString('LDAP_MEMBER_FIELD_PASSWORD_CRYPTED')] = dol_hash($this->pass_indatabase, 'openldap'); // Create OpenLDAP password (see LDAP_PASSWORD_HASH_TYPE)
2868
                }
2869
            }
2870
        }
2871
2872
        // Subscriptions
2873
        if ($this->first_subscription_date && getDolGlobalString('LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_DATE')) {
2874
            $info[getDolGlobalString('LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_DATE')] = dol_print_date($this->first_subscription_date, 'dayhourldap');
2875
        }
2876
        if (isset($this->first_subscription_amount) && getDolGlobalString('LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_AMOUNT')) {
2877
            $info[getDolGlobalString('LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_AMOUNT')] = $this->first_subscription_amount;
2878
        }
2879
        if ($this->last_subscription_date && getDolGlobalString('LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_DATE')) {
2880
            $info[getDolGlobalString('LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_DATE')] = dol_print_date($this->last_subscription_date, 'dayhourldap');
2881
        }
2882
        if (isset($this->last_subscription_amount) && getDolGlobalString('LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_AMOUNT')) {
2883
            $info[getDolGlobalString('LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_AMOUNT')] = $this->last_subscription_amount;
2884
        }
2885
2886
        return $info;
2887
    }
2888
2889
2890
    /**
2891
     *      Load type info information in the member object
2892
     *
2893
     *      @param  int     $id       Id of member to load
2894
     *      @return void
2895
     */
2896
    public function info($id)
2897
    {
2898
        $sql = 'SELECT a.rowid, a.datec as datec,';
2899
        $sql .= ' a.datevalid as datev,';
2900
        $sql .= ' a.tms as datem,';
2901
        $sql .= ' a.fk_user_author, a.fk_user_valid, a.fk_user_mod';
2902
        $sql .= ' FROM ' . MAIN_DB_PREFIX . 'adherent as a';
2903
        $sql .= ' WHERE a.rowid = ' . ((int) $id);
2904
2905
        dol_syslog(get_class($this) . "::info", LOG_DEBUG);
2906
        $result = $this->db->query($sql);
2907
        if ($result) {
2908
            if ($this->db->num_rows($result)) {
2909
                $obj = $this->db->fetch_object($result);
2910
2911
                $this->id = $obj->rowid;
2912
2913
                $this->user_creation_id = $obj->fk_user_author;
2914
                $this->user_validation_id = $obj->fk_user_valid;
2915
                $this->user_modification_id = $obj->fk_user_mod;
2916
                $this->date_creation = $this->db->jdate($obj->datec);
2917
                $this->date_validation = $this->db->jdate($obj->datev);
2918
                $this->date_modification = $this->db->jdate($obj->datem);
2919
            }
2920
2921
            $this->db->free($result);
2922
        } else {
2923
            dol_print_error($this->db);
2924
        }
2925
    }
2926
2927
    /**
2928
     *  Return number of mass Emailing received by this member with its email
2929
     *
2930
     *  @return       int     Number of EMailings
2931
     */
2932
    public function getNbOfEMailings()
2933
    {
2934
        $sql = "SELECT count(mc.email) as nb";
2935
        $sql .= " FROM " . MAIN_DB_PREFIX . "mailing_cibles as mc";
2936
        $sql .= " WHERE mc.email = '" . $this->db->escape($this->email) . "'";
2937
        $sql .= " AND mc.statut NOT IN (-1,0)"; // -1 erreur, 0 non envoye, 1 envoye avec success
2938
2939
        $resql = $this->db->query($sql);
2940
        if ($resql) {
2941
            $obj = $this->db->fetch_object($resql);
2942
            $nb = $obj->nb;
2943
2944
            $this->db->free($resql);
2945
            return $nb;
2946
        } else {
2947
            $this->error = $this->db->error();
2948
            return -1;
2949
        }
2950
    }
2951
2952
    /**
2953
     * Sets object to supplied categories.
2954
     *
2955
     * Deletes object from existing categories not supplied.
2956
     * Adds it to non existing supplied categories.
2957
     * Existing categories are left untouch.
2958
     *
2959
     * @param   int[]|int   $categories     Category or categories IDs
2960
     * @return  int                         Return integer <0 if KO, >0 if OK
2961
     */
2962
    public function setCategories($categories)
2963
    {
2964
        require_once constant('DOL_DOCUMENT_ROOT') . '/categories/class/categorie.class.php';
2965
        return parent::setCategoriesCommon($categories, Categorie::TYPE_MEMBER);
2966
    }
2967
2968
    /**
2969
     * Function used to replace a thirdparty id with another one.
2970
     *
2971
     * @param DoliDB    $db             Database handler
2972
     * @param int       $origin_id      Old thirdparty id
2973
     * @param int       $dest_id        New thirdparty id
2974
     * @return bool
2975
     */
2976
    public static function replaceThirdparty($db, $origin_id, $dest_id)
2977
    {
2978
        $tables = array('adherent');
2979
2980
        return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
2981
    }
2982
2983
    /**
2984
     * Return if a member is late (subscription late) or not
2985
     *
2986
     * @return boolean     True if late, False if not late
2987
     */
2988
    public function hasDelay()
2989
    {
2990
        global $conf;
2991
2992
        //Only valid members
2993
        if ($this->statut != self::STATUS_VALIDATED) {
0 ignored issues
show
Deprecated Code introduced by
The property Dolibarr\Core\Base\CommonObject::$statut has been deprecated: Use $status instead. ( Ignorable by Annotation )

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

2993
        if (/** @scrutinizer ignore-deprecated */ $this->statut != self::STATUS_VALIDATED) {

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
2994
            return false;
2995
        }
2996
        if (!$this->datefin) {
2997
            return false;
2998
        }
2999
3000
        $now = dol_now();
3001
3002
        return $this->datefin < ($now - $conf->adherent->subscription->warning_delay);
3003
    }
3004
3005
3006
    /**
3007
     * Send reminders by emails before subscription end
3008
     * CAN BE A CRON TASK
3009
     *
3010
     * @param   string      $daysbeforeendlist      Nb of days before end of subscription (negative number = after subscription). Can be a list of delay, separated by a semicolon, for example '10;5;0;-5'
3011
     * @return  int                                 0 if OK, <>0 if KO (this function is used also by cron so only 0 is OK)
3012
     */
3013
    public function sendReminderForExpiredSubscription($daysbeforeendlist = '10')
3014
    {
3015
        global $conf, $langs, $mysoc, $user;
3016
3017
        $error = 0;
3018
        $this->output = '';
3019
        $this->error = '';
3020
3021
        $blockingerrormsg = '';
3022
3023
        if (!isModEnabled('member')) { // Should not happen. If module disabled, cron job should not be visible.
3024
            $langs->load("agenda");
3025
            $this->output = $langs->trans('ModuleNotEnabled', $langs->transnoentitiesnoconv("Adherent"));
3026
            return 0;
3027
        }
3028
        if (!getDolGlobalString('MEMBER_REMINDER_EMAIL')) {
3029
            $langs->load("agenda");
3030
            $this->output = $langs->trans('EventRemindersByEmailNotEnabled', $langs->transnoentitiesnoconv("Adherent"));
3031
            return 0;
3032
        }
3033
3034
        $now = dol_now();
3035
        $nbok = 0;
3036
        $nbko = 0;
3037
3038
        $listofmembersok = array();
3039
        $listofmembersko = array();
3040
3041
        $arraydaysbeforeend = explode(';', $daysbeforeendlist);
3042
        foreach ($arraydaysbeforeend as $daysbeforeend) { // Loop on each delay
3043
            dol_syslog(__METHOD__ . ' - Process delta = ' . $daysbeforeend, LOG_DEBUG);
3044
3045
            if (!is_numeric($daysbeforeend)) {
3046
                $blockingerrormsg = "Value for delta is not a numeric value";
3047
                $nbko++;
3048
                break;
3049
            }
3050
3051
            $tmp = dol_getdate($now);
3052
            $datetosearchfor = dol_time_plus_duree(dol_mktime(0, 0, 0, $tmp['mon'], $tmp['mday'], $tmp['year'], 'tzserver'), $daysbeforeend, 'd');
3053
3054
            $sql = 'SELECT rowid FROM ' . MAIN_DB_PREFIX . 'adherent';
3055
            $sql .= " WHERE entity = " . ((int) $conf->entity); // Do not use getEntity('adherent').")" here, we want the batch to be on its entity only;
3056
            $sql .= " AND statut = 1";
3057
            $sql .= " AND datefin = '" . $this->db->idate($datetosearchfor) . "'";
3058
            //$sql .= " LIMIT 10000";
3059
3060
            $resql = $this->db->query($sql);
3061
            if ($resql) {
3062
                $num_rows = $this->db->num_rows($resql);
3063
3064
                include_once DOL_DOCUMENT_ROOT . '/core/class/html.formmail.class.php';
3065
                $adherent = new Adherent($this->db);
3066
                $formmail = new FormMail($this->db);
0 ignored issues
show
Bug introduced by
The type Dolibarr\Code\Adherents\Classes\FormMail was not found. Did you mean FormMail? If so, make sure to prefix the type with \.
Loading history...
3067
3068
                $i = 0;
3069
                while ($i < $num_rows) {
3070
                    $obj = $this->db->fetch_object($resql);
3071
3072
                    $adherent->fetch($obj->rowid, '', '', '', true, true);
3073
3074
                    if (empty($adherent->email)) {
3075
                        $nbko++;
3076
                        $listofmembersko[$adherent->id] = $adherent->id;
3077
                    } else {
3078
                        $adherent->fetch_thirdparty();
3079
3080
                        // Language code to use ($languagecodeformember) is default language of thirdparty, if no thirdparty, the language found from country of member then country of thirdparty, and if still not found we use the language of company.
3081
                        $languagefromcountrycode = getLanguageCodeFromCountryCode($adherent->country_code ? $adherent->country_code : $adherent->thirdparty->country_code);
3082
                        $languagecodeformember = (empty($adherent->thirdparty->default_lang) ? ($languagefromcountrycode ? $languagefromcountrycode : $mysoc->default_lang) : $adherent->thirdparty->default_lang);
3083
3084
                        // Send reminder email
3085
                        $outputlangs = new Translate('', $conf);
3086
                        $outputlangs->setDefaultLang($languagecodeformember);
3087
                        $outputlangs->loadLangs(array("main", "members"));
3088
                        dol_syslog("sendReminderForExpiredSubscription Language for member id " . $adherent->id . " set to " . $outputlangs->defaultlang . " mysoc->default_lang=" . $mysoc->default_lang);
3089
3090
                        $arraydefaultmessage = null;
3091
                        $labeltouse = getDolGlobalString('ADHERENT_EMAIL_TEMPLATE_REMIND_EXPIRATION');
3092
3093
                        if (!empty($labeltouse)) {
3094
                            $arraydefaultmessage = $formmail->getEMailTemplate($this->db, 'member', $user, $outputlangs, 0, 1, $labeltouse);
3095
                        }
3096
3097
                        if (!empty($labeltouse) && is_object($arraydefaultmessage) && $arraydefaultmessage->id > 0) {
3098
                            $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $adherent);
3099
                            //if (is_array($adherent->thirdparty)) $substitutionarraycomp = ...
3100
                            complete_substitutions_array($substitutionarray, $outputlangs, $adherent);
3101
3102
                            $subject = make_substitutions($arraydefaultmessage->topic, $substitutionarray, $outputlangs);
3103
                            $msg = make_substitutions($arraydefaultmessage->content, $substitutionarray, $outputlangs);
3104
                            $from = getDolGlobalString('ADHERENT_MAIL_FROM');
3105
                            $to = $adherent->email;
3106
                            $cc = getDolGlobalString('ADHERENT_CC_MAIL_FROM');
3107
3108
                            $trackid = 'mem' . $adherent->id;
3109
                            $moreinheader = 'X-Dolibarr-Info: sendReminderForExpiredSubscription' . "\r\n";
3110
3111
                            include_once DOL_DOCUMENT_ROOT . '/core/class/CMailFile.class.php';
3112
                            $cmail = new CMailFile($subject, $to, $from, $msg, array(), array(), array(), $cc, '', 0, 1, '', '', $trackid, $moreinheader);
3113
                            $result = $cmail->sendfile();
3114
                            if (!$result) {
3115
                                $error++;
3116
                                $this->error .= $cmail->error . ' ';
3117
                                if (!is_null($cmail->errors)) {
3118
                                    $this->errors += $cmail->errors;
3119
                                }
3120
                                $nbko++;
3121
                                $listofmembersko[$adherent->id] = $adherent->id;
3122
                            } else {
3123
                                $nbok++;
3124
                                $listofmembersok[$adherent->id] = $adherent->id;
3125
3126
                                $message = $msg;
3127
                                $sendto = $to;
3128
                                $sendtocc = '';
3129
                                $sendtobcc = '';
3130
                                $actioncode = 'EMAIL';
3131
                                $extraparams = '';
3132
3133
                                $actionmsg = '';
3134
                                $actionmsg2 = $langs->transnoentities('MailSentByTo', CMailFile::getValidAddress($from, 4, 0, 1), CMailFile::getValidAddress($sendto, 4, 0, 1));
3135
                                if ($message) {
3136
                                    $actionmsg = $langs->transnoentities('MailFrom') . ': ' . dol_escape_htmltag($from);
3137
                                    $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('MailTo') . ': ' . dol_escape_htmltag($sendto));
3138
                                    if ($sendtocc) {
3139
                                        $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('Bcc') . ": " . dol_escape_htmltag($sendtocc));
3140
                                    }
3141
                                    $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('MailTopic') . ": " . $subject);
3142
                                    $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('TextUsedInTheMessageBody') . ":");
3143
                                    $actionmsg = dol_concatdesc($actionmsg, $message);
3144
                                }
3145
3146
                                require_once constant('DOL_DOCUMENT_ROOT') . '/comm/action/class/actioncomm.class.php';
3147
3148
                                // Insert record of emails sent
3149
                                $actioncomm = new ActionComm($this->db);
0 ignored issues
show
Bug introduced by
The type Dolibarr\Code\Adherents\Classes\ActionComm was not found. Did you mean ActionComm? If so, make sure to prefix the type with \.
Loading history...
3150
3151
                                $actioncomm->type_code = 'AC_OTH_AUTO'; // Type of event ('AC_OTH', 'AC_OTH_AUTO', 'AC_XXX'...)
3152
                                $actioncomm->code = 'AC_' . $actioncode;
3153
                                $actioncomm->label = $actionmsg2;
3154
                                $actioncomm->note_private = $actionmsg;
3155
                                $actioncomm->fk_project = 0;
3156
                                $actioncomm->datep = $now;
3157
                                $actioncomm->datef = $now;
3158
                                $actioncomm->percentage = -1; // Not applicable
3159
                                $actioncomm->socid = $adherent->thirdparty->id;
3160
                                $actioncomm->contact_id = 0;
3161
                                $actioncomm->authorid = $user->id; // User saving action
3162
                                $actioncomm->userownerid = $user->id; // Owner of action
3163
                                // Fields when action is en email (content should be added into note)
3164
                                $actioncomm->email_msgid = $cmail->msgid;
3165
                                $actioncomm->email_from = $from;
3166
                                $actioncomm->email_sender = '';
3167
                                $actioncomm->email_to = $to;
3168
                                $actioncomm->email_tocc = $sendtocc;
3169
                                $actioncomm->email_tobcc = $sendtobcc;
3170
                                $actioncomm->email_subject = $subject;
3171
                                $actioncomm->errors_to = '';
3172
3173
                                $actioncomm->fk_element = $adherent->id;
3174
                                $actioncomm->elementtype = $adherent->element;
3175
3176
                                $actioncomm->extraparams = $extraparams;
3177
3178
                                $actioncomm->create($user);
3179
                            }
3180
                        } else {
3181
                            //$blockingerrormsg = "Can't find email template with label=".$labeltouse.", to use for the reminding email";
3182
3183
                            $error++;
3184
                            $this->error .= "Can't find email template with label=" . $labeltouse . ", to use for the reminding email ";
3185
3186
                            $nbko++;
3187
                            $listofmembersko[$adherent->id] = $adherent->id;
3188
3189
                            break;
3190
                        }
3191
                    }
3192
3193
                    $i++;
3194
                }
3195
            } else {
3196
                $this->error = $this->db->lasterror();
3197
                return 1;
3198
            }
3199
        }
3200
3201
        if ($blockingerrormsg) {
3202
            $this->error = $blockingerrormsg;
3203
            return 1;
3204
        } else {
3205
            $this->output = 'Found ' . ($nbok + $nbko) . ' members to send reminder to.';
3206
            $this->output .= ' Send email successfully to ' . $nbok . ' members';
3207
            if (is_array($listofmembersok)) {
3208
                $listofids = '';
3209
                $i = 0;
3210
                foreach ($listofmembersok as $idmember) {
3211
                    if ($i > 100) {
3212
                        $listofids .= ', ...';
3213
                        break;
3214
                    }
3215
                    if (empty($listofids)) {
3216
                        $listofids .= ' [';
3217
                    } else {
3218
                        $listofids .= ', ';
3219
                    }
3220
                    $listofids .= $idmember;
3221
                    $i++;
3222
                }
3223
                if ($listofids) {
3224
                    $listofids .= ']';
3225
                }
3226
3227
                $this->output .= ($listofids ? ' ids=' . $listofids : '');
3228
            }
3229
            if ($nbko) {
3230
                $this->output .= ' - Canceled for ' . $nbko . ' member (no email or email sending error)';
3231
                if (is_array($listofmembersko)) {
3232
                    $listofids = '';
3233
                    $i = 0;
3234
                    foreach ($listofmembersko as $idmember) {
3235
                        if ($i > 100) {
3236
                            $listofids .= ', ...';
3237
                            break;
3238
                        }
3239
                        if (empty($listofids)) {
3240
                            $listofids .= ' [';
3241
                        } else {
3242
                            $listofids .= ', ';
3243
                        }
3244
                        $listofids .= $idmember;
3245
                        $i++;
3246
                    }
3247
                    if ($listofids) {
3248
                        $listofids .= ']';
3249
                    }
3250
                    $this->output .= ($listofids ? ' ids=' . $listofids : '');
3251
                }
3252
            }
3253
        }
3254
3255
        return $nbko;
3256
    }
3257
3258
    /**
3259
     *  Return clicable link of object (with eventually picto)
3260
     *
3261
     *  @param      string      $option                 Where point the link (0=> main card, 1,2 => shipment, 'nolink'=>No link)
3262
     *  @param      array       $arraydata              Array of data
3263
     *  @return     string                              HTML Code for Kanban thumb.
3264
     */
3265
    public function getKanbanView($option = '', $arraydata = null)
3266
    {
3267
        $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
3268
3269
        $return = '<div class="box-flex-item box-flex-grow-zero">';
3270
        $return .= '<div class="info-box info-box-sm">';
3271
        $return .= '<span class="info-box-icon bg-infobox-action">';
3272
        if (property_exists($this, 'photo') || !empty($this->photo)) {
3273
            $return .= Form::showphoto('memberphoto', $this, 0, 60, 0, 'photokanban photoref photowithmargin photologintooltip', 'small', 0, 1);
3274
        } else {
3275
            $return .= img_picto('', 'user');
3276
        }
3277
        $return .= '</span>';
3278
        $return .= '<div class="info-box-content">';
3279
        $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">' . (method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref) . '</span>';
3280
        if ($selected >= 0) {
3281
            $return .= '<input id="cb' . $this->id . '" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="' . $this->id . '"' . ($selected ? ' checked="checked"' : '') . '>';
3282
        }
3283
        if (property_exists($this, 'type')) {
3284
            $return .= '<br><span class="info-box-label opacitymedium">' . $this->type . '</span>';
3285
        }
3286
        if (method_exists($this, 'getmorphylib')) {
3287
            $return .= '<br><span class="info-box-label">' . $this->getmorphylib('', 2) . '</span>';
3288
        }
3289
        if (method_exists($this, 'getLibStatut')) {
3290
            $return .= '<br><div class="info-box-status paddingtop">';
3291
            $return .= $this->LibStatut($this->status, $this->need_subscription, $this->datefin, 5);
3292
            $return .= '</div>';
3293
        }
3294
        $return .= '</div>';
3295
        $return .= '</div>';
3296
        $return .= '</div>';
3297
        return $return;
3298
    }
3299
}
3300