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 $this->$prop = ($value instanceof Adherent
) ?
(int)$value->id
: (int)$value;
1461 $this->loadParent();
1471 public function store(): bool
1473 global $hist, $emitter, $login;
1476 if (!$login->isAdmin() && !$login->isStaff() && !$login->isGroupManager() && $this->id
== '') {
1477 if ($this->preferences
->pref_bool_create_member
) {
1478 $this->_parent
= $login->id
;
1484 $fields = self
::getDbFields($this->zdb
);
1486 foreach ($fields as $field) {
1488 $field !== 'date_modif_adh'
1489 ||
empty($this->_id
)
1491 $prop = '_' . $this->fields
[$field]['propname'];
1493 ($field === 'bool_admin_adh'
1494 ||
$field === 'bool_exempt_adh'
1495 ||
$field === 'bool_display_info'
1496 ||
$field === 'activite_adh')
1497 && $this->$prop === false
1499 //Handle booleans for postgres ; bugs #18899 and #19354
1500 $values[$field] = $this->zdb
->isPostgres() ?
'false' : 0;
1501 } elseif ($field === 'parent_id') {
1503 if ($this->_parent
=== null) {
1504 $values['parent_id'] = new Expression('NULL');
1505 } elseif ($this->parent
instanceof Adherent
) {
1506 $values['parent_id'] = $this->_parent
->id
;
1508 $values['parent_id'] = $this->_parent
;
1511 $values[$field] = $this->$prop;
1516 //an empty value will cause date to be set to 1901-01-01, a null
1517 //will result in 0000-00-00. We want a database NULL value here.
1518 if (!$this->_birthdate
) {
1519 $values['ddn_adh'] = new Expression('NULL');
1521 if (!$this->_due_date
) {
1522 $values['date_echeance'] = new Expression('NULL');
1525 if ($this->_title
instanceof Title
) {
1526 $values['titre_adh'] = $this->_title
->id
;
1528 $values['titre_adh'] = new Expression('NULL');
1531 if (!$this->_parent
) {
1532 $values['parent_id'] = new Expression('NULL');
1535 if (!$this->_number
) {
1536 $values['num_adh'] = new Expression('NULL');
1539 //fields that cannot be null
1541 '_surname' => 'prenom_adh',
1542 '_nickname' => 'pseudo_adh',
1543 '_address' => 'adresse_adh',
1544 '_zipcode' => 'cp_adh',
1545 '_town' => 'ville_adh'
1547 foreach ($notnull as $prop => $field) {
1548 if ($this->$prop === null) {
1549 $values[$field] = '';
1553 if (empty($this->_id
)) {
1554 //we're inserting a new member
1555 unset($values[self
::PK
]);
1556 //set modification date
1557 $this->_modification_date
= date('Y-m-d');
1558 $values['date_modif_adh'] = $this->_modification_date
;
1560 $insert = $this->zdb
->insert(self
::TABLE
);
1561 $insert->values($values);
1562 $add = $this->zdb
->execute($insert);
1563 if ($add->count() > 0) {
1564 $this->_id
= $this->zdb
->getLastGeneratedValue($this);
1565 $this->_picture
= new Picture($this->_id
);
1567 if ($this->_self_adh
) {
1569 _T("Self_subscription as a member: ") .
1570 $this->getNameWithCase($this->_name
, $this->_surname
),
1575 _T("Member card added"),
1580 $event = $this->getAddEventName();
1582 $hist->add(_T("Fail to add new member."));
1583 throw new \
Exception(
1584 'An error occurred inserting new member!'
1588 //we're editing an existing member
1589 if (!$this->isDueFree()) {
1591 $due_date = Contribution
::getDueDate($this->zdb
, $this->_id
);
1593 $values['date_echeance'] = $due_date;
1597 if (!$this->_password
) {
1598 unset($values['mdp_adh']);
1601 $update = $this->zdb
->update(self
::TABLE
);
1602 $update->set($values);
1603 $update->where([self
::PK
=> $this->_id
]);
1605 $edit = $this->zdb
->execute($update);
1607 //edit == 0 does not mean there were an error, but that there
1608 //were nothing to change
1609 if ($edit->count() > 0) {
1610 $this->updateModificationDate();
1612 _T("Member card updated"),
1616 $event = $this->getEditEventName();
1620 $this->dynamicsStore();
1621 $this->storeSocials($this->id
);
1623 //send event at the end of process, once all has been stored
1624 if ($event !== null && $this->areEventsEnabled()) {
1625 $emitter->dispatch(new GaletteEvent($event, $this));
1628 } catch (Throwable
$e) {
1630 'Something went wrong :\'( | ' . $e->getMessage() . "\n" .
1631 $e->getTraceAsString(),
1639 * Update member modification date
1643 private function updateModificationDate(): void
1646 $modif_date = date('Y-m-d');
1647 $update = $this->zdb
->update(self
::TABLE
);
1649 array('date_modif_adh' => $modif_date)
1650 )->where([self
::PK
=> $this->_id
]);
1652 $this->zdb
->execute($update);
1653 $this->_modification_date
= $modif_date;
1654 } catch (Throwable
$e) {
1656 'Something went wrong updating modif date :\'( | ' .
1657 $e->getMessage() . "\n" . $e->getTraceAsString(),
1665 * Global getter method
1667 * @param string $name name of the property we want to retrieve
1671 public function __get(string $name)
1674 'admin', 'staff', 'due_free', 'appears_in_list', 'active',
1675 'row_classes', 'oldness', 'duplicate', 'groups', 'managed_groups'
1677 if (!defined('GALETTE_TESTS')) {
1678 $forbidden[] = 'password'; //keep that for tests only
1682 'sadmin', 'sstaff', 'sdue_free', 'sappears_in_list', 'sactive',
1683 'stitle', 'sstatus', 'sfullname', 'sname', 'saddress',
1684 'rbirthdate', 'sgender', 'contribstatus',
1687 $socials = array('website', 'msn', 'jabber', 'icq');
1689 if (in_array($name, $forbidden)) {
1691 'Calling property "' . $name . '" directly is discouraged.',
1696 return $this->isAdmin();
1698 return $this->isStaff();
1700 return $this->isDueFree();
1701 case 'appears_in_list':
1702 return $this->appearsInMembersList();
1704 return $this->isActive();
1706 return $this->isDuplicate();
1708 return $this->getGroups();
1709 case 'managed_groups':
1710 return $this->getManagedGroups();
1712 throw new \
RuntimeException("Call to __get for '$name' is forbidden!");
1716 if (in_array($name, $virtuals)) {
1717 if (substr($name, 0, 1) !== '_') {
1718 $real = '_' . substr($name, 1);
1724 return (($this->isAdmin()) ?
_T("Yes") : _T("No"));
1726 return (($this->isDueFree()) ?
_T("Yes") : _T("No"));
1727 case 'sappears_in_list':
1728 return (($this->appearsInMembersList()) ?
_T("Yes") : _T("No"));
1730 return (($this->$real) ?
_T("Yes") : _T("No"));
1732 return (($this->isActive()) ?
_T("Active") : _T("Inactive"));
1734 if (isset($this->_title
) && $this->_title
instanceof Title
) {
1735 return $this->_title
->tshort
;
1740 $status = new Status($this->zdb
);
1741 return $status->getLabel($this->_status
);
1743 return $this->getNameWithCase(
1746 (isset($this->_title
) ?
$this->title
: false)
1749 $address = $this->_address
;
1752 return $this->getNameWithCase($this->_name
, $this->_surname
);
1754 return $this->_birthdate
;
1756 switch ($this->gender
) {
1762 return _T('Unspecified');
1764 case 'contribstatus':
1765 return $this->getDues();
1769 //for backward compatibility
1770 if (in_array($name, $socials)) {
1771 $values = Social
::getListForMember($this->_id
, $name);
1772 return $values[0] ??
null;
1775 if (substr($name, 0, 1) !== '_') {
1776 $rname = '_' . $name;
1784 if ($this->$rname !== null) {
1785 return (int)$this->$rname;
1790 return $this->$rname ??
'';
1792 case 'creation_date':
1793 case 'modification_date':
1795 if ($this->$rname != '') {
1797 $d = new \
DateTime($this->$rname);
1798 return $d->format(__("Y-m-d"));
1799 } catch (Throwable
$e) {
1800 //oops, we've got a bad date :/
1802 'Bad date (' . $this->$rname . ') | ' .
1806 return $this->$rname;
1811 return ($this->_parent
instanceof Adherent
) ?
(int)$this->_parent
->id
: (int)$this->_parent
;
1813 if (!property_exists($this, $rname)) {
1815 "Unknown property '$rname'",
1820 return $this->$rname;
1826 * Global isset method
1827 * Required for twig to access properties via __get
1829 * @param string $name name of the property we want to retrieve
1833 public function __isset(string $name)
1836 'admin', 'staff', 'due_free', 'appears_in_list', 'active',
1837 'row_classes', 'oldness', 'duplicate', 'groups', 'managed_groups'
1839 if (!defined('GALETTE_TESTS')) {
1840 $forbidden[] = 'password'; //keep that for tests only
1844 'sadmin', 'sstaff', 'sdue_free', 'sappears_in_list', 'sactive',
1845 'stitle', 'sstatus', 'sfullname', 'sname', 'saddress',
1846 'rbirthdate', 'sgender', 'contribstatus',
1849 $socials = array('website', 'msn', 'jabber', 'icq');
1851 if (in_array($name, $forbidden)) {
1853 'Calling property "' . $name . '" directly is discouraged.',
1860 case 'appears_in_list':
1864 case 'managed_groups':
1871 if (in_array($name, $virtuals)) {
1875 //for backward compatibility
1876 if (in_array($name, $socials)) {
1880 if (substr($name, 0, 1) !== '_') {
1881 $rname = '_' . $name;
1891 case 'creation_date':
1892 case 'modification_date':
1897 return property_exists($this, $rname);
1903 * If member does not have an email address, but is attached to
1904 * another member, we'll take information from its parent.
1908 public function getEmail(): string
1910 $email = $this->_email
;
1911 if (empty($email) && $this->hasParent()) {
1912 $this->loadParent();
1913 $email = $this->parent
->email
;
1916 return $email ??
'';
1920 * Get member address.
1921 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1925 public function getAddress(): string
1927 $address = $this->_address
;
1928 if (empty($address) && $this->hasParent()) {
1929 $this->loadParent();
1930 $address = $this->parent
->address
;
1933 return $address ??
'';
1937 * Get member zipcode.
1938 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1942 public function getZipcode(): string
1944 $address = $this->_address
;
1945 $zip = $this->_zipcode
;
1946 if (empty($address) && $this->hasParent()) {
1947 $this->loadParent();
1948 $zip = $this->parent
->zipcode
;
1956 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1960 public function getTown(): string
1962 $address = $this->_address
;
1963 $town = $this->_town
;
1964 if (empty($address) && $this->hasParent()) {
1965 $this->loadParent();
1966 $town = $this->parent
->town
;
1973 * Get member country.
1974 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1978 public function getCountry(): string
1980 $address = $this->_address
;
1981 $country = $this->_country
;
1982 if (empty($address) && $this->hasParent()) {
1983 $this->loadParent();
1984 $country = $this->parent
->country
;
1987 return $country ??
'';
1995 public function getAge(): string
1997 if ($this->_birthdate
== null) {
2001 $d = \DateTime
::createFromFormat('Y-m-d', $this->_birthdate
);
2004 'Invalid birthdate: ' . $this->_birthdate
,
2012 $d->diff(new \
DateTime())->y
,
2013 _T(' (%age years old)')
2018 * Get parent inherited fields
2022 public function getParentFields(): array
2024 return $this->parent_fields
;
2028 * Handle files (photo and dynamics files)
2030 * @param array $files Files sent
2031 * @param array $cropping Cropping properties
2033 * @return array|true
2035 public function handleFiles(array $files, array $cropping = null)
2039 if (isset($files['photo'])) {
2040 if ($files['photo']['error'] === UPLOAD_ERR_OK
) {
2041 if ($files['photo']['tmp_name'] != '') {
2042 if (is_uploaded_file($files['photo']['tmp_name'])) {
2043 if ($this->preferences
->pref_force_picture_ratio
== 1 && isset($cropping)) {
2044 $res = $this->picture
->store($files['photo'], false, $cropping);
2046 $res = $this->picture
->store($files['photo']);
2050 = $this->picture
->getErrorMessage($res);
2054 } elseif ($files['photo']['error'] !== UPLOAD_ERR_NO_FILE
) {
2056 $this->picture
->getPhpErrorMessage($files['photo']['error']),
2059 $this->errors
[] = $this->picture
->getPhpErrorMessage(
2060 $files['photo']['error']
2064 $this->dynamicsFiles($files);
2066 if (count($this->errors
) > 0) {
2068 'Some errors has been thew attempting to edit/store a member files' . "\n" .
2069 print_r($this->errors
, true),
2072 return $this->errors
;
2079 * Set member as duplicate
2083 public function setDuplicate(): void
2085 //mark as duplicated
2086 $this->_duplicate
= true;
2087 $infos = $this->_others_infos_admin
;
2088 $this->_others_infos_admin
= str_replace(
2090 [$this->sname
, $this->_id
],
2091 _T('Duplicated from %name (%id)')
2093 if (!empty($infos)) {
2094 $this->_others_infos_admin
.= "\n" . $infos;
2098 //drop email, must be unique
2099 $this->_email
= null;
2100 //drop creation date
2101 $this->_creation_date
= date("Y-m-d");
2103 $this->_login
= null;
2105 $this->_picture
= new Picture();
2107 $this->_birthdate
= null;
2109 $this->_surname
= null;
2111 $this->_admin
= false;
2113 $this->_due_free
= false;
2117 * Get current errors
2121 public function getErrors(): array
2123 return $this->errors
;
2131 public function getGroups(): array
2133 if (!$this->isDepEnabled('groups')) {
2134 $this->loadGroups();
2136 return $this->_groups
;
2140 * Get user managed groups
2144 public function getManagedGroups(): array
2146 if (!$this->isDepEnabled('groups')) {
2147 $this->loadGroups();
2149 return $this->_managed_groups
;
2153 * Can current logged-in user create member
2155 * @param Login $login Login instance
2159 public function canCreate(Login
$login): bool
2161 global $preferences;
2163 if ($this->id
&& $login->id
== $this->id ||
$login->isAdmin() ||
$login->isStaff()) {
2167 if ($preferences->pref_bool_groupsmanagers_create_member
&& $login->isGroupManager()) {
2171 if ($preferences->pref_bool_create_member
&& $login->isLogged()) {
2179 * Can current logged-in user edit member
2181 * @param Login $login Login instance
2185 public function canEdit(Login
$login): bool
2187 global $preferences;
2189 //admin and staff users can edit, as well as member itself
2190 if ($this->id
&& $login->id
== $this->id ||
$login->isAdmin() ||
$login->isStaff()) {
2194 //parent can edit their child cards
2195 if ($this->hasParent() && $this->parent_id
=== $login->id
) {
2199 //group managers can edit members of groups they manage when pref is on
2200 if ($preferences->pref_bool_groupsmanagers_edit_member
&& $login->isGroupManager()) {
2201 foreach ($this->getGroups() as $g) {
2202 if ($login->isGroupManager($g->getId())) {
2212 * Can current logged-in user display member
2214 * @param Login $login Login instance
2218 public function canShow(Login
$login): bool
2220 //group managers can show members of groups they manage
2221 if ($login->isGroupManager()) {
2222 foreach ($this->getGroups() as $g) {
2223 if ($login->isGroupManager($g->getId())) {
2229 return $this->canEdit($login);
2233 * Are we currently duplicated a member?
2237 public function isDuplicate(): bool
2239 return $this->_duplicate
;
2243 * Flag creation mail sending
2245 * @param boolean $send True (default) to send creation email
2249 public function setSendmail(bool $send = true): self
2251 $this->sendmail
= $send;
2256 * Should we send administrative emails to member?
2260 public function sendEMail(): bool
2262 return $this->sendmail
;
2268 * @param integer $id Parent identifier
2272 public function setParent(int $id): self
2274 $this->_parent
= $id;
2275 $this->loadParent();
2280 * Get prefix for events
2284 protected function getEventsPrefix(): string