dolibarr 22.0.5
adherent.class.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2002-2003 Rodolphe Quiedeville <rodolphe@quiedeville.org>
3 * Copyright (C) 2002-2003 Jean-Louis Bergamo <jlb@j1b.org>
4 * Copyright (C) 2004-2012 Laurent Destailleur <eldy@users.sourceforge.net>
5 * Copyright (C) 2004 Sebastien Di Cintio <sdicintio@ressource-toi.org>
6 * Copyright (C) 2004 Benoit Mortier <benoit.mortier@opensides.be>
7 * Copyright (C) 2009-2017 Regis Houssin <regis.houssin@inodbox.com>
8 * Copyright (C) 2014-2018 Alexandre Spangaro <alexandre@inovea-conseil.com>
9 * Copyright (C) 2015 Marcos García <marcosgdf@gmail.com>
10 * Copyright (C) 2015-2025 Frédéric France <frederic.france@free.fr>
11 * Copyright (C) 2015 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
12 * Copyright (C) 2016 Juanjo Menent <jmenent@2byte.es>
13 * Copyright (C) 2018-2019 Thibault FOUCART <support@ptibogxiv.net>
14 * Copyright (C) 2019 Nicolas ZABOURI <info@inovea-conseil.com>
15 * Copyright (C) 2020 Josep Lluís Amador <joseplluis@lliuretic.cat>
16 * Copyright (C) 2021 Waël Almoman <info@almoman.com>
17 * Copyright (C) 2021 Philippe Grand <philippe.grand@atoo-net.com>
18 * Copyright (C) 2024-2025 MDW <mdeweerd@users.noreply.github.com>
19 *
20 * This program is free software; you can redistribute it and/or modify
21 * it under the terms of the GNU General Public License as published by
22 * the Free Software Foundation; either version 3 of the License, or
23 * (at your option) any later version.
24 *
25 * This program is distributed in the hope that it will be useful,
26 * but WITHOUT ANY WARRANTY; without even the implied warranty of
27 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
28 * GNU General Public License for more details.
29 *
30 * You should have received a copy of the GNU General Public License
31 * along with this program. If not, see <https://www.gnu.org/licenses/>.
32 */
33
39require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
40require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
41require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
42require_once DOL_DOCUMENT_ROOT.'/core/class/commonpeople.class.php';
43
44
49{
50 use CommonPeople;
51
55 public $element = 'member';
56
60 public $table_element = 'adherent';
61
65 public $picto = 'member';
66
70 public $mesgs;
71
75 public $login;
76
80 public $pass;
81
85 public $pass_indatabase;
86
90 public $pass_indatabase_crypted;
91
95 public $fullname;
96
101 public $civility_id;
102
106 public $civility_code;
107
111 public $civility;
112
118 public $societe;
119
123 public $company;
124
130 public $fk_soc;
131
135 public $socid;
136
140 public $socialnetworks;
141
145 public $phone;
146
150 public $phone_perso;
151
155 public $phone_pro;
156
160 public $phone_mobile;
161
165 public $fax;
166
170 public $poste;
171
175 public $morphy;
176
180 public $public;
181
186 public $default_lang;
187
191 public $photo;
192
198 public $datec;
199
205 public $datem;
206
210 public $datevalid;
211
215 public $gender;
216
220 public $birth;
221
225 public $typeid;
226
230 public $type;
231
235 public $need_subscription;
236
240 public $user_id;
241
245 public $user_login;
246
250 public $datefin;
251
252
253 // Fields loaded by fetch_subscriptions() from member table
254
258 public $first_subscription_date;
259
263 public $first_subscription_date_start;
264
268 public $first_subscription_date_end;
269
273 public $first_subscription_amount;
274
278 public $last_subscription_date;
279
283 public $last_subscription_date_start;
284
288 public $last_subscription_date_end;
289
293 public $last_subscription_amount;
294
298 public $subscriptions = array();
299
303 public $ip;
304
305 // Fields loaded by fetchPartnerships() from partnership table
306
310 public $partnerships = array();
311
315 public $invoice;
316
317
359 public $fields = array(
360 'rowid' => array('type' => 'integer', 'label' => 'TechnicalID', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 10),
361 'ref' => array('type' => 'varchar(30)', 'label' => 'Ref', 'default' => '1', 'enabled' => 1, 'visible' => 1, 'notnull' => 1, 'position' => 12, 'index' => 1),
362 'entity' => array('type' => 'integer', 'label' => 'Entity', 'default' => '1', 'enabled' => 1, 'visible' => 3, 'notnull' => 1, 'position' => 15, 'index' => 1),
363 'ref_ext' => array('type' => 'varchar(128)', 'label' => 'RefExt', 'enabled' => 1, 'visible' => 0, 'position' => 20),
364 'civility' => array('type' => 'varchar(6)', 'label' => 'Civility', 'enabled' => 1, 'visible' => -1, 'position' => 25),
365 'lastname' => array('type' => 'varchar(50)', 'label' => 'Lastname', 'enabled' => 1, 'visible' => 1, 'position' => 30, 'showoncombobox' => 1),
366 'firstname' => array('type' => 'varchar(50)', 'label' => 'Firstname', 'enabled' => 1, 'visible' => 1, 'position' => 35, 'showoncombobox' => 1),
367 'login' => array('type' => 'varchar(50)', 'label' => 'Login', 'enabled' => 1, 'visible' => 1, 'position' => 40),
368 'pass' => array('type' => 'varchar(50)', 'label' => 'Pass', 'enabled' => 1, 'visible' => 3, 'position' => 45),
369 'pass_crypted' => array('type' => 'varchar(128)', 'label' => 'Pass crypted', 'enabled' => 1, 'visible' => 3, 'position' => 50),
370 'morphy' => array('type' => 'varchar(3)', 'label' => 'MemberNature', 'enabled' => 1, 'visible' => 1, 'notnull' => 1, 'position' => 55),
371 'fk_adherent_type' => array('type' => 'integer', 'label' => 'MemberType', 'enabled' => 1, 'visible' => 1, 'notnull' => 1, 'position' => 60),
372 'societe' => array('type' => 'varchar(128)', 'label' => 'Societe', 'enabled' => 1, 'visible' => 1, 'position' => 65, 'showoncombobox' => 2),
373 'fk_soc' => array('type' => 'integer:Societe:societe/class/societe.class.php', 'label' => 'ThirdParty', 'enabled' => 1, 'visible' => 1, 'position' => 70),
374 'address' => array('type' => 'text', 'label' => 'Address', 'enabled' => 1, 'visible' => -1, 'position' => 75),
375 'zip' => array('type' => 'varchar(10)', 'label' => 'Zip', 'enabled' => 1, 'visible' => -1, 'position' => 80),
376 'town' => array('type' => 'varchar(50)', 'label' => 'Town', 'enabled' => 1, 'visible' => -1, 'position' => 85),
377 'state_id' => array('type' => 'integer', 'label' => 'State', 'enabled' => 1, 'visible' => -1, 'position' => 90),
378 'country' => array('type' => 'integer:Ccountry:core/class/ccountry.class.php', 'label' => 'Country', 'enabled' => 1, 'visible' => 1, 'position' => 95),
379 'phone' => array('type' => 'varchar(30)', 'label' => 'Phone', 'enabled' => 1, 'visible' => -1, 'position' => 115),
380 'phone_perso' => array('type' => 'varchar(30)', 'label' => 'Phone perso', 'enabled' => 1, 'visible' => -1, 'position' => 120),
381 'phone_mobile' => array('type' => 'varchar(30)', 'label' => 'Phone mobile', 'enabled' => 1, 'visible' => -1, 'position' => 125),
382 'email' => array('type' => 'varchar(255)', 'label' => 'Email', 'enabled' => 1, 'visible' => 1, 'position' => 126),
383 'url' => array('type' => 'varchar(255)', 'label' => 'Url', 'enabled' => 1, 'visible' => -1, 'position' => 127),
384 'socialnetworks' => array('type' => 'text', 'label' => 'Socialnetworks', 'enabled' => 1, 'visible' => 3, 'position' => 128),
385 'birth' => array('type' => 'date', 'label' => 'DateOfBirth', 'enabled' => 1, 'visible' => -1, 'position' => 130),
386 'gender' => array('type' => 'varchar(10)', 'label' => 'Gender', 'enabled' => 1, 'visible' => -1, 'position' => 132),
387 'photo' => array('type' => 'varchar(255)', 'label' => 'Photo', 'enabled' => 1, 'visible' => -1, 'position' => 135),
388 'public' => array('type' => 'smallint(6)', 'label' => 'Public', 'enabled' => 1, 'visible' => 3, 'notnull' => 1, 'position' => 145),
389 'datefin' => array('type' => 'datetime', 'label' => 'DateEnd', 'enabled' => 1, 'visible' => 1, 'position' => 150),
390 'default_lang' => array('type' => 'varchar(6)', 'label' => 'Default lang', 'enabled' => 1, 'visible' => -1, 'position' => 153),
391 'note_public' => array('type' => 'text', 'label' => 'NotePublic', 'enabled' => 1, 'visible' => 0, 'position' => 155),
392 'note_private' => array('type' => 'text', 'label' => 'NotePrivate', 'enabled' => 1, 'visible' => 0, 'position' => 160),
393 'datevalid' => array('type' => 'datetime', 'label' => 'DateValidation', 'enabled' => 1, 'visible' => -1, 'position' => 165),
394 'datec' => array('type' => 'datetime', 'label' => 'DateCreation', 'enabled' => 1, 'visible' => -1, 'position' => 170),
395 'tms' => array('type' => 'timestamp', 'label' => 'DateModification', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 175),
396 'fk_user_author' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserCreation', 'enabled' => 1, 'visible' => 3, 'position' => 180),
397 'fk_user_mod' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserModification', 'enabled' => 1, 'visible' => 3, 'position' => 185),
398 'fk_user_valid' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserValidation', 'enabled' => 1, 'visible' => 3, 'position' => 190),
399 'canvas' => array('type' => 'varchar(32)', 'label' => 'Canvas', 'enabled' => 1, 'visible' => 0, 'position' => 195),
400 'model_pdf' => array('type' => 'varchar(255)', 'label' => 'Model pdf', 'enabled' => 1, 'visible' => 0, 'position' => 800),
401 'import_key' => array('type' => 'varchar(14)', 'label' => 'ImportId', 'enabled' => 1, 'visible' => -2, 'position' => 805),
402 'statut' => array('type' => 'smallint(6)', 'label' => 'Statut', 'enabled' => 1, 'visible' => 1, 'notnull' => 1, 'position' => 1000, 'arrayofkeyval' => array(-1 => 'Draft', 1 => 'Validated', 0 => 'MemberStatusResiliatedShort', -2 => 'MemberStatusExcludedShort'))
403 );
404
408 const STATUS_DRAFT = -1;
420 const STATUS_EXCLUDED = -2;
421
422
428 public function __construct($db)
429 {
430 $this->db = $db;
431 $this->statut = self::STATUS_DRAFT;
432 $this->status = self::STATUS_DRAFT;
433 // l'adherent n'est pas public par default
434 $this->public = 0;
435 $this->ismultientitymanaged = 1;
436 $this->isextrafieldmanaged = 1;
437 // les champs optionnels sont vides
438 $this->array_options = array();
439
440 $this->fields['ref_ext']['visible'] = getDolGlobalInt('MAIN_LIST_SHOW_REF_EXT');
441 }
442
443
444 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
463 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 = '')
464 {
465 // phpcs:enable
466 dol_syslog('Warning using deprecated Adherent::send_an_email', LOG_WARNING);
467
468 return $this->sendEmail($text, $subject, $filename_list, $mimetype_list, $mimefilename_list, $addr_cc, $addr_bcc, $deliveryreceipt, $msgishtml, $errors_to, $moreinheader);
469 }
470
488 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 = '')
489 {
490 global $conf, $langs;
491
492 // Detect if message is HTML
493 if ($msgishtml == -1) {
494 $msgishtml = 0;
495 if (dol_textishtml($text, 0)) {
496 $msgishtml = 1;
497 }
498 }
499
500 dol_syslog('sendEmail msgishtml='.$msgishtml);
501
502 $texttosend = $this->makeSubstitution($text);
503 $subjecttosend = $this->makeSubstitution($subject);
504 if ($msgishtml) {
505 $texttosend = dol_htmlentitiesbr($texttosend);
506 }
507
508 // Send mail confirmation
509 $from = getDolGlobalString('ADHERENT_MAIL_FROM', $conf->email_from);
510
511 $trackid = 'mem'.$this->id;
512
513 // Send email (substitutionarray must be done just before this)
514 include_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
515 $mailfile = new CMailFile($subjecttosend, (string) $this->email, $from, $texttosend, $filename_list, $mimetype_list, $mimefilename_list, $addr_cc, $addr_bcc, $deliveryreceipt, $msgishtml, '', '', $trackid, $moreinheader);
516 if ($mailfile->sendfile()) {
517 return 1;
518 } else {
519 $this->error = $langs->trans("ErrorFailedToSendMail", $from, (string) $this->email).'. '.$mailfile->error;
520 return -1;
521 }
522 }
523
524
531 public function makeSubstitution($text)
532 {
533 global $langs;
534
535 $birthday = dol_print_date($this->birth, 'day');
536 $photo = isset($this->photo) ? $this->photo : '';
537 $login = isset($this->login) ? $this->login : '';
538 $type = isset($this->type) ? $this->type : '';
539 $pass = isset($this->pass) ? $this->pass : '';
540
541 $msgishtml = 0;
542 if (dol_textishtml($text, 1)) {
543 $msgishtml = 1;
544 }
545
546 $infos = '';
547 if ($this->civility_id) {
548 $infos .= $langs->transnoentities("UserTitle").": ".$this->getCivilityLabel()."\n";
549 }
550 $infos .= $langs->transnoentities("Id").": ".$this->id."\n";
551 $infos .= $langs->transnoentities("Ref").": ".$this->ref."\n";
552 $infos .= $langs->transnoentities("Lastname").": ".$this->lastname."\n";
553 $infos .= $langs->transnoentities("Firstname").": ".$this->firstname."\n";
554 $infos .= $langs->transnoentities("Company").": ".$this->company."\n";
555 $infos .= $langs->transnoentities("Address").": ".$this->address."\n";
556 $infos .= $langs->transnoentities("Zip").": ".$this->zip."\n";
557 $infos .= $langs->transnoentities("Town").": ".$this->town."\n";
558 $infos .= $langs->transnoentities("Country").": ".$this->country."\n";
559 $infos .= $langs->transnoentities("EMail").": ".$this->email."\n";
560 $infos .= $langs->transnoentities("PhonePro").": ".$this->phone."\n";
561 $infos .= $langs->transnoentities("PhonePerso").": ".$this->phone_perso."\n";
562 $infos .= $langs->transnoentities("PhoneMobile").": ".$this->phone_mobile."\n";
563 if (!getDolGlobalString('ADHERENT_LOGIN_NOT_REQUIRED')) {
564 $infos .= $langs->transnoentities("Login").": ".$login."\n";
565 $infos .= $langs->transnoentities("Password").": ".$pass."\n";
566 }
567 $infos .= $langs->transnoentities("Birthday").": ".$birthday."\n";
568 $infos .= $langs->transnoentities("Photo").": ".$photo."\n";
569 $infos .= $langs->transnoentities("Public").": ".yn($this->public);
570
571 // Substitutions
572 $substitutionarray = array(
573 '__ID__' => $this->id,
574 '__REF__' => $this->ref,
575 '__MEMBER_ID__' => $this->id,
576 '__CIVILITY__' => $this->getCivilityLabel(),
577 '__FIRSTNAME__' => $msgishtml ? dol_htmlentitiesbr($this->firstname) : ($this->firstname ? $this->firstname : ''),
578 '__LASTNAME__' => $msgishtml ? dol_htmlentitiesbr($this->lastname) : ($this->lastname ? $this->lastname : ''),
579 '__FULLNAME__' => $msgishtml ? dol_htmlentitiesbr($this->getFullName($langs)) : $this->getFullName($langs),
580 '__COMPANY__' => $msgishtml ? dol_htmlentitiesbr((string) $this->company) : ($this->company ? $this->company : ''),
581 '__ADDRESS__' => $msgishtml ? dol_htmlentitiesbr((string) $this->address) : ($this->address ? $this->address : ''),
582 '__ZIP__' => $msgishtml ? dol_htmlentitiesbr((string) $this->zip) : ($this->zip ? $this->zip : ''),
583 '__TOWN__' => $msgishtml ? dol_htmlentitiesbr((string) $this->town) : ($this->town ? $this->town : ''),
584 '__COUNTRY__' => $msgishtml ? dol_htmlentitiesbr($this->country) : ($this->country ? $this->country : ''),
585 '__EMAIL__' => $msgishtml ? dol_htmlentitiesbr((string) $this->email) : ($this->email ? $this->email : ''),
586 '__BIRTH__' => $msgishtml ? dol_htmlentitiesbr($birthday) : ($birthday ? $birthday : ''),
587 '__PHOTO__' => $msgishtml ? dol_htmlentitiesbr($photo) : $photo,
588 '__LOGIN__' => $msgishtml ? dol_htmlentitiesbr($login) : $login,
589 '__PASSWORD__' => $msgishtml ? dol_htmlentitiesbr($pass) : $pass,
590 '__PHONE__' => $msgishtml ? dol_htmlentitiesbr($this->phone) : ($this->phone ? $this->phone : ''),
591 '__PHONEPRO__' => $msgishtml ? dol_htmlentitiesbr($this->phone_perso) : ($this->phone_perso ? $this->phone_perso : ''),
592 '__PHONEMOBILE__' => $msgishtml ? dol_htmlentitiesbr($this->phone_mobile) : ($this->phone_mobile ? $this->phone_mobile : ''),
593 '__TYPE__' => $msgishtml ? dol_htmlentitiesbr($type) : $type,
594 );
595
596 complete_substitutions_array($substitutionarray, $langs, $this);
597
598 return make_substitutions($text, $substitutionarray, $langs);
599 }
600
601
609 public function getmorphylib($morphy = '', $addbadge = 0)
610 {
611 global $langs;
612 $s = '';
613
614 // Clean var
615 if (!$morphy) {
616 $morphy = $this->morphy;
617 }
618
619 if ($addbadge) {
620 $labeltoshowm = $langs->trans("Moral");
621 $labeltoshowp = $langs->trans("Physical");
622 if ($morphy == 'phy') {
623 $labeltoshow = $labeltoshowp;
624 if ($addbadge == 2) {
625 $labeltoshow = dol_strtoupper(dolGetFirstLetters($labeltoshowp));
626 if ($labeltoshow == dol_strtoupper(dolGetFirstLetters($labeltoshowm))) {
627 $labeltoshow = dol_strtoupper(dolGetFirstLetters($labeltoshowp, 2));
628 }
629 }
630 $s .= '<span class="member-individual-back paddingleftimp paddingrightimp" title="'.$langs->trans("Physical").'">'.$labeltoshow.'</span>';
631 }
632 if ($morphy == 'mor') {
633 $labeltoshow = $labeltoshowm;
634 if ($addbadge == 2) {
635 $labeltoshow = dol_strtoupper(dolGetFirstLetters($labeltoshowm));
636 if ($labeltoshow == dol_strtoupper(dolGetFirstLetters($labeltoshowp))) {
637 $labeltoshow = dol_strtoupper(dolGetFirstLetters($labeltoshowm, 2));
638 }
639 }
640 $s .= '<span class="member-company-back paddingleftimp paddingrightimp" title="'.$langs->trans("Moral").'">'.$labeltoshow.'</span>';
641 }
642 } else {
643 if ($morphy == 'phy') {
644 $s = $langs->trans("Physical");
645 } elseif ($morphy == 'mor') {
646 $s = $langs->trans("Moral");
647 }
648 }
649
650 return $s;
651 }
652
660 public function create($user, $notrigger = 0)
661 {
662 global $conf, $langs, $mysoc;
663
664 $error = 0;
665
666 $now = dol_now();
667
668 // Clean parameters
669 if (isset($this->import_key)) {
670 $this->import_key = trim($this->import_key);
671 }
672
673 // Check parameters
674 if (getDolGlobalString('ADHERENT_MAIL_REQUIRED') && !isValidEmail((string) $this->email)) {
675 $langs->load("errors");
676 $this->error = $langs->trans("ErrorBadEMail", (string) $this->email);
677 return -1;
678 }
679 if (!$this->datec) {
680 $this->datec = $now;
681 }
682 if (!getDolGlobalString('ADHERENT_LOGIN_NOT_REQUIRED')) {
683 if (empty($this->login)) {
684 $this->error = $langs->trans("ErrorWrongValueForParameterX", "Login");
685 return -1;
686 }
687 }
688
689 // setEntity will set entity with the right value if empty or change it for the right value if multicompany module is active
690 $this->entity = setEntity($this);
691
692 $this->db->begin();
693
694 // Insert member
695 $sql = "INSERT INTO ".MAIN_DB_PREFIX."adherent";
696 $sql .= " (ref, datec, login, fk_user_author, fk_user_mod, fk_user_valid, morphy, fk_adherent_type, entity, import_key, ip)";
697 $sql .= " VALUES (";
698 $sql .= " '(PROV)'";
699 $sql .= ", '".$this->db->idate($this->datec)."'";
700 $sql .= ", ".($this->login ? "'".$this->db->escape($this->login)."'" : "null");
701 $sql .= ", ".($user->id > 0 ? $user->id : "null"); // Can be null because member can be created by a guest or a script
702 $sql .= ", null, null, '".$this->db->escape($this->morphy)."'";
703 $sql .= ", ".((int) $this->typeid);
704 $sql .= ", ".((int) $this->entity);
705 $sql .= ", ".(!empty($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null");
706 $sql .= ", ".(!empty($this->ip) ? "'".$this->db->escape($this->ip)."'" : "null");
707 $sql .= ")";
708
709 dol_syslog(get_class($this)."::create", LOG_DEBUG);
710 $result = $this->db->query($sql);
711 if ($result) {
712 $id = $this->db->last_insert_id(MAIN_DB_PREFIX."adherent");
713 if ($id > 0) {
714 $this->id = $id;
715 if (getDolGlobalString('MEMBER_CODEMEMBER_ADDON') == '') {
716 // keep old numbering
717 $this->ref = (string) $id;
718 } else {
719 // auto code
720 $modfile = dol_buildpath('core/modules/member/'.getDolGlobalString('MEMBER_CODEMEMBER_ADDON').'.php', 0);
721 try {
722 require_once $modfile;
723 $modname = getDolGlobalString('MEMBER_CODEMEMBER_ADDON');
724 $modCodeMember = new $modname();
725 '@phan-var-force ModeleNumRefMembers $modCodeMember';
727 $this->ref = $modCodeMember->getNextValue($mysoc, $this);
728 } catch (Exception $e) {
729 dol_syslog($e->getMessage(), LOG_ERR);
730 $error++;
731 }
732 }
733
734 // Update minor fields
735 $result = $this->update($user, 1, 1, 0, 0, 'add'); // nosync is 1 to avoid update data of user
736 if ($result < 0) {
737 $this->db->rollback();
738 return -1;
739 }
740
741 // Add link to user
742 if ($this->user_id) {
743 // Add link to user
744 $sql = "UPDATE ".MAIN_DB_PREFIX."user SET";
745 $sql .= " fk_member = ".((int) $this->id);
746 $sql .= " WHERE rowid = ".((int) $this->user_id);
747 dol_syslog(get_class($this)."::create", LOG_DEBUG);
748 $resql = $this->db->query($sql);
749 if (!$resql) {
750 $this->error = 'Failed to update user to make link with member';
751 $this->db->rollback();
752 return -4;
753 }
754 }
755
756 if (!$notrigger) {
757 // Call trigger
758 $result = $this->call_trigger('MEMBER_CREATE', $user);
759 if ($result < 0) {
760 $error++;
761 }
762 // End call triggers
763 }
764
765 if (count($this->errors)) {
766 dol_syslog(get_class($this)."::create ".implode(',', $this->errors), LOG_ERR);
767 $this->db->rollback();
768 return -3;
769 } else {
770 $this->db->commit();
771 return $this->id;
772 }
773 } else {
774 $this->error = 'Failed to get last insert id';
775 dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
776 $this->db->rollback();
777 return -2;
778 }
779 } else {
780 $this->error = $this->db->error();
781 $this->db->rollback();
782 return -1;
783 }
784 }
785
786
798 public function update($user, $notrigger = 0, $nosyncuser = 0, $nosyncuserpass = 0, $nosyncthirdparty = 0, $action = 'update')
799 {
800 global $langs, $hookmanager;
801
802 require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
803
804 if (empty($this->country_id) && !empty($this->country_code)) {
805 $country_id = getCountry($this->country_code, '3');
806 $this->country_id = is_int($country_id) ? $country_id : 0;
807 }
808
809 $nbrowsaffected = 0;
810 $error = 0;
811
812 dol_syslog(get_class($this)."::update notrigger=".$notrigger.", nosyncuser=".$nosyncuser.", nosyncuserpass=".$nosyncuserpass." nosyncthirdparty=".$nosyncthirdparty.", email=".$this->email);
813
814 // Clean parameters
815 $this->lastname = trim($this->lastname) ? trim($this->lastname) : trim($this->lastname);
816 $this->firstname = trim($this->firstname) ? trim($this->firstname) : trim($this->firstname);
817 $this->gender = trim($this->gender);
818 // $this->address = ($this->address ? $this->address : $this->address);
819 // $this->zip = ($this->zip ? $this->zip : $this->zip);
820 // $this->town = ($this->town ? $this->town : $this->town);
821 // $this->country_id = ($this->country_id > 0 ? $this->country_id : $this->country_id);
822 // $this->state_id = ($this->state_id > 0 ? $this->state_id : $this->state_id);
823 // $this->note_public = ($this->note_public ? $this->note_public : $this->note_public);
824 // $this->note_private = ($this->note_private ? $this->note_private : $this->note_private);
825 $this->url = $this->url ? clean_url($this->url, 0) : '';
826 $this->setUpperOrLowerCase();
827 // Check parameters
828 if (getDolGlobalString('ADHERENT_MAIL_REQUIRED') && !isValidEmail((string) $this->email)) {
829 $langs->load("errors");
830 $this->error = $langs->trans("ErrorBadEMail", (string) $this->email);
831 return -1;
832 }
833
834 $this->db->begin();
835
836 $sql = "UPDATE ".MAIN_DB_PREFIX."adherent SET";
837 $sql .= " ref = '".$this->db->escape($this->ref)."'";
838 $sql .= ", civility = ".($this->civility_id ? "'".$this->db->escape($this->civility_id)."'" : "null");
839 $sql .= ", firstname = ".($this->firstname ? "'".$this->db->escape($this->firstname)."'" : "null");
840 $sql .= ", lastname = ".($this->lastname ? "'".$this->db->escape($this->lastname)."'" : "null");
841 $sql .= ", gender = ".($this->gender != -1 ? "'".$this->db->escape($this->gender)."'" : "null"); // 'man' or 'woman'
842 $sql .= ", login = ".($this->login ? "'".$this->db->escape($this->login)."'" : "null");
843 $sql .= ", societe = ".($this->company ? "'".$this->db->escape($this->company)."'" : ($this->societe ? "'".$this->db->escape($this->societe)."'" : "null"));
844 if ($this->socid) {
845 $sql .= ", fk_soc = ".($this->socid > 0 ? (int) $this->socid : "null"); // Must be modified only when creating from a third-party
846 }
847 $sql .= ", address = ".($this->address ? "'".$this->db->escape($this->address)."'" : "null");
848 $sql .= ", zip = ".($this->zip ? "'".$this->db->escape($this->zip)."'" : "null");
849 $sql .= ", town = ".($this->town ? "'".$this->db->escape($this->town)."'" : "null");
850 $sql .= ", country = ".($this->country_id > 0 ? (int) $this->country_id : "null");
851 $sql .= ", state_id = ".($this->state_id > 0 ? (int) $this->state_id : "null");
852 $sql .= ", email = '".$this->db->escape((string) $this->email)."'";
853 $sql .= ", url = ".(!empty($this->url) ? "'".$this->db->escape($this->url)."'" : "null");
854 $sql .= ", socialnetworks = ".($this->socialnetworks ? "'".$this->db->escape(json_encode($this->socialnetworks))."'" : "null");
855 $sql .= ", phone = ".($this->phone ? "'".$this->db->escape($this->phone)."'" : "null");
856 $sql .= ", phone_perso = ".($this->phone_perso ? "'".$this->db->escape($this->phone_perso)."'" : "null");
857 $sql .= ", phone_mobile = ".($this->phone_mobile ? "'".$this->db->escape($this->phone_mobile)."'" : "null");
858 $sql .= ", note_private = ".($this->note_private ? "'".$this->db->escape($this->note_private)."'" : "null");
859 $sql .= ", note_public = ".($this->note_public ? "'".$this->db->escape($this->note_public)."'" : "null");
860 $sql .= ", photo = ".($this->photo ? "'".$this->db->escape($this->photo)."'" : "null");
861 $sql .= ", public = ".(int) $this->public;
862 $sql .= ", statut = ".(int) $this->statut;
863 $sql .= ", default_lang = ".(!empty($this->default_lang) ? "'".$this->db->escape($this->default_lang)."'" : "null");
864 $sql .= ", fk_adherent_type = ".(int) $this->typeid;
865 $sql .= ", morphy = '".$this->db->escape($this->morphy)."'";
866 $sql .= ", birth = ".($this->birth ? "'".$this->db->idate($this->birth)."'" : "null");
867
868 if ($this->datefin) {
869 $sql .= ", datefin = '".$this->db->idate($this->datefin)."'"; // Must be modified only when deleting a subscription
870 }
871 if ($this->datevalid) {
872 $sql .= ", datevalid = '".$this->db->idate($this->datevalid)."'"; // Must be modified only when validating a member
873 }
874 $sql .= ", fk_user_mod = ".($user->id > 0 ? $user->id : 'null'); // Can be null because member can be create by a guest
875 $sql .= " WHERE rowid = ".((int) $this->id);
876
877 // If we change the type of membership, we set also label of new type..
878 '@phan-var-force Adherent $oldcopy';
879 if (!empty($this->oldcopy) && $this->typeid != $this->oldcopy->typeid) {
880 $sql2 = "SELECT libelle as label";
881 $sql2 .= " FROM ".MAIN_DB_PREFIX."adherent_type";
882 $sql2 .= " WHERE rowid = ".((int) $this->typeid);
883 $resql2 = $this->db->query($sql2);
884 if ($resql2) {
885 while ($obj = $this->db->fetch_object($resql2)) {
886 $this->type = $obj->label;
887 }
888 }
889 }
890
891 dol_syslog(get_class($this)."::update update member", LOG_DEBUG);
892 $resql = $this->db->query($sql);
893 if ($resql) {
894 unset($this->country_code);
895 unset($this->country);
896 unset($this->state_code);
897 unset($this->state);
898
899 $nbrowsaffected += $this->db->affected_rows($resql);
900
901 $action = 'update';
902
903 // Actions on extra fields
904 if (!$error) {
905 $result = $this->insertExtraFields();
906 if ($result < 0) {
907 $error++;
908 }
909 }
910
911 // Update password
912 if (!$error && $this->pass) {
913 dol_syslog(get_class($this)."::update update password");
914 if ($this->pass != $this->pass_indatabase && $this->pass != $this->pass_indatabase_crypted) {
915 $isencrypted = getDolGlobalString('DATABASE_PWD_ENCRYPTED') ? 1 : 0;
916
917 // If password to set differs from the one found into database
918 $result = $this->setPassword($user, $this->pass, $isencrypted, $notrigger, $nosyncuserpass);
919 if (!$nbrowsaffected) {
920 $nbrowsaffected++;
921 }
922 }
923 }
924
925 // Remove links to user and replace with new one
926 if (!$error) {
927 dol_syslog(get_class($this)."::update update link to user");
928 $sql = "UPDATE ".MAIN_DB_PREFIX."user SET fk_member = NULL WHERE fk_member = ".((int) $this->id);
929 dol_syslog(get_class($this)."::update", LOG_DEBUG);
930 $resql = $this->db->query($sql);
931 if (!$resql) {
932 $this->error = $this->db->error();
933 $this->db->rollback();
934 return -5;
935 }
936 // If there is a user linked to this member
937 if ($this->user_id > 0) {
938 $sql = "UPDATE ".MAIN_DB_PREFIX."user SET fk_member = ".((int) $this->id)." WHERE rowid = ".((int) $this->user_id);
939 dol_syslog(get_class($this)."::update", LOG_DEBUG);
940 $resql = $this->db->query($sql);
941 if (!$resql) {
942 $this->error = $this->db->error();
943 $this->db->rollback();
944 return -5;
945 }
946 }
947 }
948
949 if (!$error && $nbrowsaffected) { // If something has change in main data
950 // Update information on linked user if it is an update
951 if (!$error && $this->user_id > 0 && !$nosyncuser) {
952 require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
953
954 dol_syslog(get_class($this)."::update update linked user");
955
956 $luser = new User($this->db);
957 $result = $luser->fetch($this->user_id);
958
959 if ($result > 0) {
960 // 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.
961 if (!getDolGlobalString('ADHERENT_LOGIN_NOT_REQUIRED')) {
962 $luser->login = $this->login;
963 }
964
965 $luser->ref = $this->ref;
966 $luser->civility_id = $this->civility_id;
967 $luser->firstname = $this->firstname;
968 $luser->lastname = $this->lastname;
969 $luser->gender = $this->gender;
970 $luser->pass = isset($this->pass) ? $this->pass : '';
971 //$luser->socid=$this->fk_soc; // We do not enable this. This may transform a user into an external user.
972
973 $luser->birth = $this->birth;
974
975 $luser->address = $this->address;
976 $luser->zip = $this->zip;
977 $luser->town = $this->town;
978 $luser->country_id = $this->country_id;
979 $luser->state_id = $this->state_id;
980
981 $luser->email = $this->email;
982 $luser->socialnetworks = $this->socialnetworks;
983 $luser->office_phone = $this->phone;
984 $luser->user_mobile = $this->phone_mobile;
985
986 $luser->lang = $this->default_lang;
987
988 $luser->fk_member = $this->id;
989
990 $result = $luser->update($user, 0, 1, 1); // Use nosync to 1 to avoid cyclic updates
991 if ($result < 0) {
992 $this->error = $luser->error;
993 dol_syslog(get_class($this)."::update ".$this->error, LOG_ERR);
994 $error++;
995 }
996 } else {
997 $this->error = $luser->error;
998 $error++;
999 }
1000 }
1001
1002 // Update information on linked thirdparty if it is an update
1003 if (!$error && $this->fk_soc > 0 && !$nosyncthirdparty) {
1004 require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
1005
1006 dol_syslog(get_class($this)."::update update linked thirdparty");
1007
1008 // This member is linked with a thirdparty, so we also update thirdparty information
1009 // if this is an update.
1010 $lthirdparty = new Societe($this->db);
1011 $result = $lthirdparty->fetch($this->fk_soc);
1012
1013 if ($result > 0) {
1014 $lthirdparty->address = $this->address;
1015 $lthirdparty->zip = $this->zip;
1016 $lthirdparty->town = $this->town;
1017 $lthirdparty->email = $this->email;
1018 $lthirdparty->socialnetworks = $this->socialnetworks;
1019 $lthirdparty->phone = $this->phone;
1020 $lthirdparty->state_id = $this->state_id;
1021 $lthirdparty->country_id = $this->country_id;
1022 //$lthirdparty->phone_mobile=$this->phone_mobile;
1023 $lthirdparty->default_lang = $this->default_lang;
1024
1025 $result = $lthirdparty->update($this->fk_soc, $user, 0, 1, 1, 'update'); // Use sync to 0 to avoid cyclic updates
1026
1027 if ($result < 0) {
1028 $this->error = $lthirdparty->error;
1029 $this->errors = $lthirdparty->errors;
1030 dol_syslog(get_class($this)."::update ".$this->error, LOG_ERR);
1031 $error++;
1032 }
1033 } elseif ($result < 0) {
1034 $this->error = $lthirdparty->error;
1035 $error++;
1036 }
1037 }
1038 }
1039
1040 if (!$error && !$notrigger) {
1041 // Call trigger
1042 $result = $this->call_trigger('MEMBER_MODIFY', $user);
1043 if ($result < 0) {
1044 $error++;
1045 }
1046 // End call triggers
1047 }
1048
1049 if (!$error) {
1050 $this->db->commit();
1051 return $nbrowsaffected;
1052 } else {
1053 $this->db->rollback();
1054 return -1;
1055 }
1056 } else {
1057 $this->db->rollback();
1058 $this->error = $this->db->lasterror();
1059 return -2;
1060 }
1061 }
1062
1063
1064 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1072 public function update_end_date($user)
1073 {
1074 // phpcs:enable
1075 $this->db->begin();
1076
1077 // Search for last subscription id and end date
1078 $sql = "SELECT rowid, datec as dateop, dateadh as datedeb, datef as datefin";
1079 $sql .= " FROM ".MAIN_DB_PREFIX."subscription";
1080 $sql .= " WHERE fk_adherent = ".((int) $this->id);
1081 $sql .= " ORDER by dateadh DESC"; // Sort by start subscription date
1082
1083 dol_syslog(get_class($this)."::update_end_date", LOG_DEBUG);
1084 $resql = $this->db->query($sql);
1085 if ($resql) {
1086 // The last subscription is the one with the latest start date (first record), but the end date of the member is
1087 // the latest end date of all its subscriptions: a short subscription that starts after a longer one must not
1088 // shorten the membership. There is no record at all when the last subscription of the member was deleted.
1089 $dateop = '';
1090 $datedeb = '';
1091 $datefin = '';
1092 $dateendmember = '';
1093 $i = 0;
1094 while ($obj = $this->db->fetch_object($resql)) {
1095 $dateendsubscription = $this->db->jdate($obj->datefin);
1096 if ($i == 0) {
1097 $dateop = $this->db->jdate($obj->dateop);
1098 $datedeb = $this->db->jdate($obj->datedeb);
1099 $datefin = $dateendsubscription;
1100 }
1101 if ($dateendsubscription != '' && ($dateendmember == '' || $dateendsubscription > $dateendmember)) {
1102 $dateendmember = $dateendsubscription;
1103 }
1104 $i++;
1105 }
1106
1107 $sql = "UPDATE ".MAIN_DB_PREFIX."adherent SET";
1108 $sql .= " datefin=".($dateendmember != '' ? "'".$this->db->idate($dateendmember)."'" : "null");
1109 $sql .= " WHERE rowid = ".((int) $this->id);
1110
1111 dol_syslog(get_class($this)."::update_end_date", LOG_DEBUG);
1112 $resql = $this->db->query($sql);
1113 if ($resql) {
1114 $this->last_subscription_date = $dateop;
1115 $this->last_subscription_date_start = $datedeb;
1116 $this->last_subscription_date_end = $datefin;
1117 $this->datefin = $dateendmember;
1118 $this->db->commit();
1119 return 1;
1120 } else {
1121 $this->db->rollback();
1122 return -1;
1123 }
1124 } else {
1125 $this->error = $this->db->lasterror();
1126 $this->db->rollback();
1127 return -1;
1128 }
1129 }
1130
1138 public function delete($user, $notrigger = 0)
1139 {
1140 global $conf;
1141
1142 $result = 0;
1143 $error = 0;
1144 $errorflag = 0;
1145
1146 // Check parameters
1147 $rowid = $this->id;
1148
1149 $this->db->begin();
1150
1151 if (!$error && !$notrigger) {
1152 // Call trigger
1153 $result = $this->call_trigger('MEMBER_DELETE', $user);
1154 if ($result < 0) {
1155 $error++;
1156 }
1157 // End call triggers
1158 }
1159
1160 // Remove category
1161 $sql = "DELETE FROM ".MAIN_DB_PREFIX."categorie_member WHERE fk_member = ".((int) $rowid);
1162 dol_syslog(get_class($this)."::delete", LOG_DEBUG);
1163 $resql = $this->db->query($sql);
1164 if (!$resql) {
1165 $error++;
1166 $this->error .= $this->db->lasterror();
1167 $errorflag = -1;
1168 }
1169
1170 // Remove subscription
1171 if (!$error) {
1172 $sql = "DELETE FROM ".MAIN_DB_PREFIX."subscription WHERE fk_adherent = ".((int) $rowid);
1173 dol_syslog(get_class($this)."::delete", LOG_DEBUG);
1174 $resql = $this->db->query($sql);
1175 if (!$resql) {
1176 $error++;
1177 $this->error .= $this->db->lasterror();
1178 $errorflag = -2;
1179 }
1180 }
1181
1182 // Remove the partnerships of the member
1183 if (!$error && isModEnabled('partnership')) {
1184 require_once DOL_DOCUMENT_ROOT.'/partnership/class/partnership.class.php';
1185
1186 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."partnership WHERE fk_member = ".((int) $rowid);
1187 dol_syslog(get_class($this)."::delete", LOG_DEBUG);
1188 $resql = $this->db->query($sql);
1189 if ($resql) {
1190 while ($obj = $this->db->fetch_object($resql)) {
1191 $partnership = new Partnership($this->db);
1192 if ($partnership->fetch($obj->rowid) > 0 && $partnership->delete($user) <= 0) {
1193 $error++;
1194 $this->error .= $partnership->error;
1195 $errorflag = -9;
1196 break;
1197 }
1198 }
1199 } else {
1200 $error++;
1201 $this->error .= $this->db->lasterror();
1202 $errorflag = -9;
1203 }
1204 }
1205
1206 // Remove the links with other objects
1207 if (!$error) {
1208 $ret = $this->deleteObjectLinked();
1209 if ($ret < 0) {
1210 $error++;
1211 $errorflag = -7;
1212 }
1213 }
1214
1215 // Remove the index of the documents of the member (the files are removed after the commit)
1216 $dirofdocuments = '';
1217 $subdirofdocuments = get_exdir(0, 0, 0, 1, $this, 'member');
1218 if (!empty($conf->adherent->dir_output) && $subdirofdocuments !== '') { // Never the root directory of the module
1219 $dirofdocuments = $conf->adherent->dir_output.'/'.$subdirofdocuments;
1220 }
1221 if (!$error && $dirofdocuments) {
1222 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1223 if (deleteFilesIntoDatabaseIndex($dirofdocuments, '', '') < 0 || !$this->deleteEcmFiles(1)) {
1224 $error++;
1225 $this->error .= $this->db->lasterror();
1226 $errorflag = -8;
1227 }
1228 }
1229
1230 // Remove linked user
1231 if (!$error) {
1232 $ret = $this->setUserId(0);
1233 if ($ret < 0) {
1234 $error++;
1235 $this->error .= $this->db->lasterror();
1236 $errorflag = -3;
1237 }
1238 }
1239
1240 // Removed extrafields
1241 if (!$error) {
1242 $result = $this->deleteExtraFields();
1243 if ($result < 0) {
1244 $error++;
1245 $errorflag = -4;
1246 dol_syslog(get_class($this)."::delete erreur ".$errorflag." ".$this->error, LOG_ERR);
1247 }
1248 }
1249
1250 // Remove adherent
1251 if (!$error) {
1252 $sql = "DELETE FROM ".MAIN_DB_PREFIX."adherent WHERE rowid = ".((int) $rowid);
1253 dol_syslog(get_class($this)."::delete", LOG_DEBUG);
1254 $resql = $this->db->query($sql);
1255 if (!$resql) {
1256 $error++;
1257 $this->error .= $this->db->lasterror();
1258 $errorflag = -5;
1259 }
1260 }
1261
1262 if (!$error) {
1263 $this->db->commit();
1264
1265 // Delete the directory of the documents of the member
1266 if ($dirofdocuments) {
1267 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1268 if (dol_is_dir($dirofdocuments)) {
1269 dol_delete_dir_recursive($dirofdocuments);
1270 }
1271 }
1272
1273 return 1;
1274 } else {
1275 $this->db->rollback();
1276 return $errorflag;
1277 }
1278 }
1279
1280
1291 public function setPassword($user, $password = '', $isencrypted = 0, $notrigger = 0, $nosyncuser = 0)
1292 {
1293 global $conf, $langs;
1294
1295 $error = 0;
1296
1297 dol_syslog(get_class($this)."::setPassword user=".$user->id." password=".preg_replace('/./i', '*', $password)." isencrypted=".$isencrypted);
1298
1299 // If new password not provided, we generate one
1300 if (!$password) {
1301 require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
1302 $password = getRandomPassword(false);
1303 }
1304
1305 // Crypt password
1306 $password_crypted = dol_hash($password);
1307
1308 $password_indatabase = '';
1309 if (!$isencrypted) {
1310 $password_indatabase = $password;
1311 }
1312
1313 $this->db->begin();
1314
1315 // Mise a jour
1316 $sql = "UPDATE ".MAIN_DB_PREFIX."adherent";
1317 $sql .= " SET pass_crypted = '".$this->db->escape($password_crypted)."'";
1318 if ($isencrypted) {
1319 $sql .= ", pass = null";
1320 } else {
1321 $sql .= ", pass = '".$this->db->escape($password_indatabase)."'";
1322 }
1323 $sql .= " WHERE rowid = ".((int) $this->id);
1324
1325 //dol_syslog("Adherent::Password sql=hidden");
1326 dol_syslog(get_class($this)."::setPassword", LOG_DEBUG);
1327 $result = $this->db->query($sql);
1328 if ($result) {
1329 $nbaffectedrows = $this->db->affected_rows($result);
1330
1331 if ($nbaffectedrows) {
1332 $this->pass = $password;
1333 $this->pass_indatabase = $password_indatabase;
1334 $this->pass_indatabase_crypted = $password_crypted;
1335
1336 if ($this->user_id && !$nosyncuser) {
1337 require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
1338
1339 // This member is linked with a user, so we also update users information
1340 // if this is an update.
1341 $luser = new User($this->db);
1342 $result = $luser->fetch($this->user_id);
1343
1344 if ($result > 0) {
1345 $result = $luser->setPassword($user, $this->pass, 0, 0, 1);
1346 if (is_int($result) && $result < 0) {
1347 $this->error = $luser->error;
1348 dol_syslog(get_class($this)."::setPassword ".$this->error, LOG_ERR);
1349 $error++;
1350 }
1351 } else {
1352 $this->error = $luser->error;
1353 $error++;
1354 }
1355 }
1356
1357 if (!$error && !$notrigger) {
1358 // Call trigger
1359 $result = $this->call_trigger('MEMBER_NEW_PASSWORD', $user);
1360 if ($result < 0) {
1361 $error++;
1362 $this->db->rollback();
1363 return -1;
1364 }
1365 // End call triggers
1366 }
1367
1368 $this->db->commit();
1369 return $this->pass;
1370 } else {
1371 $this->db->rollback();
1372 return 0;
1373 }
1374 } else {
1375 $this->db->rollback();
1376 dol_print_error($this->db);
1377 return -1;
1378 }
1379 }
1380
1381
1388 public function setUserId($userid)
1389 {
1390 global $conf, $langs;
1391
1392 $this->db->begin();
1393
1394 // If user is linked to this member, remove old link to this member
1395 $sql = "UPDATE ".MAIN_DB_PREFIX."user SET fk_member = NULL WHERE fk_member = ".((int) $this->id);
1396 dol_syslog(get_class($this)."::setUserId", LOG_DEBUG);
1397 $resql = $this->db->query($sql);
1398 if (!$resql) {
1399 $this->error = $this->db->error();
1400 $this->db->rollback();
1401 return -1;
1402 }
1403
1404 // Set link to user
1405 if ($userid > 0) {
1406 $sql = "UPDATE ".MAIN_DB_PREFIX."user SET fk_member = ".((int) $this->id);
1407 $sql .= " WHERE rowid = ".((int) $userid);
1408 dol_syslog(get_class($this)."::setUserId", LOG_DEBUG);
1409 $resql = $this->db->query($sql);
1410 if (!$resql) {
1411 $this->error = $this->db->error();
1412 $this->db->rollback();
1413 return -2;
1414 }
1415 }
1416
1417 $this->db->commit();
1418
1419 return 1;
1420 }
1421
1422
1429 public function setThirdPartyId($thirdpartyid)
1430 {
1431 global $conf, $langs;
1432
1433 $this->db->begin();
1434
1435 // Remove link to third party onto any other members
1436 if ($thirdpartyid > 0) {
1437 $sql = "UPDATE ".MAIN_DB_PREFIX."adherent SET fk_soc = null";
1438 $sql .= " WHERE fk_soc = ".((int) $thirdpartyid);
1439 $sql .= " AND entity = ".$conf->entity;
1440 dol_syslog(get_class($this)."::setThirdPartyId", LOG_DEBUG);
1441 $resql = $this->db->query($sql);
1442 }
1443
1444 // Add link to third party for current member
1445 $sql = "UPDATE ".MAIN_DB_PREFIX."adherent SET fk_soc = ".($thirdpartyid > 0 ? (int) $thirdpartyid : 'null');
1446 $sql .= " WHERE rowid = ".((int) $this->id);
1447
1448 dol_syslog(get_class($this)."::setThirdPartyId", LOG_DEBUG);
1449 $resql = $this->db->query($sql);
1450 if ($resql) {
1451 $this->db->commit();
1452 return 1;
1453 } else {
1454 $this->error = $this->db->error();
1455 $this->db->rollback();
1456 return -1;
1457 }
1458 }
1459
1460
1461 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1468 public function fetch_login($login)
1469 {
1470 // phpcs:enable
1471 global $conf;
1472
1473 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."adherent";
1474 $sql .= " WHERE login='".$this->db->escape($login)."'";
1475 $sql .= " AND entity = ".$conf->entity;
1476
1477 $resql = $this->db->query($sql);
1478 if ($resql) {
1479 if ($this->db->num_rows($resql)) {
1480 $obj = $this->db->fetch_object($resql);
1481 $this->fetch($obj->rowid);
1482 }
1483 } else {
1484 dol_print_error($this->db);
1485 }
1486 }
1487
1488 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1496 public function fetch_name($firstname, $lastname)
1497 {
1498 // phpcs:enable
1499 global $conf;
1500
1501 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."adherent";
1502 $sql .= " WHERE firstname='".$this->db->escape($firstname)."'";
1503 $sql .= " AND lastname='".$this->db->escape($lastname)."'";
1504 $sql .= " AND entity = ".$conf->entity;
1505
1506 $resql = $this->db->query($sql);
1507 if ($resql) {
1508 if ($this->db->num_rows($resql)) {
1509 $obj = $this->db->fetch_object($resql);
1510 $this->fetch($obj->rowid);
1511 }
1512 } else {
1513 dol_print_error($this->db);
1514 }
1515 }
1516
1528 public function fetch($rowid, $ref = '', $fk_soc = 0, $ref_ext = '', $fetch_optionals = true, $fetch_subscriptions = true)
1529 {
1530 global $langs;
1531
1532 $sql = "SELECT d.rowid, d.ref, d.ref_ext, d.civility as civility_code, d.gender, d.firstname, d.lastname,";
1533 $sql .= " d.societe as company, d.fk_soc, d.statut, d.public, d.address, d.zip, d.town, d.note_private,";
1534 $sql .= " d.note_public,";
1535 $sql .= " d.email, d.url, d.socialnetworks, d.phone, d.phone_perso, d.phone_mobile, d.login, d.pass, d.pass_crypted,";
1536 $sql .= " d.photo, d.fk_adherent_type, d.morphy, d.entity,";
1537 $sql .= " d.datec as datec,";
1538 $sql .= " d.tms as datem,";
1539 $sql .= " d.datefin as datefin, d.default_lang,";
1540 $sql .= " d.birth as birthday,";
1541 $sql .= " d.datevalid as datev,";
1542 $sql .= " d.country,";
1543 $sql .= " d.state_id,";
1544 $sql .= " d.model_pdf,";
1545 $sql .= " c.rowid as country_id, c.code as country_code, c.label as country,";
1546 $sql .= " dep.nom as state, dep.code_departement as state_code,";
1547 $sql .= " t.libelle as type, t.subscription as subscription,";
1548 $sql .= " u.rowid as user_id, u.login as user_login";
1549 $sql .= " FROM ".MAIN_DB_PREFIX."adherent_type as t, ".MAIN_DB_PREFIX."adherent as d";
1550 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_country as c ON d.country = c.rowid";
1551 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_departements as dep ON d.state_id = dep.rowid";
1552 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as u ON d.rowid = u.fk_member";
1553 $sql .= " WHERE d.fk_adherent_type = t.rowid";
1554 if ($rowid) {
1555 $sql .= " AND d.rowid=".((int) $rowid);
1556 } elseif ($ref || $fk_soc) {
1557 $sql .= " AND d.entity IN (".getEntity('adherent').")";
1558 if ($ref) {
1559 $sql .= " AND d.ref='".$this->db->escape($ref)."'";
1560 } elseif ($fk_soc > 0) {
1561 $sql .= " AND d.fk_soc=".((int) $fk_soc);
1562 }
1563 } elseif ($ref_ext) {
1564 $sql .= " AND d.ref_ext='".$this->db->escape($ref_ext)."'";
1565 }
1566
1567 dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
1568 $resql = $this->db->query($sql);
1569 if ($resql) {
1570 if ($this->db->num_rows($resql)) {
1571 $obj = $this->db->fetch_object($resql);
1572
1573 $this->entity = $obj->entity;
1574 $this->id = $obj->rowid;
1575 $this->ref = $obj->ref;
1576 $this->ref_ext = $obj->ref_ext;
1577
1578 $this->civility_id = $obj->civility_code; // Bad. Kept for backward compatibility
1579 $this->civility_code = $obj->civility_code;
1580 $this->civility = $obj->civility_code ? ($langs->trans("Civility".$obj->civility_code) != "Civility".$obj->civility_code ? $langs->trans("Civility".$obj->civility_code) : $obj->civility_code) : '';
1581
1582 $this->firstname = $obj->firstname;
1583 $this->lastname = $obj->lastname;
1584 $this->gender = $obj->gender;
1585 $this->login = $obj->login;
1586 $this->societe = $obj->company;
1587 $this->company = $obj->company;
1588 $this->socid = $obj->fk_soc;
1589 $this->fk_soc = $obj->fk_soc; // For backward compatibility
1590 $this->address = $obj->address;
1591 $this->zip = $obj->zip;
1592 $this->town = $obj->town;
1593
1594 $this->pass = $obj->pass;
1595 $this->pass_indatabase = $obj->pass;
1596 $this->pass_indatabase_crypted = $obj->pass_crypted;
1597
1598 $this->state_id = $obj->state_id;
1599 $this->state_code = $obj->state_id ? $obj->state_code : '';
1600 $this->state = $obj->state_id ? $obj->state : '';
1601
1602 $this->country_id = $obj->country_id;
1603 $this->country_code = $obj->country_code;
1604 if ($langs->trans("Country".$obj->country_code) != "Country".$obj->country_code) {
1605 $this->country = $langs->transnoentitiesnoconv("Country".$obj->country_code);
1606 } else {
1607 $this->country = $obj->country;
1608 }
1609
1610 $this->phone = $obj->phone;
1611 $this->phone_perso = $obj->phone_perso;
1612 $this->phone_mobile = $obj->phone_mobile;
1613 $this->email = $obj->email;
1614 $this->url = $obj->url;
1615
1616 $this->socialnetworks = ($obj->socialnetworks ? (array) json_decode($obj->socialnetworks, true) : array());
1617
1618 $this->photo = $obj->photo;
1619 $this->statut = $obj->statut;
1620 $this->status = $obj->statut;
1621 $this->public = $obj->public;
1622
1623 $this->datec = $this->db->jdate($obj->datec);
1624 $this->date_creation = $this->db->jdate($obj->datec);
1625 $this->datem = $this->db->jdate($obj->datem);
1626 $this->date_modification = $this->db->jdate($obj->datem);
1627 $this->datefin = $this->db->jdate($obj->datefin);
1628 $this->datevalid = $this->db->jdate($obj->datev);
1629 $this->date_validation = $this->db->jdate($obj->datev);
1630 $this->birth = $this->db->jdate($obj->birthday);
1631
1632 $this->default_lang = $obj->default_lang;
1633
1634 $this->note_private = $obj->note_private;
1635 $this->note_public = $obj->note_public;
1636 $this->morphy = $obj->morphy;
1637
1638 $this->typeid = $obj->fk_adherent_type;
1639 $this->type = $obj->type;
1640 $this->need_subscription = $obj->subscription;
1641
1642 $this->user_id = $obj->user_id;
1643 $this->user_login = $obj->user_login;
1644
1645 $this->model_pdf = $obj->model_pdf;
1646
1647 // Retrieve all extrafield
1648 // fetch optionals attributes and labels
1649 if ($fetch_optionals) {
1650 $this->fetch_optionals();
1651 }
1652
1653 // Load other properties
1654 if ($fetch_subscriptions) {
1655 $result = $this->fetch_subscriptions();
1656 }
1657
1658 return $this->id;
1659 } else {
1660 return 0;
1661 }
1662 } else {
1663 $this->error = $this->db->lasterror();
1664 return -1;
1665 }
1666 }
1667
1668
1669 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1678 public function fetch_subscriptions()
1679 {
1680 // phpcs:enable
1681 global $langs;
1682
1683 require_once DOL_DOCUMENT_ROOT.'/adherents/class/subscription.class.php';
1684
1685 $sql = "SELECT c.rowid, c.fk_adherent, c.fk_type, c.subscription, c.note as note_public, c.fk_bank,";
1686 $sql .= " c.tms as datem,";
1687 $sql .= " c.datec as datec,";
1688 $sql .= " c.dateadh as dateh,";
1689 $sql .= " c.datef as datef";
1690 $sql .= " FROM ".MAIN_DB_PREFIX."subscription as c";
1691 $sql .= " WHERE c.fk_adherent = ".((int) $this->id);
1692 $sql .= " ORDER BY c.dateadh";
1693 dol_syslog(get_class($this)."::fetch_subscriptions", LOG_DEBUG);
1694
1695 $resql = $this->db->query($sql);
1696 if ($resql) {
1697 $this->subscriptions = array();
1698
1699 $i = 0;
1700 while ($obj = $this->db->fetch_object($resql)) {
1701 if ($i == 0) {
1702 $this->first_subscription_date = $this->db->jdate($obj->datec);
1703 $this->first_subscription_date_start = $this->db->jdate($obj->dateh);
1704 $this->first_subscription_date_end = $this->db->jdate($obj->datef);
1705 $this->first_subscription_amount = $obj->subscription;
1706 }
1707 $this->last_subscription_date = $this->db->jdate($obj->datec);
1708 $this->last_subscription_date_start = $this->db->jdate($obj->dateh);
1709 $this->last_subscription_date_end = $this->db->jdate($obj->datef);
1710 $this->last_subscription_amount = $obj->subscription;
1711
1712 $subscription = new Subscription($this->db);
1713 $subscription->id = $obj->rowid;
1714 $subscription->fk_adherent = $obj->fk_adherent;
1715 $subscription->fk_type = $obj->fk_type;
1716 $subscription->amount = $obj->subscription;
1717 $subscription->note = $obj->note_public;
1718 $subscription->note_public = $obj->note_public;
1719 $subscription->fk_bank = $obj->fk_bank;
1720 $subscription->datem = $this->db->jdate($obj->datem);
1721 $subscription->datec = $this->db->jdate($obj->datec);
1722 $subscription->dateh = $this->db->jdate($obj->dateh);
1723 $subscription->datef = $this->db->jdate($obj->datef);
1724
1725 $this->subscriptions[] = $subscription;
1726
1727 $i++;
1728 }
1729 return 1;
1730 } else {
1731 $this->error = $this->db->error().' sql='.$sql;
1732 return -1;
1733 }
1734 }
1735
1736
1743 public function fetchPartnerships($mode)
1744 {
1745 global $langs;
1746
1747 require_once DOL_DOCUMENT_ROOT.'/partnership/class/partnership.class.php';
1748
1749
1750 $this->partnerships[] = array();
1751
1752 return 1;
1753 }
1754
1755
1771 public function subscription($date, $amount, $accountid = 0, $operation = '', $label = '', $num_chq = '', $emetteur_nom = '', $emetteur_banque = '', $datesubend = 0, $fk_type = null)
1772 {
1773 global $user;
1774
1775 require_once DOL_DOCUMENT_ROOT.'/adherents/class/subscription.class.php';
1776
1777 $error = 0;
1778
1779 // Clean parameters
1780 if (!$amount) {
1781 $amount = 0;
1782 }
1783
1784 $this->db->begin();
1785
1786 if ($datesubend) {
1787 $datefin = $datesubend;
1788 } else {
1789 // If no end date, end date = date + 1 year - 1 day
1790 $datefin = dol_time_plus_duree($date, 1, 'y');
1791 $datefin = dol_time_plus_duree($datefin, -1, 'd');
1792 }
1793
1794 // Create subscription
1795 $subscription = new Subscription($this->db);
1796 $subscription->fk_adherent = $this->id;
1797 $subscription->dateh = $date; // Date of new subscription
1798 $subscription->datef = $datefin; // End data of new subscription
1799 $subscription->amount = $amount;
1800 $subscription->note = $label; // deprecated
1801 $subscription->note_public = $label;
1802 $subscription->fk_type = $fk_type;
1803
1804 if (empty($subscription->user_creation_id)) {
1805 $subscription->user_creation_id = $user->id;
1806 }
1807
1808 $rowid = $subscription->create($user);
1809 if ($rowid > 0) {
1810 // Update denormalized subscription end date (read database subscription to find values)
1811 // This will also update this->datefin
1812 $result = $this->update_end_date($user);
1813 if ($result > 0) {
1814 // Change properties of object (used by triggers)
1815 $this->last_subscription_date = dol_now();
1816 $this->last_subscription_date_start = $date;
1817 $this->last_subscription_date_end = $datefin;
1818 $this->last_subscription_amount = $amount;
1819 }
1820
1821 if (!$error) {
1822 $this->db->commit();
1823 return $rowid;
1824 } else {
1825 $this->db->rollback();
1826 return -2;
1827 }
1828 } else {
1829 $this->setErrorsFromObject($subscription);
1830 $this->db->rollback();
1831 return -1;
1832 }
1833 }
1834
1835
1855 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 = '')
1856 {
1857 global $conf, $langs, $user, $mysoc;
1858
1859 $error = 0;
1860
1861 $this->invoice = null; // This will contains invoice if an invoice is created
1862
1863 dol_syslog("subscriptionComplementaryActions subscriptionid=".$subscriptionid." option=".$option." accountid=".$accountid." datesubscription=".$datesubscription." paymentdate=".
1864 $paymentdate." label=".$label." amount=".$amount." num_chq=".$num_chq." autocreatethirdparty=".$autocreatethirdparty);
1865
1866 // Insert into bank account directlty (if option chosen for) + link to llx_subscription if option is 'bankdirect'
1867 if ($option == 'bankdirect' && $accountid) {
1868 require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
1869
1870 $acct = new Account($this->db);
1871 $result = $acct->fetch($accountid);
1872
1873 $dateop = $paymentdate;
1874
1875 $insertid = $acct->addline($dateop, $operation, $label, $amount, $num_chq, 0, $user, $emetteur_nom, $emetteur_banque);
1876 if ($insertid > 0) {
1877 $inserturlid = $acct->add_url_line($insertid, $this->id, DOL_URL_ROOT.'/adherents/card.php?rowid=', $this->getFullName($langs), 'member');
1878 if ($inserturlid > 0) {
1879 // Update table subscription
1880 $sql = "UPDATE ".MAIN_DB_PREFIX."subscription SET fk_bank=".((int) $insertid);
1881 $sql .= " WHERE rowid=".((int) $subscriptionid);
1882
1883 dol_syslog("subscription::subscription", LOG_DEBUG);
1884 $resql = $this->db->query($sql);
1885 if (!$resql) {
1886 $error++;
1887 $this->error = $this->db->lasterror();
1888 $this->errors[] = $this->error;
1889 }
1890 } else {
1891 $error++;
1892 $this->setErrorsFromObject($acct);
1893 }
1894 } else {
1895 $error++;
1896 $this->setErrorsFromObject($acct);
1897 }
1898 }
1899
1900 // If option chosen, we create invoice
1901 if (($option == 'bankviainvoice' && $accountid) || $option == 'invoiceonly') {
1902 require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
1903 require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/paymentterm.class.php';
1904
1905 $invoice = new Facture($this->db);
1906 $customer = new Societe($this->db);
1907
1908 if (!$error) {
1909 if (!($this->fk_soc > 0)) { // If not yet linked to a company
1910 if ($autocreatethirdparty) {
1911 // Create a linked thirdparty to member
1912 $companyalias = '';
1913 $fullname = $this->getFullName($langs);
1914
1915 if ($this->morphy == 'mor') {
1916 $companyname = $this->company;
1917 if (!empty($fullname)) {
1918 $companyalias = $fullname;
1919 }
1920 } else {
1921 $companyname = $fullname;
1922 if (!empty($this->company)) {
1923 $companyalias = $this->company;
1924 }
1925 }
1926
1927 $result = $customer->create_from_member($this, (string) $companyname, $companyalias);
1928 if ($result < 0) {
1929 $this->error = $customer->error;
1930 $this->errors = $customer->errors;
1931 $error++;
1932 } else {
1933 $this->fk_soc = $result;
1934 }
1935 } else {
1936 $langs->load("errors");
1937 $this->error = $langs->trans("ErrorMemberNotLinkedToAThirpartyLinkOrCreateFirst");
1938 $this->errors[] = $this->error;
1939 $error++;
1940 }
1941 }
1942 }
1943 if (!$error) {
1944 $result = $customer->fetch($this->fk_soc);
1945 if ($result <= 0) {
1946 $this->error = $customer->error;
1947 $this->errors = $customer->errors;
1948 $error++;
1949 }
1950 }
1951
1952 if (!$error) {
1953 // Create draft invoice
1954 $invoice->type = Facture::TYPE_STANDARD;
1955 $invoice->cond_reglement_id = $customer->cond_reglement_id;
1956 if (empty($invoice->cond_reglement_id)) {
1957 $paymenttermstatic = new PaymentTerm($this->db);
1958 $invoice->cond_reglement_id = $paymenttermstatic->getDefaultId();
1959 if (empty($invoice->cond_reglement_id)) {
1960 $error++;
1961 $this->error = 'ErrorNoPaymentTermRECEPFound';
1962 $this->errors[] = $this->error;
1963 }
1964 }
1965 $invoice->socid = $this->fk_soc;
1966 // set customer's payment bank account on the invoice
1967 if (!empty($customer->fk_account)) {
1968 $invoice->fk_account = $customer->fk_account;
1969 } elseif (getDolGlobalString('FACTURE_RIB_NUMBER')) {
1970 // set default bank account from invoice module settings
1971 $invoice->fk_account = (int) getDolGlobalString('FACTURE_RIB_NUMBER');
1972 }
1973 //set customer's payment method on the invoice
1974 if (!empty($customer->mode_reglement_id)) {
1975 $invoice->mode_reglement_id = $customer->mode_reglement_id;
1976 }
1977 //$invoice->date = $datesubscription;
1978 $invoice->date = dol_now();
1979
1980 // Possibility to add external linked objects with hooks
1981 $invoice->linked_objects['subscription'] = $subscriptionid;
1982 if (GETPOSTISARRAY('other_linked_objects')) {
1983 $invoice->linked_objects = array_merge($invoice->linked_objects, GETPOST('other_linked_objects', 'array:int'));
1984 }
1985
1986 $result = $invoice->create($user);
1987 if ($result <= 0) {
1988 $this->error = $invoice->error;
1989 $this->errors = $invoice->errors;
1990 $error++;
1991 } else {
1992 $this->invoice = $invoice;
1993 }
1994 }
1995
1996 if (!$error) {
1997 // Add line to draft invoice
1998 $idprodsubscription = 0;
1999 if (getDolGlobalString('ADHERENT_PRODUCT_ID_FOR_SUBSCRIPTIONS') && (isModEnabled("product") || isModEnabled("service"))) {
2000 $idprodsubscription = getDolGlobalString('ADHERENT_PRODUCT_ID_FOR_SUBSCRIPTIONS');
2001 }
2002
2003 $vattouse = 0;
2004 if (getDolGlobalString('ADHERENT_VAT_FOR_SUBSCRIPTIONS') == 'defaultforfoundationcountry') {
2005 $vattouse = get_default_tva($mysoc, $mysoc, $idprodsubscription);
2006 }
2007 //print xx".$vattouse." - ".$mysoc." - ".$customer;exit;
2008 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
2009 $result = $invoice->addline($label, 0, 1, $vattouse, 0, 0, $idprodsubscription, 0, $datesubscription, '', 0, 0, 0, 'TTC', $amount, 1);
2010 if ($result <= 0) {
2011 $this->error = $invoice->error;
2012 $this->errors = $invoice->errors;
2013 $error++;
2014 }
2015 }
2016
2017 if (!$error) {
2018 // Validate invoice
2019 $result = $invoice->validate($user);
2020 if ($result <= 0) {
2021 $this->error = $invoice->error;
2022 $this->errors = $invoice->errors;
2023 $error++;
2024 }
2025 }
2026
2027 if (!$error) {
2028 // TODO Link invoice with subscription ?
2029 }
2030
2031 // Add payment onto invoice
2032 if (!$error && $option == 'bankviainvoice' && $accountid) {
2033 require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
2034 require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
2035 require_once DOL_DOCUMENT_ROOT.'/core/lib/functions.lib.php';
2036
2037 $amounts = array();
2038 $amounts[$invoice->id] = (float) price2num($amount);
2039
2040 $paiement = new Paiement($this->db);
2041 $paiement->datepaye = $paymentdate;
2042 $paiement->amounts = $amounts;
2043 $paiement->paiementcode = $operation;
2044 $paiement->paiementid = dol_getIdFromCode($this->db, $operation, 'c_paiement', 'code', 'id', 1);
2045 $paiement->num_payment = $num_chq;
2046 $paiement->note_public = $label;
2047 $paiement->ext_payment_id = $ext_payment_id;
2048 $paiement->ext_payment_site = $ext_payment_site;
2049
2050 if (!$error) {
2051 // Create payment line for invoice
2052 $paiement_id = $paiement->create($user);
2053 if (!($paiement_id > 0)) {
2054 $this->error = $paiement->error;
2055 $this->errors = $paiement->errors;
2056 $error++;
2057 }
2058 }
2059
2060 if (!$error) {
2061 // Add transaction into bank account
2062 $bank_line_id = $paiement->addPaymentToBank($user, 'payment', '(SubscriptionPayment)', $accountid, $emetteur_nom, $emetteur_banque);
2063 if (!($bank_line_id > 0)) {
2064 $this->error = $paiement->error;
2065 $this->errors = $paiement->errors;
2066 $error++;
2067 }
2068 }
2069
2070 if (!$error && !empty($bank_line_id)) {
2071 // Update fk_bank into subscription table
2072 $sql = 'UPDATE '.MAIN_DB_PREFIX.'subscription SET fk_bank='.((int) $bank_line_id);
2073 $sql .= ' WHERE rowid='.((int) $subscriptionid);
2074
2075 $result = $this->db->query($sql);
2076 if (!$result) {
2077 $error++;
2078 }
2079 }
2080
2081 if (!$error) {
2082 // Set invoice as paid
2083 $invoice->setPaid($user);
2084 }
2085 }
2086
2087 if (!$error) {
2088 // Define output language
2089 $outputlangs = $langs;
2090 $newlang = '';
2091 $lang_id = GETPOST('lang_id');
2092 if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && !empty($lang_id)) {
2093 $newlang = $lang_id;
2094 }
2095 if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
2096 $newlang = $customer->default_lang;
2097 }
2098 if (!empty($newlang)) {
2099 $outputlangs = new Translate("", $conf);
2100 $outputlangs->setDefaultLang($newlang);
2101 }
2102 // Generate PDF (whatever is option MAIN_DISABLE_PDF_AUTOUPDATE) so we can include it into email
2103 //if (!getDolGlobalString('MAIN_DISABLE_PDF_AUTOUPDATE'))
2104
2105 $invoice->fetch($invoice->id); // Reload invoice object data
2106 $invoice->generateDocument($invoice->model_pdf, $outputlangs);
2107 }
2108 }
2109
2110 if ($error) {
2111 return -1;
2112 } else {
2113 return 1;
2114 }
2115 }
2116
2117
2124 public function validate($user)
2125 {
2126 global $langs, $conf;
2127
2128 $error = 0;
2129 $now = dol_now();
2130
2131 // Check parameters
2132 if ($this->statut == self::STATUS_VALIDATED) {
2133 dol_syslog(get_class($this)."::validate statut of member does not allow this", LOG_WARNING);
2134 return 0;
2135 }
2136
2137 $this->db->begin();
2138
2139 $sql = "UPDATE ".MAIN_DB_PREFIX."adherent SET";
2140 $sql .= " statut = ".self::STATUS_VALIDATED;
2141 $sql .= ", datevalid = '".$this->db->idate($now)."'";
2142 $sql .= ", fk_user_valid = ".((int) $user->id);
2143 $sql .= " WHERE rowid = ".((int) $this->id);
2144
2145 dol_syslog(get_class($this)."::validate", LOG_DEBUG);
2146 $result = $this->db->query($sql);
2147 if ($result) {
2148 $this->statut = self::STATUS_VALIDATED;
2149
2150 // Call trigger
2151 $result = $this->call_trigger('MEMBER_VALIDATE', $user);
2152 if ($result < 0) {
2153 $error++;
2154 $this->db->rollback();
2155 return -1;
2156 }
2157 // End call triggers
2158
2159 $this->datevalid = $now;
2160
2161 $this->db->commit();
2162 return 1;
2163 } else {
2164 $this->error = $this->db->error();
2165 $this->db->rollback();
2166 return -1;
2167 }
2168 }
2169
2170
2177 public function resiliate($user)
2178 {
2179 global $langs, $conf;
2180
2181 $error = 0;
2182
2183 // Check parameters
2184 if ($this->statut == self::STATUS_RESILIATED) {
2185 dol_syslog(get_class($this)."::resiliate statut of member does not allow this", LOG_WARNING);
2186 return 0;
2187 }
2188
2189 $this->db->begin();
2190
2191 $sql = "UPDATE ".MAIN_DB_PREFIX."adherent SET";
2192 $sql .= " statut = ".((int) self::STATUS_RESILIATED);
2193 $sql .= ", fk_user_valid = ".((int) $user->id);
2194 $sql .= " WHERE rowid = ".((int) $this->id);
2195
2196 $result = $this->db->query($sql);
2197 if ($result) {
2198 $this->statut = self::STATUS_RESILIATED;
2199
2200 // Call trigger
2201 $result = $this->call_trigger('MEMBER_RESILIATE', $user);
2202 if ($result < 0) {
2203 $error++;
2204 $this->db->rollback();
2205 return -1;
2206 }
2207 // End call triggers
2208
2209 $this->db->commit();
2210 return 1;
2211 } else {
2212 $this->error = $this->db->error();
2213 $this->db->rollback();
2214 return -1;
2215 }
2216 }
2217
2227 public function exclude($user)
2228 {
2229 $error = 0;
2230
2231 // Check parameters
2232 if ($this->statut == self::STATUS_EXCLUDED) {
2233 dol_syslog(get_class($this)."::resiliate statut of member does not allow this", LOG_WARNING);
2234 return 0;
2235 }
2236
2237 $this->db->begin();
2238
2239 $sql = "UPDATE ".MAIN_DB_PREFIX."adherent SET";
2240 $sql .= " statut = ".((int) self::STATUS_EXCLUDED);
2241 $sql .= ", fk_user_valid = ".((int) $user->id);
2242 $sql .= " WHERE rowid = ".((int) $this->id);
2243
2244 $result = $this->db->query($sql);
2245 if ($result) {
2246 $this->statut = self::STATUS_EXCLUDED;
2247
2248 // Call trigger
2249 $result = $this->call_trigger('MEMBER_EXCLUDE', $user);
2250 if ($result < 0) {
2251 $error++;
2252 $this->db->rollback();
2253 return -1;
2254 }
2255 // End call triggers
2256
2257 $this->db->commit();
2258 return 1;
2259 } else {
2260 $this->error = $this->db->error();
2261 $this->db->rollback();
2262 return -1;
2263 }
2264 }
2265
2266 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2272 public function add_to_abo()
2273 {
2274 // phpcs:enable
2275 global $langs;
2276
2277 include_once DOL_DOCUMENT_ROOT.'/mailmanspip/class/mailmanspip.class.php';
2278 $mailmanspip = new MailmanSpip($this->db);
2279
2280 $err = 0;
2281
2282 // mailman
2283 if (getDolGlobalString('ADHERENT_USE_MAILMAN') && isModEnabled('mailmanspip')) {
2284 $result = $mailmanspip->add_to_mailman($this);
2285
2286 if ($result < 0) {
2287 if (!empty($mailmanspip->error)) {
2288 $this->errors[] = $mailmanspip->error;
2289 }
2290 $err += 1;
2291 }
2292 foreach ($mailmanspip->mladded_ko as $tmplist => $tmpemail) {
2293 $langs->load("errors");
2294 $this->errors[] = $langs->trans("ErrorFailedToAddToMailmanList", $tmpemail, $tmplist);
2295 }
2296 foreach ($mailmanspip->mladded_ok as $tmplist => $tmpemail) {
2297 $langs->load("mailmanspip");
2298 $this->mesgs[] = $langs->trans("SuccessToAddToMailmanList", $tmpemail, $tmplist);
2299 }
2300 }
2301
2302 // spip
2303 if (getDolGlobalString('ADHERENT_USE_SPIP') && isModEnabled('mailmanspip')) {
2304 $result = $mailmanspip->add_to_spip($this);
2305 if ($result < 0) {
2306 $this->errors[] = $mailmanspip->error;
2307 $err += 1;
2308 }
2309 }
2310 if ($err) {
2311 return -$err;
2312 } else {
2313 return 1;
2314 }
2315 }
2316
2317
2318 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2324 public function del_to_abo()
2325 {
2326 // phpcs:enable
2327 global $conf, $langs;
2328
2329 include_once DOL_DOCUMENT_ROOT.'/mailmanspip/class/mailmanspip.class.php';
2330 $mailmanspip = new MailmanSpip($this->db);
2331
2332 $err = 0;
2333
2334 // mailman
2335 if (getDolGlobalString('ADHERENT_USE_MAILMAN')) {
2336 $result = $mailmanspip->del_to_mailman($this);
2337 if ($result < 0) {
2338 if (!empty($mailmanspip->error)) {
2339 $this->errors[] = $mailmanspip->error;
2340 }
2341 $err += 1;
2342 }
2343
2344 foreach ($mailmanspip->mlremoved_ko as $tmplist => $tmpemail) {
2345 $langs->load("errors");
2346 $this->errors[] = $langs->trans("ErrorFailedToRemoveToMailmanList", $tmpemail, $tmplist);
2347 }
2348 foreach ($mailmanspip->mlremoved_ok as $tmplist => $tmpemail) {
2349 $langs->load("mailmanspip");
2350 $this->mesgs[] = $langs->trans("SuccessToRemoveToMailmanList", $tmpemail, $tmplist);
2351 }
2352 }
2353
2354 if (getDolGlobalString('ADHERENT_USE_SPIP') && isModEnabled('mailmanspip')) {
2355 $result = $mailmanspip->del_to_spip($this);
2356 if ($result < 0) {
2357 $this->errors[] = $mailmanspip->error;
2358 $err += 1;
2359 }
2360 }
2361 if ($err) {
2362 // error
2363 return -$err;
2364 } else {
2365 return 1;
2366 }
2367 }
2368
2369
2375 public function getCivilityLabel()
2376 {
2377 global $langs;
2378 $langs->load("dict");
2379
2380 $code = (empty($this->civility_id) ? '' : $this->civility_id);
2381 if (empty($code)) {
2382 return '';
2383 }
2384 return $langs->getLabelFromKey($this->db, "Civility".$code, "c_civility", "code", "label", $code);
2385 }
2386
2393 public function getTooltipContentArray($params)
2394 {
2395 global $langs;
2396
2397 $langs->loadLangs(['members', 'companies']);
2398 $nofetch = !empty($params['nofetch']);
2399
2400 $datas = array();
2401
2402 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
2403 $langs->load("users");
2404 return ['optimize' => $langs->trans("ShowUser")];
2405 }
2406 if (!empty($this->photo)) {
2407 $photo = '<div class="photointooltip floatright">';
2408 $photo .= Form::showphoto('memberphoto', $this, 80, 0, 0, 'photoref photowithmargin photologintooltip', 'small', 0, 1);
2409 $photo .= '</div>';
2410 $datas['photo'] = $photo;
2411 }
2412
2413 $datas['divopen'] = '<div class="centpercent">';
2414 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Member").'</u> '.$this->getLibStatut(4);
2415 if (!empty($this->morphy)) {
2416 $datas['picto'] .= '&nbsp;' . $this->getmorphylib('', 1);
2417 }
2418 if (!empty($this->ref)) {
2419 $datas['ref'] = '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref;
2420 }
2421 if (!empty($this->login)) {
2422 $datas['login'] = '<br><b>'.$langs->trans('Login').':</b> '.$this->login;
2423 }
2424 if (!empty($this->firstname) || !empty($this->lastname)) {
2425 $datas['name'] = '<br><b>'.$langs->trans('Name').':</b> '.$this->getFullName($langs);
2426 }
2427 if (!empty($this->company)) {
2428 $datas['company'] = '<br><b>'.$langs->trans('Company').':</b> '.$this->company;
2429 }
2430 if (!empty($this->email)) {
2431 $datas['email'] = '<br><b>'.$langs->trans("EMail").':</b> '.$this->email;
2432 }
2433 $datas['address'] = '<br><b>'.$langs->trans("Address").':</b> '.dol_format_address($this, 1, ' ', $langs);
2434 // show categories for this record only in ajax to not overload lists
2435 if (isModEnabled('category') && !$nofetch) {
2436 require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
2437 $form = new Form($this->db);
2438 $datas['categories'] = '<br>' . $form->showCategories($this->id, Categorie::TYPE_MEMBER, 1);
2439 }
2440 $datas['divclose'] = '</div>';
2441
2442 return $datas;
2443 }
2444
2458 public function getNomUrl($withpictoimg = 0, $maxlen = 0, $option = 'card', $mode = '', $morecss = '', $save_lastsearch_value = -1, $notooltip = 0, $addlinktonotes = 0)
2459 {
2460 global $conf, $langs, $hookmanager;
2461
2462 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER') && $withpictoimg) {
2463 $withpictoimg = 0;
2464 }
2465
2466 $result = '';
2467 $linkstart = '';
2468 $linkend = '';
2469 $classfortooltip = 'classfortooltip';
2470 $dataparams = '';
2471 $params = [
2472 'id' => $this->id,
2473 'objecttype' => $this->element,
2474 'option' => $option,
2475 'nofetch' => 1,
2476 ];
2477 if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
2478 $classfortooltip = 'classforajaxtooltip';
2479 $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
2480 $label = '';
2481 } else {
2482 $label = implode($this->getTooltipContentArray($params));
2483 }
2484
2485 $url = DOL_URL_ROOT.'/adherents/card.php?rowid='.((int) $this->id);
2486 if ($option == 'subscription') {
2487 $url = DOL_URL_ROOT.'/adherents/subscription.php?rowid='.((int) $this->id);
2488 }
2489
2490 if ($option != 'nolink') {
2491 // Add param to save lastsearch_values or not
2492 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
2493 if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
2494 $add_save_lastsearch_values = 1;
2495 }
2496 if ($add_save_lastsearch_values) {
2497 $url .= '&save_lastsearch_values=1';
2498 }
2499 }
2500
2501 $linkstart .= '<a href="'.$url.'"';
2502 $linkclose = "";
2503 if (empty($notooltip)) {
2504 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
2505 $langs->load("users");
2506 $label = $langs->trans("ShowUser");
2507 $linkclose .= ' alt="'.dolPrintHTMLForAttribute($label).'"';
2508 }
2509 $linkclose .= ($label ? ' title="'.dolPrintHTMLForAttribute($label).'"' : ' title="tocomplete"');
2510 $linkclose .= $dataparams.' class="'.$classfortooltip.($morecss ? ' '.$morecss : '').'"';
2511 }
2512
2513 $linkstart .= $linkclose.'>';
2514 $linkend = '</a>';
2515
2516 $result .= $linkstart;
2517
2518 if ($withpictoimg) {
2519 $paddafterimage = '';
2520 if (abs($withpictoimg) == 1 || abs($withpictoimg) == 4) {
2521 $morecss .= ' paddingrightonly';
2522 }
2523 // Only picto
2524 if ($withpictoimg > 0) {
2525 $picto = '<span class="nopadding'.($morecss ? ' userimg'.$morecss : '').'">'.img_object('', 'user', $paddafterimage.' '.($notooltip ? '' : $dataparams), 0, 0, $notooltip ? 0 : 1).'</span>';
2526 } else {
2527 // Picto must be a photo
2528 $picto = '<span class="nopadding'.($morecss ? ' userimg'.$morecss : '').'"'.($paddafterimage ? ' '.$paddafterimage : '').'>';
2529 $picto .= Form::showphoto('memberphoto', $this, 0, 0, 0, 'userphoto'.(($withpictoimg == -3 || $withpictoimg == -4) ? 'small' : ''), 'mini', 0, 1);
2530 $picto .= '</span>';
2531 }
2532 $result .= $picto;
2533 }
2534 if (($withpictoimg > -2 && $withpictoimg != 2) || $withpictoimg == -4) {
2535 if (!getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
2536 $result .= '<span class="nopadding valignmiddle'.((!isset($this->statut) || $this->statut) ? '' : ' strikefordisabled').
2537 ($morecss ? ' usertext'.$morecss : '').'">';
2538 }
2539 if ($mode == 'login') {
2540 $result .= dol_trunc(isset($this->login) ? $this->login : '', $maxlen);
2541 } elseif ($mode == 'ref') {
2542 $result .= $this->ref;
2543 } else {
2544 $result .= $this->getFullName($langs, 0, ($mode == 'firstname' ? 2 : ($mode == 'lastname' ? 4 : -1)), $maxlen);
2545 }
2546 if (!getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
2547 $result .= '</span>';
2548 }
2549 }
2550
2551 $result .= $linkend;
2552
2553 if ($addlinktonotes) {
2554 if ($this->note_private) {
2555 $notetoshow = $langs->trans("ViewPrivateNote").':<br>'.dol_string_nohtmltag($this->note_private, 1);
2556 $result .= ' <span class="note inline-block">';
2557 $result .= '<a href="'.DOL_URL_ROOT.'/adherents/note.php?id='.$this->id.'" class="classfortooltip" title="'.dol_escape_htmltag($notetoshow).'">';
2558 $result .= img_picto('', 'note');
2559 $result .= '</a>';
2560 $result .= '</span>';
2561 }
2562 }
2563 global $action;
2564 $hookmanager->initHooks(array($this->element . 'dao'));
2565 $parameters = array('id' => $this->id, 'getnomurl' => &$result);
2566 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
2567 if ($reshook > 0) {
2568 $result = $hookmanager->resPrint;
2569 } else {
2570 $result .= $hookmanager->resPrint;
2571 }
2572 return $result;
2573 }
2574
2581 public function getLibStatut($mode = 0)
2582 {
2583 return $this->LibStatut($this->status, $this->need_subscription, $this->datefin, $mode);
2584 }
2585
2586 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2596 public function LibStatut($status, $need_subscription, $date_end_subscription, $mode = 0)
2597 {
2598 // phpcs:enable
2599 global $langs;
2600 $langs->load("members");
2601
2602 $statusType = '';
2603 $labelStatus = '';
2604 $labelStatusShort = '';
2605
2606 if ($status == self::STATUS_DRAFT) {
2607 $statusType = 'status0';
2608 $labelStatus = $langs->trans("MemberStatusDraft");
2609 $labelStatusShort = $langs->trans("MemberStatusDraftShort");
2610 } elseif ($status >= self::STATUS_VALIDATED) {
2611 if ($need_subscription === 0) {
2612 $statusType = 'status4';
2613 $labelStatus = $langs->trans("Validated").' - '.$langs->trans("MemberStatusNoSubscription");
2614 $labelStatusShort = $langs->trans("MemberStatusNoSubscriptionShort");
2615 } elseif (!$date_end_subscription) {
2616 $statusType = 'status1';
2617 $labelStatus = $langs->trans("Validated").' - '.$langs->trans("WaitingSubscription");
2618 $labelStatusShort = $langs->trans("WaitingSubscriptionShort");
2619 } elseif ($date_end_subscription < dol_now()) { // expired
2620 $statusType = 'status2';
2621 $labelStatus = $langs->trans("Validated").' - '.$langs->trans("MemberStatusActiveLate");
2622 $labelStatusShort = $langs->trans("MemberStatusActiveLateShort");
2623 } else {
2624 $statusType = 'status4';
2625 $labelStatus = $langs->trans("Validated").' - '.$langs->trans("MemberStatusPaid");
2626 $labelStatusShort = $langs->trans("MemberStatusPaidShort");
2627 }
2628 } elseif ($status == self::STATUS_RESILIATED) {
2629 $statusType = 'status6';
2630 $labelStatus = $langs->transnoentitiesnoconv("MemberStatusResiliated");
2631 $labelStatusShort = $langs->transnoentitiesnoconv("MemberStatusResiliatedShort");
2632 } elseif ($status == self::STATUS_EXCLUDED) {
2633 $statusType = 'status10';
2634 $labelStatus = $langs->transnoentitiesnoconv("MemberStatusExcluded");
2635 $labelStatusShort = $langs->transnoentitiesnoconv("MemberStatusExcludedShort");
2636 }
2637
2638 return dolGetStatus($labelStatus, $labelStatusShort, '', $statusType, $mode);
2639 }
2640
2641
2647 public function loadStateBoard()
2648 {
2649 global $conf;
2650
2651 $this->nb = array();
2652
2653 $sql = "SELECT count(a.rowid) as nb";
2654 $sql .= " FROM ".MAIN_DB_PREFIX."adherent as a";
2655 $sql .= " WHERE a.statut > 0";
2656 $sql .= " AND a.entity IN (".getEntity('adherent').")";
2657
2658 $resql = $this->db->query($sql);
2659 if ($resql) {
2660 while ($obj = $this->db->fetch_object($resql)) {
2661 $this->nb["members"] = $obj->nb;
2662 }
2663 $this->db->free($resql);
2664 return 1;
2665 } else {
2666 dol_print_error($this->db);
2667 $this->error = $this->db->error();
2668 return -1;
2669 }
2670 }
2671
2672 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2680 public function load_board($user, $mode)
2681 {
2682 // phpcs:enable
2683 global $conf, $langs;
2684
2685 if ($user->socid) {
2686 return -1; // protection pour eviter appel par utilisateur externe
2687 }
2688
2689 $now = dol_now();
2690
2691 $sql = "SELECT a.rowid, a.datefin, a.statut";
2692 $sql .= " FROM ".MAIN_DB_PREFIX."adherent as a";
2693 $sql .= ", ".MAIN_DB_PREFIX."adherent_type as t";
2694 $sql .= " WHERE a.fk_adherent_type = t.rowid";
2695 if ($mode == 'expired') {
2696 $sql .= " AND a.statut = ".self::STATUS_VALIDATED;
2697 $sql .= " AND a.entity IN (".getEntity('adherent').")";
2698 $sql .= " AND ((a.datefin IS NULL or a.datefin < '".$this->db->idate($now)."') AND t.subscription = '1')";
2699 } elseif ($mode == 'shift') {
2700 $sql .= " AND a.statut = ".self::STATUS_DRAFT;
2701 $sql .= " AND a.entity IN (".getEntity('adherent').")";
2702 }
2703
2704 $resql = $this->db->query($sql);
2705 if ($resql) {
2706 $langs->load("members");
2707
2708 $warning_delay = 0;
2709 $url = '';
2710 $label = '';
2711 $labelShort = '';
2712
2713 if ($mode == 'expired') {
2714 $warning_delay = $conf->adherent->subscription->warning_delay / 60 / 60 / 24;
2715 $label = $langs->trans("MembersWithSubscriptionToReceive");
2716 $labelShort = $langs->trans("MembersWithSubscriptionToReceiveShort");
2717 $url = DOL_URL_ROOT.'/adherents/list.php?mainmenu=members&amp;statut='.self::STATUS_VALIDATED.'&amp;filter=outofdate';
2718 } elseif ($mode == 'shift') {
2719 $warning_delay = $conf->adherent->subscription->warning_delay / 60 / 60 / 24;
2720 $url = DOL_URL_ROOT.'/adherents/list.php?mainmenu=members&amp;statut='.self::STATUS_DRAFT;
2721 $label = $langs->trans("MembersListToValid");
2722 $labelShort = $langs->trans("ToValidate");
2723 }
2724
2725 $response = new WorkboardResponse();
2726 $response->warning_delay = $warning_delay;
2727 $response->label = $label;
2728 $response->labelShort = $labelShort;
2729 $response->url = $url;
2730 $response->img = img_object('', "user");
2731
2732 $adherentstatic = new Adherent($this->db);
2733
2734 while ($obj = $this->db->fetch_object($resql)) {
2735 $response->nbtodo++;
2736
2737 $adherentstatic->datefin = $this->db->jdate($obj->datefin);
2738 $adherentstatic->statut = $obj->statut;
2739 $adherentstatic->status = $obj->statut;
2740
2741 if ($adherentstatic->hasDelay()) {
2742 $response->nbtodolate++;
2743 }
2744 }
2745
2746 return $response;
2747 } else {
2748 dol_print_error($this->db);
2749 $this->error = $this->db->error();
2750 return -1;
2751 }
2752 }
2753
2754
2766 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
2767 {
2768 global $conf, $langs;
2769
2770 $langs->load("orders");
2771
2772 if (!dol_strlen($modele)) {
2773 $modele = 'standard';
2774
2775 if ($this->model_pdf) {
2776 $modele = $this->model_pdf;
2777 } elseif (getDolGlobalString('ADHERENT_ADDON_PDF')) {
2778 $modele = getDolGlobalString('ADHERENT_ADDON_PDF');
2779 }
2780 }
2781
2782 $modelpath = "core/modules/member/doc/";
2783
2784 return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
2785 }
2786
2787
2795 public function initAsSpecimen()
2796 {
2797 global $user, $langs;
2798 $now = dol_now();
2799
2800 // Initialise parameters
2801 $this->id = 0;
2802 $this->ref = 'ABC001';
2803 $this->entity = 1;
2804 $this->specimen = 1;
2805 $this->civility_id = 'MR';
2806 $this->lastname = 'DOLIBARR';
2807 $this->firstname = 'SPECIMEN';
2808 $this->gender = 'man';
2809 $this->login = 'dolibspec';
2810 $this->pass = 'dolibspec';
2811 $this->company = 'Societe ABC';
2812 $this->address = '61 jump street';
2813 $this->zip = '75000';
2814 $this->town = 'Paris';
2815 $this->country_id = 1;
2816 $this->country_code = 'FR';
2817 $this->country = 'France';
2818 $this->morphy = 'mor';
2819 $this->email = 'specimen@specimen.com';
2820 $this->socialnetworks = array(
2821 'skype' => 'skypepseudo',
2822 'twitter' => 'twitterpseudo',
2823 'facebook' => 'facebookpseudo',
2824 'linkedin' => 'linkedinpseudo',
2825 );
2826 $this->phone = '0999999999';
2827 $this->phone_perso = '0999999998';
2828 $this->phone_mobile = '0999999997';
2829 $this->note_public = 'This is a public note';
2830 $this->note_private = 'This is a private note';
2831 $this->birth = $now;
2832 $this->photo = '';
2833 $this->public = 1;
2834 $this->statut = self::STATUS_DRAFT;
2835 $this->status = self::STATUS_DRAFT;
2836
2837 $this->datefin = $now;
2838 $this->datevalid = $now;
2839 $this->default_lang = '';
2840
2841 $this->typeid = 1; // Id type adherent
2842 $this->type = 'Type adherent'; // Libelle type adherent
2843 $this->need_subscription = 0;
2844
2845 $this->first_subscription_date = $now;
2846 $this->first_subscription_date_start = $this->first_subscription_date;
2847 $this->first_subscription_date_end = dol_time_plus_duree($this->first_subscription_date_start, 1, 'y');
2848 $this->first_subscription_amount = 10;
2849
2850 $this->last_subscription_date = $this->first_subscription_date;
2851 $this->last_subscription_date_start = $this->first_subscription_date;
2852 $this->last_subscription_date_end = dol_time_plus_duree($this->last_subscription_date_start, 1, 'y');
2853 $this->last_subscription_amount = 10;
2854 return 1;
2855 }
2856
2857
2858 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2859 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
2869 public function _load_ldap_dn($info, $mode = 0)
2870 {
2871 // phpcs:enable
2872 global $conf;
2873 $dn = '';
2874 if ($mode == 0) {
2875 $dn = getDolGlobalString('LDAP_KEY_MEMBERS') . "=".$info[getDolGlobalString('LDAP_KEY_MEMBERS')]."," . getDolGlobalString('LDAP_MEMBER_DN');
2876 }
2877 if ($mode == 1) {
2878 $dn = getDolGlobalString('LDAP_MEMBER_DN');
2879 }
2880 if ($mode == 2) {
2881 $dn = getDolGlobalString('LDAP_KEY_MEMBERS') . "=".$info[getDolGlobalString('LDAP_KEY_MEMBERS')];
2882 }
2883 return $dn;
2884 }
2885
2886
2887 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2888 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
2894 public function _load_ldap_info()
2895 {
2896 // phpcs:enable
2897 global $conf, $langs;
2898
2899 $info = array();
2900 $socialnetworks = getArrayOfSocialNetworks();
2901 $keymodified = false;
2902
2903 // Object classes
2904 $info["objectclass"] = explode(',', getDolGlobalString('LDAP_MEMBER_OBJECT_CLASS'));
2905
2906 $this->fullname = $this->getFullName($langs);
2907
2908 // For avoid ldap error when firstname and lastname are empty
2909 if ($this->morphy == 'mor' && (empty($this->fullname) || $this->fullname == $this->company)) {
2910 $this->fullname = $this->company;
2911 $this->lastname = $this->company;
2912 }
2913
2914 // Possible LDAP KEY (constname => varname)
2915 $ldapkey = array(
2916 'LDAP_MEMBER_FIELD_FULLNAME' => 'fullname',
2917 'LDAP_MEMBER_FIELD_NAME' => 'lastname',
2918 'LDAP_MEMBER_FIELD_LOGIN' => 'login',
2919 'LDAP_MEMBER_FIELD_LOGIN_SAMBA' => 'login',
2920 'LDAP_MEMBER_FIELD_MAIL' => 'email'
2921 );
2922
2923 // Member
2924 foreach ($ldapkey as $constname => $varname) {
2925 if (!empty($this->$varname) && getDolGlobalString($constname)) {
2926 $info[getDolGlobalString($constname)] = $this->$varname;
2927
2928 // Check if it is the LDAP key and if its value has been changed
2929 if (getDolGlobalString('LDAP_KEY_MEMBERS') && getDolGlobalString('LDAP_KEY_MEMBERS') == getDolGlobalString($constname)) {
2930 if (!empty($this->oldcopy) && $this->$varname != $this->oldcopy->$varname) {
2931 $keymodified = true; // For check if LDAP key has been modified
2932 }
2933 }
2934 }
2935 }
2936 if ($this->firstname && getDolGlobalString('LDAP_MEMBER_FIELD_FIRSTNAME')) {
2937 $info[getDolGlobalString('LDAP_MEMBER_FIELD_FIRSTNAME')] = $this->firstname;
2938 }
2939 if ($this->poste && getDolGlobalString('LDAP_MEMBER_FIELD_TITLE')) {
2940 $info[getDolGlobalString('LDAP_MEMBER_FIELD_TITLE')] = $this->poste;
2941 }
2942 if ($this->company && getDolGlobalString('LDAP_MEMBER_FIELD_COMPANY')) {
2943 $info[getDolGlobalString('LDAP_MEMBER_FIELD_COMPANY')] = $this->company;
2944 }
2945 if ($this->address && getDolGlobalString('LDAP_MEMBER_FIELD_ADDRESS')) {
2946 $info[getDolGlobalString('LDAP_MEMBER_FIELD_ADDRESS')] = $this->address;
2947 }
2948 if ($this->zip && getDolGlobalString('LDAP_MEMBER_FIELD_ZIP')) {
2949 $info[getDolGlobalString('LDAP_MEMBER_FIELD_ZIP')] = $this->zip;
2950 }
2951 if ($this->town && getDolGlobalString('LDAP_MEMBER_FIELD_TOWN')) {
2952 $info[getDolGlobalString('LDAP_MEMBER_FIELD_TOWN')] = $this->town;
2953 }
2954 if ($this->country_code && getDolGlobalString('LDAP_MEMBER_FIELD_COUNTRY')) {
2955 $info[getDolGlobalString('LDAP_MEMBER_FIELD_COUNTRY')] = $this->country_code;
2956 }
2957 foreach ($socialnetworks as $key => $value) {
2958 if ($this->socialnetworks[$value['label']] && getDolGlobalString('LDAP_MEMBER_FIELD_'.strtoupper($value['label']))) {
2959 $info[getDolGlobalString('LDAP_MEMBER_FIELD_'.strtoupper($value['label']))] = $this->socialnetworks[$value['label']];
2960 }
2961 }
2962 if ($this->phone && getDolGlobalString('LDAP_MEMBER_FIELD_PHONE')) {
2963 $info[getDolGlobalString('LDAP_MEMBER_FIELD_PHONE')] = $this->phone;
2964 }
2965 if ($this->phone_perso && getDolGlobalString('LDAP_MEMBER_FIELD_PHONE_PERSO')) {
2966 $info[getDolGlobalString('LDAP_MEMBER_FIELD_PHONE_PERSO')] = $this->phone_perso;
2967 }
2968 if ($this->phone_mobile && getDolGlobalString('LDAP_MEMBER_FIELD_MOBILE')) {
2969 $info[getDolGlobalString('LDAP_MEMBER_FIELD_MOBILE')] = $this->phone_mobile;
2970 }
2971 if ($this->fax && getDolGlobalString('LDAP_MEMBER_FIELD_FAX')) {
2972 $info[getDolGlobalString('LDAP_MEMBER_FIELD_FAX')] = $this->fax;
2973 }
2974 if ($this->note_private && getDolGlobalString('LDAP_MEMBER_FIELD_DESCRIPTION')) {
2975 $info[getDolGlobalString('LDAP_MEMBER_FIELD_DESCRIPTION')] = dol_string_nohtmltag($this->note_private, 2);
2976 }
2977 if ($this->note_public && getDolGlobalString('LDAP_MEMBER_FIELD_NOTE_PUBLIC')) {
2978 $info[getDolGlobalString('LDAP_MEMBER_FIELD_NOTE_PUBLIC')] = dol_string_nohtmltag($this->note_public, 2);
2979 }
2980 if ($this->birth && getDolGlobalString('LDAP_MEMBER_FIELD_BIRTHDATE')) {
2981 $info[getDolGlobalString('LDAP_MEMBER_FIELD_BIRTHDATE')] = dol_print_date($this->birth, 'dayhourldap');
2982 }
2983 if (isset($this->statut) && getDolGlobalString('LDAP_FIELD_MEMBER_STATUS')) {
2984 $info[getDolGlobalString('LDAP_FIELD_MEMBER_STATUS')] = $this->statut;
2985 }
2986 if ($this->datefin && getDolGlobalString('LDAP_FIELD_MEMBER_END_LASTSUBSCRIPTION')) {
2987 $info[getDolGlobalString('LDAP_FIELD_MEMBER_END_LASTSUBSCRIPTION')] = dol_print_date($this->datefin, 'dayhourldap');
2988 }
2989
2990 // When password is modified
2991 if (!empty($this->pass)) {
2992 if (getDolGlobalString('LDAP_MEMBER_FIELD_PASSWORD')) {
2993 $info[getDolGlobalString('LDAP_MEMBER_FIELD_PASSWORD')] = $this->pass; // this->pass = Unencrypted password
2994 }
2995 if (getDolGlobalString('LDAP_MEMBER_FIELD_PASSWORD_CRYPTED')) {
2996 $info[getDolGlobalString('LDAP_MEMBER_FIELD_PASSWORD_CRYPTED')] = dol_hash($this->pass, 'openldap'); // Create OpenLDAP password (see LDAP_PASSWORD_HASH_TYPE)
2997 }
2998 } elseif (getDolGlobalString('LDAP_SERVER_PROTOCOLVERSION') !== '3') {
2999 // Set LDAP password if possible
3000 // If ldap key is modified and LDAPv3 we use ldap_rename function for avoid lose encrypt password
3001 if (getDolGlobalString('DATABASE_PWD_ENCRYPTED')) { // This should be on on default installation
3002 // Just for the case we use old md5 encryption (deprecated, no more used, kept for compatibility)
3003 if (!getDolGlobalString('MAIN_SECURITY_HASH_ALGO') || getDolGlobalString('MAIN_SECURITY_HASH_ALGO') == 'md5') {
3004 if ($this->pass_indatabase_crypted && getDolGlobalString('LDAP_MEMBER_FIELD_PASSWORD_CRYPTED')) {
3005 // Create OpenLDAP MD5 password from Dolibarr MD5 password
3006 // Note: This suppose that "pass_indatabase_crypted" is a md5 (this should not happen anymore)"
3007 $info[getDolGlobalString('LDAP_MEMBER_FIELD_PASSWORD_CRYPTED')] = dolGetLdapPasswordHash($this->pass_indatabase_crypted, 'md5frommd5');
3008 }
3009 }
3010 } elseif (!empty($this->pass_indatabase)) {
3011 // Use $this->pass_indatabase value if exists
3012 if (getDolGlobalString('LDAP_MEMBER_FIELD_PASSWORD')) {
3013 $info[getDolGlobalString('LDAP_MEMBER_FIELD_PASSWORD')] = $this->pass_indatabase; // $this->pass_indatabase = Unencrypted password
3014 }
3015 if (getDolGlobalString('LDAP_MEMBER_FIELD_PASSWORD_CRYPTED')) {
3016 $info[getDolGlobalString('LDAP_MEMBER_FIELD_PASSWORD_CRYPTED')] = dol_hash($this->pass_indatabase, 'openldap'); // Create OpenLDAP password (see LDAP_PASSWORD_HASH_TYPE)
3017 }
3018 }
3019 }
3020
3021 // Subscriptions
3022 if ($this->first_subscription_date && getDolGlobalString('LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_DATE')) {
3023 $info[getDolGlobalString('LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_DATE')] = dol_print_date($this->first_subscription_date, 'dayhourldap');
3024 }
3025 if (isset($this->first_subscription_amount) && getDolGlobalString('LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_AMOUNT')) {
3026 $info[getDolGlobalString('LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_AMOUNT')] = $this->first_subscription_amount;
3027 }
3028 if ($this->last_subscription_date && getDolGlobalString('LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_DATE')) {
3029 $info[getDolGlobalString('LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_DATE')] = dol_print_date($this->last_subscription_date, 'dayhourldap');
3030 }
3031 if (isset($this->last_subscription_amount) && getDolGlobalString('LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_AMOUNT')) {
3032 $info[getDolGlobalString('LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_AMOUNT')] = $this->last_subscription_amount;
3033 }
3034
3035 return $info;
3036 }
3037
3038
3045 public function info($id)
3046 {
3047 $sql = 'SELECT a.rowid, a.datec as datec,';
3048 $sql .= ' a.datevalid as datev,';
3049 $sql .= ' a.tms as datem,';
3050 $sql .= ' a.fk_user_author, a.fk_user_valid, a.fk_user_mod';
3051 $sql .= ' FROM '.MAIN_DB_PREFIX.'adherent as a';
3052 $sql .= ' WHERE a.rowid = '.((int) $id);
3053
3054 dol_syslog(get_class($this)."::info", LOG_DEBUG);
3055 $result = $this->db->query($sql);
3056 if ($result) {
3057 if ($this->db->num_rows($result)) {
3058 $obj = $this->db->fetch_object($result);
3059
3060 $this->id = $obj->rowid;
3061
3062 $this->user_creation_id = $obj->fk_user_author;
3063 $this->user_validation_id = $obj->fk_user_valid;
3064 $this->user_modification_id = $obj->fk_user_mod;
3065 $this->date_creation = $this->db->jdate($obj->datec);
3066 $this->date_validation = $this->db->jdate($obj->datev);
3067 $this->date_modification = $this->db->jdate($obj->datem);
3068 }
3069
3070 $this->db->free($result);
3071 } else {
3072 dol_print_error($this->db);
3073 }
3074 }
3075
3081 public function getNbOfEMailings()
3082 {
3083 $sql = "SELECT count(mc.email) as nb";
3084 $sql .= " FROM ".MAIN_DB_PREFIX."mailing_cibles as mc";
3085 $sql .= " WHERE mc.email = '".$this->db->escape($this->email)."'";
3086 $sql .= " AND mc.statut NOT IN (-1,0)"; // -1 erreur, 0 non envoye, 1 envoye avec success
3087
3088 $resql = $this->db->query($sql);
3089 if ($resql) {
3090 $obj = $this->db->fetch_object($resql);
3091 $nb = $obj->nb;
3092
3093 $this->db->free($resql);
3094 return $nb;
3095 } else {
3096 $this->error = $this->db->error();
3097 return -1;
3098 }
3099 }
3100
3111 public function setCategories($categories)
3112 {
3113 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
3114 return parent::setCategoriesCommon($categories, Categorie::TYPE_MEMBER);
3115 }
3116
3125 public static function replaceThirdparty($db, $origin_id, $dest_id)
3126 {
3127 $tables = array('adherent');
3128
3129 return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
3130 }
3131
3137 public function hasDelay()
3138 {
3139 global $conf;
3140
3141 //Only valid members
3142 if ($this->statut != self::STATUS_VALIDATED) {
3143 return false;
3144 }
3145 if (!$this->datefin) {
3146 return false;
3147 }
3148
3149 $now = dol_now();
3150
3151 return $this->datefin < ($now - $conf->adherent->subscription->warning_delay);
3152 }
3153
3154
3163 public function sendReminderForExpiredSubscription($daysbeforeendlist = '10', $fk_adherent_type = 0)
3164 {
3165 global $conf, $langs, $mysoc, $user;
3166
3167 $error = 0;
3168 $this->output = '';
3169 $this->error = '';
3170
3171 $blockingerrormsg = '';
3172
3173 if (!isModEnabled('member')) { // Should not happen. If module disabled, cron job should not be visible.
3174 $langs->load("agenda");
3175 $this->output = $langs->trans('ModuleNotEnabled', $langs->transnoentitiesnoconv("Adherent"));
3176 return 0;
3177 }
3178 if (!getDolGlobalString('MEMBER_REMINDER_EMAIL')) {
3179 $langs->load("agenda");
3180 $this->output = $langs->trans('EventRemindersByEmailNotEnabled', $langs->transnoentitiesnoconv("Adherent"));
3181 return 0;
3182 }
3183
3184 $now = dol_now();
3185 $nbok = 0;
3186 $nbko = 0;
3187
3188 $listofmembersok = array();
3189 $listofmembersko = array();
3190
3191 $arraydaysbeforeend = explode(';', $daysbeforeendlist);
3192 foreach ($arraydaysbeforeend as $daysbeforeend) { // Loop on each delay
3193 dol_syslog(__METHOD__.' - Process delta = '.$daysbeforeend, LOG_DEBUG);
3194
3195 if (!is_numeric($daysbeforeend)) {
3196 $blockingerrormsg = "Value for delta is not a numeric value";
3197 $nbko++;
3198 break;
3199 }
3200
3201 $tmp = dol_getdate($now);
3202 $datetosearchfor = dol_time_plus_duree(dol_mktime(0, 0, 0, $tmp['mon'], $tmp['mday'], $tmp['year'], 'tzserver'), (int) $daysbeforeend, 'd');
3203 $datetosearchforend = dol_time_plus_duree(dol_mktime(23, 59, 59, $tmp['mon'], $tmp['mday'], $tmp['year'], 'tzserver'), (int) $daysbeforeend, 'd');
3204
3205 $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.'adherent';
3206 $sql .= " WHERE entity = ".((int) $conf->entity); // Do not use getEntity('adherent').")" here, we want the batch to be on its entity only;
3207 $sql .= " AND statut = 1";
3208 $sql .= " AND datefin >= '".$this->db->idate($datetosearchfor)."'";
3209 $sql .= " AND datefin <= '".$this->db->idate($datetosearchforend)."'";
3210 if ((int) $fk_adherent_type > 0) {
3211 $sql .= " AND fk_adherent_type = ".((int) $fk_adherent_type);
3212 }
3213 //$sql .= " LIMIT 10000";
3214
3215 $resql = $this->db->query($sql);
3216 if ($resql) {
3217 $num_rows = $this->db->num_rows($resql);
3218
3219 include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
3220 $formmail = new FormMail($this->db);
3221
3222 $i = 0;
3223 while ($i < $num_rows) {
3224 $obj = $this->db->fetch_object($resql);
3225
3226 // A new object for each member: fetch() does not reset the properties loaded for the previous member,
3227 // like ->thirdparty that would be reused for a member that has no third party.
3228 $adherent = new Adherent($this->db);
3229 $adherent->fetch($obj->rowid, '', 0, '', true, true);
3230
3231 if (empty($adherent->email)) {
3232 $nbko++;
3233 $listofmembersko[$adherent->id] = $adherent->id;
3234 } else {
3235 $thirdpartyres = $adherent->fetch_thirdparty();
3236 if ($thirdpartyres === -1) {
3237 $languagecodeformember = $mysoc->default_lang;
3238 } else {
3239 // 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.
3240 $languagefromcountrycode = getLanguageCodeFromCountryCode($adherent->country_code ? $adherent->country_code : (is_object($adherent->thirdparty) ? $adherent->thirdparty->country_code : ''));
3241 $languagecodeformember = (empty($adherent->thirdparty->default_lang) ? ($languagefromcountrycode ? $languagefromcountrycode : $mysoc->default_lang) : $adherent->thirdparty->default_lang);
3242 }
3243 if (!empty($adherent->default_lang)) {
3244 // The language set on the member itself has priority
3245 $languagecodeformember = $adherent->default_lang;
3246 }
3247
3248 // Send reminder email
3249 $outputlangs = new Translate('', $conf);
3250 $outputlangs->setDefaultLang($languagecodeformember);
3251 $outputlangs->loadLangs(array("main", "members"));
3252 dol_syslog("sendReminderForExpiredSubscription Language for member id ".$adherent->id." set to ".$outputlangs->defaultlang." mysoc->default_lang=".$mysoc->default_lang);
3253
3254 $arraydefaultmessage = null;
3255 $labeltouse = getDolGlobalString('ADHERENT_EMAIL_TEMPLATE_REMIND_EXPIRATION');
3256
3257 if (!empty($labeltouse)) {
3258 $arraydefaultmessage = $formmail->getEMailTemplate($this->db, 'member', $user, $outputlangs, 0, 1, $labeltouse);
3259 }
3260
3261 if (!empty($labeltouse) && is_object($arraydefaultmessage) && $arraydefaultmessage->id > 0) {
3262 $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $adherent);
3263 //if (is_array($adherent->thirdparty)) $substitutionarraycomp = ...
3264 complete_substitutions_array($substitutionarray, $outputlangs, $adherent);
3265
3266 $subject = make_substitutions($arraydefaultmessage->topic, $substitutionarray, $outputlangs);
3267 $msg = make_substitutions($arraydefaultmessage->content, $substitutionarray, $outputlangs);
3268 $from = getDolGlobalString('ADHERENT_MAIL_FROM', $conf->email_from);
3269 $to = $adherent->email;
3270 $cc = getDolGlobalString('ADHERENT_CC_MAIL_FROM');
3271
3272 $trackid = 'mem'.$adherent->id;
3273 $moreinheader = 'X-Dolibarr-Info: sendReminderForExpiredSubscription'."\r\n";
3274
3275 include_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
3276 $cmail = new CMailFile($subject, $to, $from, $msg, array(), array(), array(), $cc, '', 0, 1, '', '', $trackid, $moreinheader);
3277 $result = $cmail->sendfile();
3278 if (!$result) {
3279 $error++;
3280 $this->error .= $cmail->error.' ';
3281 if (!is_null($cmail->errors)) {
3282 $this->errors += $cmail->errors;
3283 }
3284 $nbko++;
3285 $listofmembersko[$adherent->id] = $adherent->id;
3286 } else {
3287 $nbok++;
3288 $listofmembersok[$adherent->id] = $adherent->id;
3289
3290 $message = $msg;
3291 $sendto = $to;
3292 $sendtocc = '';
3293 $sendtobcc = '';
3294 $actioncode = 'EMAIL';
3295 $extraparams = array();
3296
3297 $actionmsg = '';
3298 $actionmsg2 = $langs->transnoentities('MailSentByTo', CMailFile::getValidAddress($from, 4, 0, 1), CMailFile::getValidAddress($sendto, 4, 0, 1));
3299 if ($message) {
3300 $actionmsg = $langs->transnoentities('MailFrom').': '.dol_escape_htmltag($from);
3301 $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('MailTo').': '.dol_escape_htmltag($sendto));
3302 if ($sendtocc) {
3303 $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('Bcc').": ".dol_escape_htmltag($sendtocc));
3304 }
3305 $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('MailTopic').": ".$subject);
3306 $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('TextUsedInTheMessageBody').":");
3307 $actionmsg = dol_concatdesc($actionmsg, $message);
3308 }
3309
3310 require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
3311
3312 // Insert record of emails sent
3313 $actioncomm = new ActionComm($this->db);
3314
3315 $actioncomm->type_code = 'AC_OTH_AUTO'; // Type of event ('AC_OTH', 'AC_OTH_AUTO', 'AC_XXX'...)
3316 $actioncomm->code = 'AC_'.$actioncode;
3317 $actioncomm->label = $actionmsg2;
3318 $actioncomm->note_private = $actionmsg;
3319 $actioncomm->fk_project = 0;
3320 $actioncomm->datep = $now;
3321 $actioncomm->datef = $now;
3322 $actioncomm->percentage = -1; // Not applicable
3323 $actioncomm->socid = (is_object($adherent->thirdparty) ? $adherent->thirdparty->id : 0);
3324 $actioncomm->contact_id = 0;
3325 $actioncomm->authorid = $user->id; // User saving action
3326 $actioncomm->userownerid = $user->id; // Owner of action
3327 // Fields when action is en email (content should be added into note)
3328 $actioncomm->email_msgid = $cmail->msgid;
3329 $actioncomm->email_from = $from;
3330 $actioncomm->email_sender = '';
3331 $actioncomm->email_to = $to;
3332 $actioncomm->email_tocc = $sendtocc;
3333 $actioncomm->email_tobcc = $sendtobcc;
3334 $actioncomm->email_subject = $subject;
3335 $actioncomm->errors_to = '';
3336
3337 $actioncomm->fk_element = $adherent->id;
3338 $actioncomm->elementid = $adherent->id;
3339 $actioncomm->elementtype = $adherent->element;
3340
3341 $actioncomm->extraparams = $extraparams;
3342
3343 $actioncomm->create($user);
3344 }
3345 } else {
3346 //$blockingerrormsg = "Can't find email template with label=".$labeltouse.", to use for the reminding email";
3347
3348 $error++;
3349 $this->error .= "Can't find email template with label=".$labeltouse.", to use for the reminding email ";
3350
3351 $nbko++;
3352 $listofmembersko[$adherent->id] = $adherent->id;
3353
3354 break;
3355 }
3356 }
3357
3358 $i++;
3359 }
3360 } else {
3361 $this->error = $this->db->lasterror();
3362 return 1;
3363 }
3364 }
3365
3366 if ($blockingerrormsg) {
3367 $this->error = $blockingerrormsg;
3368 return 1;
3369 } else {
3370 $this->output = 'Found '.($nbok + $nbko).' members to send reminder to.';
3371 $this->output .= ' Send email successfully to '.$nbok.' members';
3372 if (is_array($listofmembersok)) {
3373 $listofids = '';
3374 $i = 0;
3375 foreach ($listofmembersok as $idmember) {
3376 if ($i > 100) {
3377 $listofids .= ', ...';
3378 break;
3379 }
3380 if (empty($listofids)) {
3381 $listofids .= ' [';
3382 } else {
3383 $listofids .= ', ';
3384 }
3385 $listofids .= $idmember;
3386 $i++;
3387 }
3388 if ($listofids) {
3389 $listofids .= ']';
3390 }
3391
3392 $this->output .= ($listofids ? ' ids='.$listofids : '');
3393 }
3394 if ($nbko) {
3395 $this->output .= ' - Canceled for '.$nbko.' member (no email or email sending error)';
3396 if (is_array($listofmembersko)) {
3397 $listofids = '';
3398 $i = 0;
3399 foreach ($listofmembersko as $idmember) {
3400 if ($i > 100) {
3401 $listofids .= ', ...';
3402 break;
3403 }
3404 if (empty($listofids)) {
3405 $listofids .= ' [';
3406 } else {
3407 $listofids .= ', ';
3408 }
3409 $listofids .= $idmember;
3410 $i++;
3411 }
3412 if ($listofids) {
3413 $listofids .= ']';
3414 }
3415 $this->output .= ($listofids ? ' ids='.$listofids : '');
3416 }
3417 }
3418 }
3419
3420 return $nbko;
3421 }
3422
3430 public function getKanbanView($option = '', $arraydata = null)
3431 {
3432 $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
3433
3434 $return = '<div class="box-flex-item box-flex-grow-zero">';
3435 $return .= '<div class="info-box info-box-sm">';
3436 $return .= '<span class="info-box-icon bg-infobox-action">';
3437 if (property_exists($this, 'photo') || !empty($this->photo)) {
3438 $return .= Form::showphoto('memberphoto', $this, 0, 60, 0, 'photokanban photowithmargin photologintooltip', 'small', 0, 1);
3439 } else {
3440 $return .= img_picto('', 'user');
3441 }
3442 $return .= '</span>';
3443 $return .= '<div class="info-box-content">';
3444 $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref).'</span>';
3445 if ($selected >= 0) {
3446 $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
3447 }
3448 $return .= '<br><span class="info-box-label paddingright">'.$this->getmorphylib('', 2).'</span>';
3449 $return .= '<span class="info-box-label opacitymedium">'.$this->type.'</span>';
3450
3451 if (method_exists($this, 'getLibStatut')) {
3452 $return .= '<br><div class="info-box-status paddingtop">';
3453 $return .= $this->LibStatut($this->status, $this->need_subscription, $this->datefin, 5);
3454 $return .= '</div>';
3455 }
3456 $return .= '</div>';
3457 $return .= '</div>';
3458 $return .= '</div>';
3459 return $return;
3460 }
3461}
$object ref
Definition info.php:90
Class to manage bank accounts.
Class to manage agenda events (actions)
Class to manage members of a foundation.
setThirdPartyId($thirdpartyid)
Set link to a third party.
hasDelay()
Return if a member is late (subscription late) or not.
exclude($user)
Functiun to exclude (set adherent.status to -2) a member TODO A private note should be added to know ...
add_to_abo()
Function to add member into external tools mailing-list, spip, etc.
loadStateBoard()
Load indicators this->nb in state board.
_load_ldap_dn($info, $mode=0)
Retourne chaine DN complete dans l'annuaire LDAP pour l'objet.
update($user, $notrigger=0, $nosyncuser=0, $nosyncuserpass=0, $nosyncthirdparty=0, $action='update')
Update a member in database (standard information and password)
setCategories($categories)
Sets object to supplied categories.
getTooltipContentArray($params)
getTooltipContentArray
getNbOfEMailings()
Return number of mass Emailing received by this member with its email.
update_end_date($user)
Update denormalized last subscription date.
static replaceThirdparty($db, $origin_id, $dest_id)
Function used to replace a thirdparty id with another one.
makeSubstitution($text)
Make substitution of tags into text with value of current object.
const STATUS_EXCLUDED
Excluded.
LibStatut($status, $need_subscription, $date_end_subscription, $mode=0)
Renvoi le libelle d'un statut donne.
fetch_name($firstname, $lastname)
Method to load member from its name.
initAsSpecimen()
Initialise an instance with random values.
fetch($rowid, $ref='', $fk_soc=0, $ref_ext='', $fetch_optionals=true, $fetch_subscriptions=true)
Load member from database.
del_to_abo()
Function to delete a member from external tools like mailing-list, spip, etc.
resiliate($user)
Fonction qui resilie un adherent.
getCivilityLabel()
Return civility label of a member.
getmorphylib($morphy='', $addbadge=0)
Return translated label by the nature of a adherent (physical or moral)
sendEmail($text, $subject, $filename_list=array(), $mimetype_list=array(), $mimefilename_list=array(), $addr_cc="", $addr_bcc="", $deliveryreceipt=0, $msgishtml=-1, $errors_to='', $moreinheader='')
Function sending an email to the current member with the text supplied in parameter.
fetchPartnerships($mode)
Function to get partnerships array.
load_board($user, $mode)
Load indicators for dashboard (this->nbtodo and this->nbtodolate)
setPassword($user, $password='', $isencrypted=0, $notrigger=0, $nosyncuser=0)
Change password of a user.
$fields
'type' field format: 'integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortf...
getKanbanView($option='', $arraydata=null)
Return clickable link of object (with eventually picto)
const STATUS_DRAFT
Draft status.
const STATUS_RESILIATED
Resiliated (membership end and was not renew)
sendReminderForExpiredSubscription($daysbeforeendlist='10', $fk_adherent_type=0)
Send reminders by emails before subscription end CAN BE A CRON TASK.
fetch_login($login)
Method to load member from its login.
_load_ldap_info()
Initialise tableau info (tableau des attributes LDAP)
getLibStatut($mode=0)
Retourne le libelle du statut d'un adherent (brouillon, valide, resilie, exclu)
info($id)
Load type info information in the member object.
__construct($db)
Constructor.
subscription($date, $amount, $accountid=0, $operation='', $label='', $num_chq='', $emetteur_nom='', $emetteur_banque='', $datesubend=0, $fk_type=null)
Insert subscription into database and eventually add links to banks, mailman, etc....
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='')
Function sending an email to the current member with the text supplied in parameter.
getNomUrl($withpictoimg=0, $maxlen=0, $option='card', $mode='', $morecss='', $save_lastsearch_value=-1, $notooltip=0, $addlinktonotes=0)
Return clickable name (with picto eventually)
generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0, $moreparams=null)
Create a document onto disk according to template module.
subscriptionComplementaryActions($subscriptionid, $option, $accountid, $datesubscription, $paymentdate, $operation, $label, $amount, $num_chq, $emetteur_nom='', $emetteur_banque='', $autocreatethirdparty=0, $ext_payment_id='', $ext_payment_site='')
Do complementary actions after subscription recording.
setUserId($userid)
Set link to a user.
const STATUS_VALIDATED
Validated status.
fetch_subscriptions()
Function to get member subscriptions data: subscriptions, first_subscription_date,...
validate($user)
Function that validate a member.
Class to send emails (with attachments or not) Usage: $mailfile = new CMailFile($subject,...
static getValidAddress($address, $format, $encode=0, $maxnumberofemail=0)
Return a formatted address string for SMTP protocol.
Parent class of all other business classes (invoices, contracts, proposals, orders,...
fetch_optionals($rowid=null, $optionsArray=null)
Function to get extra fields of an object into $this->array_options This method is in most cases call...
deleteEcmFiles($mode=0)
Delete related files of object in database.
commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
Common function for all objects extending CommonObject for generating documents.
deleteObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='', $rowid=0, $f_user=null, $notrigger=0)
Delete all links between an object $this.
setErrorsFromObject($object)
setErrorsFromObject
deleteExtraFields()
Delete all extra fields values for the current object.
static commonReplaceThirdparty(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a thirdparty id with another one.
insertExtraFields($trigger='', $userused=null)
Add/Update all extra fields values for the current object.
call_trigger($triggerName, $user)
Call trigger based on this instance.
Class to manage invoices.
const TYPE_STANDARD
Standard invoice.
Class to manage generation of HTML components Only common components must be here.
static showphoto($modulepart, $object, $width=100, $height=0, $caneditfield=0, $cssclass='photowithmargin', $imagesize='', $addlinktofullsize=1, $cache=0, $forcecapture='', $noexternsourceoverwrite=0)
Return HTML code to output a photo.
Class permettant la generation du formulaire html d'envoi de mail unitaire Usage: $formail = new Form...
Class to manage mailman and spip.
Class to manage payments of customer invoices.
Class for Partnership.
Class to manage payment terms records in dictionary.
Class to manage third parties objects (customers, suppliers, prospects...)
Class to manage subscriptions of foundation members.
Class to manage translations.
Class to manage Dolibarr users.
print $langs trans("Ref").' m titre as m m statut as status
Or an array listing all the potential status of the object: array: int of the status => translated la...
Definition index.php:171
getFullName($langs, $option=0, $nameorder=-1, $maxlen=0)
Return full name (civility+' '+name+' '+lastname)
setUpperOrLowerCase()
Set to upper or ucwords/lower if needed.
getCountry($searchkey, $withcode='', $dbtouse=null, $outputlangs=null, $entconv=1, $searchlabel='')
Return country label, code or id from an id, code or label.
dol_time_plus_duree($time, $duration_value, $duration_unit, $ruleforendofmonth=0)
Add a delay to a date.
Definition date.lib.php:125
print $script_file $mode $langs defaultlang(is_numeric($duration_value) ? " delay=". $duration_value :"").(is_numeric($duration_value2) ? " after cd cd cd description as p label as s rowid as s nom as s email
Sender: Who sends the email ("Sender" has sent emails on behalf of "From").
dol_delete_dir_recursive($dir, $count=0, $nophperrors=0, $onlysub=0, &$countdeleted=0, $indexdatabase=1, $nolog=0, $level=0)
Remove a directory $dir and its subdirectories (or only files and subdirectories)
dol_is_dir($folder)
Test if filename is a directory.
deleteFilesIntoDatabaseIndex($dir, $file, $mode='uploaded', $object=null)
Delete files into database index using search criteria.
clean_url($url, $http=1)
Clean an url string.
dol_mktime($hour, $minute, $second, $month, $day, $year, $gm='auto', $check=1)
Return a timestamp date built from detailed information (by default a local PHP server timestamp) Rep...
dol_getIdFromCode($db, $key, $tablename, $fieldkey='code', $fieldid='id', $entityfilter=0, $filters='', $useCache=true)
Return an id or code from a code or id.
getLanguageCodeFromCountryCode($countrycode)
Return default language from country code.
setEntity($currentobject)
Set entity id to use when to create an object.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2, $allowothertags=array())
Show picto whatever it's its name (generic function)
dol_format_address($object, $withcountry=0, $sep="\n", $outputlangs=null, $mode=0, $extralangcode='')
Return a formatted address (part address/zip/town/state) according to country rules.
dol_string_nohtmltag($stringtoclean, $removelinefeed=1, $pagecodeto='UTF-8', $strip_tags=0, $removedoublespaces=1)
Clean a string from all HTML tags and entities.
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $allowothertags=array())
Show a picto called object_picto (generic function)
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
GETPOSTISARRAY($paramname, $method=0)
Return true if the parameter $paramname is submit from a POST OR GET as an array.
dol_now($mode='auto')
Return date for now.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
dol_concatdesc($text1, $text2, $forxml=false, $invert=false)
Concat 2 descriptions with a new line between them (second operand after first one with appropriate n...
dolGetFirstLetters($s, $nbofchar=1)
Return first letters of a strings.
dol_strtoupper($string, $encoding="UTF-8")
Convert a string to upper.
yn($yesno, $format=1, $color=0)
Return yes or no in current language.
complete_substitutions_array(&$substitutionarray, $outputlangs, $object=null, $parameters=null, $callfunc="completesubstitutionarray")
Complete the $substitutionarray with more entries coming from external module that had set the "subst...
dolGetStatus($statusLabel='', $statusLabelShort='', $html='', $statusType='status0', $displayMode=0, $url='', $params=array())
Output the badge of a status.
make_substitutions($text, $substitutionarray, $outputlangs=null, $converttextinhtmlifnecessary=0)
Make substitution into a text string, replacing keys with vals from $substitutionarray (oldval=>newva...
getArrayOfSocialNetworks()
Get array of social network dictionary.
dol_textishtml($msg, $option=0)
Return if a text is a html content.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
dol_trunc($string, $size=40, $trunc='right', $stringencoding='UTF-8', $nodot=0, $display=0)
Truncate a string to a particular length adding '…' if string larger than length.
dol_htmlentitiesbr($stringtoencode, $nl2brmode=0, $pagecodefrom='UTF-8', $removelasteolbr=1)
This function is called to encode a string into a HTML string but differs from htmlentities because a...
isValidEmail($address, $acceptsupervisorkey=0, $acceptuserkey=0)
Return true if email syntax is ok.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
get_default_tva(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod=0, $idprodfournprice=0)
Function that return vat rate of a product line (according to seller, buyer and product vat rate) VAT...
get_exdir($num, $level, $alpha, $withoutslash, $object, $modulepart='')
Return a path to have a the directory according to object where files are stored.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
dol_getdate($timestamp, $fast=false, $forcetimezone='')
Return an array with locale date info.
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0, $cleanalsojavascript=0)
Returns text escaped for inclusion in HTML alt or title or value tags, or into values of HTML input f...
div refaddress div address
global $conf
The following vars must be defined: $type2label $form $conf, $lang, The following vars may also be de...
Definition member.php:79
if(preg_match('/(crypted|dolcrypt):/i', $dolibarr_main_db_pass)||!empty($dolibarr_main_db_encrypted_pass)) $conf db type
Definition repair.php:158
getRandomPassword($generic=false, $replaceambiguouschars=null, $length=32)
Return a generated password using default module.
dol_hash($chain, $type='0', $nosalt=0, $mode=0)
Returns a hash (non reversible encryption) of a string.
dolGetLdapPasswordHash($password, $type='md5')
Returns a specific ldap hash of a password.