dolibarr 23.0.4
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-2026 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
358 public $fields = array(
359 'rowid' => array('type' => 'integer', 'label' => 'TechnicalID', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 10),
360 'ref' => array('type' => 'varchar(30)', 'label' => 'Ref', 'default' => '1', 'enabled' => 1, 'visible' => 1, 'notnull' => 1, 'position' => 12, 'index' => 1),
361 'entity' => array('type' => 'integer', 'label' => 'Entity', 'default' => '1', 'enabled' => 1, 'visible' => 3, 'notnull' => 1, 'position' => 15, 'index' => 1),
362 'ref_ext' => array('type' => 'varchar(128)', 'label' => 'RefExt', 'enabled' => 1, 'visible' => 0, 'position' => 20),
363 'civility' => array('type' => 'varchar(6)', 'label' => 'Civility', 'enabled' => 1, 'visible' => -1, 'position' => 25),
364 'lastname' => array('type' => 'varchar(50)', 'label' => 'Lastname', 'enabled' => 1, 'visible' => 1, 'position' => 30, 'showoncombobox' => 1),
365 'firstname' => array('type' => 'varchar(50)', 'label' => 'Firstname', 'enabled' => 1, 'visible' => 1, 'position' => 35, 'showoncombobox' => 1),
366 'login' => array('type' => 'varchar(50)', 'label' => 'Login', 'enabled' => 1, 'visible' => 1, 'position' => 40),
367 'pass' => array('type' => 'varchar(50)', 'label' => 'Pass', 'enabled' => 1, 'visible' => 3, 'position' => 45),
368 'pass_crypted' => array('type' => 'varchar(128)', 'label' => 'Pass crypted', 'enabled' => 1, 'visible' => 3, 'position' => 50),
369 'morphy' => array('type' => 'varchar(3)', 'label' => 'MemberNature', 'enabled' => 1, 'visible' => 1, 'notnull' => 1, 'position' => 55),
370 'fk_adherent_type' => array('type' => 'integer', 'label' => 'MemberType', 'enabled' => 1, 'visible' => 1, 'notnull' => 1, 'position' => 60),
371 'societe' => array('type' => 'varchar(128)', 'label' => 'Societe', 'enabled' => 1, 'visible' => 1, 'position' => 65, 'showoncombobox' => 2),
372 'fk_soc' => array('type' => 'integer:Societe:societe/class/societe.class.php', 'label' => 'LinkedToDolibarrThirdParty', 'enabled' => 1, 'visible' => 1, 'position' => 70),
373 'address' => array('type' => 'text', 'label' => 'Address', 'enabled' => 1, 'visible' => -1, 'position' => 75),
374 'zip' => array('type' => 'varchar(10)', 'label' => 'Zip', 'enabled' => 1, 'visible' => -1, 'position' => 80),
375 'town' => array('type' => 'varchar(50)', 'label' => 'Town', 'enabled' => 1, 'visible' => -1, 'position' => 85),
376 'state_id' => array('type' => 'integer', 'label' => 'State', 'enabled' => 1, 'visible' => -1, 'position' => 90),
377 'country' => array('type' => 'integer:Ccountry:core/class/ccountry.class.php', 'label' => 'Country', 'enabled' => 1, 'visible' => 1, 'position' => 95),
378 'phone' => array('type' => 'varchar(30)', 'label' => 'Phone', 'enabled' => 1, 'visible' => -1, 'position' => 115),
379 'phone_perso' => array('type' => 'varchar(30)', 'label' => 'Phone perso', 'enabled' => 1, 'visible' => -1, 'position' => 120),
380 'phone_mobile' => array('type' => 'varchar(30)', 'label' => 'Phone mobile', 'enabled' => 1, 'visible' => -1, 'position' => 125),
381 'email' => array('type' => 'varchar(255)', 'label' => 'Email', 'enabled' => 1, 'visible' => 1, 'position' => 126),
382 'url' => array('type' => 'varchar(255)', 'label' => 'Url', 'enabled' => 1, 'visible' => -1, 'position' => 127),
383 'socialnetworks' => array('type' => 'text', 'label' => 'Socialnetworks', 'enabled' => 1, 'visible' => 3, 'position' => 128),
384 'birth' => array('type' => 'date', 'label' => 'DateOfBirth', 'enabled' => 1, 'visible' => -1, 'position' => 130),
385 'gender' => array('type' => 'varchar(10)', 'label' => 'Gender', 'enabled' => 1, 'visible' => -1, 'position' => 132),
386 'photo' => array('type' => 'varchar(255)', 'label' => 'Photo', 'enabled' => 1, 'visible' => -1, 'position' => 135),
387 'public' => array('type' => 'smallint(6)', 'label' => 'Public', 'enabled' => 1, 'visible' => 3, 'notnull' => 1, 'position' => 145),
388 'datefin' => array('type' => 'datetime', 'label' => 'DateEnd', 'enabled' => 1, 'visible' => 1, 'position' => 150),
389 'default_lang' => array('type' => 'varchar(6)', 'label' => 'Default lang', 'enabled' => 1, 'visible' => -1, 'position' => 153),
390 'note_public' => array('type' => 'text', 'label' => 'NotePublic', 'enabled' => 1, 'visible' => 0, 'position' => 155),
391 'note_private' => array('type' => 'text', 'label' => 'NotePrivate', 'enabled' => 1, 'visible' => 0, 'position' => 160),
392 'datevalid' => array('type' => 'datetime', 'label' => 'DateValidation', 'enabled' => 1, 'visible' => -1, 'position' => 165),
393 'datec' => array('type' => 'datetime', 'label' => 'DateCreation', 'enabled' => 1, 'visible' => -1, 'position' => 170),
394 'tms' => array('type' => 'timestamp', 'label' => 'DateModification', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 175),
395 'fk_user_author' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserCreation', 'enabled' => 1, 'visible' => 3, 'position' => 180),
396 'fk_user_mod' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserModification', 'enabled' => 1, 'visible' => 3, 'position' => 185),
397 'fk_user_valid' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserValidation', 'enabled' => 1, 'visible' => 3, 'position' => 190),
398 'canvas' => array('type' => 'varchar(32)', 'label' => 'Canvas', 'enabled' => 1, 'visible' => 0, 'position' => 195),
399 'model_pdf' => array('type' => 'varchar(255)', 'label' => 'Model pdf', 'enabled' => 1, 'visible' => 0, 'position' => 800),
400 'import_key' => array('type' => 'varchar(14)', 'label' => 'ImportId', 'enabled' => 1, 'visible' => -2, 'position' => 805),
401 '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'))
402 );
403
407 const STATUS_DRAFT = -1;
419 const STATUS_EXCLUDED = -2;
420
421
427 public function __construct($db)
428 {
429 $this->db = $db;
430 $this->statut = self::STATUS_DRAFT;
431 $this->status = self::STATUS_DRAFT;
432 // l'adherent n'est pas public par default
433 $this->public = 0;
434 $this->ismultientitymanaged = 1;
435 $this->isextrafieldmanaged = 1;
436 // les champs optionnels sont vides
437 $this->array_options = array();
438
439 $this->fields['ref_ext']['visible'] = getDolGlobalInt('MAIN_LIST_SHOW_REF_EXT');
440 }
441
442
443 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
462 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 = '')
463 {
464 // phpcs:enable
465 dol_syslog('Warning using deprecated Adherent::send_an_email', LOG_WARNING);
466
467 return $this->sendEmail($text, $subject, $filename_list, $mimetype_list, $mimefilename_list, $addr_cc, $addr_bcc, $deliveryreceipt, $msgishtml, $errors_to, $moreinheader);
468 }
469
487 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 = '')
488 {
489 global $conf, $langs;
490
491 // Detect if message is HTML
492 if ($msgishtml == -1) {
493 $msgishtml = 0;
494 if (dol_textishtml($text, 0)) {
495 $msgishtml = 1;
496 }
497 }
498
499 dol_syslog('sendEmail msgishtml='.$msgishtml);
500
501 $texttosend = $this->makeSubstitution($text);
502 $subjecttosend = $this->makeSubstitution($subject);
503 if ($msgishtml) {
504 $texttosend = dol_htmlentitiesbr($texttosend);
505 }
506
507 // Send mail confirmation
508 $from = getDolGlobalString('ADHERENT_MAIL_FROM', $conf->email_from);
509
510 $trackid = 'mem'.$this->id;
511
512 // Send email (substitutionarray must be done just before this)
513 include_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
514 $mailfile = new CMailFile($subjecttosend, (string) $this->email, $from, $texttosend, $filename_list, $mimetype_list, $mimefilename_list, $addr_cc, $addr_bcc, $deliveryreceipt, $msgishtml, '', '', $trackid, $moreinheader);
515 if ($mailfile->sendfile()) {
516 return 1;
517 } else {
518 $this->error = $langs->trans("ErrorFailedToSendMail", $from, (string) $this->email).'. '.$mailfile->error;
519 return -1;
520 }
521 }
522
523
530 public function makeSubstitution($text)
531 {
532 global $langs;
533
534 $birthday = dol_print_date($this->birth, 'day');
535 $photo = isset($this->photo) ? $this->photo : '';
536 $login = isset($this->login) ? $this->login : '';
537 $type = isset($this->type) ? $this->type : '';
538 $pass = isset($this->pass) ? $this->pass : '';
539
540 $msgishtml = 0;
541 if (dol_textishtml($text, 1)) {
542 $msgishtml = 1;
543 }
544
545 $infos = '';
546 if ($this->civility_id) {
547 $infos .= $langs->transnoentities("UserTitle").": ".$this->getCivilityLabel()."\n";
548 }
549 $infos .= $langs->transnoentities("Id").": ".$this->id."\n";
550 $infos .= $langs->transnoentities("Ref").": ".$this->ref."\n";
551 $infos .= $langs->transnoentities("Lastname").": ".$this->lastname."\n";
552 $infos .= $langs->transnoentities("Firstname").": ".$this->firstname."\n";
553 $infos .= $langs->transnoentities("Company").": ".$this->company."\n";
554 $infos .= $langs->transnoentities("Address").": ".$this->address."\n";
555 $infos .= $langs->transnoentities("Zip").": ".$this->zip."\n";
556 $infos .= $langs->transnoentities("Town").": ".$this->town."\n";
557 $infos .= $langs->transnoentities("Country").": ".$this->country."\n";
558 $infos .= $langs->transnoentities("EMail").": ".$this->email."\n";
559 $infos .= $langs->transnoentities("PhonePro").": ".$this->phone."\n";
560 $infos .= $langs->transnoentities("PhonePerso").": ".$this->phone_perso."\n";
561 $infos .= $langs->transnoentities("PhoneMobile").": ".$this->phone_mobile."\n";
562 if (!getDolGlobalString('ADHERENT_LOGIN_NOT_REQUIRED')) {
563 $infos .= $langs->transnoentities("Login").": ".$login."\n";
564 $infos .= $langs->transnoentities("Password").": ".$pass."\n";
565 }
566 $infos .= $langs->transnoentities("Birthday").": ".$birthday."\n";
567 $infos .= $langs->transnoentities("Photo").": ".$photo."\n";
568 $infos .= $langs->transnoentities("Public").": ".yn($this->public);
569
570 // Substitutions
571 $substitutionarray = array(
572 '__ID__' => $this->id,
573 '__REF__' => $this->ref,
574 '__MEMBER_ID__' => $this->id,
575 '__CIVILITY__' => $this->getCivilityLabel(),
576 '__FIRSTNAME__' => $msgishtml ? dol_htmlentitiesbr($this->firstname) : ($this->firstname ? $this->firstname : ''),
577 '__LASTNAME__' => $msgishtml ? dol_htmlentitiesbr($this->lastname) : ($this->lastname ? $this->lastname : ''),
578 '__FULLNAME__' => $msgishtml ? dol_htmlentitiesbr($this->getFullName($langs)) : $this->getFullName($langs),
579 '__COMPANY__' => $msgishtml ? dol_htmlentitiesbr((string) $this->company) : ($this->company ? $this->company : ''),
580 '__ADDRESS__' => $msgishtml ? dol_htmlentitiesbr((string) $this->address) : ($this->address ? $this->address : ''),
581 '__ZIP__' => $msgishtml ? dol_htmlentitiesbr((string) $this->zip) : ($this->zip ? $this->zip : ''),
582 '__TOWN__' => $msgishtml ? dol_htmlentitiesbr((string) $this->town) : ($this->town ? $this->town : ''),
583 '__COUNTRY__' => $msgishtml ? dol_htmlentitiesbr($this->country) : ($this->country ? $this->country : ''),
584 '__EMAIL__' => $msgishtml ? dol_htmlentitiesbr((string) $this->email) : ($this->email ? $this->email : ''),
585 '__BIRTH__' => $msgishtml ? dol_htmlentitiesbr($birthday) : ($birthday ? $birthday : ''),
586 '__PHOTO__' => $msgishtml ? dol_htmlentitiesbr($photo) : $photo,
587 '__LOGIN__' => $msgishtml ? dol_htmlentitiesbr($login) : $login,
588 '__PASSWORD__' => $msgishtml ? dol_htmlentitiesbr($pass) : $pass,
589 '__PHONE__' => $msgishtml ? dol_htmlentitiesbr($this->phone) : ($this->phone ? $this->phone : ''),
590 '__PHONEPRO__' => $msgishtml ? dol_htmlentitiesbr($this->phone_perso) : ($this->phone_perso ? $this->phone_perso : ''),
591 '__PHONEMOBILE__' => $msgishtml ? dol_htmlentitiesbr($this->phone_mobile) : ($this->phone_mobile ? $this->phone_mobile : ''),
592 '__TYPE__' => $msgishtml ? dol_htmlentitiesbr($type) : $type,
593 );
594
595 complete_substitutions_array($substitutionarray, $langs, $this);
596
597 return make_substitutions($text, $substitutionarray, $langs);
598 }
599
600
608 public function getmorphylib($morphy = '', $addbadge = 0)
609 {
610 global $langs;
611 $s = '';
612
613 // Clean var
614 if (!$morphy) {
615 $morphy = $this->morphy;
616 }
617
618 if ($addbadge) {
619 $labeltoshowm = $langs->trans("Moral");
620 $labeltoshowp = $langs->trans("Physical");
621 if ($morphy == 'phy') {
622 $labeltoshow = $labeltoshowp;
623 if ($addbadge == 2) {
624 $labeltoshow = dol_strtoupper(dolGetFirstLetters($labeltoshowp));
625 if ($labeltoshow == dol_strtoupper(dolGetFirstLetters($labeltoshowm))) {
626 $labeltoshow = dol_strtoupper(dolGetFirstLetters($labeltoshowp, 2));
627 }
628 }
629 $s .= '<span class="member-individual-back paddingleftimp paddingrightimp" title="'.$langs->trans("Physical").'">'.$labeltoshow.'</span>';
630 }
631 if ($morphy == 'mor') {
632 $labeltoshow = $labeltoshowm;
633 if ($addbadge == 2) {
634 $labeltoshow = dol_strtoupper(dolGetFirstLetters($labeltoshowm));
635 if ($labeltoshow == dol_strtoupper(dolGetFirstLetters($labeltoshowp))) {
636 $labeltoshow = dol_strtoupper(dolGetFirstLetters($labeltoshowm, 2));
637 }
638 }
639 $s .= '<span class="member-company-back paddingleftimp paddingrightimp" title="'.$langs->trans("Moral").'">'.$labeltoshow.'</span>';
640 }
641 } else {
642 if ($morphy == 'phy') {
643 $s = $langs->trans("Physical");
644 } elseif ($morphy == 'mor') {
645 $s = $langs->trans("Moral");
646 }
647 }
648
649 return $s;
650 }
651
659 public function create($user, $notrigger = 0)
660 {
661 global $langs, $mysoc;
662
663 $error = 0;
664
665 $now = dol_now();
666
667 // Clean parameters
668 if (isset($this->import_key)) {
669 $this->import_key = trim($this->import_key);
670 }
671
672 // Check parameters
673 if (getDolGlobalString('ADHERENT_MAIL_REQUIRED') && !isValidEmail((string) $this->email)) {
674 $langs->load("errors");
675 $this->error = $langs->trans("ErrorBadEMail", (string) $this->email);
676 return -1;
677 }
678 if (!$this->datec) {
679 $this->datec = $now;
680 }
681 if (!getDolGlobalString('ADHERENT_LOGIN_NOT_REQUIRED')) {
682 if (empty($this->login)) {
683 $this->error = $langs->trans("ErrorWrongValueForParameterX", "Login");
684 return -1;
685 }
686 }
687
688 // setEntity will set entity with the right value if empty or change it for the right value if multicompany module is active
689 $this->entity = setEntity($this);
690
691 $this->db->begin();
692
693 // Insert member
694 $sql = "INSERT INTO ".MAIN_DB_PREFIX."adherent";
695 $sql .= " (ref, datec, login, fk_user_author, fk_user_mod, fk_user_valid, morphy, fk_adherent_type, entity, import_key, ip)";
696 $sql .= " VALUES (";
697 $sql .= " '(PROV)'";
698 $sql .= ", '".$this->db->idate($this->datec)."'";
699 $sql .= ", ".($this->login ? "'".$this->db->escape($this->login)."'" : "null");
700 $sql .= ", ".($user->id > 0 ? $user->id : "null"); // Can be null because member can be created by a guest or a script
701 $sql .= ", null, null, '".$this->db->escape($this->morphy)."'";
702 $sql .= ", ".((int) $this->typeid);
703 $sql .= ", ".((int) $this->entity);
704 $sql .= ", ".(!empty($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null");
705 $sql .= ", ".(!empty($this->ip) ? "'".$this->db->escape($this->ip)."'" : "null");
706 $sql .= ")";
707
708 dol_syslog(get_class($this)."::create", LOG_DEBUG);
709 $result = $this->db->query($sql);
710 if ($result) {
711 $id = $this->db->last_insert_id(MAIN_DB_PREFIX."adherent");
712 if ($id > 0) {
713 $this->id = $id;
714
715 $modulenum = getDolGlobalString('MEMBER_CODEMEMBER_ADDON', 'mod_member_simple');
716
717 $modfile = dol_buildpath('core/modules/member/'.$modulenum.'.php', 0);
718 try {
719 require_once $modfile;
720 $modname = $modulenum;
721 $modCodeMember = new $modname();
722 '@phan-var-force ModeleNumRefMembers $modCodeMember';
724 $this->ref = $modCodeMember->getNextValue($mysoc, $this);
725 } catch (Exception $e) {
726 dol_syslog($e->getMessage(), LOG_ERR);
727 $error++;
728 }
729
730 // Update minor fields
731 $result = $this->update($user, 1, 1, 0, 0, 'add'); // nosync is 1 to avoid update data of user
732 if ($result < 0) {
733 $this->db->rollback();
734 return -1;
735 }
736
737 // Add link to user
738 if ($this->user_id) {
739 // Add link to user
740 $sql = "UPDATE ".MAIN_DB_PREFIX."user SET";
741 $sql .= " fk_member = ".((int) $this->id);
742 $sql .= " WHERE rowid = ".((int) $this->user_id);
743 dol_syslog(get_class($this)."::create", LOG_DEBUG);
744 $resql = $this->db->query($sql);
745 if (!$resql) {
746 $this->error = 'Failed to update user to make link with member';
747 $this->db->rollback();
748 return -4;
749 }
750 }
751
752 if (!$notrigger) {
753 // Call trigger
754 $result = $this->call_trigger('MEMBER_CREATE', $user);
755 if ($result < 0) {
756 $error++;
757 }
758 // End call triggers
759 }
760
761 if (count($this->errors)) {
762 dol_syslog(get_class($this)."::create ".implode(',', $this->errors), LOG_ERR);
763 $this->db->rollback();
764 return -3;
765 } else {
766 $this->db->commit();
767 return $this->id;
768 }
769 } else {
770 $this->error = 'Failed to get last insert id';
771 dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
772 $this->db->rollback();
773 return -2;
774 }
775 } else {
776 $this->error = $this->db->error();
777 $this->db->rollback();
778 return -1;
779 }
780 }
781
782
794 public function update($user, $notrigger = 0, $nosyncuser = 0, $nosyncuserpass = 0, $nosyncthirdparty = 0, $action = 'update')
795 {
796 global $langs, $hookmanager;
797
798 require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
799
800 if (empty($this->country_id) && !empty($this->country_code)) {
801 $country_id = getCountry($this->country_code, '3');
802 $this->country_id = is_int($country_id) ? $country_id : 0;
803 }
804
805 $nbrowsaffected = 0;
806 $error = 0;
807
808 dol_syslog(get_class($this)."::update notrigger=".$notrigger.", nosyncuser=".$nosyncuser.", nosyncuserpass=".$nosyncuserpass." nosyncthirdparty=".$nosyncthirdparty.", email=".$this->email);
809
810 // Clean parameters
811 $this->lastname = trim($this->lastname) ? trim($this->lastname) : trim($this->lastname);
812 $this->firstname = trim($this->firstname) ? trim($this->firstname) : trim($this->firstname);
813 // civility_code is the reference property. Fall back to the deprecated civility_id alias only when civility_code was not set by the caller.
814 if (empty($this->civility_code) && !empty($this->civility_id)) {
815 $this->civility_code = $this->civility_id;
816 }
817 if (isset($this->gender)) {
818 $this->gender = trim($this->gender);
819 }
820 // $this->address = ($this->address ? $this->address : $this->address);
821 // $this->zip = ($this->zip ? $this->zip : $this->zip);
822 // $this->town = ($this->town ? $this->town : $this->town);
823 // $this->country_id = ($this->country_id > 0 ? $this->country_id : $this->country_id);
824 // $this->state_id = ($this->state_id > 0 ? $this->state_id : $this->state_id);
825 // $this->note_public = ($this->note_public ? $this->note_public : $this->note_public);
826 // $this->note_private = ($this->note_private ? $this->note_private : $this->note_private);
827 $this->url = $this->url ? clean_url($this->url, 0) : '';
828 $this->setUpperOrLowerCase();
829
830 // Check parameters
831 if (getDolGlobalString('ADHERENT_MAIL_REQUIRED') && !isValidEmail((string) $this->email)) {
832 $langs->load("errors");
833 $this->error = $langs->trans("ErrorBadEMail", (string) $this->email);
834 return -1;
835 }
836
837 $this->db->begin();
838
839 $sql = "UPDATE ".MAIN_DB_PREFIX."adherent SET";
840 $sql .= " ref = '".$this->db->escape($this->ref)."'";
841 $sql .= ", ref_ext = ".(empty($this->ref_ext) ? "null" : "'".$this->db->escape($this->ref_ext)."'");
842 $sql .= ", civility = ".($this->civility_code ? "'".$this->db->escape($this->civility_code)."'" : "null");
843 $sql .= ", firstname = ".($this->firstname ? "'".$this->db->escape($this->firstname)."'" : "null");
844 $sql .= ", lastname = ".($this->lastname ? "'".$this->db->escape($this->lastname)."'" : "null");
845 $sql .= ", gender = ".($this->gender != -1 ? "'".$this->db->escape($this->gender)."'" : "null"); // 'man' or 'woman'
846 $sql .= ", login = ".($this->login ? "'".$this->db->escape($this->login)."'" : "null");
847 $sql .= ", societe = ".($this->company ? "'".$this->db->escape($this->company)."'" : ($this->societe ? "'".$this->db->escape($this->societe)."'" : "null"));
848 if ($this->socid) {
849 $sql .= ", fk_soc = ".($this->socid > 0 ? (int) $this->socid : "null"); // Must be modified only when creating from a third-party
850 }
851 $sql .= ", address = ".($this->address ? "'".$this->db->escape($this->address)."'" : "null");
852 $sql .= ", zip = ".($this->zip ? "'".$this->db->escape($this->zip)."'" : "null");
853 $sql .= ", town = ".($this->town ? "'".$this->db->escape($this->town)."'" : "null");
854 $sql .= ", country = ".($this->country_id > 0 ? (int) $this->country_id : "null");
855 $sql .= ", state_id = ".($this->state_id > 0 ? (int) $this->state_id : "null");
856 $sql .= ", email = '".$this->db->escape((string) $this->email)."'";
857 $sql .= ", url = ".(!empty($this->url) ? "'".$this->db->escape($this->url)."'" : "null");
858 $sql .= ", socialnetworks = ".($this->socialnetworks ? "'".$this->db->escape(json_encode($this->socialnetworks))."'" : "null");
859 $sql .= ", phone = ".($this->phone ? "'".$this->db->escape($this->phone)."'" : "null");
860 $sql .= ", phone_perso = ".($this->phone_perso ? "'".$this->db->escape($this->phone_perso)."'" : "null");
861 $sql .= ", phone_mobile = ".($this->phone_mobile ? "'".$this->db->escape($this->phone_mobile)."'" : "null");
862 $sql .= ", note_private = ".($this->note_private ? "'".$this->db->escape($this->note_private)."'" : "null");
863 $sql .= ", note_public = ".($this->note_public ? "'".$this->db->escape($this->note_public)."'" : "null");
864 $sql .= ", photo = ".($this->photo ? "'".$this->db->escape($this->photo)."'" : "null");
865 $sql .= ", public = ".(int) $this->public;
866 $sql .= ", statut = ".(int) $this->statut;
867 $sql .= ", default_lang = ".(!empty($this->default_lang) ? "'".$this->db->escape($this->default_lang)."'" : "null");
868 $sql .= ", fk_adherent_type = ".(int) $this->typeid;
869 $sql .= ", morphy = '".$this->db->escape($this->morphy)."'";
870 $sql .= ", birth = ".($this->birth ? "'".$this->db->idate($this->birth)."'" : "null");
871
872 if ($this->datefin) {
873 $sql .= ", datefin = '".$this->db->idate($this->datefin)."'"; // Must be modified only when deleting a subscription
874 }
875 if ($this->datevalid) {
876 $sql .= ", datevalid = '".$this->db->idate($this->datevalid)."'"; // Must be modified only when validating a member
877 }
878 $sql .= ", fk_user_mod = ".($user->id > 0 ? $user->id : 'null'); // Can be null because member can be create by a guest
879 $sql .= " WHERE rowid = ".((int) $this->id);
880
881 // If we change the type of membership, we set also label of new type..
882 '@phan-var-force Adherent $oldcopy';
883 if (!empty($this->oldcopy) && $this->typeid != $this->oldcopy->typeid) {
884 $sql2 = "SELECT libelle as label";
885 $sql2 .= " FROM ".MAIN_DB_PREFIX."adherent_type";
886 $sql2 .= " WHERE rowid = ".((int) $this->typeid);
887 $resql2 = $this->db->query($sql2);
888 if ($resql2) {
889 while ($obj = $this->db->fetch_object($resql2)) {
890 $this->type = $obj->label;
891 }
892 }
893 }
894
895 dol_syslog(get_class($this)."::update update member", LOG_DEBUG);
896 $resql = $this->db->query($sql);
897 if ($resql) {
898 unset($this->country_code);
899 unset($this->country);
900 unset($this->state_code);
901 unset($this->state);
902
903 $nbrowsaffected += $this->db->affected_rows($resql);
904
905 $action = 'update';
906
907 // Actions on extra fields
908 $result = $this->insertExtraFields();
909 if ($result < 0) {
910 $error++;
911 }
912
913 // Update password
914 if (!$error && $this->pass) {
915 dol_syslog(get_class($this)."::update update password");
916 if ($this->pass != $this->pass_indatabase && $this->pass != $this->pass_indatabase_crypted) {
917 $isencrypted = getDolGlobalString('DATABASE_PWD_ENCRYPTED') ? 1 : 0;
918
919 // If password to set differs from the one found into database
920 $result = $this->setPassword($user, $this->pass, $isencrypted, $notrigger, $nosyncuserpass);
921 if (!$nbrowsaffected) {
922 $nbrowsaffected++;
923 }
924 }
925 }
926
927 // Remove links to user and replace with new one
928 if (!$error) {
929 dol_syslog(get_class($this)."::update update link to user");
930 $sql = "UPDATE ".MAIN_DB_PREFIX."user SET fk_member = NULL WHERE fk_member = ".((int) $this->id);
931 dol_syslog(get_class($this)."::update", LOG_DEBUG);
932 $resql = $this->db->query($sql);
933 if (!$resql) {
934 $this->error = $this->db->error();
935 $this->db->rollback();
936 return -5;
937 }
938 // If there is a user linked to this member
939 if ($this->user_id > 0) {
940 $sql = "UPDATE ".MAIN_DB_PREFIX."user SET fk_member = ".((int) $this->id)." WHERE rowid = ".((int) $this->user_id);
941 dol_syslog(get_class($this)."::update", LOG_DEBUG);
942 $resql = $this->db->query($sql);
943 if (!$resql) {
944 $this->error = $this->db->error();
945 $this->db->rollback();
946 return -5;
947 }
948 }
949 }
950
951 if (!$error && $nbrowsaffected) { // If something has change in main data
952 // Update information on linked user if it is an update
953 if ($this->user_id > 0 && !$nosyncuser) {
954 require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
955
956 dol_syslog(get_class($this)."::update update linked user");
957
958 $luser = new User($this->db);
959 $result = $luser->fetch($this->user_id);
960
961 if ($result >= 0) {
962 // 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.
963 if (!getDolGlobalString('ADHERENT_LOGIN_NOT_REQUIRED')) {
964 $luser->login = $this->login;
965 }
966
967 $luser->ref = $this->ref;
968 $luser->civility_code = $this->civility_code;
969 $luser->firstname = $this->firstname;
970 $luser->lastname = $this->lastname;
971 $luser->gender = $this->gender;
972 $luser->pass = isset($this->pass) ? $this->pass : '';
973 //$luser->socid=$this->fk_soc; // We do not enable this. This may transform a user into an external user.
974
975 $luser->birth = $this->birth;
976
977 $luser->address = $this->address;
978 $luser->zip = $this->zip;
979 $luser->town = $this->town;
980 $luser->country_id = $this->country_id;
981 $luser->state_id = $this->state_id;
982
983 $luser->email = $this->email;
984 $luser->socialnetworks = $this->socialnetworks;
985 $luser->office_phone = $this->phone;
986 $luser->user_mobile = $this->phone_mobile;
987
988 $luser->lang = $this->default_lang;
989
990 $luser->fk_member = $this->id;
991
992 $result = $luser->update($user, 0, 1, 1); // Use nosync to 1 to avoid cyclic updates
993 if ($result < 0) {
994 $this->error = $luser->error;
995 dol_syslog(get_class($this)."::update ".$this->error, LOG_ERR);
996 $error++;
997 }
998 } else {
999 $this->error = $luser->error;
1000 $error++;
1001 }
1002 }
1003
1004 // Update information on linked thirdparty if it is an update
1005 if (!$error && $this->socid > 0 && !$nosyncthirdparty) {
1006 require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
1007
1008 dol_syslog(get_class($this)."::update update linked thirdparty");
1009
1010 // This member is linked with a thirdparty, so we also update thirdparty information
1011 // if this is an update.
1012 $lthirdparty = new Societe($this->db);
1013 $result = $lthirdparty->fetch($this->socid);
1014
1015 if ($result > 0) {
1016 $lthirdparty->address = $this->address;
1017 $lthirdparty->zip = $this->zip;
1018 $lthirdparty->town = $this->town;
1019 $lthirdparty->email = $this->email;
1020 $lthirdparty->socialnetworks = $this->socialnetworks;
1021 $lthirdparty->phone = $this->phone;
1022 $lthirdparty->state_id = $this->state_id;
1023 $lthirdparty->country_id = $this->country_id;
1024 //$lthirdparty->phone_mobile=$this->phone_mobile;
1025 $lthirdparty->default_lang = $this->default_lang;
1026
1027 $result = $lthirdparty->update($this->socid, $user, 0, 1, 1, 'update'); // Use sync to 0 to avoid cyclic updates
1028
1029 if ($result < 0) {
1030 $this->error = $lthirdparty->error;
1031 $this->errors = $lthirdparty->errors;
1032 dol_syslog(get_class($this)."::update ".$this->error, LOG_ERR);
1033 $error++;
1034 }
1035 } elseif ($result < 0) {
1036 $this->error = $lthirdparty->error;
1037 $error++;
1038 }
1039 }
1040 }
1041
1042 if (!$error && !$notrigger) {
1043 // Call trigger
1044 $result = $this->call_trigger('MEMBER_MODIFY', $user);
1045 if ($result < 0) {
1046 $error++;
1047 }
1048 // End call triggers
1049 }
1050
1051 if (!$error) {
1052 $this->db->commit();
1053 return $nbrowsaffected;
1054 } else {
1055 $this->db->rollback();
1056 return -1;
1057 }
1058 } else {
1059 $this->db->rollback();
1060 $this->error = $this->db->lasterror();
1061 return -2;
1062 }
1063 }
1064
1065
1066 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1074 public function update_end_date($user)
1075 {
1076 // phpcs:enable
1077 $this->db->begin();
1078
1079 // Search for last subscription id and end date
1080 $sql = "SELECT rowid, datec as dateop, dateadh as datedeb, datef as datefin";
1081 $sql .= " FROM ".MAIN_DB_PREFIX."subscription";
1082 $sql .= " WHERE fk_adherent = ".((int) $this->id);
1083 $sql .= " ORDER by dateadh DESC"; // Sort by start subscription date
1084
1085 dol_syslog(get_class($this)."::update_end_date", LOG_DEBUG);
1086 $resql = $this->db->query($sql);
1087 if ($resql) {
1088 // The last subscription is the one with the latest start date (first record), but the end date of the member is
1089 // the latest end date of all its subscriptions: a short subscription that starts after a longer one must not
1090 // shorten the membership. There is no record at all when the last subscription of the member was deleted.
1091 $dateop = '';
1092 $datedeb = '';
1093 $datefin = '';
1094 $dateendmember = '';
1095 $i = 0;
1096 while ($obj = $this->db->fetch_object($resql)) {
1097 $dateendsubscription = $this->db->jdate($obj->datefin);
1098 if ($i == 0) {
1099 $dateop = $this->db->jdate($obj->dateop);
1100 $datedeb = $this->db->jdate($obj->datedeb);
1101 $datefin = $dateendsubscription;
1102 }
1103 if ($dateendsubscription != '' && ($dateendmember == '' || $dateendsubscription > $dateendmember)) {
1104 $dateendmember = $dateendsubscription;
1105 }
1106 $i++;
1107 }
1108
1109 $sql = "UPDATE ".MAIN_DB_PREFIX."adherent SET";
1110 $sql .= " datefin=".($dateendmember != '' ? "'".$this->db->idate($dateendmember)."'" : "null");
1111 $sql .= " WHERE rowid = ".((int) $this->id);
1112
1113 dol_syslog(get_class($this)."::update_end_date", LOG_DEBUG);
1114 $resql = $this->db->query($sql);
1115 if ($resql) {
1116 $this->last_subscription_date = $dateop;
1117 $this->last_subscription_date_start = $datedeb;
1118 $this->last_subscription_date_end = $datefin;
1119 $this->datefin = $dateendmember;
1120 $this->db->commit();
1121 return 1;
1122 } else {
1123 $this->db->rollback();
1124 return -1;
1125 }
1126 } else {
1127 $this->error = $this->db->lasterror();
1128 $this->db->rollback();
1129 return -1;
1130 }
1131 }
1132
1140 public function delete($user, $notrigger = 0)
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 (!$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 linked user
1183 if (!$error) {
1184 $ret = $this->setUserId(0);
1185 if ($ret < 0) {
1186 $error++;
1187 $this->error .= $this->db->lasterror();
1188 $errorflag = -3;
1189 }
1190 }
1191
1192 // Removed extrafields
1193 if (!$error) {
1194 $result = $this->deleteExtraFields();
1195 if ($result < 0) {
1196 $error++;
1197 $errorflag = -4;
1198 dol_syslog(get_class($this)."::delete erreur ".$errorflag." ".$this->error, LOG_ERR);
1199 }
1200 }
1201
1202 // Remove adherent
1203 if (!$error) {
1204 $sql = "DELETE FROM ".MAIN_DB_PREFIX."adherent WHERE rowid = ".((int) $rowid);
1205 dol_syslog(get_class($this)."::delete", LOG_DEBUG);
1206 $resql = $this->db->query($sql);
1207 if (!$resql) {
1208 $error++;
1209 $this->error .= $this->db->lasterror();
1210 $errorflag = -5;
1211 }
1212 }
1213
1214 if (!$error) {
1215 $this->db->commit();
1216 return 1;
1217 } else {
1218 $this->db->rollback();
1219 return $errorflag;
1220 }
1221 }
1222
1233 public function mergeMembers($member_origin_id)
1234 {
1235 global $conf, $langs, $hookmanager, $user, $action;
1236
1237 $error = 0;
1238 $member_origin = new Adherent($this->db); // The member that we will delete
1239
1240 dol_syslog("mergeMembers merge member id=".$member_origin_id." (will be deleted) into the member id=".$this->id);
1241 if ($member_origin->fetch($member_origin_id) < 1) {
1242 $this->error = $langs->trans('ErrorRecordNotFound');
1243 $error++;
1244 }
1245
1246 if (!$error) {
1247 $this->db->begin();
1248 $listofproperties = array(
1249 'ref_ext', 'civility', 'lastname', 'firstname', 'morphy', 'societe', 'socid', 'user_id','address',
1250 'zip', 'town', 'state_id', 'country', 'phone', 'phone_perso', 'phone_mobile', 'email',
1251 'url', 'socialnetworks', 'birth', 'gender', 'photo', 'public', 'datefin', 'default_lang',
1252 'canvas', 'model_pdf', 'import_key'
1253 );
1254 foreach ($listofproperties as $property) {
1255 if (empty($this->$property)) {
1256 $this->$property = $member_origin->$property;
1257 }
1258 }
1259
1260 // Concat some data
1261 $listofproperties = array(
1262 'note_public', 'note_private'
1263 );
1264 foreach ($listofproperties as $property) {
1265 $this->$property = dol_concatdesc($this->$property, $member_origin->$property);
1266 }
1267
1268 // Merge extrafields
1269 if (is_array($member_origin->array_options)) {
1270 foreach ($member_origin->array_options as $key => $val) {
1271 if (empty($this->array_options[$key])) {
1272 $this->array_options[$key] = $val;
1273 }
1274 }
1275 }
1276
1277 // Merge categories
1278 include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
1279 $static_cat = new Categorie($this->db);
1280 $custcats_ori = $static_cat->containing($member_origin->id, 'member', 'id');
1281 $custcats = $static_cat->containing($this->id, 'member', 'id');
1282 $custcats = array_merge($custcats, $custcats_ori);
1283 $this->setCategories($custcats);
1284
1285 $result = $this->update($user, 1, 1, 1, 1, 'merge');
1286 if ($result < 0) {
1287 $error++;
1288 }
1289
1290 // Merge subscriptions
1291 if (!$error && $member_origin->fetch_subscriptions() < 1) {
1292 $error++;
1293 }
1294
1295 if (!$error) {
1296 foreach ($member_origin->subscriptions as $key => $subscription) {
1297 $subscription->fk_adherent = $this->id;
1298 $result = $subscription->update($user);
1299 if ($result < 0) {
1300 $error++;
1301 break;
1302 }
1303 }
1304 }
1305
1306 // External modules should update their ones too
1307 if (!$error) {
1308 $parameters = array('member_origin' => $member_origin->id, 'member_dest' => $this->id);
1309 $reshook = $hookmanager->executeHooks('replaceMember', $parameters, $this, $action);
1310
1311 if ($reshook < 0) {
1312 $this->setErrorsFromObject($hookmanager);
1313 $error++;
1314 }
1315 }
1316
1317 if (!$error) {
1318 $this->context = array('merge' => 1, 'mergefromid' => $member_origin->id);
1319
1320 // Call trigger
1321 $result = $this->call_trigger('MEMBER_MODIFY', $user);
1322 if ($result < 0) {
1323 $error++;
1324 }
1325 // End call triggers
1326 }
1327
1328 if (!$error) {
1329 // We finally remove the old member
1330 if ($member_origin->delete($user) < 1) {
1331 $this->setErrorsFromObject($member_origin);
1332 $error++;
1333 }
1334 }
1335
1336 if (!$error) {
1337 // Move files from the dir of the third party to delete into the dir of the third party to keep
1338 if (!empty($conf->adherent->multidir_output[$this->entity])) {
1339 $srcdir = $conf->adherent->multidir_output[$this->entity]."/".$member_origin->id;
1340 $destdir = $conf->adherent->multidir_output[$this->entity]."/".$this->id;
1341
1342 if (dol_is_dir($srcdir)) {
1343 $dirlist = dol_dir_list($srcdir, 'files', 1);
1344 foreach ($dirlist as $filetomove) {
1345 $destfile = $destdir.'/'.$filetomove['relativename'];
1346 $result = dol_move($filetomove['fullname'], $destfile, '0', 0, 0, 1);
1347 if (!$result) {
1348 $error++;
1349 }
1350 }
1351 }
1352 }
1353 }
1354
1355 if (!$error) {
1356 $this->db->commit();
1357 return 0;
1358 } else {
1359 $langs->load("errors");
1360 $this->error = $langs->trans('ErrorMembersMerge');
1361 $this->db->rollback();
1362 return -1;
1363 }
1364 }
1365 return -1;
1366 }
1367
1378 public function setPassword($user, $password = '', $isencrypted = 0, $notrigger = 0, $nosyncuser = 0)
1379 {
1380 global $conf, $langs;
1381
1382 $error = 0;
1383
1384 dol_syslog(get_class($this)."::setPassword user=".$user->id." password=".preg_replace('/./i', '*', $password)." isencrypted=".$isencrypted);
1385
1386 // If new password not provided, we generate one
1387 if (!$password) {
1388 require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
1389 $password = getRandomPassword(false);
1390 }
1391
1392 // Crypt password
1393 $password_crypted = dol_hash($password);
1394
1395 $password_indatabase = '';
1396 if (!$isencrypted) {
1397 $password_indatabase = $password;
1398 }
1399
1400 $this->db->begin();
1401
1402 // Mise a jour
1403 $sql = "UPDATE ".MAIN_DB_PREFIX."adherent";
1404 $sql .= " SET pass_crypted = '".$this->db->escape($password_crypted)."'";
1405 if ($isencrypted) {
1406 $sql .= ", pass = null";
1407 } else {
1408 $sql .= ", pass = '".$this->db->escape($password_indatabase)."'";
1409 }
1410 $sql .= " WHERE rowid = ".((int) $this->id);
1411
1412 //dol_syslog("Adherent::Password sql=hidden");
1413 dol_syslog(get_class($this)."::setPassword", LOG_DEBUG);
1414 $result = $this->db->query($sql);
1415 if ($result) {
1416 $nbaffectedrows = $this->db->affected_rows($result);
1417
1418 if ($nbaffectedrows) {
1419 $this->pass = $password;
1420 $this->pass_indatabase = $password_indatabase;
1421 $this->pass_indatabase_crypted = $password_crypted;
1422
1423 if ($this->user_id && !$nosyncuser) {
1424 require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
1425
1426 // This member is linked with a user, so we also update users information
1427 // if this is an update.
1428 $luser = new User($this->db);
1429 $result = $luser->fetch($this->user_id);
1430
1431 if ($result >= 0) {
1432 $result = $luser->setPassword($user, $this->pass, 0, 0, 1);
1433 if (is_int($result) && $result < 0) {
1434 $this->error = $luser->error;
1435 dol_syslog(get_class($this)."::setPassword ".$this->error, LOG_ERR);
1436 $error++;
1437 }
1438 } else {
1439 $this->error = $luser->error;
1440 $error++;
1441 }
1442 }
1443
1444 if (!$error && !$notrigger) {
1445 // Call trigger
1446 $result = $this->call_trigger('MEMBER_NEW_PASSWORD', $user);
1447 if ($result < 0) {
1448 $error++;
1449 $this->db->rollback();
1450 return -1;
1451 }
1452 // End call triggers
1453 }
1454
1455 $this->db->commit();
1456 return $this->pass;
1457 } else {
1458 $this->db->rollback();
1459 return 0;
1460 }
1461 } else {
1462 $this->db->rollback();
1463 dol_print_error($this->db);
1464 return -1;
1465 }
1466 }
1467
1468
1475 public function setUserId($userid)
1476 {
1477 global $conf, $langs;
1478
1479 $this->db->begin();
1480
1481 // If user is linked to this member, remove old link to this member
1482 $sql = "UPDATE ".MAIN_DB_PREFIX."user SET fk_member = NULL WHERE fk_member = ".((int) $this->id);
1483 dol_syslog(get_class($this)."::setUserId", LOG_DEBUG);
1484 $resql = $this->db->query($sql);
1485 if (!$resql) {
1486 $this->error = $this->db->error();
1487 $this->db->rollback();
1488 return -1;
1489 }
1490
1491 // Set link to user
1492 if ($userid > 0) {
1493 $sql = "UPDATE ".MAIN_DB_PREFIX."user SET fk_member = ".((int) $this->id);
1494 $sql .= " WHERE rowid = ".((int) $userid);
1495 dol_syslog(get_class($this)."::setUserId", LOG_DEBUG);
1496 $resql = $this->db->query($sql);
1497 if (!$resql) {
1498 $this->error = $this->db->error();
1499 $this->db->rollback();
1500 return -2;
1501 }
1502 }
1503
1504 $this->db->commit();
1505
1506 return 1;
1507 }
1508
1509
1516 public function setThirdPartyId($thirdpartyid)
1517 {
1518 global $conf, $langs;
1519
1520 $this->db->begin();
1521
1522 // Remove link to third party onto any other members
1523 if ($thirdpartyid > 0) {
1524 $sql = "UPDATE ".MAIN_DB_PREFIX."adherent SET fk_soc = null";
1525 $sql .= " WHERE fk_soc = ".((int) $thirdpartyid);
1526 $sql .= " AND entity = ".$conf->entity;
1527 dol_syslog(get_class($this)."::setThirdPartyId", LOG_DEBUG);
1528 $resql = $this->db->query($sql);
1529 }
1530
1531 // Add link to third party for current member
1532 $sql = "UPDATE ".MAIN_DB_PREFIX."adherent SET fk_soc = ".($thirdpartyid > 0 ? (int) $thirdpartyid : 'null');
1533 $sql .= " WHERE rowid = ".((int) $this->id);
1534
1535 dol_syslog(get_class($this)."::setThirdPartyId", LOG_DEBUG);
1536 $resql = $this->db->query($sql);
1537 if ($resql) {
1538 $this->db->commit();
1539 return 1;
1540 } else {
1541 $this->error = $this->db->error();
1542 $this->db->rollback();
1543 return -1;
1544 }
1545 }
1546
1547
1548 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1555 public function fetch_login($login)
1556 {
1557 // phpcs:enable
1558 global $conf;
1559
1560 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."adherent";
1561 $sql .= " WHERE login='".$this->db->escape($login)."'";
1562 $sql .= " AND entity = ".$conf->entity;
1563
1564 $resql = $this->db->query($sql);
1565 if ($resql) {
1566 if ($this->db->num_rows($resql)) {
1567 $obj = $this->db->fetch_object($resql);
1568 $this->fetch($obj->rowid);
1569 }
1570 } else {
1571 dol_print_error($this->db);
1572 }
1573 }
1574
1575 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1583 public function fetch_name($firstname, $lastname)
1584 {
1585 // phpcs:enable
1586 global $conf;
1587
1588 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."adherent";
1589 $sql .= " WHERE firstname='".$this->db->escape($firstname)."'";
1590 $sql .= " AND lastname='".$this->db->escape($lastname)."'";
1591 $sql .= " AND entity = ".$conf->entity;
1592
1593 $resql = $this->db->query($sql);
1594 if ($resql) {
1595 if ($this->db->num_rows($resql)) {
1596 $obj = $this->db->fetch_object($resql);
1597 $this->fetch($obj->rowid);
1598 }
1599 } else {
1600 dol_print_error($this->db);
1601 }
1602 }
1603
1615 public function fetch($rowid, $ref = '', $socid = 0, $ref_ext = '', $fetch_optionals = true, $fetch_subscriptions = true)
1616 {
1617 global $langs;
1618
1619 $sql = "SELECT d.rowid, d.ref, d.ref_ext, d.civility as civility_code, d.gender, d.firstname, d.lastname,";
1620 $sql .= " d.societe as company, d.fk_soc as socid, d.statut, d.public, d.address, d.zip, d.town, d.note_private,";
1621 $sql .= " d.note_public,";
1622 $sql .= " d.email, d.url, d.socialnetworks, d.phone, d.phone_perso, d.phone_mobile, d.login, d.pass, d.pass_crypted,";
1623 $sql .= " d.photo, d.fk_adherent_type, d.morphy, d.entity,";
1624 $sql .= " d.datec as datec,";
1625 $sql .= " GREATEST(d.tms, COALESCE(aef.tms, d.tms)) as datem,";
1626 $sql .= " d.datefin as datefin, d.default_lang,";
1627 $sql .= " d.birth as birthday,";
1628 $sql .= " d.datevalid as datev,";
1629 $sql .= " d.country,";
1630 $sql .= " d.state_id,";
1631 $sql .= " d.model_pdf,";
1632 $sql .= " c.rowid as country_id, c.code as country_code, c.label as country,";
1633 $sql .= " dep.nom as state, dep.code_departement as state_code,";
1634 $sql .= " t.libelle as type, t.subscription as subscription,";
1635 $sql .= " u.rowid as user_id, u.login as user_login";
1636 $sql .= " FROM ".MAIN_DB_PREFIX."adherent_type as t, ".MAIN_DB_PREFIX."adherent as d";
1637 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'adherent_extrafields as aef ON aef.fk_object = d.rowid';
1638 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_country as c ON d.country = c.rowid";
1639 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_departements as dep ON d.state_id = dep.rowid";
1640 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as u ON d.rowid = u.fk_member";
1641 $sql .= " WHERE d.fk_adherent_type = t.rowid";
1642 if ($rowid) {
1643 $sql .= " AND d.rowid=".((int) $rowid);
1644 } elseif ($ref || $socid) {
1645 $sql .= " AND d.entity IN (".getEntity('adherent').")";
1646 if ($ref) {
1647 $sql .= " AND d.ref='".$this->db->escape($ref)."'";
1648 } elseif ($socid > 0) {
1649 $sql .= " AND d.fk_soc=".((int) $socid);
1650 }
1651 } elseif ($ref_ext) {
1652 $sql .= " AND d.ref_ext='".$this->db->escape($ref_ext)."'";
1653 }
1654
1655 dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
1656 $resql = $this->db->query($sql);
1657 if ($resql) {
1658 if ($this->db->num_rows($resql)) {
1659 $obj = $this->db->fetch_object($resql);
1660
1661 $this->entity = $obj->entity;
1662 $this->id = $obj->rowid;
1663 $this->ref = $obj->ref;
1664 $this->ref_ext = $obj->ref_ext;
1665
1666 $this->civility_id = $obj->civility_code; // Bad. Kept for backward compatibility
1667 $this->civility_code = $obj->civility_code;
1668 $this->civility = $obj->civility_code ? ($langs->trans("Civility".$obj->civility_code) != "Civility".$obj->civility_code ? $langs->trans("Civility".$obj->civility_code) : $obj->civility_code) : '';
1669
1670 $this->firstname = $obj->firstname;
1671 $this->lastname = $obj->lastname;
1672 $this->gender = $obj->gender;
1673 $this->login = $obj->login;
1674 $this->societe = $obj->company;
1675 $this->company = $obj->company;
1676 $this->socid = $obj->socid;
1677 $this->fk_soc = $obj->socid; // For backward compatibility
1678 $this->address = $obj->address;
1679 $this->zip = $obj->zip;
1680 $this->town = $obj->town;
1681
1682 $this->pass = $obj->pass;
1683 $this->pass_indatabase = $obj->pass;
1684 $this->pass_indatabase_crypted = $obj->pass_crypted;
1685
1686 $this->state_id = $obj->state_id;
1687 $this->state_code = $obj->state_id ? $obj->state_code : '';
1688 $this->state = $obj->state_id ? $obj->state : '';
1689
1690 $this->country_id = $obj->country_id;
1691 $this->country_code = $obj->country_code;
1692 if ($langs->trans("Country".$obj->country_code) != "Country".$obj->country_code) {
1693 $this->country = $langs->transnoentitiesnoconv("Country".$obj->country_code);
1694 } else {
1695 $this->country = $obj->country;
1696 }
1697
1698 $this->phone = $obj->phone;
1699 $this->phone_perso = $obj->phone_perso;
1700 $this->phone_mobile = $obj->phone_mobile;
1701 $this->email = $obj->email;
1702 $this->url = $obj->url;
1703
1704 $this->socialnetworks = ($obj->socialnetworks ? (array) json_decode($obj->socialnetworks, true) : array());
1705
1706 $this->photo = $obj->photo;
1707 $this->statut = $obj->statut;
1708 $this->status = $obj->statut;
1709 $this->public = $obj->public;
1710
1711 $this->datec = $this->db->jdate($obj->datec);
1712 $this->date_creation = $this->db->jdate($obj->datec);
1713 $this->datem = $this->db->jdate($obj->datem);
1714 $this->date_modification = $this->db->jdate($obj->datem);
1715 $this->datefin = $this->db->jdate($obj->datefin);
1716 $this->datevalid = $this->db->jdate($obj->datev);
1717 $this->date_validation = $this->db->jdate($obj->datev);
1718 $this->birth = $this->db->jdate($obj->birthday);
1719
1720 $this->default_lang = $obj->default_lang;
1721
1722 $this->note_private = $obj->note_private;
1723 $this->note_public = $obj->note_public;
1724 $this->morphy = $obj->morphy;
1725
1726 $this->typeid = $obj->fk_adherent_type;
1727 $this->type = $obj->type;
1728 $this->need_subscription = $obj->subscription;
1729
1730 $this->user_id = $obj->user_id;
1731 $this->user_login = $obj->user_login;
1732
1733 $this->model_pdf = $obj->model_pdf;
1734
1735 // Retrieve all extrafield
1736 // fetch optionals attributes and labels
1737 if ($fetch_optionals) {
1738 $this->fetch_optionals();
1739 }
1740
1741 // Load other properties
1742 if ($fetch_subscriptions) {
1743 $result = $this->fetch_subscriptions();
1744 }
1745
1746 return $this->id;
1747 } else {
1748 return 0;
1749 }
1750 } else {
1751 $this->error = $this->db->lasterror();
1752 return -1;
1753 }
1754 }
1755
1756
1757 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1766 public function fetch_subscriptions()
1767 {
1768 // phpcs:enable
1769 require_once DOL_DOCUMENT_ROOT.'/adherents/class/subscription.class.php';
1770
1771 $sql = "SELECT c.rowid, c.fk_adherent, c.fk_type, c.subscription, c.note as note_public, c.fk_bank,";
1772 $sql .= " c.tms as datem,";
1773 $sql .= " c.datec as datec,";
1774 $sql .= " c.dateadh as dateh,";
1775 $sql .= " c.datef as datef";
1776 $sql .= " FROM ".MAIN_DB_PREFIX."subscription as c";
1777 $sql .= " WHERE c.fk_adherent = ".((int) $this->id);
1778 $sql .= " ORDER BY c.dateadh";
1779 dol_syslog(get_class($this)."::fetch_subscriptions", LOG_DEBUG);
1780
1781 $resql = $this->db->query($sql);
1782 if ($resql) {
1783 $this->subscriptions = array();
1784
1785 $i = 0;
1786 while ($obj = $this->db->fetch_object($resql)) {
1787 if ($i == 0) {
1788 $this->first_subscription_date = $this->db->jdate($obj->datec);
1789 $this->first_subscription_date_start = $this->db->jdate($obj->dateh);
1790 $this->first_subscription_date_end = $this->db->jdate($obj->datef);
1791 $this->first_subscription_amount = $obj->subscription;
1792 }
1793 $this->last_subscription_date = $this->db->jdate($obj->datec);
1794 $this->last_subscription_date_start = $this->db->jdate($obj->dateh);
1795 $this->last_subscription_date_end = $this->db->jdate($obj->datef);
1796 $this->last_subscription_amount = (float) $obj->subscription;
1797
1798 $subscription = new Subscription($this->db);
1799 $subscription->id = $obj->rowid;
1800 $subscription->fk_adherent = $obj->fk_adherent;
1801 $subscription->fk_type = $obj->fk_type;
1802 $subscription->amount = (float) $obj->subscription;
1803 $subscription->note = $obj->note_public;
1804 $subscription->note_public = $obj->note_public;
1805 $subscription->fk_bank = $obj->fk_bank;
1806 $subscription->datem = $this->db->jdate($obj->datem);
1807 $subscription->datec = $this->db->jdate($obj->datec);
1808 $subscription->dateh = $this->db->jdate($obj->dateh);
1809 $subscription->datef = $this->db->jdate($obj->datef);
1810
1811 $this->subscriptions[] = $subscription;
1812
1813 $i++;
1814 }
1815 return 1;
1816 } else {
1817 $this->error = $this->db->error().' sql='.$sql;
1818 return -1;
1819 }
1820 }
1821
1822
1829 public function fetchPartnerships($mode)
1830 {
1831 require_once DOL_DOCUMENT_ROOT.'/partnership/class/partnership.class.php';
1832
1833
1834 $this->partnerships[] = array();
1835
1836 return 1;
1837 }
1838
1839
1856 public function subscription($date, $amount, $accountid = 0, $operation = '', $label = '', $num_chq = '', $emetteur_nom = '', $emetteur_banque = '', $datesubend = 0, $fk_type = null, $ref_ext = '')
1857 {
1858 global $user;
1859
1860 require_once DOL_DOCUMENT_ROOT.'/adherents/class/subscription.class.php';
1861
1862 $error = 0;
1863
1864 // Clean parameters
1865 if (!$amount) {
1866 $amount = 0;
1867 }
1868
1869 $this->db->begin();
1870
1871 if ($datesubend) {
1872 $datefin = $datesubend;
1873 } else {
1874 // If no end date, end date = date + 1 year - 1 day
1875 $datefin = dol_time_plus_duree($date, 1, 'y');
1876 $datefin = dol_time_plus_duree($datefin, -1, 'd');
1877 }
1878
1879 // Create subscription
1880 $subscription = new Subscription($this->db);
1881 $subscription->fk_adherent = $this->id;
1882 $subscription->dateh = $date; // Date of new subscription
1883 $subscription->datef = $datefin; // End data of new subscription
1884 $subscription->amount = $amount;
1885 $subscription->note_public = $label;
1886 $subscription->note_private = '';
1887 $subscription->fk_type = $fk_type;
1888 $subscription->ref_ext = $ref_ext;
1889
1890 if (empty($subscription->user_creation_id)) {
1891 $subscription->user_creation_id = $user->id;
1892 }
1893
1894 $rowid = $subscription->create($user);
1895 if ($rowid > 0) {
1896 // Update denormalized subscription end date (read database subscription to find values)
1897 // This will also update this->datefin
1898 $result = $this->update_end_date($user);
1899 if ($result > 0) {
1900 // Change properties of object (used by triggers)
1901 $this->last_subscription_date = dol_now();
1902 $this->last_subscription_date_start = $date;
1903 $this->last_subscription_date_end = $datefin;
1904 $this->last_subscription_amount = $amount;
1905 } else {
1906 $error++;
1907 }
1908
1909 if (!$error) {
1910 $this->db->commit();
1911 return $rowid;
1912 } else {
1913 $this->db->rollback();
1914 return -2;
1915 }
1916 } else {
1917 $this->setErrorsFromObject($subscription);
1918 $this->db->rollback();
1919 return -1;
1920 }
1921 }
1922
1923
1943 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 = '')
1944 {
1945 global $conf, $langs, $user, $mysoc;
1946
1947 $error = 0;
1948
1949 $this->invoice = null; // This will contains invoice if an invoice is created
1950
1951 dol_syslog("subscriptionComplementaryActions subscriptionid=".$subscriptionid." option=".$option." accountid=".$accountid." datesubscription=".$datesubscription." paymentdate=".
1952 $paymentdate." label=".$label." amount=".$amount." num_chq=".$num_chq." autocreatethirdparty=".$autocreatethirdparty);
1953
1954 // Insert into bank account directlty (if option chosen for) + link to llx_subscription if option is 'bankdirect'
1955 if ($option == 'bankdirect' && $accountid) {
1956 require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
1957
1958 $acct = new Account($this->db);
1959 $result = $acct->fetch($accountid);
1960
1961 $dateop = $paymentdate;
1962
1963 $insertid = $acct->addline($dateop, $operation, $label, $amount, $num_chq, 0, $user, $emetteur_nom, $emetteur_banque);
1964 if ($insertid > 0) {
1965 $inserturlid = $acct->add_url_line($insertid, $this->id, DOL_URL_ROOT.'/adherents/card.php?rowid=', $this->getFullName($langs), 'member');
1966 if ($inserturlid > 0) {
1967 // Update table subscription
1968 $sql = "UPDATE ".MAIN_DB_PREFIX."subscription SET fk_bank=".((int) $insertid);
1969 $sql .= " WHERE rowid=".((int) $subscriptionid);
1970
1971 dol_syslog("subscription::subscription", LOG_DEBUG);
1972 $resql = $this->db->query($sql);
1973 if (!$resql) {
1974 $error++;
1975 $this->error = $this->db->lasterror();
1976 $this->errors[] = $this->error;
1977 }
1978 } else {
1979 $error++;
1980 $this->setErrorsFromObject($acct);
1981 }
1982 } else {
1983 $error++;
1984 $this->setErrorsFromObject($acct);
1985 }
1986 }
1987
1988 // If option chosen, we create invoice
1989 if (($option == 'bankviainvoice' && $accountid) || $option == 'invoiceonly') {
1990 require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
1991 require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/paymentterm.class.php';
1992
1993 $invoice = new Facture($this->db);
1994 $customer = new Societe($this->db);
1995
1996 if (!$error) {
1997 if (!($this->socid > 0)) { // If not yet linked to a company
1998 if ($autocreatethirdparty) {
1999 // Create a linked thirdparty to member
2000 $companyalias = '';
2001 $fullname = $this->getFullName($langs);
2002
2003 if ($this->morphy == 'mor') {
2004 $companyname = $this->company;
2005 if (!empty($fullname)) {
2006 $companyalias = $fullname;
2007 }
2008 } else {
2009 $companyname = $fullname;
2010 if (!empty($this->company)) {
2011 $companyalias = $this->company;
2012 }
2013 }
2014
2015 $result = $customer->create_from_member($this, (string) $companyname, $companyalias);
2016 if ($result < 0) {
2017 $this->error = $customer->error;
2018 $this->errors = $customer->errors;
2019 $error++;
2020 } else {
2021 $this->fk_soc = $result;
2022 $this->socid = $result;
2023 }
2024 } else {
2025 $langs->load("errors");
2026 $this->error = $langs->trans("ErrorMemberNotLinkedToAThirpartyLinkOrCreateFirst");
2027 $this->errors[] = $this->error;
2028 $error++;
2029 }
2030 }
2031 }
2032 if (!$error) {
2033 $result = $customer->fetch($this->socid);
2034 if ($result <= 0) {
2035 $this->error = $customer->error;
2036 $this->errors = $customer->errors;
2037 $error++;
2038 }
2039 }
2040
2041 if (!$error) {
2042 // Create draft invoice
2043 $invoice->type = Facture::TYPE_STANDARD;
2044 $invoice->cond_reglement_id = $customer->cond_reglement_id;
2045 if (empty($invoice->cond_reglement_id)) {
2046 $paymenttermstatic = new PaymentTerm($this->db);
2047 $invoice->cond_reglement_id = $paymenttermstatic->getDefaultId();
2048 if (empty($invoice->cond_reglement_id)) {
2049 $error++;
2050 $this->error = 'ErrorNoPaymentTermRECEPFound';
2051 $this->errors[] = $this->error;
2052 }
2053 }
2054 $invoice->socid = $this->socid;
2055 // set customer's payment bank account on the invoice
2056 if (!empty($customer->fk_account)) {
2057 $invoice->fk_account = $customer->fk_account;
2058 } elseif (getDolGlobalString('FACTURE_RIB_NUMBER')) {
2059 // set default bank account from invoice module settings
2060 $invoice->fk_account = (int) getDolGlobalString('FACTURE_RIB_NUMBER');
2061 }
2062 //set customer's payment method on the invoice
2063 if (!empty($customer->mode_reglement_id)) {
2064 $invoice->mode_reglement_id = $customer->mode_reglement_id;
2065 }
2066 //$invoice->date = $datesubscription;
2067 $invoice->date = dol_now();
2068
2069 // Possibility to add external linked objects with hooks
2070 $invoice->linked_objects['subscription'] = $subscriptionid;
2071 if (GETPOSTISARRAY('other_linked_objects')) {
2072 $invoice->linked_objects = array_merge($invoice->linked_objects, GETPOST('other_linked_objects', 'array:int'));
2073 }
2074
2075 $result = $invoice->create($user);
2076 if ($result <= 0) {
2077 $this->setErrorsFromObject($invoice);
2078 $error++;
2079 } else {
2080 $this->invoice = $invoice;
2081 }
2082 }
2083
2084 if (!$error) {
2085 // Add line to draft invoice
2086 $idprodsubscription = 0;
2087 if (getDolGlobalString('ADHERENT_PRODUCT_ID_FOR_SUBSCRIPTIONS') && (isModEnabled("product") || isModEnabled("service"))) {
2088 $idprodsubscription = getDolGlobalString('ADHERENT_PRODUCT_ID_FOR_SUBSCRIPTIONS');
2089 }
2090
2091 $vattouse = 0;
2092 if (getDolGlobalString('ADHERENT_VAT_FOR_SUBSCRIPTIONS') == 'defaultforfoundationcountry') {
2093 $vattouse = get_default_tva($mysoc, $mysoc, $idprodsubscription);
2094 }
2095 //print xx".$vattouse." - ".$mysoc." - ".$customer;exit;
2096 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
2097 $result = $invoice->addline($label, 0, 1, $vattouse, 0, 0, $idprodsubscription, 0, $datesubscription, '', 0, 0, 0, 'TTC', $amount, 1);
2098 if ($result <= 0) {
2099 $this->setErrorsFromObject($invoice);
2100 $error++;
2101 }
2102 }
2103
2104 if (!$error) {
2105 // Validate invoice
2106 $result = $invoice->validate($user);
2107 if ($result <= 0) {
2108 $this->setErrorsFromObject($invoice);
2109 $error++;
2110 }
2111 }
2112
2113 if (!$error) {
2114 // TODO Link invoice with subscription ?
2115 }
2116
2117 // Add payment onto invoice
2118 if (!$error && $option == 'bankviainvoice' && $accountid) {
2119 require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
2120 require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
2121 require_once DOL_DOCUMENT_ROOT.'/core/lib/functions.lib.php';
2122
2123 $amounts = array();
2124 $amounts[$invoice->id] = (float) price2num($amount);
2125
2126 $paiement = new Paiement($this->db);
2127 $paiement->datepaye = $paymentdate;
2128 $paiement->amounts = $amounts;
2129 $paiement->paiementcode = $operation;
2130 $paiement->paiementid = dol_getIdFromCode($this->db, $operation, 'c_paiement', 'code', 'id', 1);
2131 $paiement->num_payment = $num_chq;
2132 $paiement->note_public = $label;
2133 $paiement->ext_payment_id = $ext_payment_id;
2134 $paiement->ext_payment_site = $ext_payment_site;
2135
2136 // Create payment line for invoice
2137 $paiement_id = $paiement->create($user);
2138 if (!($paiement_id > 0)) {
2139 $this->setErrorsFromObject($paiement);
2140 $error++;
2141 }
2142
2143 if (!$error) {
2144 // Add transaction into bank account
2145 $bank_line_id = $paiement->addPaymentToBank($user, 'payment', '(SubscriptionPayment)', $accountid, $emetteur_nom, $emetteur_banque);
2146 if (!($bank_line_id > 0)) {
2147 $this->setErrorsFromObject($paiement);
2148 $error++;
2149 }
2150 }
2151
2152 if (!$error && !empty($bank_line_id)) {
2153 // Update fk_bank into subscription table
2154 $sql = 'UPDATE '.MAIN_DB_PREFIX.'subscription SET fk_bank='.((int) $bank_line_id);
2155 $sql .= ' WHERE rowid='.((int) $subscriptionid);
2156
2157 $result = $this->db->query($sql);
2158 if (!$result) {
2159 $error++;
2160 }
2161 }
2162
2163 if (!$error) {
2164 // Set invoice as paid
2165 $invoice->setPaid($user);
2166 }
2167 }
2168
2169 if (!$error) {
2170 // Define output language
2171 $outputlangs = $langs;
2172 $newlang = '';
2173 $lang_id = GETPOST('lang_id');
2174 if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && !empty($lang_id)) {
2175 $newlang = $lang_id;
2176 }
2177 if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
2178 $newlang = $customer->default_lang;
2179 }
2180 if (!empty($newlang)) {
2181 $outputlangs = new Translate("", $conf);
2182 $outputlangs->setDefaultLang($newlang);
2183 }
2184 // Generate PDF (whatever is option MAIN_DISABLE_PDF_AUTOUPDATE) so we can include it into email
2185 //if (!getDolGlobalString('MAIN_DISABLE_PDF_AUTOUPDATE'))
2186
2187 $invoice->fetch($invoice->id); // Reload invoice object data
2188 $invoice->generateDocument($invoice->model_pdf, $outputlangs);
2189 }
2190 }
2191
2192 if ($error) {
2193 return -1;
2194 } else {
2195 return 1;
2196 }
2197 }
2198
2199
2206 public function validate($user)
2207 {
2208 global $langs, $conf;
2209
2210 $error = 0;
2211 $now = dol_now();
2212
2213 // Check parameters
2214 if ($this->statut == self::STATUS_VALIDATED) {
2215 dol_syslog(get_class($this)."::validate statut of member does not allow this", LOG_WARNING);
2216 return 0;
2217 }
2218
2219 $this->db->begin();
2220
2221 $sql = "UPDATE ".MAIN_DB_PREFIX."adherent SET";
2222 $sql .= " statut = ".self::STATUS_VALIDATED;
2223 $sql .= ", datevalid = '".$this->db->idate($now)."'";
2224 $sql .= ", fk_user_valid = ".((int) $user->id);
2225 $sql .= " WHERE rowid = ".((int) $this->id);
2226
2227 dol_syslog(get_class($this)."::validate", LOG_DEBUG);
2228 $result = $this->db->query($sql);
2229 if ($result) {
2230 $this->statut = self::STATUS_VALIDATED;
2231
2232 // Call trigger
2233 $result = $this->call_trigger('MEMBER_VALIDATE', $user);
2234 if ($result < 0) {
2235 $error++;
2236 $this->db->rollback();
2237 return -1;
2238 }
2239 // End call triggers
2240
2241 $this->datevalid = $now;
2242
2243 $this->db->commit();
2244 return 1;
2245 } else {
2246 $this->error = $this->db->error();
2247 $this->db->rollback();
2248 return -1;
2249 }
2250 }
2251
2252
2259 public function resiliate($user)
2260 {
2261 global $langs, $conf;
2262
2263 $error = 0;
2264
2265 // Check parameters
2266 if ($this->statut == self::STATUS_RESILIATED) {
2267 dol_syslog(get_class($this)."::resiliate statut of member does not allow this", LOG_WARNING);
2268 return 0;
2269 }
2270
2271 $this->db->begin();
2272
2273 $sql = "UPDATE ".MAIN_DB_PREFIX."adherent SET";
2274 $sql .= " statut = ".((int) self::STATUS_RESILIATED);
2275 $sql .= ", fk_user_valid = ".((int) $user->id);
2276 $sql .= " WHERE rowid = ".((int) $this->id);
2277
2278 $result = $this->db->query($sql);
2279 if ($result) {
2280 $this->statut = self::STATUS_RESILIATED;
2281
2282 // Call trigger
2283 $result = $this->call_trigger('MEMBER_RESILIATE', $user);
2284 if ($result < 0) {
2285 $error++;
2286 $this->db->rollback();
2287 return -1;
2288 }
2289 // End call triggers
2290
2291 $this->db->commit();
2292 return 1;
2293 } else {
2294 $this->error = $this->db->error();
2295 $this->db->rollback();
2296 return -1;
2297 }
2298 }
2299
2309 public function exclude($user)
2310 {
2311 $error = 0;
2312
2313 // Check parameters
2314 if ($this->statut == self::STATUS_EXCLUDED) {
2315 dol_syslog(get_class($this)."::resiliate statut of member does not allow this", LOG_WARNING);
2316 return 0;
2317 }
2318
2319 $this->db->begin();
2320
2321 $sql = "UPDATE ".MAIN_DB_PREFIX."adherent SET";
2322 $sql .= " statut = ".((int) self::STATUS_EXCLUDED);
2323 $sql .= ", fk_user_valid = ".((int) $user->id);
2324 $sql .= " WHERE rowid = ".((int) $this->id);
2325
2326 $result = $this->db->query($sql);
2327 if ($result) {
2328 $this->statut = self::STATUS_EXCLUDED;
2329
2330 // Call trigger
2331 $result = $this->call_trigger('MEMBER_EXCLUDE', $user);
2332 if ($result < 0) {
2333 $error++;
2334 $this->db->rollback();
2335 return -1;
2336 }
2337 // End call triggers
2338
2339 $this->db->commit();
2340 return 1;
2341 } else {
2342 $this->error = $this->db->error();
2343 $this->db->rollback();
2344 return -1;
2345 }
2346 }
2347
2348 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2354 public function add_to_abo()
2355 {
2356 // phpcs:enable
2357 global $langs;
2358
2359 include_once DOL_DOCUMENT_ROOT.'/mailmanspip/class/mailmanspip.class.php';
2360 $mailmanspip = new MailmanSpip($this->db);
2361
2362 $err = 0;
2363
2364 // mailman
2365 if (getDolGlobalString('ADHERENT_USE_MAILMAN') && isModEnabled('mailmanspip')) {
2366 $result = $mailmanspip->add_to_mailman($this);
2367
2368 if ($result < 0) {
2369 if (!empty($mailmanspip->error)) {
2370 $this->errors[] = $mailmanspip->error;
2371 }
2372 $err += 1;
2373 }
2374 foreach ($mailmanspip->mladded_ko as $tmplist => $tmpemail) {
2375 $langs->load("errors");
2376 $this->errors[] = $langs->trans("ErrorFailedToAddToMailmanList", $tmpemail, $tmplist);
2377 }
2378 foreach ($mailmanspip->mladded_ok as $tmplist => $tmpemail) {
2379 $langs->load("mailmanspip");
2380 $this->mesgs[] = $langs->trans("SuccessToAddToMailmanList", $tmpemail, $tmplist);
2381 }
2382 }
2383
2384 // spip
2385 if (getDolGlobalString('ADHERENT_USE_SPIP') && isModEnabled('mailmanspip')) {
2386 $result = $mailmanspip->add_to_spip($this);
2387 if ($result < 0) {
2388 $this->errors[] = $mailmanspip->error;
2389 $err += 1;
2390 }
2391 }
2392 if ($err) {
2393 return -$err;
2394 } else {
2395 return 1;
2396 }
2397 }
2398
2399
2400 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2406 public function del_to_abo()
2407 {
2408 // phpcs:enable
2409 global $conf, $langs;
2410
2411 include_once DOL_DOCUMENT_ROOT.'/mailmanspip/class/mailmanspip.class.php';
2412 $mailmanspip = new MailmanSpip($this->db);
2413
2414 $err = 0;
2415
2416 // mailman
2417 if (getDolGlobalString('ADHERENT_USE_MAILMAN')) {
2418 $result = $mailmanspip->del_to_mailman($this);
2419 if ($result < 0) {
2420 if (!empty($mailmanspip->error)) {
2421 $this->errors[] = $mailmanspip->error;
2422 }
2423 $err += 1;
2424 }
2425
2426 foreach ($mailmanspip->mlremoved_ko as $tmplist => $tmpemail) {
2427 $langs->load("errors");
2428 $this->errors[] = $langs->trans("ErrorFailedToRemoveToMailmanList", $tmpemail, $tmplist);
2429 }
2430 foreach ($mailmanspip->mlremoved_ok as $tmplist => $tmpemail) {
2431 $langs->load("mailmanspip");
2432 $this->mesgs[] = $langs->trans("SuccessToRemoveToMailmanList", $tmpemail, $tmplist);
2433 }
2434 }
2435
2436 if (getDolGlobalString('ADHERENT_USE_SPIP') && isModEnabled('mailmanspip')) {
2437 $result = $mailmanspip->del_to_spip($this);
2438 if ($result < 0) {
2439 $this->errors[] = $mailmanspip->error;
2440 $err += 1;
2441 }
2442 }
2443 if ($err) {
2444 // error
2445 return -$err;
2446 } else {
2447 return 1;
2448 }
2449 }
2450
2451
2457 public function getCivilityLabel()
2458 {
2459 global $langs;
2460 $langs->load("dict");
2461
2462 $code = (empty($this->civility_id) ? '' : $this->civility_id);
2463 if (empty($code)) {
2464 return '';
2465 }
2466 return $langs->getLabelFromKey($this->db, "Civility".$code, "c_civility", "code", "label", $code);
2467 }
2468
2475 public function getTooltipContentArray($params)
2476 {
2477 global $langs;
2478
2479 $langs->loadLangs(['members', 'companies']);
2480 $nofetch = !empty($params['nofetch']);
2481
2482 $datas = array();
2483
2484 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
2485 $langs->load("users");
2486 return ['optimize' => $langs->trans("ShowUser")];
2487 }
2488 if (!empty($this->photo)) {
2489 $photo = '<div class="photointooltip floatright">';
2490 $photo .= Form::showphoto('memberphoto', $this, 80, 0, 0, 'photoref photowithmargin photologintooltip', 'small', 0, 1);
2491 $photo .= '</div>';
2492 $datas['photo'] = $photo;
2493 }
2494
2495 $datas['divopen'] = '<div class="centpercent">';
2496 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Member").'</u> '.$this->getLibStatut(4);
2497 if (!empty($this->morphy)) {
2498 $datas['picto'] .= '&nbsp;' . $this->getmorphylib('', 1);
2499 }
2500 if (!empty($this->ref)) {
2501 $datas['ref'] = '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref;
2502 }
2503 if (!empty($this->login)) {
2504 $datas['login'] = '<br><b>'.$langs->trans('Login').':</b> '.$this->login;
2505 }
2506 if (!empty($this->firstname) || !empty($this->lastname)) {
2507 $datas['name'] = '<br><b>'.$langs->trans('Name').':</b> '.$this->getFullName($langs);
2508 }
2509 if (!empty($this->company)) {
2510 $datas['company'] = '<br><b>'.$langs->trans('Company').':</b> '.$this->company;
2511 }
2512 if (!empty($this->email)) {
2513 $datas['email'] = '<br><b>'.$langs->trans("EMail").':</b> '.$this->email;
2514 }
2515 $datas['address'] = '<br><b>'.$langs->trans("Address").':</b> '.dol_format_address($this, 1, ' ', $langs);
2516 // show categories for this record only in ajax to not overload lists
2517 if (isModEnabled('category') && !$nofetch) {
2518 require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
2519 $form = new Form($this->db);
2520 $datas['categories'] = '<br>' . $form->showCategories($this->id, Categorie::TYPE_MEMBER, 1);
2521 }
2522 $datas['divclose'] = '</div>';
2523
2524 return $datas;
2525 }
2526
2540 public function getNomUrl($withpictoimg = 0, $maxlen = 0, $option = 'card', $mode = '', $morecss = '', $save_lastsearch_value = -1, $notooltip = 0, $addlinktonotes = 0)
2541 {
2542 global $conf, $langs, $hookmanager;
2543
2544 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER') && $withpictoimg) {
2545 $withpictoimg = 0;
2546 }
2547
2548 $result = '';
2549 $linkstart = '';
2550 $linkend = '';
2551 $classfortooltip = 'classfortooltip';
2552 $dataparams = '';
2553 $params = [
2554 'id' => $this->id,
2555 'objecttype' => $this->element,
2556 'option' => $option,
2557 'nofetch' => 1,
2558 ];
2559 if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
2560 $classfortooltip = 'classforajaxtooltip';
2561 $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
2562 $label = '';
2563 } else {
2564 $label = implode($this->getTooltipContentArray($params));
2565 }
2566
2567 $baseurl = DOL_URL_ROOT . '/adherents/card.php';
2568 if ($option == 'subscription') {
2569 $baseurl = DOL_URL_ROOT . '/adherents/subscription.php';
2570 }
2571 $query = ['rowid' => $this->id];
2572
2573 if ($option != 'nolink') {
2574 // Add param to save lastsearch_values or not
2575 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
2576 if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
2577 $add_save_lastsearch_values = 1;
2578 }
2579 if ($add_save_lastsearch_values) {
2580 $query = array_merge($query, ['save_lastsearch_values' => 1]);
2581 }
2582 }
2583 $url = dolBuildUrl($baseurl, $query);
2584
2585 $linkstart .= '<a href="'.$url.'"';
2586 $linkclose = "";
2587 if (empty($notooltip)) {
2588 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
2589 $langs->load("users");
2590 $label = $langs->trans("ShowUser");
2591 $linkclose .= ' alt="'.dolPrintHTMLForAttribute($label).'"';
2592 }
2593 $linkclose .= ($label ? ' title="'.dolPrintHTMLForAttribute($label).'"' : ' title="tocomplete"');
2594 $linkclose .= $dataparams.' class="'.$classfortooltip.($morecss ? ' '.$morecss : '').'"';
2595 }
2596
2597 $linkstart .= $linkclose.'>';
2598 $linkend = '</a>';
2599
2600 $result .= $linkstart;
2601
2602 if ($withpictoimg) {
2603 if (abs($withpictoimg) == 1 || abs($withpictoimg) == 4) {
2604 $morecss .= ' paddingrightonly';
2605 }
2606 // Only picto
2607 if ($withpictoimg > 0) {
2608 $picto = '<span class="nopadding'.($morecss ? ' userimg'.$morecss : '').'">'.img_object('', 'user', ' '.($notooltip ? '' : $dataparams), 0, 0, $notooltip ? 0 : 1).'</span>';
2609 } else {
2610 // Picto must be a photo
2611 $picto = '<span class="nopadding'.($morecss ? ' userimg'.$morecss : '').'">';
2612 $picto .= Form::showphoto('memberphoto', $this, 0, 0, 0, 'userphoto'.(($withpictoimg == -3 || $withpictoimg == -4) ? 'small' : ''), 'mini', 0, 1);
2613 $picto .= '</span>';
2614 }
2615 $result .= $picto;
2616 }
2617 if (($withpictoimg > -2 && $withpictoimg != 2) || $withpictoimg == -4) {
2618 if (!getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
2619 $result .= '<span class="nopadding valignmiddle'.((!isset($this->status) || $this->status) ? '' : ' strikefordisabled').
2620 ($morecss ? ' usertext'.$morecss : '').'">';
2621 }
2622 if ($mode == 'login') {
2623 $result .= dol_trunc(isset($this->login) ? $this->login : '', $maxlen);
2624 } elseif ($mode == 'ref') {
2625 $result .= $this->ref;
2626 } else {
2627 $result .= $this->getFullName($langs, 0, ($mode == 'firstname' ? 2 : ($mode == 'lastname' ? 4 : -1)), $maxlen);
2628 }
2629 if (!getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
2630 $result .= '</span>';
2631 }
2632 }
2633
2634 $result .= $linkend;
2635
2636 if ($addlinktonotes) {
2637 if ($this->note_private) {
2638 $notetoshow = $langs->trans("ViewPrivateNote").':<br>'.dol_string_nohtmltag($this->note_private, 1);
2639 $result .= ' <span class="note inline-block">';
2640 $result .= '<a href="'.DOL_URL_ROOT.'/adherents/note.php?id='.$this->id.'" class="classfortooltip" title="'.dol_escape_htmltag($notetoshow).'">';
2641 $result .= img_picto('', 'note');
2642 $result .= '</a>';
2643 $result .= '</span>';
2644 }
2645 }
2646 global $action;
2647 $hookmanager->initHooks(array($this->element . 'dao'));
2648 $parameters = array('id' => $this->id, 'getnomurl' => &$result);
2649 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
2650 if ($reshook > 0) {
2651 $result = $hookmanager->resPrint;
2652 } else {
2653 $result .= $hookmanager->resPrint;
2654 }
2655 return $result;
2656 }
2657
2664 public function getLibStatut($mode = 0)
2665 {
2666 return $this->LibStatut($this->status, $this->need_subscription, $this->datefin, $mode);
2667 }
2668
2669 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2679 public function LibStatut($status, $need_subscription, $date_end_subscription, $mode = 0)
2680 {
2681 // phpcs:enable
2682 global $langs;
2683 $langs->load("members");
2684
2685 $statusType = '';
2686 $labelStatus = '';
2687 $labelStatusShort = '';
2688
2689 if ($status == self::STATUS_DRAFT) {
2690 $statusType = 'status0';
2691 $labelStatus = $langs->trans("MemberStatusDraft");
2692 $labelStatusShort = $langs->trans("MemberStatusDraftShort");
2693 } elseif ($status >= self::STATUS_VALIDATED) {
2694 if (empty($need_subscription)) {
2695 $statusType = 'status4';
2696 $labelStatus = $langs->trans("Validated").' - '.$langs->trans("SubscriptionNotNeeded");
2697 $labelStatusShort = $langs->trans("MemberStatusNoSubscriptionShort");
2698 } elseif (!$date_end_subscription) {
2699 $statusType = 'status1';
2700 $labelStatus = $langs->trans("Validated").' - '.$langs->trans("WaitingSubscription");
2701 $labelStatusShort = $langs->trans("WaitingSubscriptionShort");
2702 } elseif ($date_end_subscription < dol_now()) { // expired
2703 $statusType = 'status2';
2704 $labelStatus = $langs->trans("Validated").' - '.$langs->trans("MemberStatusActiveLate");
2705 $labelStatusShort = $langs->trans("MemberStatusActiveLateShort");
2706 } else {
2707 $statusType = 'status4';
2708 $labelStatus = $langs->trans("Validated").' - '.$langs->trans("MemberStatusPaid");
2709 $labelStatusShort = $langs->trans("MemberStatusPaidShort");
2710 }
2711 } elseif ($status == self::STATUS_RESILIATED) {
2712 $statusType = 'status6';
2713 $labelStatus = $langs->transnoentitiesnoconv("MemberStatusResiliated");
2714 $labelStatusShort = $langs->transnoentitiesnoconv("MemberStatusResiliatedShort");
2715 } elseif ($status == self::STATUS_EXCLUDED) {
2716 $statusType = 'status10';
2717 $labelStatus = $langs->transnoentitiesnoconv("MemberStatusExcluded");
2718 $labelStatusShort = $langs->transnoentitiesnoconv("MemberStatusExcludedShort");
2719 }
2720
2721 return dolGetStatus($labelStatus, $labelStatusShort, '', $statusType, $mode);
2722 }
2723
2724
2730 public function loadStateBoard()
2731 {
2732 global $conf;
2733
2734 $this->nb = array();
2735
2736 $sql = "SELECT count(a.rowid) as nb";
2737 $sql .= " FROM ".MAIN_DB_PREFIX."adherent as a";
2738 $sql .= " WHERE a.statut > 0";
2739 $sql .= " AND a.entity IN (".getEntity('adherent').")";
2740
2741 $resql = $this->db->query($sql);
2742 if ($resql) {
2743 while ($obj = $this->db->fetch_object($resql)) {
2744 $this->nb["members"] = $obj->nb;
2745 }
2746 $this->db->free($resql);
2747 return 1;
2748 } else {
2749 dol_print_error($this->db);
2750 $this->error = $this->db->error();
2751 return -1;
2752 }
2753 }
2754
2755 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2763 public function load_board($user, $mode)
2764 {
2765 // phpcs:enable
2766 global $conf, $langs;
2767
2768 if ($user->socid) {
2769 return -1; // protection pour eviter appel par utilisateur externe
2770 }
2771
2772 $now = dol_now();
2773
2774 $sql = "SELECT a.rowid, a.datefin, a.statut as status";
2775 $sql .= " FROM ".MAIN_DB_PREFIX."adherent as a";
2776 $sql .= ", ".MAIN_DB_PREFIX."adherent_type as t";
2777 $sql .= " WHERE a.fk_adherent_type = t.rowid";
2778 if ($mode == 'expired') {
2779 $sql .= " AND a.statut = ".self::STATUS_VALIDATED;
2780 $sql .= " AND a.entity IN (".getEntity('adherent').")";
2781 $sql .= " AND ((a.datefin IS NULL or a.datefin < '".$this->db->idate($now)."') AND t.subscription = '1')";
2782 } elseif ($mode == 'shift') {
2783 $sql .= " AND a.statut = ".self::STATUS_DRAFT;
2784 $sql .= " AND a.entity IN (".getEntity('adherent').")";
2785 }
2786
2787 $resql = $this->db->query($sql);
2788 if ($resql) {
2789 $langs->load("members");
2790
2791 $warning_delay = 0;
2792 $url = '';
2793 $label = '';
2794 $labelShort = '';
2795
2796 if ($mode == 'expired') {
2797 $warning_delay = getWarningDelay('member', 'subscription') / 60 / 60 / 24;
2798 $label = $langs->trans("MembersWithSubscriptionToReceive");
2799 $labelShort = $langs->trans("MembersWithSubscriptionToReceiveShort");
2800 $url = dolBuildUrl(DOL_URL_ROOT.'/adherents/list.php', ['mainmenu' => 'members', 'statut' => self::STATUS_VALIDATED, 'filter' => 'outofdate']);
2801 } elseif ($mode == 'shift') {
2802 $warning_delay = getWarningDelay('member', 'subscription') / 60 / 60 / 24;
2803 $url = dolBuildUrl(DOL_URL_ROOT.'/adherents/list.php', ['mainmenu' => 'members', 'statut' => self::STATUS_DRAFT]);
2804 $label = $langs->trans("MembersListToValid");
2805 $labelShort = $langs->trans("ToValidate");
2806 }
2807
2808 $response = new WorkboardResponse();
2809 $response->warning_delay = $warning_delay;
2810 $response->label = $label;
2811 $response->labelShort = $labelShort;
2812 $response->url = $url;
2813 $response->img = img_object('', "user");
2814
2815 $adherentstatic = new Adherent($this->db);
2816
2817 while ($obj = $this->db->fetch_object($resql)) {
2818 $response->nbtodo++;
2819
2820 $adherentstatic->datefin = $this->db->jdate($obj->datefin);
2821 $adherentstatic->statut = $obj->status;
2822 $adherentstatic->status = $obj->status;
2823
2824 if ($adherentstatic->hasDelay()) {
2825 $response->nbtodolate++;
2826 }
2827 }
2828
2829 return $response;
2830 } else {
2831 dol_print_error($this->db);
2832 $this->error = $this->db->error();
2833 return -1;
2834 }
2835 }
2836
2837
2849 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
2850 {
2851 global $conf, $langs;
2852
2853 $langs->load("orders");
2854
2855 if (!dol_strlen($modele)) {
2856 $modele = 'standard';
2857
2858 if ($this->model_pdf) {
2859 $modele = $this->model_pdf;
2860 } elseif (getDolGlobalString('ADHERENT_ADDON_PDF')) {
2861 $modele = getDolGlobalString('ADHERENT_ADDON_PDF');
2862 }
2863 }
2864
2865 $modelpath = "core/modules/member/doc/";
2866
2867 return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
2868 }
2869
2870
2878 public function initAsSpecimen()
2879 {
2880 global $user, $langs;
2881 $now = dol_now();
2882
2883 // Initialise parameters
2884 $this->id = 0;
2885 $this->ref = 'ABC001';
2886 $this->entity = 1;
2887 $this->specimen = 1;
2888 $this->civility_id = 'MR';
2889 $this->lastname = 'DOLIBARR';
2890 $this->firstname = 'SPECIMEN';
2891 $this->gender = 'man';
2892 $this->login = 'dolibspec';
2893 $this->pass = 'dolibspec';
2894 $this->company = 'Societe ABC';
2895 $this->address = '61 jump street';
2896 $this->zip = '75000';
2897 $this->town = 'Paris';
2898 $this->country_id = 1;
2899 $this->country_code = 'FR';
2900 $this->country = 'France';
2901 $this->morphy = 'mor';
2902 $this->email = 'specimen@specimen.com';
2903 $this->socialnetworks = array(
2904 'skype' => 'skypepseudo',
2905 'twitter' => 'twitterpseudo',
2906 'facebook' => 'facebookpseudo',
2907 'linkedin' => 'linkedinpseudo',
2908 );
2909 $this->phone = '0999999999';
2910 $this->phone_perso = '0999999998';
2911 $this->phone_mobile = '0999999997';
2912 $this->note_public = 'This is a public note';
2913 $this->note_private = 'This is a private note';
2914 $this->birth = $now;
2915 $this->photo = '';
2916 $this->public = 1;
2917 $this->statut = self::STATUS_DRAFT;
2918 $this->status = self::STATUS_DRAFT;
2919
2920 $this->datefin = $now;
2921 $this->datevalid = $now;
2922 $this->default_lang = '';
2923
2924 $this->typeid = 1; // Id type adherent
2925 $this->type = 'Type adherent'; // Libelle type adherent
2926 $this->need_subscription = 0;
2927
2928 $this->first_subscription_date = $now;
2929 $this->first_subscription_date_start = $this->first_subscription_date;
2930 $this->first_subscription_date_end = dol_time_plus_duree($this->first_subscription_date_start, 1, 'y');
2931 $this->first_subscription_amount = 10;
2932
2933 $this->last_subscription_date = $this->first_subscription_date;
2934 $this->last_subscription_date_start = $this->first_subscription_date;
2935 $this->last_subscription_date_end = dol_time_plus_duree($this->last_subscription_date_start, 1, 'y');
2936 $this->last_subscription_amount = 10;
2937 return 1;
2938 }
2939
2940
2941 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2942 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
2952 public function _load_ldap_dn($info, $mode = 0)
2953 {
2954 // phpcs:enable
2955 global $conf;
2956 $dn = '';
2957 if ($mode == 0) {
2958 $dn = getDolGlobalString('LDAP_KEY_MEMBERS') . "=".$info[getDolGlobalString('LDAP_KEY_MEMBERS')]."," . getDolGlobalString('LDAP_MEMBER_DN');
2959 }
2960 if ($mode == 1) {
2961 $dn = getDolGlobalString('LDAP_MEMBER_DN');
2962 }
2963 if ($mode == 2) {
2964 $dn = getDolGlobalString('LDAP_KEY_MEMBERS') . "=".$info[getDolGlobalString('LDAP_KEY_MEMBERS')];
2965 }
2966 return $dn;
2967 }
2968
2969
2970 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2971 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
2977 public function _load_ldap_info()
2978 {
2979 // phpcs:enable
2980 global $conf, $langs;
2981
2982 $info = array();
2983 $socialnetworks = getArrayOfSocialNetworks();
2984 $keymodified = false;
2985
2986 // Object classes
2987 $info["objectclass"] = explode(',', getDolGlobalString('LDAP_MEMBER_OBJECT_CLASS'));
2988
2989 $this->fullname = $this->getFullName($langs);
2990
2991 // For avoid ldap error when firstname and lastname are empty
2992 if ($this->morphy == 'mor' && (empty($this->fullname) || $this->fullname == $this->company)) {
2993 $this->fullname = $this->company;
2994 $this->lastname = $this->company;
2995 }
2996
2997 // Possible LDAP KEY (constname => varname)
2998 $ldapkey = array(
2999 'LDAP_MEMBER_FIELD_FULLNAME' => 'fullname',
3000 'LDAP_MEMBER_FIELD_NAME' => 'lastname',
3001 'LDAP_MEMBER_FIELD_LOGIN' => 'login',
3002 'LDAP_MEMBER_FIELD_LOGIN_SAMBA' => 'login',
3003 'LDAP_MEMBER_FIELD_MAIL' => 'email'
3004 );
3005
3006 // Member
3007 foreach ($ldapkey as $constname => $varname) {
3008 if (!empty($this->$varname) && getDolGlobalString($constname)) {
3009 $info[getDolGlobalString($constname)] = $this->$varname;
3010
3011 // Check if it is the LDAP key and if its value has been changed
3012 if (getDolGlobalString('LDAP_KEY_MEMBERS') && getDolGlobalString('LDAP_KEY_MEMBERS') == getDolGlobalString($constname)) {
3013 if (!empty($this->oldcopy) && $this->$varname != $this->oldcopy->$varname) {
3014 $keymodified = true; // For check if LDAP key has been modified
3015 }
3016 }
3017 }
3018 }
3019 if ($this->firstname && getDolGlobalString('LDAP_MEMBER_FIELD_FIRSTNAME')) {
3020 $info[getDolGlobalString('LDAP_MEMBER_FIELD_FIRSTNAME')] = $this->firstname;
3021 }
3022 if ($this->poste && getDolGlobalString('LDAP_MEMBER_FIELD_TITLE')) {
3023 $info[getDolGlobalString('LDAP_MEMBER_FIELD_TITLE')] = $this->poste;
3024 }
3025 if ($this->company && getDolGlobalString('LDAP_MEMBER_FIELD_COMPANY')) {
3026 $info[getDolGlobalString('LDAP_MEMBER_FIELD_COMPANY')] = $this->company;
3027 }
3028 if ($this->address && getDolGlobalString('LDAP_MEMBER_FIELD_ADDRESS')) {
3029 $info[getDolGlobalString('LDAP_MEMBER_FIELD_ADDRESS')] = $this->address;
3030 }
3031 if ($this->zip && getDolGlobalString('LDAP_MEMBER_FIELD_ZIP')) {
3032 $info[getDolGlobalString('LDAP_MEMBER_FIELD_ZIP')] = $this->zip;
3033 }
3034 if ($this->town && getDolGlobalString('LDAP_MEMBER_FIELD_TOWN')) {
3035 $info[getDolGlobalString('LDAP_MEMBER_FIELD_TOWN')] = $this->town;
3036 }
3037 if ($this->country_code && getDolGlobalString('LDAP_MEMBER_FIELD_COUNTRY')) {
3038 $info[getDolGlobalString('LDAP_MEMBER_FIELD_COUNTRY')] = $this->country_code;
3039 }
3040 foreach ($socialnetworks as $key => $value) {
3041 if ($this->socialnetworks[$value['label']] && getDolGlobalString('LDAP_MEMBER_FIELD_'.strtoupper($value['label']))) {
3042 $info[getDolGlobalString('LDAP_MEMBER_FIELD_'.strtoupper($value['label']))] = $this->socialnetworks[$value['label']];
3043 }
3044 }
3045 if ($this->phone && getDolGlobalString('LDAP_MEMBER_FIELD_PHONE')) {
3046 $info[getDolGlobalString('LDAP_MEMBER_FIELD_PHONE')] = $this->phone;
3047 }
3048 if ($this->phone_perso && getDolGlobalString('LDAP_MEMBER_FIELD_PHONE_PERSO')) {
3049 $info[getDolGlobalString('LDAP_MEMBER_FIELD_PHONE_PERSO')] = $this->phone_perso;
3050 }
3051 if ($this->phone_mobile && getDolGlobalString('LDAP_MEMBER_FIELD_MOBILE')) {
3052 $info[getDolGlobalString('LDAP_MEMBER_FIELD_MOBILE')] = $this->phone_mobile;
3053 }
3054 if ($this->fax && getDolGlobalString('LDAP_MEMBER_FIELD_FAX')) {
3055 $info[getDolGlobalString('LDAP_MEMBER_FIELD_FAX')] = $this->fax;
3056 }
3057 if ($this->note_private && getDolGlobalString('LDAP_MEMBER_FIELD_DESCRIPTION')) {
3058 $info[getDolGlobalString('LDAP_MEMBER_FIELD_DESCRIPTION')] = dol_string_nohtmltag($this->note_private, 2);
3059 }
3060 if ($this->note_public && getDolGlobalString('LDAP_MEMBER_FIELD_NOTE_PUBLIC')) {
3061 $info[getDolGlobalString('LDAP_MEMBER_FIELD_NOTE_PUBLIC')] = dol_string_nohtmltag($this->note_public, 2);
3062 }
3063 if ($this->birth && getDolGlobalString('LDAP_MEMBER_FIELD_BIRTHDATE')) {
3064 $info[getDolGlobalString('LDAP_MEMBER_FIELD_BIRTHDATE')] = dol_print_date($this->birth, 'dayhourldap');
3065 }
3066 if (isset($this->statut) && getDolGlobalString('LDAP_FIELD_MEMBER_STATUS')) {
3067 $info[getDolGlobalString('LDAP_FIELD_MEMBER_STATUS')] = $this->statut;
3068 }
3069 if ($this->datefin && getDolGlobalString('LDAP_FIELD_MEMBER_END_LASTSUBSCRIPTION')) {
3070 $info[getDolGlobalString('LDAP_FIELD_MEMBER_END_LASTSUBSCRIPTION')] = dol_print_date($this->datefin, 'dayhourldap');
3071 }
3072
3073 // When password is modified
3074 if (!empty($this->pass)) {
3075 if (getDolGlobalString('LDAP_MEMBER_FIELD_PASSWORD')) {
3076 $info[getDolGlobalString('LDAP_MEMBER_FIELD_PASSWORD')] = $this->pass; // this->pass = Unencrypted password
3077 }
3078 if (getDolGlobalString('LDAP_MEMBER_FIELD_PASSWORD_CRYPTED')) {
3079 $info[getDolGlobalString('LDAP_MEMBER_FIELD_PASSWORD_CRYPTED')] = dol_hash($this->pass, 'openldap'); // Create OpenLDAP password (see LDAP_PASSWORD_HASH_TYPE)
3080 }
3081 } elseif (getDolGlobalString('LDAP_SERVER_PROTOCOLVERSION') !== '3') {
3082 // Set LDAP password if possible
3083 // If ldap key is modified and LDAPv3 we use ldap_rename function for avoid lose encrypt password
3084 if (getDolGlobalString('DATABASE_PWD_ENCRYPTED')) { // This should be on on default installation
3085 // Just for the case we use old md5 encryption (deprecated, no more used, kept for compatibility)
3086 if (!getDolGlobalString('MAIN_SECURITY_HASH_ALGO') || getDolGlobalString('MAIN_SECURITY_HASH_ALGO') == 'md5') {
3087 if ($this->pass_indatabase_crypted && getDolGlobalString('LDAP_MEMBER_FIELD_PASSWORD_CRYPTED')) {
3088 // Create OpenLDAP MD5 password from Dolibarr MD5 password
3089 // Note: This suppose that "pass_indatabase_crypted" is a md5 (this should not happen anymore)"
3090 $info[getDolGlobalString('LDAP_MEMBER_FIELD_PASSWORD_CRYPTED')] = dolGetLdapPasswordHash($this->pass_indatabase_crypted, 'md5frommd5');
3091 }
3092 }
3093 } elseif (!empty($this->pass_indatabase)) {
3094 // Use $this->pass_indatabase value if exists
3095 if (getDolGlobalString('LDAP_MEMBER_FIELD_PASSWORD')) {
3096 $info[getDolGlobalString('LDAP_MEMBER_FIELD_PASSWORD')] = $this->pass_indatabase; // $this->pass_indatabase = Unencrypted password
3097 }
3098 if (getDolGlobalString('LDAP_MEMBER_FIELD_PASSWORD_CRYPTED')) {
3099 $info[getDolGlobalString('LDAP_MEMBER_FIELD_PASSWORD_CRYPTED')] = dol_hash($this->pass_indatabase, 'openldap'); // Create OpenLDAP password (see LDAP_PASSWORD_HASH_TYPE)
3100 }
3101 }
3102 }
3103
3104 // Subscriptions
3105 if ($this->first_subscription_date && getDolGlobalString('LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_DATE')) {
3106 $info[getDolGlobalString('LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_DATE')] = dol_print_date($this->first_subscription_date, 'dayhourldap');
3107 }
3108 if (isset($this->first_subscription_amount) && getDolGlobalString('LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_AMOUNT')) {
3109 $info[getDolGlobalString('LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_AMOUNT')] = $this->first_subscription_amount;
3110 }
3111 if ($this->last_subscription_date && getDolGlobalString('LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_DATE')) {
3112 $info[getDolGlobalString('LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_DATE')] = dol_print_date($this->last_subscription_date, 'dayhourldap');
3113 }
3114 if (isset($this->last_subscription_amount) && getDolGlobalString('LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_AMOUNT')) {
3115 $info[getDolGlobalString('LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_AMOUNT')] = $this->last_subscription_amount;
3116 }
3117
3118 return $info;
3119 }
3120
3121
3128 public function info($id)
3129 {
3130 $sql = 'SELECT a.rowid, a.datec as datec,';
3131 $sql .= ' a.datevalid as datev,';
3132 $sql .= ' GREATEST(a.tms, COALESCE(aef.tms, a.tms)) as datem,';
3133 $sql .= ' a.fk_user_author, a.fk_user_valid, a.fk_user_mod';
3134 $sql .= ' FROM '.MAIN_DB_PREFIX.'adherent as a';
3135 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'adherent_extrafields as aef ON aef.fk_object = a.rowid';
3136 $sql .= ' WHERE a.rowid = '.((int) $id);
3137
3138 dol_syslog(get_class($this)."::info", LOG_DEBUG);
3139 $result = $this->db->query($sql);
3140 if ($result) {
3141 if ($this->db->num_rows($result)) {
3142 $obj = $this->db->fetch_object($result);
3143
3144 $this->id = $obj->rowid;
3145
3146 $this->user_creation_id = $obj->fk_user_author;
3147 $this->user_validation_id = $obj->fk_user_valid;
3148 $this->user_modification_id = $obj->fk_user_mod;
3149 $this->date_creation = $this->db->jdate($obj->datec);
3150 $this->date_validation = $this->db->jdate($obj->datev);
3151 $this->date_modification = $this->db->jdate($obj->datem);
3152 }
3153
3154 $this->db->free($result);
3155 } else {
3156 dol_print_error($this->db);
3157 }
3158 }
3159
3165 public function getNbOfEMailings()
3166 {
3167 $sql = "SELECT count(mc.email) as nb";
3168 $sql .= " FROM ".MAIN_DB_PREFIX."mailing_cibles as mc";
3169 $sql .= " WHERE mc.email = '".$this->db->escape($this->email)."'";
3170 $sql .= " AND mc.statut NOT IN (-1,0)"; // -1 erreur, 0 non envoye, 1 envoye avec success
3171
3172 $resql = $this->db->query($sql);
3173 if ($resql) {
3174 $obj = $this->db->fetch_object($resql);
3175 $nb = (int) $obj->nb;
3176
3177 $this->db->free($resql);
3178 return $nb;
3179 } else {
3180 $this->error = $this->db->error();
3181 return -1;
3182 }
3183 }
3184
3195 public function setCategories($categories)
3196 {
3197 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
3198 return parent::setCategoriesCommon($categories, Categorie::TYPE_MEMBER);
3199 }
3200
3209 public static function replaceThirdparty($db, $origin_id, $dest_id)
3210 {
3211 $tables = array('adherent');
3212
3213 return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
3214 }
3215
3221 public function hasDelay()
3222 {
3223 global $conf;
3224
3225 //Only valid members
3226 if ($this->status != self::STATUS_VALIDATED) {
3227 return false;
3228 }
3229 if (!$this->datefin) {
3230 return false;
3231 }
3232
3233 $now = dol_now();
3234
3235 return $this->datefin < ($now - getWarningDelay('member', 'subscription'));
3236 }
3237
3238
3247 public function sendReminderForExpiredSubscription($daysbeforeendlist = '10', $fk_adherent_type = 0)
3248 {
3249 global $conf, $langs, $mysoc, $user;
3250
3251 $error = 0;
3252 $this->output = '';
3253 $this->error = '';
3254
3255 $blockingerrormsg = '';
3256
3257 if (!isModEnabled('member')) { // Should not happen. If module disabled, cron job should not be visible.
3258 $langs->load("agenda");
3259 $this->output = $langs->trans('ModuleNotEnabled', $langs->transnoentitiesnoconv("Adherent"));
3260 return 0;
3261 }
3262 if (!getDolGlobalString('MEMBER_REMINDER_EMAIL')) {
3263 $langs->load("agenda");
3264 $this->output = $langs->trans('EventRemindersByEmailNotEnabled', $langs->transnoentitiesnoconv("Adherent"));
3265 return 0;
3266 }
3267
3268 $now = dol_now();
3269 $nbok = 0;
3270 $nbko = 0;
3271
3272 $listofmembersok = array();
3273 $listofmembersko = array();
3274
3275 $arraydaysbeforeend = explode(';', $daysbeforeendlist);
3276 foreach ($arraydaysbeforeend as $daysbeforeend) { // Loop on each delay
3277 dol_syslog(__METHOD__.' - Process delta = '.$daysbeforeend, LOG_DEBUG);
3278
3279 if (!is_numeric($daysbeforeend)) {
3280 $blockingerrormsg = "Value for delta is not a numeric value";
3281 $nbko++;
3282 break;
3283 }
3284
3285 $tmp = dol_getdate($now);
3286 $datetosearchfor = dol_time_plus_duree(dol_mktime(0, 0, 0, $tmp['mon'], $tmp['mday'], $tmp['year'], 'tzserver'), (int) $daysbeforeend, 'd');
3287 $datetosearchforend = dol_time_plus_duree(dol_mktime(23, 59, 59, $tmp['mon'], $tmp['mday'], $tmp['year'], 'tzserver'), (int) $daysbeforeend, 'd');
3288
3289 $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.'adherent';
3290 $sql .= " WHERE entity = ".((int) $conf->entity); // Do not use getEntity('adherent').")" here, we want the batch to be on its entity only;
3291 $sql .= " AND statut = 1";
3292 $sql .= " AND datefin >= '".$this->db->idate($datetosearchfor)."'";
3293 $sql .= " AND datefin <= '".$this->db->idate($datetosearchforend)."'";
3294 if ((int) $fk_adherent_type > 0) {
3295 $sql .= " AND fk_adherent_type = ".((int) $fk_adherent_type);
3296 }
3297 //$sql .= " LIMIT 10000";
3298
3299 $resql = $this->db->query($sql);
3300 if ($resql) {
3301 $num_rows = $this->db->num_rows($resql);
3302
3303 include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
3304 $formmail = new FormMail($this->db);
3305
3306 $i = 0;
3307 while ($i < $num_rows) {
3308 $obj = $this->db->fetch_object($resql);
3309
3310 // A new object for each member: fetch() does not reset the properties loaded for the previous member,
3311 // like ->thirdparty that would be reused for a member that has no third party.
3312 $adherent = new Adherent($this->db);
3313 $adherent->fetch($obj->rowid, '', 0, '', true, true);
3314
3315 if (empty($adherent->email)) {
3316 $nbko++;
3317 $listofmembersko[$adherent->id] = $adherent->id;
3318 } else {
3319 $thirdpartyres = $adherent->fetch_thirdparty();
3320 if ($thirdpartyres === -1) {
3321 $languagecodeformember = $mysoc->default_lang;
3322 } else {
3323 // 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.
3324 $languagefromcountrycode = getLanguageCodeFromCountryCode($adherent->country_code ? $adherent->country_code : (is_object($adherent->thirdparty) ? $adherent->thirdparty->country_code : ''));
3325 $languagecodeformember = (empty($adherent->thirdparty->default_lang) ? ($languagefromcountrycode ? $languagefromcountrycode : $mysoc->default_lang) : $adherent->thirdparty->default_lang);
3326 }
3327 if (!empty($adherent->default_lang)) {
3328 // The language set on the member itself has priority
3329 $languagecodeformember = $adherent->default_lang;
3330 }
3331
3332 // Send reminder email
3333 $outputlangs = new Translate('', $conf);
3334 $outputlangs->setDefaultLang($languagecodeformember);
3335 $outputlangs->loadLangs(array("main", "members"));
3336 dol_syslog("sendReminderForExpiredSubscription Language for member id ".$adherent->id." set to ".$outputlangs->defaultlang." mysoc->default_lang=".$mysoc->default_lang);
3337
3338 $arraydefaultmessage = null;
3339 $labeltouse = getDolGlobalString('ADHERENT_EMAIL_TEMPLATE_REMIND_EXPIRATION');
3340
3341 if (!empty($labeltouse)) {
3342 $arraydefaultmessage = $formmail->getEMailTemplate($this->db, 'member', $user, $outputlangs, 0, 1, $labeltouse);
3343 }
3344
3345 if (!empty($labeltouse) && is_object($arraydefaultmessage) && $arraydefaultmessage->id > 0) {
3346 $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $adherent);
3347 //if (is_array($adherent->thirdparty)) $substitutionarraycomp = ...
3348 complete_substitutions_array($substitutionarray, $outputlangs, $adherent);
3349
3350 $subject = make_substitutions($arraydefaultmessage->topic, $substitutionarray, $outputlangs);
3351 $msg = make_substitutions($arraydefaultmessage->content, $substitutionarray, $outputlangs);
3352 $from = getDolGlobalString('ADHERENT_MAIL_FROM', $conf->email_from);
3353 $to = $adherent->email;
3354 $cc = getDolGlobalString('ADHERENT_CC_MAIL_FROM');
3355
3356 $trackid = 'mem'.$adherent->id;
3357 $moreinheader = 'X-Dolibarr-Info: sendReminderForExpiredSubscription'."\r\n";
3358
3359 include_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
3360 $cmail = new CMailFile($subject, $to, $from, $msg, array(), array(), array(), $cc, '', 0, 1, '', '', $trackid, $moreinheader);
3361 $result = $cmail->sendfile();
3362 if (!$result) {
3363 $error++;
3364 $this->error .= $cmail->error.' ';
3365 if (!is_null($cmail->errors)) {
3366 $this->errors += $cmail->errors;
3367 }
3368 $nbko++;
3369 $listofmembersko[$adherent->id] = $adherent->id;
3370 } else {
3371 $nbok++;
3372 $listofmembersok[$adherent->id] = $adherent->id;
3373
3374 $message = $msg;
3375 $sendto = $to;
3376 $sendtocc = '';
3377 $sendtobcc = '';
3378 $actioncode = 'EMAIL';
3379 $extraparams = array();
3380
3381 $actionmsg = '';
3382 $actionmsg2 = $langs->transnoentities('MailSentByTo', CMailFile::getValidAddress($from, 4, 0, 1), CMailFile::getValidAddress($sendto, 4, 0, 1));
3383 if ($message) {
3384 $actionmsg = $langs->transnoentities('MailFrom').': '.dol_escape_htmltag($from);
3385 $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('MailTo').': '.dol_escape_htmltag($sendto));
3386 // if ($sendtocc) {
3387 // $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('Bcc').": ".dol_escape_htmltag($sendtocc));
3388 // }
3389 $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('MailTopic').": ".$subject);
3390 $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('TextUsedInTheMessageBody').":");
3391 $actionmsg = dol_concatdesc($actionmsg, $message);
3392 }
3393
3394 require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
3395
3396 // Insert record of emails sent
3397 $actioncomm = new ActionComm($this->db);
3398
3399 $actioncomm->type_code = 'AC_OTH_AUTO'; // Type of event ('AC_OTH', 'AC_OTH_AUTO', 'AC_XXX'...)
3400 $actioncomm->code = 'AC_'.$actioncode;
3401 $actioncomm->label = $actionmsg2;
3402 $actioncomm->note_private = $actionmsg;
3403 $actioncomm->fk_project = 0;
3404 $actioncomm->datep = $now;
3405 $actioncomm->datef = $now;
3406 $actioncomm->percentage = -1; // Not applicable
3407 $actioncomm->socid = (is_object($adherent->thirdparty) ? $adherent->thirdparty->id : 0);
3408 $actioncomm->contact_id = 0;
3409 $actioncomm->authorid = $user->id; // User saving action
3410 $actioncomm->userownerid = $user->id; // Owner of action
3411 // Fields when action is an email (content should be added into note)
3412 $actioncomm->email_msgid = $cmail->msgid;
3413 $actioncomm->email_from = $from;
3414 $actioncomm->email_sender = '';
3415 $actioncomm->email_to = $to;
3416 $actioncomm->email_tocc = $sendtocc;
3417 $actioncomm->email_tobcc = $sendtobcc;
3418 $actioncomm->email_subject = $subject;
3419 $actioncomm->errors_to = '';
3420
3421 $actioncomm->fk_element = $adherent->id;
3422 $actioncomm->elementid = $adherent->id;
3423 $actioncomm->elementtype = $adherent->element;
3424
3425 $actioncomm->extraparams = $extraparams;
3426
3427 $actioncomm->create($user);
3428 }
3429 } else {
3430 //$blockingerrormsg = "Can't find email template with label=".$labeltouse.", to use for the reminding email";
3431
3432 $error++;
3433 $this->error .= "Can't find email template with label=".$labeltouse.", to use for the reminding email ";
3434
3435 $nbko++;
3436 $listofmembersko[$adherent->id] = $adherent->id;
3437
3438 break;
3439 }
3440 }
3441
3442 $i++;
3443 }
3444 } else {
3445 $this->error = $this->db->lasterror();
3446 return 1;
3447 }
3448 }
3449
3450 if ($blockingerrormsg) {
3451 $this->error = $blockingerrormsg;
3452 return 1;
3453 } else {
3454 $this->output = 'Found '.($nbok + $nbko).' members to send reminder to.';
3455 $this->output .= ' Send email successfully to '.$nbok.' members';
3456 $listofids = '';
3457 $i = 0;
3458 foreach ($listofmembersok as $idmember) {
3459 if ($i > 100) {
3460 $listofids .= ', ...';
3461 break;
3462 }
3463 if (empty($listofids)) {
3464 $listofids .= ' [';
3465 } else {
3466 $listofids .= ', ';
3467 }
3468 $listofids .= $idmember;
3469 $i++;
3470 }
3471 if ($listofids) {
3472 $listofids .= ']';
3473 }
3474 $this->output .= ($listofids ? ' ids='.$listofids : '');
3475
3476 if ($nbko) {
3477 $this->output .= ' - Canceled for '.$nbko.' member (no email or email sending error)';
3478 $listofids = '';
3479 $i = 0;
3480 foreach ($listofmembersko as $idmember) {
3481 if ($i > 100) {
3482 $listofids .= ', ...';
3483 break;
3484 }
3485 if (empty($listofids)) {
3486 $listofids .= ' [';
3487 } else {
3488 $listofids .= ', ';
3489 }
3490 $listofids .= $idmember;
3491 $i++;
3492 }
3493 if ($listofids) {
3494 $listofids .= ']';
3495 }
3496 $this->output .= ($listofids ? ' ids='.$listofids : '');
3497 }
3498 }
3499
3500 return $nbko;
3501 }
3502
3510 public function getKanbanView($option = '', $arraydata = null)
3511 {
3512 $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
3513
3514 $return = '<div class="box-flex-item box-flex-grow-zero">';
3515 $return .= '<div class="info-box info-box-sm">';
3516 $return .= '<span class="info-box-icon bg-infobox-action">';
3517 if (!empty($this->photo)) {
3518 $return .= Form::showphoto('memberphoto', $this, 0, 60, 0, 'photokanban photowithmargin photologintooltip', 'small', 0, 1);
3519 } else {
3520 $return .= img_picto('', 'user');
3521 }
3522 $return .= '</span>';
3523 $return .= '<div class="info-box-content">';
3524 $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">' . $this->getNomUrl() . '</span>';
3525 if ($selected >= 0) {
3526 $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
3527 }
3528 $return .= '<br><span class="info-box-label paddingright">'.$this->getmorphylib('', 2).'</span>';
3529 $return .= '<span class="info-box-label opacitymedium">'.$this->type.'</span>';
3530
3531 $return .= '<br><div class="info-box-status paddingtop">';
3532 $return .= $this->LibStatut($this->status, $this->need_subscription, $this->datefin, 5);
3533 $return .= '</div>';
3534 $return .= '</div>';
3535 $return .= '</div>';
3536 $return .= '</div>';
3537 return $return;
3538 }
3539}
$object ref
Definition info.php:90
Class to manage bank accounts.
Class to manage agenda events (actions)
Class to manage members of a foundation.
mergeMembers($member_origin_id)
Merge a member with current one, deleting the given company $member_origin_id.
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.
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.
subscription($date, $amount, $accountid=0, $operation='', $label='', $num_chq='', $emetteur_nom='', $emetteur_banque='', $datesubend=0, $fk_type=null, $ref_ext='')
Insert subscription into database and eventually add links to banks, mailman, etc....
__construct($db)
Constructor.
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,...
fetch($rowid, $ref='', $socid=0, $ref_ext='', $fetch_optionals=true, $fetch_subscriptions=true)
Load member from database.
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.
Class to manage categories.
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...
commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
Common function for all objects extending CommonObject for generating documents.
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.
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, $usesharelinkifavailable=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 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.
global $mysoc
dol_time_plus_duree($time, $duration_value, $duration_unit, $ruleforendofmonth=0, $tz='')
Add a delay to a date.
Definition date.lib.php:128
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_move($srcfile, $destfile, $newmask='0', $overwriteifexists=1, $testvirus=0, $indexdatabase=1, $moreinfo=array(), $entity=null)
Move a file into another name.
dol_dir_list($utf8_path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0, $nbsecondsold=0)
Scan a directory and return a list of files/directories.
Definition files.lib.php:64
dol_is_dir($folder)
Test if filename is a directory.
clean_url($url, $http=1)
Clean an url string.
dol_now($mode='gmt')
Return date for now.
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.
dolBuildUrl($url, $params=[], $addtoken=false)
Return path of url.
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.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
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_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false, $decorate=0)
Output date in a string format according to outputlangs (or langs if not defined).
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.
isModEnabled($module)
Is Dolibarr module enabled.
getWarningDelay($module, $parmlevel1, $parmlevel2='')
Return a warning delay You can use it like this: if (getWarningDelay('module', 'paramlevel1')) It rep...
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...
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
if(preg_match('/(crypted|dolcrypt):/i', $dolibarr_main_db_pass)||!empty($dolibarr_main_db_encrypted_pass)) $conf db type
'integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]',...
Definition repair.php:132
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.