3 /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
6 * Member class for galette
10 * Copyright © 2009-2023 The Galette Team
12 * This file is part of Galette (http://galette.tuxfamily.org).
14 * Galette is free software: you can redistribute it and/or modify
15 * it under the terms of the GNU General Public License as published by
16 * the Free Software Foundation, either version 3 of the License, or
17 * (at your option) any later version.
19 * Galette is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 * GNU General Public License for more details.
24 * You should have received a copy of the GNU General Public License
25 * along with Galette. If not, see <http://www.gnu.org/licenses/>.
30 * @author Johan Cwiklinski <johan@x-tnd.be>
31 * @copyright 2009-2023 The Galette Team
32 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL License 3.0 or (at your option) any later version
33 * @link http://galette.tuxfamily.org
34 * @since Available since 0.7dev - 2009-06-02
37 namespace Galette\Entity
;
39 use Galette\Events\GaletteEvent
;
40 use Galette\Features\Socials
;
43 use Laminas\Db\Sql\Expression
;
45 use Galette\Core\Picture
;
46 use Galette\Core\GaletteMail
;
47 use Galette\Core\Password
;
48 use Galette\Core\Preferences
;
49 use Galette\Core\History
;
50 use Galette\Repository\Groups
;
51 use Galette\Core\Login
;
52 use Galette\Repository\Members
;
53 use Galette\Features\Dynamics
;
56 * Member class for galette
61 * @author Johan Cwiklinski <johan@x-tnd.be>
62 * @copyright 2009-2023 The Galette Team
63 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL License 3.0 or (at your option) any later version
64 * @link http://galette.tuxfamily.org
65 * @since Available since 0.7dev - 02-06-2009
67 * @property integer $id
68 * @property integer|Title $title Either a title id or an instance of Title
69 * @property string $stitle Title label
70 * @property string company_name
71 * @property string $name
72 * @property string $surname
73 * @property string $nickname
74 * @property string $birthdate Localized birthdate
75 * @property string $rbirthdate Raw birthdate
76 * @property string $birth_place
77 * @property integer $gender
78 * @property string $sgender Gender label
79 * @property string $job
80 * @property string $language
81 * @property integer $status
82 * @property string $sstatus Status label
83 * @property string $address
84 * @property string $zipcode
85 * @property string $town
86 * @property string $country
87 * @property string $phone
88 * @property string $gsm
89 * @property string $email
90 * @property string $gnupgid
91 * @property string $fingerprint
92 * @property string $login
93 * @property string $creation_date Localized creation date
94 * @property string $modification_date Localized modification date
95 * @property string $due_date Localized due date
96 * @property string $others_infos
97 * @property string $others_infos_admin
98 * @property Picture $picture
99 * @property array $groups
100 * @property array $managed_groups
101 * @property integer|Adherent $parent Parent id if parent dep is not loaded, Adherent instance otherwise
102 * @property array $children
103 * @property boolean $admin better to rely on isAdmin()
104 * @property boolean $staff better to rely on isStaff()
105 * @property boolean $due_free better to rely on isDueFree()
106 * @property boolean $appears_in_list better to rely on appearsInMembersList()
107 * @property boolean $active better to rely on isActive()
108 * @property boolean $duplicate better to rely on isDuplicate()
109 * @property string $sadmin yes/no
110 * @property string $sstaff yes/no
111 * @property string $sdue_free yes/no
112 * @property string $sappears_in_list yes/no
113 * @property string $sactive yes/no
114 * @property string $sfullname
115 * @property string $sname
116 * @property string $saddress
117 * @property string $contribstatus State of member contributions
118 * @property string $days_remaining
119 * @property-read integer $parent_id
120 * @property Social $social Social networks/Contact
121 * @property string $number Member number
129 public const TABLE
= 'adherents';
130 public const PK
= 'id_adh';
133 public const MAN
= 1;
134 public const WOMAN
= 2;
136 public const AFTER_ADD_DEFAULT
= 0;
137 public const AFTER_ADD_TRANS
= 1;
138 public const AFTER_ADD_NEW
= 2;
139 public const AFTER_ADD_SHOW
= 3;
140 public const AFTER_ADD_LIST
= 4;
141 public const AFTER_ADD_HOME
= 5;
146 private $_company_name;
151 private $_birth_place;
157 //Contact information
166 private $_fingerprint;
167 //Galette relative information
168 private $_appears_in_list;
170 private $_staff = false;
174 private $_creation_date;
175 private $_modification_date;
177 private $_others_infos;
178 private $_others_infos_admin;
181 private $_days_remaining;
182 private $_groups = [];
183 private $_managed_groups = [];
186 private $_duplicate = false;
190 private $_row_classes;
192 private $_self_adh = false;
193 private $_deps = array(
204 private $preferences;
208 private $parent_fields = [
215 private $errors = [];
217 private $sendmail = false;
220 * Default constructor
222 * @param Db $zdb Database instance
223 * @param mixed $args Either a ResultSet row, its id or its
224 * login or its email for to load s specific
225 * member, or null to just instantiate object
226 * @param false|array|null $deps Dependencies configuration, see Adherent::$_deps
228 public function __construct(Db
$zdb, $args = null, $deps = null)
234 if ($deps !== null) {
235 if (is_array($deps)) {
236 $this->_deps
= array_merge(
240 } elseif ($deps === false) {
242 $this->_deps
= array_fill_keys(
243 array_keys($this->_deps
),
248 '$deps should be an array, ' . gettype($deps) . ' given!',
254 if ($args == null ||
is_int($args)) {
255 if (is_int($args) && $args > 0) {
258 $this->_active
= true;
259 $this->_language
= $i18n->getID();
260 $this->_creation_date
= date("Y-m-d");
261 $this->_status
= $this->getDefaultStatus();
262 $this->_title
= null;
263 $this->_gender
= self
::NC
;
264 $gp = new Password($this->zdb
);
265 $this->_password
= $gp->makeRandomPassword();
266 $this->_picture
= new Picture();
267 $this->_admin
= false;
268 $this->_staff
= false;
269 $this->_due_free
= false;
270 $this->_appears_in_list
= false;
271 $this->_parent
= null;
273 if ($this->_deps
['dynamics'] === true) {
274 $this->loadDynamicFields();
277 } elseif (is_object($args)) {
278 $this->loadFromRS($args);
279 } elseif (is_string($args)) {
280 $this->loadFromLoginOrMail($args);
285 * Loads a member from its id
287 * @param int $id the identifier for the member to load
289 * @return bool true if query succeed, false otherwise
291 public function load(int $id): bool
294 $select = $this->zdb
->select(self
::TABLE
, 'a');
297 array('b' => PREFIX_DB
. Status
::TABLE
),
298 'a.' . Status
::PK
. '=b.' . Status
::PK
,
299 array('priorite_statut')
300 )->where(array(self
::PK
=> $id));
302 $results = $this->zdb
->execute($select);
304 if ($results->count() === 0) {
308 $this->loadFromRS($results->current());
310 } catch (Throwable
$e) {
312 'Cannot load member form id `' . $id . '` | ' . $e->getMessage(),
320 * Loads a member from its login
322 * @param string $login login for the member to load
326 public function loadFromLoginOrMail(string $login): bool
329 $select = $this->zdb
->select(self
::TABLE
);
330 if (GaletteMail
::isValidEmail($login)) {
331 //we got a valid email address, use it
332 $select->where(array('email_adh' => $login));
334 ///we did not get an email address, consider using login
335 $select->where(array('login_adh' => $login));
338 $results = $this->zdb
->execute($select);
339 $result = $results->current();
341 $this->loadFromRS($result);
344 } catch (Throwable
$e) {
346 'Cannot load member form login `' . $login . '` | ' .
355 * Populate object from a resultset row
357 * @param ResultSet $r the resultset row
361 private function loadFromRS($r): void
363 $this->_self_adh
= false;
364 $this->_id
= $r->id_adh
;
366 if ($r->titre_adh
!== null) {
367 $this->_title
= new Title((int)$r->titre_adh
);
369 $this->_company_name
= $r->societe_adh
;
370 $this->_name
= $r->nom_adh
;
371 $this->_surname
= $r->prenom_adh
;
372 $this->_nickname
= $r->pseudo_adh
;
373 if ($r->ddn_adh
!= '1901-01-01') {
374 $this->_birthdate
= $r->ddn_adh
;
376 $this->_birth_place
= $r->lieu_naissance
;
377 $this->_gender
= (int)$r->sexe_adh
;
378 $this->_job
= $r->prof_adh
;
379 $this->_language
= $r->pref_lang
;
380 $this->_active
= $r->activite_adh
== 1;
381 $this->_status
= (int)$r->id_statut
;
382 //Contact information
383 $this->_address
= $r->adresse_adh
;
384 $this->_zipcode
= $r->cp_adh
;
385 $this->_town
= $r->ville_adh
;
386 $this->_country
= $r->pays_adh
;
387 $this->_phone
= $r->tel_adh
;
388 $this->_gsm
= $r->gsm_adh
;
389 $this->_email
= $r->email_adh
;
390 $this->_gnupgid
= $r->gpgid
;
391 $this->_fingerprint
= $r->fingerprint
;
392 //Galette relative information
393 $this->_appears_in_list
= $r->bool_display_info
== 1;
394 $this->_admin
= $r->bool_admin_adh
== 1;
396 isset($r->priorite_statut
)
397 && $r->priorite_statut
< Members
::NON_STAFF_MEMBERS
399 $this->_staff
= true;
401 $this->_due_free
= $r->bool_exempt_adh
== 1;
402 $this->_login
= $r->login_adh
;
403 $this->_password
= $r->mdp_adh
;
404 $this->_creation_date
= $r->date_crea_adh
;
405 if ($r->date_modif_adh
!= '1901-01-01') {
406 $this->_modification_date
= $r->date_modif_adh
;
408 $this->_modification_date
= $this->_creation_date
;
410 $this->_due_date
= $r->date_echeance
;
411 $this->_others_infos
= $r->info_public_adh
;
412 $this->_others_infos_admin
= $r->info_adh
;
413 $this->_number
= $r->num_adh
;
415 if ($r->parent_id
!== null) {
416 $this->_parent
= (int)$r->parent_id
;
417 if ($this->_deps
['parent'] === true) {
422 if ($this->_deps
['children'] === true) {
423 $this->loadChildren();
426 if ($this->_deps
['picture'] === true) {
427 $this->_picture
= new Picture($this->_id
);
430 if ($this->_deps
['groups'] === true) {
434 if ($this->_deps
['dues'] === true) {
438 if ($this->_deps
['dynamics'] === true) {
439 $this->loadDynamicFields();
442 if ($this->_deps
['socials'] === true) {
443 $this->loadSocials();
452 private function loadParent(): void
454 if (!$this->_parent
instanceof Adherent
) {
455 $deps = array_fill_keys(array_keys($this->_deps
), false);
456 $this->_parent
= new Adherent($this->zdb
, (int)$this->_parent
, $deps);
461 * Load member children
465 private function loadChildren(): void
467 $this->_children
= array();
470 $select = $this->zdb
->select(self
::TABLE
);
473 )->where(['parent_id' => $this->_id
]);
475 $results = $this->zdb
->execute($select);
477 if ($results->count() > 0) {
478 foreach ($results as $row) {
479 $deps = $this->_deps
;
480 $deps['children'] = false;
481 $deps['parent'] = false;
482 $this->_children
[] = new Adherent($this->zdb
, (int)$row->$id, $deps);
485 } catch (Throwable
$e) {
487 'Cannot load children for member #' . $this->_id
. ' | ' .
500 public function loadGroups(): void
502 $this->_groups
= Groups
::loadGroups($this->_id
);
503 $this->_managed_groups
= Groups
::loadManagedGroups($this->_id
);
507 * Load member social network/contact information
511 public function loadSocials(): void
513 $this->_socials
= Social
::getListForMember($this->_id
);
517 * Retrieve status from preferences
522 private function getDefaultStatus(): int
525 if ($preferences->pref_statut
!= '') {
526 return $preferences->pref_statut
;
529 'Unable to get pref_statut; is it defined in preferences?',
532 return Status
::DEFAULT_STATUS
;
537 * Check for dues status
541 private function checkDues(): void
543 //how many days since our beloved member has been created
544 $now = new \
DateTime();
545 $this->_oldness
= $now->diff(
546 new \
DateTime($this->_creation_date
)
549 if ($this->isDueFree()) {
550 //no fee required, we don't care about dates
551 $this->_row_classes
.= ' cotis-exempt';
553 //ok, fee is required. Let's check the dates
554 if ($this->_due_date
== '') {
555 $this->_row_classes
.= ' cotis-never';
557 // To count the days remaining, the next begin date is required.
558 $due_date = new \
DateTime($this->_due_date
);
559 $next_begin_date = clone $due_date;
560 $next_begin_date->add(new \
DateInterval('P1D'));
561 $date_diff = $now->diff($next_begin_date);
562 $this->_days_remaining
= $date_diff->days
;
564 if ($date_diff->invert
== 0 && $date_diff->days
>= 0) {
565 $this->_days_remaining
= $date_diff->days
;
566 if ($this->_days_remaining
<= 30) {
567 if ($date_diff->days
== 0) {
568 $this->_row_classes
.= ' cotis-lastday';
570 $this->_row_classes
.= ' cotis-soon';
572 $this->_row_classes
.= ' cotis-ok';
575 } elseif ($date_diff->invert
== 1 && $date_diff->days
>= 0) {
576 $this->_days_remaining
= $date_diff->days
;
577 //check if member is still active
578 $this->_row_classes
.= $this->isActive() ?
' cotis-late' : ' cotis-old';
589 public function isAdmin(): bool
591 return $this->_admin
;
595 * Is user member of staff?
599 public function isStaff(): bool
601 return $this->_staff
;
605 * Is member freed of dues?
609 public function isDueFree(): bool
611 return $this->_due_free
;
615 * Is member in specified group?
617 * @param string $group_name Group name
621 public function isGroupMember(string $group_name): bool
623 if (!$this->isDepEnabled('groups')) {
627 foreach ($this->_groups
as $g) {
628 if ($g->getName() == $group_name) {
636 * Is member manager of specified group?
638 * @param string $group_name Group name
642 public function isGroupManager(string $group_name): bool
644 if (!$this->isDepEnabled('groups')) {
648 foreach ($this->_managed_groups
as $mg) {
649 if ($mg->getName() == $group_name) {
657 * Does current member represents a company?
661 public function isCompany(): bool
663 return trim($this->_company_name ??
'') != '';
667 * Is current member a man?
671 public function isMan(): bool
673 return (int)$this->_gender
=== self
::MAN
;
677 * Is current member a woman?
681 public function isWoman(): bool
683 return (int)$this->_gender
=== self
::WOMAN
;
688 * Can member appears in public members list?
692 public function appearsInMembersList(): bool
694 return $this->_appears_in_list
;
702 public function isActive(): bool
704 return $this->_active
;
708 * Does member have uploaded a picture?
712 public function hasPicture(): bool
714 return $this->_picture
->hasPicture();
718 * Does member have a parent?
722 public function hasParent(): bool
724 return !empty($this->_parent
);
728 * Does member have children?
732 public function hasChildren(): bool
734 if ($this->_children
=== null) {
737 'Children has not been loaded!',
743 return count($this->_children
) > 0;
748 * Get row class related to current fee status
750 * @param boolean $public we want the class for public pages
752 * @return string the class to apply
754 public function getRowClass(bool $public = false): string
756 $strclass = ($this->isActive()) ?
'active' : 'inactive';
757 if ($public === false) {
758 $strclass .= $this->_row_classes
;
764 * Get current member due status
766 * @return string i18n string representing state of due
768 public function getDues(): string
771 $never_contributed = false;
772 $now = new \
DateTime();
773 // To count the days remaining, the next begin date is required.
774 if ($this->_due_date
=== null) {
775 $this->_due_date
= $now->format('Y-m-d');
776 $never_contributed = true;
778 $due_date = new \
DateTime($this->_due_date
);
779 $next_begin_date = clone $due_date;
780 $next_begin_date->add(new \
DateInterval('P1D'));
781 $date_diff = $now->diff($next_begin_date);
782 if ($this->isDueFree()) {
783 $ret = _T("Freed of dues");
784 } elseif ($never_contributed === true) {
785 $patterns = array('/%days/', '/%date/');
786 $cdate = new \
DateTime($this->_creation_date
);
789 $cdate->format(__("Y-m-d"))
791 if ($this->_active
) {
795 _T("Never contributed: Registered %days days ago (since %date)")
798 $ret = _T("Never contributed");
800 // Last active or first expired day
801 } elseif ($this->_days_remaining
== 0) {
802 if ($date_diff->invert
== 0) {
803 $ret = _T("Last day!");
805 $ret = _T("Late since today!");
808 } elseif ($date_diff->invert
== 0 && $this->_days_remaining
> 0) {
809 $patterns = array('/%days/', '/%date/');
811 $this->_days_remaining
,
812 $due_date->format(__("Y-m-d"))
817 _T("%days days remaining (ending on %date)")
820 } elseif ($date_diff->invert
== 1 && $this->_days_remaining
> 0) {
821 $patterns = array('/%days/', '/%date/');
823 // We need the number of days expired, not the number of days remaining.
824 $this->_days_remaining +
1,
825 $due_date->format(__("Y-m-d"))
827 if ($this->_active
) {
831 _T("Late of %days days (since %date)")
834 $ret = _T("No longer member");
841 * Retrieve Full name and surname for the specified member id
843 * @param Db $zdb Database instance
844 * @param integer $id Member id
845 * @param boolean $wid Add member id
846 * @param boolean $wnick Add member nickname
848 * @return string formatted Name and Surname
850 public static function getSName(Db
$zdb, int $id, bool $wid = false, bool $wnick = false): string
853 $select = $zdb->select(self
::TABLE
);
854 $select->where([self
::PK
=> $id]);
856 $results = $zdb->execute($select);
857 $row = $results->current();
858 return self
::getNameWithCase(
862 ($wid === true ?
$row->id_adh
: false),
863 ($wnick === true ?
$row->pseudo_adh
: false)
865 } catch (Throwable
$e) {
867 'Cannot get formatted name for member form id `' . $id . '` | ' .
876 * Get member name with correct case
878 * @param string $name Member name
879 * @param string $surname Member surname
880 * @param false|Title $title Member title to show or false
881 * @param false|integer $id Member id to display or false
882 * @param false|string $nick Member nickname to display or false
886 public static function getNameWithCase(
895 if ($title instanceof Title
) {
896 $str .= $title->tshort
. ' ';
899 $str .= mb_strtoupper($name ??
'', 'UTF-8') . ' ' .
900 ucwords(mb_strtolower($surname ??
'', 'UTF-8'), " \t\r\n\f\v-_|");
902 if ($id !== false ||
!empty($nick)) {
914 if ($id !== false ||
!empty($nick)) {
917 return strip_tags($str);
921 * Change password for a given user
923 * @param Db $zdb Database instance
924 * @param integer $id_adh Member identifier
925 * @param string $pass New password
929 public static function updatePassword(Db
$zdb, int $id_adh, string $pass): bool
932 $cpass = password_hash($pass, PASSWORD_BCRYPT
);
934 $update = $zdb->update(self
::TABLE
);
936 array('mdp_adh' => $cpass)
937 )->where([self
::PK
=> $id_adh]);
938 $zdb->execute($update);
940 'Password for `' . $id_adh . '` has been updated.',
944 } catch (Throwable
$e) {
946 'An error occurred while updating password for `' . $id_adh .
947 '` | ' . $e->getMessage(),
957 * @param string $field Field name
961 private function getFieldLabel(string $field): string
963 $label = $this->fields
[$field]['label'] ??
'';
965 $label = str_replace(' ', ' ', $label);
966 //remove trailing ':' and then trim
967 $label = trim(trim($label, ':'));
972 * Retrieve fields from database
974 * @param Db $zdb Database instance
978 public static function getDbFields(Db
$zdb): array
980 $columns = $zdb->getColumns(self
::TABLE
);
982 foreach ($columns as $col) {
983 $fields[] = $col->getName();
989 * Mark as self membership
993 public function setSelfMembership(): void
995 $this->_self_adh
= true;
999 * Is member up to date?
1003 public function isUp2Date(): bool
1005 if (!$this->isDepEnabled('dues')) {
1009 if ($this->isDueFree()) {
1010 //member is due free, he's up to date.
1013 //let's check from due date, if present
1014 if ($this->_due_date
== null) {
1017 $due_date = new \
DateTime($this->_due_date
);
1018 $now = new \
DateTime();
1019 $now->setTime(0, 0, 0);
1020 return $due_date >= $now;
1028 * @param Preferences $preferences Preferences instance
1029 * @param array $fields Members fields configuration
1030 * @param History $history History instance
1034 public function setDependencies(
1035 Preferences
$preferences,
1039 $this->preferences
= $preferences;
1040 $this->fields
= $fields;
1041 $this->history
= $history;
1045 * Check posted values validity
1047 * @param array $values All values to check, basically the $_POST array
1048 * after sending the form
1049 * @param array $required Array of required fields
1050 * @param array $disabled Array of disabled fields
1052 * @return true|array
1054 public function check(array $values, array $required, array $disabled)
1058 $this->errors
= array();
1061 foreach ($values as &$rawvalue) {
1062 if (is_string($rawvalue)) {
1063 $rawvalue = strip_tags($rawvalue);
1067 $fields = self
::getDbFields($this->zdb
);
1069 //reset company name if needed
1070 if (!isset($values['is_company'])) {
1071 unset($values['is_company']);
1072 $values['societe_adh'] = '';
1075 //no parent if checkbox was unchecked
1077 !isset($values['attach'])
1078 && empty($this->_id
)
1079 && isset($values['parent_id'])
1081 unset($values['parent_id']);
1084 if (isset($values['duplicate'])) {
1085 //if we're duplicating, keep a trace (if an error occurs)
1086 $this->_duplicate
= true;
1089 foreach ($fields as $key) {
1090 //first, let's sanitize values
1091 $key = strtolower($key);
1092 $prop = '_' . $this->fields
[$key]['propname'];
1094 if (isset($values[$key])) {
1095 $value = $values[$key];
1096 if ($value !== true && $value !== false) {
1097 //@phpstan-ignore-next-line
1098 $value = trim($value ??
'');
1100 } elseif (empty($this->_id
)) {
1102 case 'bool_admin_adh':
1103 case 'bool_exempt_adh':
1104 case 'bool_display_info':
1107 case 'activite_adh':
1108 //values that are set at object instantiation
1111 case 'date_crea_adh':
1117 //values that are set at object instantiation
1118 $value = $this->$prop;
1128 //keep stored value on update
1129 if ($prop != '_password' ||
isset($values['mdp_adh']) && isset($values['mdp_adh2'])) {
1130 $value = $this->$prop;
1136 // if the field is enabled, check it
1137 if (!isset($disabled[$key])) {
1138 // fill up the adherent structure
1139 if ($value !== null && $value !== true && $value !== false && !is_object($value)) {
1140 $value = stripslashes($value);
1142 $this->$prop = $value;
1144 // now, check validity
1145 if ($value !== null && $value != '') {
1146 if ($key !== 'mdp_adh') {
1147 $this->validate($key, $value, $values);
1149 } elseif (empty($this->_id
)) {
1150 //ensure login and password are not empty
1151 if (($key == 'login_adh' ||
$key == 'mdp_adh') && !isset($required[$key])) {
1152 $p = new Password($this->zdb
);
1153 $generated_value = $p->makeRandomPassword(15);
1154 if ($key == 'login_adh') {
1155 //'@' is not permitted in logins
1156 $this->$prop = str_replace('@', 'a', $generated_value);
1158 $this->$prop = $generated_value;
1165 //password checks need data to be previously set
1166 if (isset($values['mdp_adh'])) {
1167 $this->validate('mdp_adh', $values['mdp_adh'], $values);
1170 // missing required fields?
1171 foreach ($required as $key => $val) {
1172 $prop = '_' . $this->fields
[$key]['propname'];
1174 if (!isset($disabled[$key])) {
1175 $mandatory_missing = false;
1176 if (!isset($this->$prop) ||
$this->$prop == '') {
1177 $mandatory_missing = true;
1178 } elseif ($key === 'titre_adh' && $this->$prop == '-1') {
1179 $mandatory_missing = true;
1182 if ($mandatory_missing === true) {
1183 $this->errors
[] = str_replace(
1185 '<a href="#' . $key . '">' . $this->getFieldLabel($key) . '</a>',
1186 _T("- Mandatory field %field empty.")
1192 //attach to/detach from parent
1193 if (isset($values['detach_parent'])) {
1194 $this->_parent
= null;
1197 if ($login->isGroupManager() && !$login->isAdmin() && !$login->isStaff() && $this->parent_id
!== $login->id
) {
1198 if (!isset($values['groups_adh'])) {
1199 $this->errors
[] = _T('You have to select a group you own!');
1201 $owned_group = false;
1202 foreach ($values['groups_adh'] as $group) {
1203 list($gid) = explode('|', $group);
1204 if ($login->isGroupManager($gid)) {
1205 $owned_group = true;
1208 if ($owned_group === false) {
1209 $this->errors
[] = _T('You have to select a group you own!');
1214 $this->dynamicsCheck($values, $required, $disabled);
1215 $this->checkSocials($values);
1217 if (count($this->errors
) > 0) {
1219 'Some errors has been thew attempting to edit/store a member' . "\n" .
1220 print_r($this->errors
, true),
1223 return $this->errors
;
1228 'Member checked successfully.',
1236 * Validate data for given key
1237 * Set valid data in current object, also resets errors list
1239 * @param string $field Field name
1240 * @param mixed $value Value we want to set
1241 * @param array $values All values, for some references
1245 public function validate(string $field, $value, array $values): void
1247 global $preferences;
1249 $prop = '_' . $this->fields
[$field]['propname'];
1251 if ($value === null ||
(is_string($value) && trim($value) == '')) {
1252 //empty values are OK
1253 $this->$prop = $value;
1259 case 'date_crea_adh':
1260 case 'date_modif_adh_':
1262 case 'date_echeance':
1264 $d = \DateTime
::createFromFormat(__("Y-m-d"), $value);
1266 //try with non localized date
1267 $d = \DateTime
::createFromFormat("Y-m-d", $value);
1269 throw new \
Exception('Incorrect format');
1273 if ($field === 'ddn_adh') {
1274 $now = new \
DateTime();
1275 $now->setTime(0, 0, 0);
1276 $d->setTime(0, 0, 0);
1278 $diff = $now->diff($d);
1279 $days = (int)$diff->format('%R%a');
1281 $this->errors
[] = _T('- Birthdate must be set in the past!');
1284 $years = (int)$diff->format('%R%Y');
1285 if ($years <= -200) {
1286 $this->errors
[] = str_replace(
1289 _T('- Members must be less than 200 years old (currently %years)!')
1293 $this->$prop = $d->format('Y-m-d');
1294 } catch (Throwable
$e) {
1296 'Wrong date format. field: ' . $field .
1297 ', value: ' . $value . ', expected fmt: ' .
1298 __("Y-m-d") . ' | ' . $e->getMessage(),
1301 $this->errors
[] = str_replace(
1308 $this->getFieldLabel($field)
1310 _T("- Wrong date format (%date_format) for %field!")
1315 if ($value !== null && $value !== '') {
1316 if ($value == '-1') {
1317 $this->$prop = null;
1318 } elseif (!$value instanceof Title
) {
1319 $this->$prop = new Title((int)$value);
1322 $this->$prop = null;
1326 if (!GaletteMail
::isValidEmail($value)) {
1327 $this->errors
[] = _T("- Non-valid E-Mail address!") .
1328 ' (' . $this->getFieldLabel($field) . ')';
1330 if ($field == 'email_adh') {
1332 $select = $this->zdb
->select(self
::TABLE
);
1335 )->where(array('email_adh' => $value));
1336 if (!empty($this->_id
)) {
1337 $select->where
->notEqualTo(
1343 $results = $this->zdb
->execute($select);
1344 if ($results->count() !== 0) {
1345 $this->errors
[] = _T("- This E-Mail address is already used by another member!");
1347 } catch (Throwable
$e) {
1349 'An error occurred checking member email uniqueness.',
1352 $this->errors
[] = _T("An error has occurred while looking if login already exists.");
1357 /** FIXME: add a preference for login length */
1358 if (strlen($value) < 2) {
1359 $this->errors
[] = str_replace(
1362 _T("- The username must be composed of at least %i characters!")
1365 //check if login does not contain the @ character
1366 if (strpos($value, '@') != false) {
1367 $this->errors
[] = _T("- The username cannot contain the @ character");
1369 //check if login is already taken
1371 $select = $this->zdb
->select(self
::TABLE
);
1374 )->where(array('login_adh' => $value));
1375 if (!empty($this->_id
)) {
1376 $select->where
->notEqualTo(
1382 $results = $this->zdb
->execute($select);
1384 $results->count() !== 0
1385 ||
$value == $preferences->pref_admin_login
1387 $this->errors
[] = _T("- This username is already in use, please choose another one!");
1389 } catch (Throwable
$e) {
1391 'An error occurred checking member login uniqueness.',
1394 $this->errors
[] = _T("An error has occurred while looking if login already exists.");
1401 $this->_self_adh
!== true
1402 && (!isset($values['mdp_adh2'])
1403 ||
$values['mdp_adh2'] != $value)
1405 $this->errors
[] = _T("- The passwords don't match!");
1407 $this->_self_adh
=== true
1408 && !crypt($value, $values['mdp_crypt']) == $values['mdp_crypt']
1410 $this->errors
[] = _T("Password misrepeated: ");
1412 $pinfos = password_get_info($value);
1413 //check if value is already a hash
1414 if ($pinfos['algo'] == 0) {
1415 $this->$prop = password_hash(
1420 $pwcheck = new \Galette\Util\
Password($preferences);
1421 $pwcheck->setAdherent($this);
1422 if (!$pwcheck->isValid($value)) {
1423 $this->errors
= array_merge(
1425 $pwcheck->getErrors()
1433 $this->$prop = (int)$value;
1434 //check if status exists
1435 $select = $this->zdb
->select(Status
::TABLE
);
1436 $select->where([Status
::PK
=> $value]);
1438 $results = $this->zdb
->execute($select);
1439 $result = $results->current();
1441 $this->errors
[] = str_replace(
1444 _T("Status #%id does not exists in database.")
1448 } catch (Throwable
$e) {
1450 'An error occurred checking status existence: ' . $e->getMessage(),
1453 $this->errors
[] = _T("An error has occurred while looking if status does exists.");
1457 if (in_array($value, [self
::NC
, self
::MAN
, self
::WOMAN
])) {
1458 $this->$prop = (int)$value;
1460 $this->errors
[] = _T("Gender %gender does not exists!");
1464 $this->$prop = ($value instanceof Adherent
) ?
(int)$value->id
: (int)$value;
1465 $this->loadParent();
1475 public function store(): bool
1477 global $hist, $emitter, $login;
1480 if (!$login->isAdmin() && !$login->isStaff() && !$login->isGroupManager() && $this->id
== '') {
1481 if ($this->preferences
->pref_bool_create_member
) {
1482 $this->_parent
= $login->id
;
1488 $fields = self
::getDbFields($this->zdb
);
1490 foreach ($fields as $field) {
1492 $field !== 'date_modif_adh'
1493 ||
empty($this->_id
)
1495 $prop = '_' . $this->fields
[$field]['propname'];
1497 ($field === 'bool_admin_adh'
1498 ||
$field === 'bool_exempt_adh'
1499 ||
$field === 'bool_display_info'
1500 ||
$field === 'activite_adh')
1501 && $this->$prop === false
1503 //Handle booleans for postgres ; bugs #18899 and #19354
1504 $values[$field] = $this->zdb
->isPostgres() ?
'false' : 0;
1505 } elseif ($field === 'parent_id') {
1507 if ($this->_parent
=== null) {
1508 $values['parent_id'] = new Expression('NULL');
1509 } elseif ($this->parent
instanceof Adherent
) {
1510 $values['parent_id'] = $this->_parent
->id
;
1512 $values['parent_id'] = $this->_parent
;
1515 $values[$field] = $this->$prop;
1520 //an empty value will cause date to be set to 1901-01-01, a null
1521 //will result in 0000-00-00. We want a database NULL value here.
1522 if (!$this->_birthdate
) {
1523 $values['ddn_adh'] = new Expression('NULL');
1525 if (!$this->_due_date
) {
1526 $values['date_echeance'] = new Expression('NULL');
1529 if ($this->_title
instanceof Title
) {
1530 $values['titre_adh'] = $this->_title
->id
;
1532 $values['titre_adh'] = new Expression('NULL');
1535 if (!$this->_parent
) {
1536 $values['parent_id'] = new Expression('NULL');
1539 if (!$this->_number
) {
1540 $values['num_adh'] = new Expression('NULL');
1543 //fields that cannot be null
1545 '_surname' => 'prenom_adh',
1546 '_nickname' => 'pseudo_adh',
1547 '_address' => 'adresse_adh',
1548 '_zipcode' => 'cp_adh',
1549 '_town' => 'ville_adh'
1551 foreach ($notnull as $prop => $field) {
1552 if ($this->$prop === null) {
1553 $values[$field] = '';
1558 if (empty($this->_id
)) {
1559 //we're inserting a new member
1560 unset($values[self
::PK
]);
1561 //set modification date
1562 $this->_modification_date
= date('Y-m-d');
1563 $values['date_modif_adh'] = $this->_modification_date
;
1565 $insert = $this->zdb
->insert(self
::TABLE
);
1566 $insert->values($values);
1567 $add = $this->zdb
->execute($insert);
1568 if ($add->count() > 0) {
1569 $this->_id
= $this->zdb
->getLastGeneratedValue($this);
1570 $this->_picture
= new Picture($this->_id
);
1572 if ($this->_self_adh
) {
1574 _T("Self_subscription as a member: ") .
1575 $this->getNameWithCase($this->_name
, $this->_surname
),
1580 _T("Member card added"),
1586 $event = 'member.add';
1588 $hist->add(_T("Fail to add new member."));
1589 throw new \
Exception(
1590 'An error occurred inserting new member!'
1594 //we're editing an existing member
1595 if (!$this->isDueFree()) {
1597 $due_date = Contribution
::getDueDate($this->zdb
, $this->_id
);
1599 $values['date_echeance'] = $due_date;
1603 if (!$this->_password
) {
1604 unset($values['mdp_adh']);
1607 $update = $this->zdb
->update(self
::TABLE
);
1608 $update->set($values);
1609 $update->where([self
::PK
=> $this->_id
]);
1611 $edit = $this->zdb
->execute($update);
1613 //edit == 0 does not mean there were an error, but that there
1614 //were nothing to change
1615 if ($edit->count() > 0) {
1616 $this->updateModificationDate();
1618 _T("Member card updated"),
1623 $event = 'member.edit';
1628 $success = $this->dynamicsStore();
1629 $this->storeSocials($this->id
);
1632 //send event at the end of process, once all has been stored
1633 if ($event !== null) {
1634 $emitter->dispatch(new GaletteEvent($event, $this));
1637 } catch (Throwable
$e) {
1639 'Something went wrong :\'( | ' . $e->getMessage() . "\n" .
1640 $e->getTraceAsString(),
1648 * Update member modification date
1652 private function updateModificationDate(): void
1655 $modif_date = date('Y-m-d');
1656 $update = $this->zdb
->update(self
::TABLE
);
1658 array('date_modif_adh' => $modif_date)
1659 )->where([self
::PK
=> $this->_id
]);
1661 $edit = $this->zdb
->execute($update);
1662 $this->_modification_date
= $modif_date;
1663 } catch (Throwable
$e) {
1665 'Something went wrong updating modif date :\'( | ' .
1666 $e->getMessage() . "\n" . $e->getTraceAsString(),
1674 * Global getter method
1676 * @param string $name name of the property we want to retrieve
1680 public function __get(string $name)
1683 'admin', 'staff', 'due_free', 'appears_in_list', 'active',
1684 'row_classes', 'oldness', 'duplicate', 'groups', 'managed_groups'
1686 if (!defined('GALETTE_TESTS')) {
1687 $forbidden[] = 'password'; //keep that for tests only
1691 'sadmin', 'sstaff', 'sdue_free', 'sappears_in_list', 'sactive',
1692 'stitle', 'sstatus', 'sfullname', 'sname', 'saddress',
1693 'rbirthdate', 'sgender', 'contribstatus',
1696 $socials = array('website', 'msn', 'jabber', 'icq');
1698 if (in_array($name, $forbidden)) {
1700 'Calling property "' . $name . '" directly is discouraged.',
1705 return $this->isAdmin();
1707 return $this->isStaff();
1709 return $this->isDueFree();
1710 case 'appears_in_list':
1711 return $this->appearsInMembersList();
1713 return $this->isActive();
1715 return $this->isDuplicate();
1717 return $this->getGroups();
1718 case 'managed_groups':
1719 return $this->getManagedGroups();
1721 throw new \
RuntimeException("Call to __get for '$name' is forbidden!");
1725 if (in_array($name, $virtuals)) {
1726 if (substr($name, 0, 1) !== '_') {
1727 $real = '_' . substr($name, 1);
1734 case 'sappears_in_list':
1736 return (($this->$real) ?
_T("Yes") : _T("No"));
1739 return (($this->$real) ?
_T("Active") : _T("Inactive"));
1742 if (isset($this->_title
) && $this->_title
instanceof Title
) {
1743 return $this->_title
->tshort
;
1749 $status = new Status($this->zdb
);
1750 return $status->getLabel($this->_status
);
1752 return $this->getNameWithCase(
1755 (isset($this->_title
) ?
$this->title
: false)
1758 $address = $this->_address
;
1761 return $this->getNameWithCase($this->_name
, $this->_surname
);
1763 return $this->_birthdate
;
1765 switch ($this->gender
) {
1771 return _T('Unspecified');
1773 case 'contribstatus':
1774 return $this->getDues();
1778 //for backward compatibility
1779 if (in_array($name, $socials)) {
1780 $values = Social
::getListForMember($this->_id
, $name);
1781 return $values[0] ??
null;
1784 if (substr($name, 0, 1) !== '_') {
1785 $rname = '_' . $name;
1793 if ($this->$rname !== null) {
1794 return (int)$this->$rname;
1799 return $this->$rname ??
'';
1801 case 'creation_date':
1802 case 'modification_date':
1804 if ($this->$rname != '') {
1806 $d = new \
DateTime($this->$rname);
1807 return $d->format(__("Y-m-d"));
1808 } catch (Throwable
$e) {
1809 //oops, we've got a bad date :/
1811 'Bad date (' . $this->$rname . ') | ' .
1815 return $this->$rname;
1820 return ($this->_parent
instanceof Adherent
) ?
(int)$this->_parent
->id
: (int)$this->_parent
;
1822 if (!property_exists($this, $rname)) {
1824 "Unknown property '$rname'",
1829 return $this->$rname;
1835 * Global isset method
1836 * Required for twig to access properties via __get
1838 * @param string $name name of the property we want to retrieve
1842 public function __isset(string $name)
1845 'admin', 'staff', 'due_free', 'appears_in_list', 'active',
1846 'row_classes', 'oldness', 'duplicate', 'groups', 'managed_groups'
1848 if (!defined('GALETTE_TESTS')) {
1849 $forbidden[] = 'password'; //keep that for tests only
1853 'sadmin', 'sstaff', 'sdue_free', 'sappears_in_list', 'sactive',
1854 'stitle', 'sstatus', 'sfullname', 'sname', 'saddress',
1855 'rbirthdate', 'sgender', 'contribstatus',
1858 $socials = array('website', 'msn', 'jabber', 'icq');
1860 if (in_array($name, $forbidden)) {
1862 'Calling property "' . $name . '" directly is discouraged.',
1869 case 'appears_in_list':
1873 case 'managed_groups':
1880 if (in_array($name, $virtuals)) {
1884 //for backward compatibility
1885 if (in_array($name, $socials)) {
1889 if (substr($name, 0, 1) !== '_') {
1890 $rname = '_' . $name;
1900 case 'creation_date':
1901 case 'modification_date':
1906 return property_exists($this, $rname);
1914 * If member does not have an email address, but is attached to
1915 * another member, we'll take information from its parent.
1919 public function getEmail(): string
1921 $email = $this->_email
;
1922 if (empty($email)) {
1923 $this->loadParent();
1924 $email = $this->parent
->email
;
1927 //@phpstan-ignore-next-line
1928 return $email ??
'';
1932 * Get member address.
1933 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1937 public function getAddress(): string
1939 $address = $this->_address
;
1940 if (empty($address) && $this->hasParent()) {
1941 $this->loadParent();
1942 $address = $this->parent
->address
;
1945 return $address ??
'';
1949 * Get member zipcode.
1950 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1954 public function getZipcode(): string
1956 $address = $this->_address
;
1957 $zip = $this->_zipcode
;
1958 if (empty($address) && $this->hasParent()) {
1959 $this->loadParent();
1960 $zip = $this->parent
->zipcode
;
1968 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1972 public function getTown(): string
1974 $address = $this->_address
;
1975 $town = $this->_town
;
1976 if (empty($address) && $this->hasParent()) {
1977 $this->loadParent();
1978 $town = $this->parent
->town
;
1985 * Get member country.
1986 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1990 public function getCountry(): string
1992 $address = $this->_address
;
1993 $country = $this->_country
;
1994 if (empty($address) && $this->hasParent()) {
1995 $this->loadParent();
1996 $country = $this->parent
->country
;
1999 return $country ??
'';
2007 public function getAge(): string
2009 if ($this->_birthdate
== null) {
2013 $d = \DateTime
::createFromFormat('Y-m-d', $this->_birthdate
);
2016 'Invalid birthdate: ' . $this->_birthdate
,
2024 $d->diff(new \
DateTime())->y
,
2025 _T(' (%age years old)')
2030 * Get parent inherited fields
2034 public function getParentFields(): array
2036 return $this->parent_fields
;
2040 * Handle files (photo and dynamics files)
2042 * @param array $files Files sent
2044 * @return array|true
2046 public function handleFiles(array $files)
2050 if (isset($files['photo'])) {
2051 if ($files['photo']['error'] === UPLOAD_ERR_OK
) {
2052 if ($files['photo']['tmp_name'] != '') {
2053 if (is_uploaded_file($files['photo']['tmp_name'])) {
2054 $res = $this->picture
->store($files['photo']);
2057 = $this->picture
->getErrorMessage($res);
2061 } elseif ($files['photo']['error'] !== UPLOAD_ERR_NO_FILE
) {
2063 $this->picture
->getPhpErrorMessage($files['photo']['error']),
2066 $this->errors
[] = $this->picture
->getPhpErrorMessage(
2067 $files['photo']['error']
2071 $this->dynamicsFiles($files);
2073 if (count($this->errors
) > 0) {
2075 'Some errors has been thew attempting to edit/store a member files' . "\n" .
2076 print_r($this->errors
, true),
2079 return $this->errors
;
2086 * Set member as duplicate
2090 public function setDuplicate(): void
2092 //mark as duplicated
2093 $this->_duplicate
= true;
2094 $infos = $this->_others_infos_admin
;
2095 $this->_others_infos_admin
= str_replace(
2097 [$this->sname
, $this->_id
],
2098 _T('Duplicated from %name (%id)')
2100 if (!empty($infos)) {
2101 $this->_others_infos_admin
.= "\n" . $infos;
2105 //drop email, must be unique
2106 $this->_email
= null;
2107 //drop creation date
2108 $this->_creation_date
= date("Y-m-d");
2110 $this->_login
= null;
2112 $this->_picture
= new Picture();
2114 $this->_birthdate
= null;
2116 $this->_surname
= null;
2118 $this->_admin
= false;
2120 $this->_due_free
= false;
2124 * Get current errors
2128 public function getErrors(): array
2130 return $this->errors
;
2138 public function getGroups(): array
2140 if (!$this->isDepEnabled('groups')) {
2141 $this->loadGroups();
2143 return $this->_groups
;
2147 * Get user managed groups
2151 public function getManagedGroups(): array
2153 if (!$this->isDepEnabled('groups')) {
2154 $this->loadGroups();
2156 return $this->_managed_groups
;
2160 * Can current logged-in user create member
2162 * @param Login $login Login instance
2166 public function canCreate(Login
$login): bool
2168 global $preferences;
2170 if ($this->id
&& $login->id
== $this->id ||
$login->isAdmin() ||
$login->isStaff()) {
2174 if ($preferences->pref_bool_groupsmanagers_create_member
&& $login->isGroupManager()) {
2178 if ($preferences->pref_bool_create_member
&& $login->isLogged()) {
2186 * Can current logged-in user edit member
2188 * @param Login $login Login instance
2192 public function canEdit(Login
$login): bool
2194 global $preferences;
2196 //admin and staff users can edit, as well as member itself
2197 if ($this->id
&& $login->id
== $this->id ||
$login->isAdmin() ||
$login->isStaff()) {
2201 //parent can edit their child cards
2202 if ($this->hasParent() && $this->parent_id
=== $login->id
) {
2206 //group managers can edit members of groups they manage when pref is on
2207 if ($preferences->pref_bool_groupsmanagers_edit_member
&& $login->isGroupManager()) {
2208 foreach ($this->getGroups() as $g) {
2209 if ($login->isGroupManager($g->getId())) {
2219 * Can current logged-in user display member
2221 * @param Login $login Login instance
2225 public function canShow(Login
$login): bool
2227 //group managers can show members of groups they manage
2228 if ($login->isGroupManager()) {
2229 foreach ($this->getGroups() as $g) {
2230 if ($login->isGroupManager($g->getId())) {
2236 return $this->canEdit($login);
2240 * Are we currently duplicated a member?
2244 public function isDuplicate(): bool
2246 return $this->_duplicate
;
2250 * Flag creation mail sending
2252 * @param boolean $send True (default) to send creation email
2256 public function setSendmail(bool $send = true): self
2258 $this->sendmail
= $send;
2263 * Should we send administrative emails to member?
2267 public function sendEMail(): bool
2269 return $this->sendmail
;
2275 * @param integer $id Parent identifier
2279 public function setParent(int $id): self
2281 $this->_parent
= $id;
2282 $this->loadParent();
2287 * Reset dependencies to load
2291 public function disableAllDeps(): self
2293 foreach ($this->_deps
as &$dep) {
2300 * Enable all dependencies to load
2304 public function enableAllDeps(): self
2306 foreach ($this->_deps
as &$dep) {
2313 * Enable a load dependency
2315 * @param string $name Dependency name
2319 public function enableDep(string $name): self
2321 if (!isset($this->_deps
[$name])) {
2323 'dependency ' . $name . ' does not exists!',
2327 $this->_deps
[$name] = true;
2334 * Enable a load dependency
2336 * @param string $name Dependency name
2340 public function disableDep(string $name): self
2342 if (!isset($this->_deps
[$name])) {
2344 'dependency ' . $name . ' does not exists!',
2348 $this->_deps
[$name] = false;
2355 * Is load dependency enabled?
2357 * @param string $name Dependency name
2361 protected function isDepEnabled(string $name): bool
2363 return $this->_deps
[$name];