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
;
40 use Galette\Events\GaletteEvent
;
41 use Galette\Features\HasEvent
;
42 use Galette\Features\Socials
;
45 use Laminas\Db\Sql\Expression
;
47 use Galette\Core\Picture
;
48 use Galette\Core\GaletteMail
;
49 use Galette\Core\Password
;
50 use Galette\Core\Preferences
;
51 use Galette\Core\History
;
52 use Galette\Repository\Groups
;
53 use Galette\Core\Login
;
54 use Galette\Repository\Members
;
55 use Galette\Features\Dynamics
;
58 * Member class for galette
63 * @author Johan Cwiklinski <johan@x-tnd.be>
64 * @copyright 2009-2023 The Galette Team
65 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL License 3.0 or (at your option) any later version
66 * @link http://galette.tuxfamily.org
67 * @since Available since 0.7dev - 02-06-2009
69 * @property integer $id
70 * @property integer|Title $title Either a title id or an instance of Title
71 * @property string $stitle Title label
72 * @property string $company_name
73 * @property string $name
74 * @property ?string $surname
75 * @property string $nickname
76 * @property string $birthdate Localized birthdate
77 * @property string $rbirthdate Raw birthdate
78 * @property string $birth_place
79 * @property integer $gender
80 * @property string $sgender Gender label
81 * @property string $job
82 * @property string $language
83 * @property integer $status
84 * @property string $sstatus Status label
85 * @property string $address
86 * @property string $zipcode
87 * @property string $town
88 * @property string $country
89 * @property string $phone
90 * @property string $gsm
91 * @property string $email
92 * @property string $gnupgid
93 * @property string $fingerprint
94 * @property string $login
95 * @property string $creation_date Localized creation date
96 * @property string $modification_date Localized modification date
97 * @property string $due_date Localized due date
98 * @property string $others_infos
99 * @property string $others_infos_admin
100 * @property Picture $picture
101 * @property array $groups
102 * @property array $managed_groups
103 * @property integer|Adherent $parent Parent id if parent dep is not loaded, Adherent instance otherwise
104 * @property array $children
105 * @property boolean $admin better to rely on isAdmin()
106 * @property boolean $staff better to rely on isStaff()
107 * @property boolean $due_free better to rely on isDueFree()
108 * @property boolean $appears_in_list better to rely on appearsInMembersList()
109 * @property boolean $active better to rely on isActive()
110 * @property boolean $duplicate better to rely on isDuplicate()
111 * @property string $sadmin yes/no
112 * @property string $sstaff yes/no
113 * @property string $sdue_free yes/no
114 * @property string $sappears_in_list yes/no
115 * @property string $sactive yes/no
116 * @property string $sfullname
117 * @property string $sname
118 * @property string $saddress
119 * @property string $contribstatus State of member contributions
120 * @property integer $days_remaining
121 * @property-read integer $parent_id
122 * @property Social $social Social networks/Contact
123 * @property string $number Member number
124 * @property-read bool $self_adh
132 public const TABLE
= 'adherents';
133 public const PK
= 'id_adh';
136 public const MAN
= 1;
137 public const WOMAN
= 2;
139 public const AFTER_ADD_DEFAULT
= 0;
140 public const AFTER_ADD_TRANS
= 1;
141 public const AFTER_ADD_NEW
= 2;
142 public const AFTER_ADD_SHOW
= 3;
143 public const AFTER_ADD_LIST
= 4;
144 public const AFTER_ADD_HOME
= 5;
149 private $_company_name;
154 private $_birth_place;
160 //Contact information
169 private $_fingerprint;
170 //Galette relative information
171 private $_appears_in_list;
173 private $_staff = false;
177 private $_creation_date;
178 private $_modification_date;
180 private $_others_infos;
181 private $_others_infos_admin;
184 private $_days_remaining;
185 private $_groups = [];
186 private $_managed_groups = [];
188 private $_children = [];
189 private $_duplicate = false;
193 private $_row_classes;
195 private $_self_adh = false;
198 private $preferences;
202 private $parent_fields = [
209 private $errors = [];
211 private $sendmail = false;
214 * Default constructor
216 * @param Db $zdb Database instance
217 * @param mixed $args Either a ResultSet row, its id or its
218 * login or its email for to load s specific
219 * member, or null to just instantiate object
220 * @param false|array|null $deps Dependencies configuration, see Adherent::$_deps
222 public function __construct(Db
$zdb, $args = null, $deps = null)
228 if ($deps !== null) {
229 if (is_array($deps)) {
230 $this->setDeps($deps);
231 } elseif ($deps === false) {
233 $this->disableAllDeps();
236 '$deps should be an array, ' . gettype($deps) . ' given!',
245 ->withoutDeleteEvent()
248 if ($args == null ||
is_int($args)) {
249 if (is_int($args) && $args > 0) {
252 $this->_active
= true;
253 $this->_language
= $i18n->getID();
254 $this->_creation_date
= date("Y-m-d");
255 $this->_status
= $this->getDefaultStatus();
256 $this->_title
= null;
257 $this->_gender
= self
::NC
;
258 $gp = new Password($this->zdb
);
259 $this->_password
= $gp->makeRandomPassword();
260 $this->_picture
= new Picture();
261 $this->_admin
= false;
262 $this->_staff
= false;
263 $this->_due_free
= false;
264 $this->_appears_in_list
= false;
265 $this->_parent
= null;
267 if ($this->_deps
['dynamics'] === true) {
268 $this->loadDynamicFields();
271 } elseif (is_object($args)) {
272 $this->loadFromRS($args);
273 } elseif (is_string($args)) {
274 $this->loadFromLoginOrMail($args);
279 * Loads a member from its id
281 * @param int $id the identifier for the member to load
283 * @return bool true if query succeed, false otherwise
285 public function load(int $id): bool
288 $select = $this->zdb
->select(self
::TABLE
, 'a');
291 array('b' => PREFIX_DB
. Status
::TABLE
),
292 'a.' . Status
::PK
. '=b.' . Status
::PK
,
293 array('priorite_statut')
294 )->where(array(self
::PK
=> $id));
296 $results = $this->zdb
->execute($select);
298 if ($results->count() === 0) {
302 /** @var ArrayObject $result */
303 $result = $results->current();
304 $this->loadFromRS($result);
306 } catch (Throwable
$e) {
308 'Cannot load member form id `' . $id . '` | ' . $e->getMessage(),
316 * Loads a member from its login
318 * @param string $login login for the member to load
322 public function loadFromLoginOrMail(string $login): bool
325 $select = $this->zdb
->select(self
::TABLE
);
326 if (GaletteMail
::isValidEmail($login)) {
327 //we got a valid email address, use it
328 $select->where(array('email_adh' => $login));
330 ///we did not get an email address, consider using login
331 $select->where(array('login_adh' => $login));
334 $results = $this->zdb
->execute($select);
335 if ($results->count() > 0) {
336 /** @var ArrayObject $result */
337 $result = $results->current();
338 $this->loadFromRS($result);
341 } catch (Throwable
$e) {
343 'Cannot load member form login `' . $login . '` | ' .
352 * Populate object from a resultset row
354 * @param ArrayObject $r the resultset row
358 private function loadFromRS(ArrayObject
$r): void
360 $this->_self_adh
= false;
361 $this->_id
= $r->id_adh
;
363 if ($r->titre_adh
!== null) {
364 $this->_title
= new Title((int)$r->titre_adh
);
366 $this->_company_name
= $r->societe_adh
;
367 $this->_name
= $r->nom_adh
;
368 $this->_surname
= $r->prenom_adh
;
369 $this->_nickname
= $r->pseudo_adh
;
370 if ($r->ddn_adh
!= '1901-01-01') {
371 $this->_birthdate
= $r->ddn_adh
;
373 $this->_birth_place
= $r->lieu_naissance
;
374 $this->_gender
= (int)$r->sexe_adh
;
375 $this->_job
= $r->prof_adh
;
376 $this->_language
= $r->pref_lang
;
377 $this->_active
= $r->activite_adh
== 1;
378 $this->_status
= (int)$r->id_statut
;
379 //Contact information
380 $this->_address
= $r->adresse_adh
;
381 $this->_zipcode
= $r->cp_adh
;
382 $this->_town
= $r->ville_adh
;
383 $this->_country
= $r->pays_adh
;
384 $this->_phone
= $r->tel_adh
;
385 $this->_gsm
= $r->gsm_adh
;
386 $this->_email
= $r->email_adh
;
387 $this->_gnupgid
= $r->gpgid
;
388 $this->_fingerprint
= $r->fingerprint
;
389 //Galette relative information
390 $this->_appears_in_list
= $r->bool_display_info
== 1;
391 $this->_admin
= $r->bool_admin_adh
== 1;
393 isset($r->priorite_statut
)
394 && $r->priorite_statut
< Members
::NON_STAFF_MEMBERS
396 $this->_staff
= true;
398 $this->_due_free
= $r->bool_exempt_adh
== 1;
399 $this->_login
= $r->login_adh
;
400 $this->_password
= $r->mdp_adh
;
401 $this->_creation_date
= $r->date_crea_adh
;
402 if ($r->date_modif_adh
!= '1901-01-01') {
403 $this->_modification_date
= $r->date_modif_adh
;
405 $this->_modification_date
= $this->_creation_date
;
407 $this->_due_date
= $r->date_echeance
;
408 $this->_others_infos
= $r->info_public_adh
;
409 $this->_others_infos_admin
= $r->info_adh
;
410 $this->_number
= $r->num_adh
;
412 if ($r->parent_id
!== null) {
413 $this->_parent
= (int)$r->parent_id
;
414 if ($this->_deps
['parent'] === true) {
419 if ($this->_deps
['children'] === true) {
420 $this->loadChildren();
423 if ($this->_deps
['picture'] === true) {
424 $this->_picture
= new Picture($this->_id
);
427 if ($this->_deps
['groups'] === true) {
431 if ($this->_deps
['dues'] === true) {
435 if ($this->_deps
['dynamics'] === true) {
436 $this->loadDynamicFields();
439 if ($this->_deps
['socials'] === true) {
440 $this->loadSocials();
449 private function loadParent(): void
451 if ($this->_parent
!== null && !$this->_parent
instanceof Adherent
) {
452 $deps = array_fill_keys(array_keys($this->_deps
), false);
453 $this->_parent
= new Adherent($this->zdb
, (int)$this->_parent
, $deps);
458 * Load member children
462 private function loadChildren(): void
464 $this->_children
= array();
467 $select = $this->zdb
->select(self
::TABLE
);
470 )->where(['parent_id' => $this->_id
]);
472 $results = $this->zdb
->execute($select);
474 if ($results->count() > 0) {
475 foreach ($results as $row) {
476 $deps = $this->_deps
;
477 $deps['children'] = false;
478 $deps['parent'] = false;
479 $this->_children
[] = new Adherent($this->zdb
, (int)$row->$id, $deps);
482 } catch (Throwable
$e) {
484 'Cannot load children for member #' . $this->_id
. ' | ' .
497 public function loadGroups(): void
499 $this->_groups
= Groups
::loadGroups($this->_id
);
500 $this->_managed_groups
= Groups
::loadManagedGroups($this->_id
);
504 * Load member social network/contact information
508 public function loadSocials(): void
510 $this->_socials
= Social
::getListForMember($this->_id
);
514 * Retrieve status from preferences
519 private function getDefaultStatus(): int
522 if ($preferences->pref_statut
!= '') {
523 return $preferences->pref_statut
;
526 'Unable to get pref_statut; is it defined in preferences?',
529 return Status
::DEFAULT_STATUS
;
534 * Check for dues status
538 private function checkDues(): void
540 //how many days since our beloved member has been created
541 $now = new \
DateTime();
542 $this->_oldness
= $now->diff(
543 new \
DateTime($this->_creation_date
)
546 if ($this->isDueFree()) {
547 //no fee required, we don't care about dates
548 $this->_row_classes
.= ' cotis-exempt';
550 //ok, fee is required. Let's check the dates
551 if ($this->_due_date
== '') {
552 $this->_row_classes
.= ' cotis-never';
554 // To count the days remaining, the next begin date is required.
555 $due_date = new \
DateTime($this->_due_date
);
556 $next_begin_date = clone $due_date;
557 $next_begin_date->add(new \
DateInterval('P1D'));
558 $date_diff = $now->diff($next_begin_date);
559 $this->_days_remaining
= $date_diff->days
;
561 if ($date_diff->invert
== 0 && $date_diff->days
>= 0) {
562 $this->_days_remaining
= $date_diff->days
;
563 if ($this->_days_remaining
<= 30) {
564 if ($date_diff->days
== 0) {
565 $this->_row_classes
.= ' cotis-lastday';
567 $this->_row_classes
.= ' cotis-soon';
569 $this->_row_classes
.= ' cotis-ok';
572 } elseif ($date_diff->invert
== 1 && $date_diff->days
>= 0) {
573 $this->_days_remaining
= $date_diff->days
;
574 //check if member is still active
575 $this->_row_classes
.= $this->isActive() ?
' cotis-late' : ' cotis-old';
586 public function isAdmin(): bool
588 return $this->_admin
;
592 * Is user member of staff?
596 public function isStaff(): bool
598 return $this->_staff
;
602 * Is member freed of dues?
606 public function isDueFree(): bool
608 return $this->_due_free
;
612 * Is member in specified group?
614 * @param string $group_name Group name
618 public function isGroupMember(string $group_name): bool
620 if (!$this->isDepEnabled('groups')) {
624 foreach ($this->_groups
as $g) {
625 if ($g->getName() == $group_name) {
633 * Is member manager of specified group?
635 * @param string $group_name Group name
639 public function isGroupManager(string $group_name): bool
641 if (!$this->isDepEnabled('groups')) {
645 foreach ($this->_managed_groups
as $mg) {
646 if ($mg->getName() == $group_name) {
654 * Does current member represents a company?
658 public function isCompany(): bool
660 return trim($this->_company_name ??
'') != '';
664 * Is current member a man?
668 public function isMan(): bool
670 return (int)$this->_gender
=== self
::MAN
;
674 * Is current member a woman?
678 public function isWoman(): bool
680 return (int)$this->_gender
=== self
::WOMAN
;
685 * Can member appears in public members list?
689 public function appearsInMembersList(): bool
691 return $this->_appears_in_list
;
699 public function isActive(): bool
701 return $this->_active
;
705 * Does member have uploaded a picture?
709 public function hasPicture(): bool
711 return $this->_picture
->hasPicture();
715 * Does member have a parent?
719 public function hasParent(): bool
721 return !empty($this->_parent
);
725 * Does member have children?
729 public function hasChildren(): bool
731 if ($this->_children
=== null) {
734 'Children has not been loaded!',
740 return count($this->_children
) > 0;
745 * Get row class related to current fee status
747 * @param boolean $public we want the class for public pages
749 * @return string the class to apply
751 public function getRowClass(bool $public = false): string
753 $strclass = ($this->isActive()) ?
'active-account' : 'inactive-account';
754 if ($public === false) {
755 $strclass .= $this->_row_classes
;
761 * Get current member due status
763 * @return string i18n string representing state of due
765 public function getDues(): string
768 $never_contributed = false;
769 $now = new \
DateTime();
770 // To count the days remaining, the next begin date is required.
771 if ($this->_due_date
=== null) {
772 $this->_due_date
= $now->format('Y-m-d');
773 $never_contributed = true;
775 $due_date = new \
DateTime($this->_due_date
);
776 $next_begin_date = clone $due_date;
777 $next_begin_date->add(new \
DateInterval('P1D'));
778 $date_diff = $now->diff($next_begin_date);
779 if ($this->isDueFree()) {
780 $ret = _T("Freed of dues");
781 } elseif ($never_contributed === true) {
782 $patterns = array('/%days/', '/%date/');
783 $cdate = new \
DateTime($this->_creation_date
);
786 $cdate->format(__("Y-m-d"))
788 if ($this->_active
) {
792 _T("Never contributed: Registered %days days ago (since %date)")
795 $ret = _T("Never contributed");
797 // Last active or first expired day
798 } elseif ($this->_days_remaining
== 0) {
799 if ($date_diff->invert
== 0) {
800 $ret = _T("Last day!");
802 $ret = _T("Late since today!");
805 } elseif ($date_diff->invert
== 0 && $this->_days_remaining
> 0) {
806 $patterns = array('/%days/', '/%date/');
808 $this->_days_remaining
,
809 $due_date->format(__("Y-m-d"))
814 _T("%days days remaining (ending on %date)")
817 } elseif ($date_diff->invert
== 1 && $this->_days_remaining
> 0) {
818 $patterns = array('/%days/', '/%date/');
820 // We need the number of days expired, not the number of days remaining.
821 $this->_days_remaining +
1,
822 $due_date->format(__("Y-m-d"))
824 if ($this->_active
) {
828 _T("Late of %days days (since %date)")
831 $ret = _T("No longer member");
838 * Retrieve Full name and surname for the specified member id
840 * @param Db $zdb Database instance
841 * @param integer $id Member id
842 * @param boolean $wid Add member id
843 * @param boolean $wnick Add member nickname
845 * @return string formatted Name and Surname
847 public static function getSName(Db
$zdb, int $id, bool $wid = false, bool $wnick = false): string
850 $select = $zdb->select(self
::TABLE
);
851 $select->where([self
::PK
=> $id]);
853 $results = $zdb->execute($select);
854 $row = $results->current();
855 return self
::getNameWithCase(
859 ($wid === true ?
$row->id_adh
: false),
860 ($wnick === true ?
$row->pseudo_adh
: false)
862 } catch (Throwable
$e) {
864 'Cannot get formatted name for member form id `' . $id . '` | ' .
873 * Get member name with correct case
875 * @param string $name Member name
876 * @param string $surname Member surname
877 * @param false|Title $title Member title to show or false
878 * @param false|integer $id Member id to display or false
879 * @param false|string $nick Member nickname to display or false
883 public static function getNameWithCase(
892 if ($title instanceof Title
) {
893 $str .= $title->tshort
. ' ';
896 $str .= mb_strtoupper($name ??
'', 'UTF-8') . ' ' .
897 ucwords(mb_strtolower($surname ??
'', 'UTF-8'), " \t\r\n\f\v-_|");
899 if ($id !== false ||
!empty($nick)) {
911 if ($id !== false ||
!empty($nick)) {
914 return strip_tags($str);
918 * Change password for a given user
920 * @param Db $zdb Database instance
921 * @param integer $id_adh Member identifier
922 * @param string $pass New password
926 public static function updatePassword(Db
$zdb, int $id_adh, string $pass): bool
929 $cpass = password_hash($pass, PASSWORD_BCRYPT
);
931 $update = $zdb->update(self
::TABLE
);
933 array('mdp_adh' => $cpass)
934 )->where([self
::PK
=> $id_adh]);
935 $zdb->execute($update);
937 'Password for `' . $id_adh . '` has been updated.',
941 } catch (Throwable
$e) {
943 'An error occurred while updating password for `' . $id_adh .
944 '` | ' . $e->getMessage(),
954 * @param string $field Field name
958 private function getFieldLabel(string $field): string
960 $label = $this->fields
[$field]['label'] ??
'';
962 $label = str_replace(' ', ' ', $label);
963 //remove trailing ':' and then trim
964 $label = trim(trim($label, ':'));
969 * Retrieve fields from database
971 * @param Db $zdb Database instance
975 public static function getDbFields(Db
$zdb): array
977 $columns = $zdb->getColumns(self
::TABLE
);
979 foreach ($columns as $col) {
980 $fields[] = $col->getName();
986 * Mark as self membership
990 public function setSelfMembership(): void
992 $this->_self_adh
= true;
996 * Is member up to date?
1000 public function isUp2Date(): bool
1002 if (!$this->isDepEnabled('dues')) {
1006 if ($this->isDueFree()) {
1007 //member is due free, he's up to date.
1010 //let's check from due date, if present
1011 if ($this->_due_date
== null) {
1014 $due_date = new \
DateTime($this->_due_date
);
1015 $now = new \
DateTime();
1016 $now->setTime(0, 0, 0);
1017 return $due_date >= $now;
1025 * @param Preferences $preferences Preferences instance
1026 * @param array $fields Members fields configuration
1027 * @param History $history History instance
1031 public function setDependencies(
1032 Preferences
$preferences,
1036 $this->preferences
= $preferences;
1037 $this->fields
= $fields;
1038 $this->history
= $history;
1042 * Check posted values validity
1044 * @param array $values All values to check, basically the $_POST array
1045 * after sending the form
1046 * @param array $required Array of required fields
1047 * @param array $disabled Array of disabled fields
1049 * @return true|array
1051 public function check(array $values, array $required, array $disabled)
1055 $this->errors
= array();
1058 foreach ($values as &$rawvalue) {
1059 if (is_string($rawvalue)) {
1060 $rawvalue = strip_tags($rawvalue);
1064 $fields = self
::getDbFields($this->zdb
);
1066 //reset company name if needed
1067 if (!isset($values['is_company'])) {
1068 unset($values['is_company']);
1069 $values['societe_adh'] = '';
1072 //no parent if checkbox was unchecked
1074 !isset($values['attach'])
1075 && empty($this->_id
)
1076 && isset($values['parent_id'])
1078 unset($values['parent_id']);
1081 if (isset($values['duplicate'])) {
1082 //if we're duplicating, keep a trace (if an error occurs)
1083 $this->_duplicate
= true;
1086 foreach ($fields as $key) {
1087 //first, let's sanitize values
1088 $key = strtolower($key);
1089 $prop = '_' . $this->fields
[$key]['propname'];
1091 if (isset($values[$key])) {
1092 $value = $values[$key];
1093 if ($value !== true && $value !== false) {
1094 //@phpstan-ignore-next-line
1095 $value = trim($value ??
'');
1097 } elseif (empty($this->_id
)) {
1099 case 'bool_admin_adh':
1100 case 'bool_exempt_adh':
1101 case 'bool_display_info':
1104 case 'activite_adh':
1105 //values that are set at object instantiation
1108 case 'date_crea_adh':
1114 //values that are set at object instantiation
1115 $value = $this->$prop;
1125 //keep stored value on update
1126 if ($prop != '_password' ||
isset($values['mdp_adh']) && isset($values['mdp_adh2'])) {
1127 $value = $this->$prop;
1133 // if the field is enabled, check it
1134 if (!isset($disabled[$key])) {
1135 // fill up the adherent structure
1136 if ($value !== null && $value !== true && $value !== false && !is_object($value)) {
1137 $value = stripslashes($value);
1139 $this->$prop = $value;
1141 // now, check validity
1142 if ($value !== null && $value != '') {
1143 if ($key !== 'mdp_adh') {
1144 $this->validate($key, $value, $values);
1146 } elseif (empty($this->_id
)) {
1147 //ensure login and password are not empty
1148 if (($key == 'login_adh' ||
$key == 'mdp_adh') && !isset($required[$key])) {
1149 $p = new Password($this->zdb
);
1150 $generated_value = $p->makeRandomPassword(15);
1151 if ($key == 'login_adh') {
1152 //'@' is not permitted in logins
1153 $this->$prop = str_replace('@', 'a', $generated_value);
1155 $this->$prop = $generated_value;
1162 //password checks need data to be previously set
1163 if (isset($values['mdp_adh'])) {
1164 $this->validate('mdp_adh', $values['mdp_adh'], $values);
1167 // missing required fields?
1168 foreach ($required as $key => $val) {
1169 $prop = '_' . $this->fields
[$key]['propname'];
1171 if (!isset($disabled[$key])) {
1172 $mandatory_missing = false;
1173 if (!isset($this->$prop) ||
$this->$prop == '') {
1174 $mandatory_missing = true;
1175 } elseif ($key === 'titre_adh' && $this->$prop == '-1') {
1176 $mandatory_missing = true;
1179 if ($mandatory_missing === true) {
1180 $this->errors
[] = str_replace(
1182 '<a href="#' . $key . '">' . $this->getFieldLabel($key) . '</a>',
1183 _T("- Mandatory field %field empty.")
1189 //attach to/detach from parent
1190 if (isset($values['detach_parent'])) {
1191 $this->_parent
= null;
1194 if ($login->isGroupManager() && !$login->isAdmin() && !$login->isStaff() && $this->parent_id
!== $login->id
) {
1195 if (!isset($values['groups_adh'])) {
1196 $this->errors
[] = _T('You have to select a group you own!');
1198 $owned_group = false;
1199 foreach ($values['groups_adh'] as $group) {
1200 list($gid) = explode('|', $group);
1201 if ($login->isGroupManager($gid)) {
1202 $owned_group = true;
1205 if ($owned_group === false) {
1206 $this->errors
[] = _T('You have to select a group you own!');
1211 $this->dynamicsCheck($values, $required, $disabled);
1212 $this->checkSocials($values);
1214 if (count($this->errors
) > 0) {
1216 'Some errors has been thew attempting to edit/store a member' . "\n" .
1217 print_r($this->errors
, true),
1220 return $this->errors
;
1225 'Member checked successfully.',
1233 * Validate data for given key
1234 * Set valid data in current object, also resets errors list
1236 * @param string $field Field name
1237 * @param mixed $value Value we want to set
1238 * @param array $values All values, for some references
1242 public function validate(string $field, $value, array $values): void
1244 global $preferences;
1246 $prop = '_' . $this->fields
[$field]['propname'];
1248 if ($value === null ||
(is_string($value) && trim($value) == '')) {
1249 //empty values are OK
1250 $this->$prop = $value;
1256 case 'date_crea_adh':
1257 case 'date_modif_adh_':
1259 case 'date_echeance':
1261 $d = \DateTime
::createFromFormat(__("Y-m-d"), $value);
1263 //try with non localized date
1264 $d = \DateTime
::createFromFormat("Y-m-d", $value);
1266 throw new \
Exception('Incorrect format');
1270 if ($field === 'ddn_adh') {
1271 $now = new \
DateTime();
1272 $now->setTime(0, 0, 0);
1273 $d->setTime(0, 0, 0);
1275 $diff = $now->diff($d);
1276 $days = (int)$diff->format('%R%a');
1278 $this->errors
[] = _T('- Birthdate must be set in the past!');
1281 $years = (int)$diff->format('%R%Y');
1282 if ($years <= -200) {
1283 $this->errors
[] = str_replace(
1286 _T('- Members must be less than 200 years old (currently %years)!')
1290 $this->$prop = $d->format('Y-m-d');
1291 } catch (Throwable
$e) {
1293 'Wrong date format. field: ' . $field .
1294 ', value: ' . $value . ', expected fmt: ' .
1295 __("Y-m-d") . ' | ' . $e->getMessage(),
1298 $this->errors
[] = str_replace(
1305 $this->getFieldLabel($field)
1307 _T("- Wrong date format (%date_format) for %field!")
1312 if ($value !== null && $value !== '') {
1313 if ($value == '-1') {
1314 $this->$prop = null;
1315 } elseif (!$value instanceof Title
) {
1316 $this->$prop = new Title((int)$value);
1319 $this->$prop = null;
1323 if (!GaletteMail
::isValidEmail($value)) {
1324 $this->errors
[] = _T("- Non-valid E-Mail address!") .
1325 ' (' . $this->getFieldLabel($field) . ')';
1329 $select = $this->zdb
->select(self
::TABLE
);
1332 )->where(array('email_adh' => $value));
1333 if (!empty($this->_id
)) {
1334 $select->where
->notEqualTo(
1340 $results = $this->zdb
->execute($select);
1341 if ($results->count() !== 0) {
1342 $this->errors
[] = _T("- This E-Mail address is already used by another member!");
1344 } catch (Throwable
$e) {
1346 'An error occurred checking member email uniqueness.',
1349 $this->errors
[] = _T("An error has occurred while looking if login already exists.");
1353 /** FIXME: add a preference for login length */
1354 if (strlen($value) < 2) {
1355 $this->errors
[] = str_replace(
1358 _T("- The username must be composed of at least %i characters!")
1361 //check if login does not contain the @ character
1362 if (strpos($value, '@') != false) {
1363 $this->errors
[] = _T("- The username cannot contain the @ character");
1365 //check if login is already taken
1367 $select = $this->zdb
->select(self
::TABLE
);
1370 )->where(array('login_adh' => $value));
1371 if (!empty($this->_id
)) {
1372 $select->where
->notEqualTo(
1378 $results = $this->zdb
->execute($select);
1380 $results->count() !== 0
1381 ||
$value == $preferences->pref_admin_login
1383 $this->errors
[] = _T("- This username is already in use, please choose another one!");
1385 } catch (Throwable
$e) {
1387 'An error occurred checking member login uniqueness.',
1390 $this->errors
[] = _T("An error has occurred while looking if login already exists.");
1397 $this->_self_adh
!== true
1398 && (!isset($values['mdp_adh2'])
1399 ||
$values['mdp_adh2'] != $value)
1401 $this->errors
[] = _T("- The passwords don't match!");
1403 $this->_self_adh
=== true
1404 && !crypt($value, $values['mdp_crypt']) == $values['mdp_crypt']
1406 $this->errors
[] = _T("Password misrepeated: ");
1408 $pinfos = password_get_info($value);
1409 //check if value is already a hash
1410 if ($pinfos['algo'] == 0) {
1411 $this->$prop = password_hash(
1416 $pwcheck = new \Galette\Util\
Password($preferences);
1417 $pwcheck->setAdherent($this);
1418 if (!$pwcheck->isValid($value)) {
1419 $this->errors
= array_merge(
1421 $pwcheck->getErrors()
1429 $this->$prop = (int)$value;
1430 //check if status exists
1431 $select = $this->zdb
->select(Status
::TABLE
);
1432 $select->where([Status
::PK
=> $value]);
1434 $results = $this->zdb
->execute($select);
1435 $result = $results->current();
1437 $this->errors
[] = str_replace(
1440 _T("Status #%id does not exists in database.")
1444 } catch (Throwable
$e) {
1446 'An error occurred checking status existence: ' . $e->getMessage(),
1449 $this->errors
[] = _T("An error has occurred while looking if status does exists.");
1453 if (in_array($value, [self
::NC
, self
::MAN
, self
::WOMAN
])) {
1454 $this->$prop = (int)$value;
1456 $this->errors
[] = _T("Gender %gender does not exists!");
1460 $pid = ($value instanceof Adherent
) ?
(int)$value->id
: (int)$value;
1461 if ($pid === $this->id
) {
1462 $this->errors
[] = _T("A member cannot be its own parent!");
1463 $this->$prop = null;
1465 $this->$prop = $pid;
1466 $this->loadParent();
1477 public function store(): bool
1479 global $hist, $emitter, $login;
1482 if (!$login->isAdmin() && !$login->isStaff() && !$login->isGroupManager() && $this->id
== '') {
1483 if ($this->preferences
->pref_bool_create_member
) {
1484 $this->_parent
= $login->id
;
1490 $fields = self
::getDbFields($this->zdb
);
1492 foreach ($fields as $field) {
1494 $field !== 'date_modif_adh'
1495 ||
empty($this->_id
)
1497 $prop = '_' . $this->fields
[$field]['propname'];
1499 ($field === 'bool_admin_adh'
1500 ||
$field === 'bool_exempt_adh'
1501 ||
$field === 'bool_display_info'
1502 ||
$field === 'activite_adh')
1503 && $this->$prop === false
1505 //Handle booleans for postgres ; bugs #18899 and #19354
1506 $values[$field] = $this->zdb
->isPostgres() ?
'false' : 0;
1507 } elseif ($field === 'parent_id') {
1509 if ($this->_parent
=== null) {
1510 $values['parent_id'] = new Expression('NULL');
1511 } elseif ($this->parent
instanceof Adherent
) {
1512 $values['parent_id'] = $this->_parent
->id
;
1514 $values['parent_id'] = $this->_parent
;
1517 $values[$field] = $this->$prop;
1522 //an empty value will cause date to be set to 1901-01-01, a null
1523 //will result in 0000-00-00. We want a database NULL value here.
1524 if (!$this->_birthdate
) {
1525 $values['ddn_adh'] = new Expression('NULL');
1527 if (!$this->_due_date
) {
1528 $values['date_echeance'] = new Expression('NULL');
1531 if ($this->_title
instanceof Title
) {
1532 $values['titre_adh'] = $this->_title
->id
;
1534 $values['titre_adh'] = new Expression('NULL');
1537 if (!$this->_parent
) {
1538 $values['parent_id'] = new Expression('NULL');
1541 if (!$this->_number
) {
1542 $values['num_adh'] = new Expression('NULL');
1545 //fields that cannot be null
1547 '_surname' => 'prenom_adh',
1548 '_nickname' => 'pseudo_adh',
1549 '_address' => 'adresse_adh',
1550 '_zipcode' => 'cp_adh',
1551 '_town' => 'ville_adh'
1553 foreach ($notnull as $prop => $field) {
1554 if ($this->$prop === null) {
1555 $values[$field] = '';
1559 if (empty($this->_id
)) {
1560 //we're inserting a new member
1561 unset($values[self
::PK
]);
1562 //set modification date
1563 $this->_modification_date
= date('Y-m-d');
1564 $values['date_modif_adh'] = $this->_modification_date
;
1566 $insert = $this->zdb
->insert(self
::TABLE
);
1567 $insert->values($values);
1568 $add = $this->zdb
->execute($insert);
1569 if ($add->count() > 0) {
1570 $this->_id
= $this->zdb
->getLastGeneratedValue($this);
1571 $this->_picture
= new Picture($this->_id
);
1573 if ($this->_self_adh
) {
1575 _T("Self_subscription as a member: ") .
1576 $this->getNameWithCase($this->_name
, $this->_surname
),
1581 _T("Member card added"),
1586 $event = $this->getAddEventName();
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"),
1622 $event = $this->getEditEventName();
1626 $this->dynamicsStore();
1627 $this->storeSocials($this->id
);
1629 //send event at the end of process, once all has been stored
1630 if ($event !== null && $this->areEventsEnabled()) {
1631 $emitter->dispatch(new GaletteEvent($event, $this));
1634 } catch (Throwable
$e) {
1636 'Something went wrong :\'( | ' . $e->getMessage() . "\n" .
1637 $e->getTraceAsString(),
1645 * Update member modification date
1649 private function updateModificationDate(): void
1652 $modif_date = date('Y-m-d');
1653 $update = $this->zdb
->update(self
::TABLE
);
1655 array('date_modif_adh' => $modif_date)
1656 )->where([self
::PK
=> $this->_id
]);
1658 $this->zdb
->execute($update);
1659 $this->_modification_date
= $modif_date;
1660 } catch (Throwable
$e) {
1662 'Something went wrong updating modif date :\'( | ' .
1663 $e->getMessage() . "\n" . $e->getTraceAsString(),
1671 * Global getter method
1673 * @param string $name name of the property we want to retrieve
1677 public function __get(string $name)
1680 'admin', 'staff', 'due_free', 'appears_in_list', 'active',
1681 'row_classes', 'oldness', 'duplicate', 'groups', 'managed_groups'
1683 if (!defined('GALETTE_TESTS')) {
1684 $forbidden[] = 'password'; //keep that for tests only
1688 'sadmin', 'sstaff', 'sdue_free', 'sappears_in_list', 'sactive',
1689 'stitle', 'sstatus', 'sfullname', 'sname', 'saddress',
1690 'rbirthdate', 'sgender', 'contribstatus',
1693 $socials = array('website', 'msn', 'jabber', 'icq');
1695 if (in_array($name, $forbidden)) {
1697 'Calling property "' . $name . '" directly is discouraged.',
1702 return $this->isAdmin();
1704 return $this->isStaff();
1706 return $this->isDueFree();
1707 case 'appears_in_list':
1708 return $this->appearsInMembersList();
1710 return $this->isActive();
1712 return $this->isDuplicate();
1714 return $this->getGroups();
1715 case 'managed_groups':
1716 return $this->getManagedGroups();
1718 throw new \
RuntimeException("Call to __get for '$name' is forbidden!");
1722 if (in_array($name, $virtuals)) {
1723 if (substr($name, 0, 1) !== '_') {
1724 $real = '_' . substr($name, 1);
1730 return (($this->isAdmin()) ?
_T("Yes") : _T("No"));
1732 return (($this->isDueFree()) ?
_T("Yes") : _T("No"));
1733 case 'sappears_in_list':
1734 return (($this->appearsInMembersList()) ?
_T("Yes") : _T("No"));
1736 return (($this->$real) ?
_T("Yes") : _T("No"));
1738 return (($this->isActive()) ?
_T("Active") : _T("Inactive"));
1740 if (isset($this->_title
) && $this->_title
instanceof Title
) {
1741 return $this->_title
->tshort
;
1746 $status = new Status($this->zdb
);
1747 return $status->getLabel($this->_status
);
1749 return $this->getNameWithCase(
1752 (isset($this->_title
) ?
$this->title
: false)
1755 $address = $this->_address
;
1758 return $this->getNameWithCase($this->_name
, $this->_surname
);
1760 return $this->_birthdate
;
1762 switch ($this->gender
) {
1768 return _T('Unspecified');
1770 case 'contribstatus':
1771 return $this->getDues();
1775 //for backward compatibility
1776 if (in_array($name, $socials)) {
1777 $values = Social
::getListForMember($this->_id
, $name);
1778 return $values[0] ??
null;
1781 if (substr($name, 0, 1) !== '_') {
1782 $rname = '_' . $name;
1790 if ($this->$rname !== null) {
1791 return (int)$this->$rname;
1796 return $this->$rname ??
'';
1798 case 'creation_date':
1799 case 'modification_date':
1801 if ($this->$rname != '') {
1803 $d = new \
DateTime($this->$rname);
1804 return $d->format(__("Y-m-d"));
1805 } catch (Throwable
$e) {
1806 //oops, we've got a bad date :/
1808 'Bad date (' . $this->$rname . ') | ' .
1812 return $this->$rname;
1817 return ($this->_parent
instanceof Adherent
) ?
(int)$this->_parent
->id
: (int)$this->_parent
;
1819 if (!property_exists($this, $rname)) {
1821 "Unknown property '$rname'",
1826 return $this->$rname;
1832 * Global isset method
1833 * Required for twig to access properties via __get
1835 * @param string $name name of the property we want to retrieve
1839 public function __isset(string $name)
1842 'admin', 'staff', 'due_free', 'appears_in_list', 'active',
1843 'row_classes', 'oldness', 'duplicate', 'groups', 'managed_groups'
1845 if (!defined('GALETTE_TESTS')) {
1846 $forbidden[] = 'password'; //keep that for tests only
1850 'sadmin', 'sstaff', 'sdue_free', 'sappears_in_list', 'sactive',
1851 'stitle', 'sstatus', 'sfullname', 'sname', 'saddress',
1852 'rbirthdate', 'sgender', 'contribstatus',
1855 $socials = array('website', 'msn', 'jabber', 'icq');
1857 if (in_array($name, $forbidden)) {
1859 'Calling property "' . $name . '" directly is discouraged.',
1866 case 'appears_in_list':
1870 case 'managed_groups':
1877 if (in_array($name, $virtuals)) {
1881 //for backward compatibility
1882 if (in_array($name, $socials)) {
1886 if (substr($name, 0, 1) !== '_') {
1887 $rname = '_' . $name;
1897 case 'creation_date':
1898 case 'modification_date':
1903 return property_exists($this, $rname);
1909 * If member does not have an email address, but is attached to
1910 * another member, we'll take information from its parent.
1914 public function getEmail(): string
1916 $email = $this->_email
;
1917 if (empty($email) && $this->hasParent()) {
1918 $this->loadParent();
1919 $email = $this->parent
->email
;
1922 return $email ??
'';
1926 * Get member address.
1927 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1931 public function getAddress(): string
1933 $address = $this->_address
;
1934 if (empty($address) && $this->hasParent()) {
1935 $this->loadParent();
1936 $address = $this->parent
->address
;
1939 return $address ??
'';
1943 * Get member zipcode.
1944 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1948 public function getZipcode(): string
1950 $address = $this->_address
;
1951 $zip = $this->_zipcode
;
1952 if (empty($address) && $this->hasParent()) {
1953 $this->loadParent();
1954 $zip = $this->parent
->zipcode
;
1962 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1966 public function getTown(): string
1968 $address = $this->_address
;
1969 $town = $this->_town
;
1970 if (empty($address) && $this->hasParent()) {
1971 $this->loadParent();
1972 $town = $this->parent
->town
;
1979 * Get member country.
1980 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1984 public function getCountry(): string
1986 $address = $this->_address
;
1987 $country = $this->_country
;
1988 if (empty($address) && $this->hasParent()) {
1989 $this->loadParent();
1990 $country = $this->parent
->country
;
1993 return $country ??
'';
2001 public function getAge(): string
2003 if ($this->_birthdate
== null) {
2007 $d = \DateTime
::createFromFormat('Y-m-d', $this->_birthdate
);
2010 'Invalid birthdate: ' . $this->_birthdate
,
2018 $d->diff(new \
DateTime())->y
,
2019 _T(' (%age years old)')
2024 * Get parent inherited fields
2028 public function getParentFields(): array
2030 return $this->parent_fields
;
2034 * Handle files (photo and dynamics files)
2036 * @param array $files Files sent
2037 * @param array $cropping Cropping properties
2039 * @return array|true
2041 public function handleFiles(array $files, array $cropping = null)
2045 if (isset($files['photo'])) {
2046 if ($files['photo']['error'] === UPLOAD_ERR_OK
) {
2047 if ($files['photo']['tmp_name'] != '') {
2048 if (is_uploaded_file($files['photo']['tmp_name'])) {
2049 if ($this->preferences
->pref_force_picture_ratio
== 1 && isset($cropping)) {
2050 $res = $this->picture
->store($files['photo'], false, $cropping);
2052 $res = $this->picture
->store($files['photo']);
2056 = $this->picture
->getErrorMessage($res);
2060 } elseif ($files['photo']['error'] !== UPLOAD_ERR_NO_FILE
) {
2062 $this->picture
->getPhpErrorMessage($files['photo']['error']),
2065 $this->errors
[] = $this->picture
->getPhpErrorMessage(
2066 $files['photo']['error']
2070 $this->dynamicsFiles($files);
2072 if (count($this->errors
) > 0) {
2074 'Some errors has been thew attempting to edit/store a member files' . "\n" .
2075 print_r($this->errors
, true),
2078 return $this->errors
;
2085 * Set member as duplicate
2089 public function setDuplicate(): void
2091 //mark as duplicated
2092 $this->_duplicate
= true;
2093 $infos = $this->_others_infos_admin
;
2094 $this->_others_infos_admin
= str_replace(
2096 [$this->sname
, $this->_id
],
2097 _T('Duplicated from %name (%id)')
2099 if (!empty($infos)) {
2100 $this->_others_infos_admin
.= "\n" . $infos;
2104 //drop email, must be unique
2105 $this->_email
= null;
2106 //drop creation date
2107 $this->_creation_date
= date("Y-m-d");
2109 $this->_login
= null;
2111 $this->_picture
= new Picture();
2113 $this->_birthdate
= null;
2115 $this->_surname
= null;
2117 $this->_admin
= false;
2119 $this->_due_free
= false;
2123 * Get current errors
2127 public function getErrors(): array
2129 return $this->errors
;
2137 public function getGroups(): array
2139 if (!$this->isDepEnabled('groups')) {
2140 $this->loadGroups();
2142 return $this->_groups
;
2146 * Get user managed groups
2150 public function getManagedGroups(): array
2152 if (!$this->isDepEnabled('groups')) {
2153 $this->loadGroups();
2155 return $this->_managed_groups
;
2159 * Can current logged-in user create member
2161 * @param Login $login Login instance
2165 public function canCreate(Login
$login): bool
2167 global $preferences;
2169 if ($this->id
&& $login->id
== $this->id ||
$login->isAdmin() ||
$login->isStaff()) {
2173 if ($preferences->pref_bool_groupsmanagers_create_member
&& $login->isGroupManager()) {
2177 if ($preferences->pref_bool_create_member
&& $login->isLogged()) {
2185 * Can current logged-in user edit member
2187 * @param Login $login Login instance
2191 public function canEdit(Login
$login): bool
2193 global $preferences;
2195 //admin and staff users can edit, as well as member itself
2196 if ($this->id
&& $login->id
== $this->id ||
$login->isAdmin() ||
$login->isStaff()) {
2200 //parent can edit their child cards
2201 if ($this->hasParent() && $this->parent_id
=== $login->id
) {
2205 //group managers can edit members of groups they manage when pref is on
2206 if ($preferences->pref_bool_groupsmanagers_edit_member
&& $login->isGroupManager()) {
2207 foreach ($this->getGroups() as $g) {
2208 if ($login->isGroupManager($g->getId())) {
2218 * Can current logged-in user display member
2220 * @param Login $login Login instance
2224 public function canShow(Login
$login): bool
2226 //group managers can show members of groups they manage
2227 if ($login->isGroupManager()) {
2228 foreach ($this->getGroups() as $g) {
2229 if ($login->isGroupManager($g->getId())) {
2235 return $this->canEdit($login);
2239 * Are we currently duplicated a member?
2243 public function isDuplicate(): bool
2245 return $this->_duplicate
;
2249 * Flag creation mail sending
2251 * @param boolean $send True (default) to send creation email
2255 public function setSendmail(bool $send = true): self
2257 $this->sendmail
= $send;
2262 * Should we send administrative emails to member?
2266 public function sendEMail(): bool
2268 return $this->sendmail
;
2274 * @param integer $id Parent identifier
2278 public function setParent(int $id): self
2280 $this->_parent
= $id;
2281 $this->loadParent();
2286 * Get prefix for events
2290 protected function getEventsPrefix(): string