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\Socials
;
44 use Laminas\Db\Sql\Expression
;
46 use Galette\Core\Picture
;
47 use Galette\Core\GaletteMail
;
48 use Galette\Core\Password
;
49 use Galette\Core\Preferences
;
50 use Galette\Core\History
;
51 use Galette\Repository\Groups
;
52 use Galette\Core\Login
;
53 use Galette\Repository\Members
;
54 use Galette\Features\Dynamics
;
57 * Member class for galette
62 * @author Johan Cwiklinski <johan@x-tnd.be>
63 * @copyright 2009-2023 The Galette Team
64 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL License 3.0 or (at your option) any later version
65 * @link http://galette.tuxfamily.org
66 * @since Available since 0.7dev - 02-06-2009
68 * @property integer $id
69 * @property integer|Title $title Either a title id or an instance of Title
70 * @property string $stitle Title label
71 * @property string $company_name
72 * @property string $name
73 * @property ?string $surname
74 * @property string $nickname
75 * @property string $birthdate Localized birthdate
76 * @property string $rbirthdate Raw birthdate
77 * @property string $birth_place
78 * @property integer $gender
79 * @property string $sgender Gender label
80 * @property string $job
81 * @property string $language
82 * @property integer $status
83 * @property string $sstatus Status label
84 * @property string $address
85 * @property string $zipcode
86 * @property string $town
87 * @property string $country
88 * @property string $phone
89 * @property string $gsm
90 * @property string $email
91 * @property string $gnupgid
92 * @property string $fingerprint
93 * @property string $login
94 * @property string $creation_date Localized creation date
95 * @property string $modification_date Localized modification date
96 * @property string $due_date Localized due date
97 * @property string $others_infos
98 * @property string $others_infos_admin
99 * @property Picture $picture
100 * @property array $groups
101 * @property array $managed_groups
102 * @property integer|Adherent $parent Parent id if parent dep is not loaded, Adherent instance otherwise
103 * @property array $children
104 * @property boolean $admin better to rely on isAdmin()
105 * @property boolean $staff better to rely on isStaff()
106 * @property boolean $due_free better to rely on isDueFree()
107 * @property boolean $appears_in_list better to rely on appearsInMembersList()
108 * @property boolean $active better to rely on isActive()
109 * @property boolean $duplicate better to rely on isDuplicate()
110 * @property string $sadmin yes/no
111 * @property string $sstaff yes/no
112 * @property string $sdue_free yes/no
113 * @property string $sappears_in_list yes/no
114 * @property string $sactive yes/no
115 * @property string $sfullname
116 * @property string $sname
117 * @property string $saddress
118 * @property string $contribstatus State of member contributions
119 * @property integer $days_remaining
120 * @property-read integer $parent_id
121 * @property Social $social Social networks/Contact
122 * @property string $number Member number
123 * @property-read bool $self_adh
130 public const TABLE
= 'adherents';
131 public const PK
= 'id_adh';
134 public const MAN
= 1;
135 public const WOMAN
= 2;
137 public const AFTER_ADD_DEFAULT
= 0;
138 public const AFTER_ADD_TRANS
= 1;
139 public const AFTER_ADD_NEW
= 2;
140 public const AFTER_ADD_SHOW
= 3;
141 public const AFTER_ADD_LIST
= 4;
142 public const AFTER_ADD_HOME
= 5;
147 private $_company_name;
152 private $_birth_place;
158 //Contact information
167 private $_fingerprint;
168 //Galette relative information
169 private $_appears_in_list;
171 private $_staff = false;
175 private $_creation_date;
176 private $_modification_date;
178 private $_others_infos;
179 private $_others_infos_admin;
182 private $_days_remaining;
183 private $_groups = [];
184 private $_managed_groups = [];
186 private $_children = [];
187 private $_duplicate = false;
191 private $_row_classes;
193 private $_self_adh = false;
196 private $preferences;
200 private $parent_fields = [
207 private $errors = [];
209 private $sendmail = false;
212 * Default constructor
214 * @param Db $zdb Database instance
215 * @param mixed $args Either a ResultSet row, its id or its
216 * login or its email for to load s specific
217 * member, or null to just instantiate object
218 * @param false|array|null $deps Dependencies configuration, see Adherent::$_deps
220 public function __construct(Db
$zdb, $args = null, $deps = null)
226 if ($deps !== null) {
227 if (is_array($deps)) {
228 $this->setDeps($deps);
229 } elseif ($deps === false) {
231 $this->disableAllDeps();
234 '$deps should be an array, ' . gettype($deps) . ' given!',
240 if ($args == null ||
is_int($args)) {
241 if (is_int($args) && $args > 0) {
244 $this->_active
= true;
245 $this->_language
= $i18n->getID();
246 $this->_creation_date
= date("Y-m-d");
247 $this->_status
= $this->getDefaultStatus();
248 $this->_title
= null;
249 $this->_gender
= self
::NC
;
250 $gp = new Password($this->zdb
);
251 $this->_password
= $gp->makeRandomPassword();
252 $this->_picture
= new Picture();
253 $this->_admin
= false;
254 $this->_staff
= false;
255 $this->_due_free
= false;
256 $this->_appears_in_list
= false;
257 $this->_parent
= null;
259 if ($this->_deps
['dynamics'] === true) {
260 $this->loadDynamicFields();
263 } elseif (is_object($args)) {
264 $this->loadFromRS($args);
265 } elseif (is_string($args)) {
266 $this->loadFromLoginOrMail($args);
271 * Loads a member from its id
273 * @param int $id the identifier for the member to load
275 * @return bool true if query succeed, false otherwise
277 public function load(int $id): bool
280 $select = $this->zdb
->select(self
::TABLE
, 'a');
283 array('b' => PREFIX_DB
. Status
::TABLE
),
284 'a.' . Status
::PK
. '=b.' . Status
::PK
,
285 array('priorite_statut')
286 )->where(array(self
::PK
=> $id));
288 $results = $this->zdb
->execute($select);
290 if ($results->count() === 0) {
294 /** @var ArrayObject $result */
295 $result = $results->current();
296 $this->loadFromRS($result);
298 } catch (Throwable
$e) {
300 'Cannot load member form id `' . $id . '` | ' . $e->getMessage(),
308 * Loads a member from its login
310 * @param string $login login for the member to load
314 public function loadFromLoginOrMail(string $login): bool
317 $select = $this->zdb
->select(self
::TABLE
);
318 if (GaletteMail
::isValidEmail($login)) {
319 //we got a valid email address, use it
320 $select->where(array('email_adh' => $login));
322 ///we did not get an email address, consider using login
323 $select->where(array('login_adh' => $login));
326 $results = $this->zdb
->execute($select);
327 if ($results->count() > 0) {
328 /** @var ArrayObject $result */
329 $result = $results->current();
330 $this->loadFromRS($result);
333 } catch (Throwable
$e) {
335 'Cannot load member form login `' . $login . '` | ' .
344 * Populate object from a resultset row
346 * @param ArrayObject $r the resultset row
350 private function loadFromRS(ArrayObject
$r): void
352 $this->_self_adh
= false;
353 $this->_id
= $r->id_adh
;
355 if ($r->titre_adh
!== null) {
356 $this->_title
= new Title((int)$r->titre_adh
);
358 $this->_company_name
= $r->societe_adh
;
359 $this->_name
= $r->nom_adh
;
360 $this->_surname
= $r->prenom_adh
;
361 $this->_nickname
= $r->pseudo_adh
;
362 if ($r->ddn_adh
!= '1901-01-01') {
363 $this->_birthdate
= $r->ddn_adh
;
365 $this->_birth_place
= $r->lieu_naissance
;
366 $this->_gender
= (int)$r->sexe_adh
;
367 $this->_job
= $r->prof_adh
;
368 $this->_language
= $r->pref_lang
;
369 $this->_active
= $r->activite_adh
== 1;
370 $this->_status
= (int)$r->id_statut
;
371 //Contact information
372 $this->_address
= $r->adresse_adh
;
373 $this->_zipcode
= $r->cp_adh
;
374 $this->_town
= $r->ville_adh
;
375 $this->_country
= $r->pays_adh
;
376 $this->_phone
= $r->tel_adh
;
377 $this->_gsm
= $r->gsm_adh
;
378 $this->_email
= $r->email_adh
;
379 $this->_gnupgid
= $r->gpgid
;
380 $this->_fingerprint
= $r->fingerprint
;
381 //Galette relative information
382 $this->_appears_in_list
= $r->bool_display_info
== 1;
383 $this->_admin
= $r->bool_admin_adh
== 1;
385 isset($r->priorite_statut
)
386 && $r->priorite_statut
< Members
::NON_STAFF_MEMBERS
388 $this->_staff
= true;
390 $this->_due_free
= $r->bool_exempt_adh
== 1;
391 $this->_login
= $r->login_adh
;
392 $this->_password
= $r->mdp_adh
;
393 $this->_creation_date
= $r->date_crea_adh
;
394 if ($r->date_modif_adh
!= '1901-01-01') {
395 $this->_modification_date
= $r->date_modif_adh
;
397 $this->_modification_date
= $this->_creation_date
;
399 $this->_due_date
= $r->date_echeance
;
400 $this->_others_infos
= $r->info_public_adh
;
401 $this->_others_infos_admin
= $r->info_adh
;
402 $this->_number
= $r->num_adh
;
404 if ($r->parent_id
!== null) {
405 $this->_parent
= (int)$r->parent_id
;
406 if ($this->_deps
['parent'] === true) {
411 if ($this->_deps
['children'] === true) {
412 $this->loadChildren();
415 if ($this->_deps
['picture'] === true) {
416 $this->_picture
= new Picture($this->_id
);
419 if ($this->_deps
['groups'] === true) {
423 if ($this->_deps
['dues'] === true) {
427 if ($this->_deps
['dynamics'] === true) {
428 $this->loadDynamicFields();
431 if ($this->_deps
['socials'] === true) {
432 $this->loadSocials();
441 private function loadParent(): void
443 if ($this->_parent
!== null && !$this->_parent
instanceof Adherent
) {
444 $deps = array_fill_keys(array_keys($this->_deps
), false);
445 $this->_parent
= new Adherent($this->zdb
, (int)$this->_parent
, $deps);
450 * Load member children
454 private function loadChildren(): void
456 $this->_children
= array();
459 $select = $this->zdb
->select(self
::TABLE
);
462 )->where(['parent_id' => $this->_id
]);
464 $results = $this->zdb
->execute($select);
466 if ($results->count() > 0) {
467 foreach ($results as $row) {
468 $deps = $this->_deps
;
469 $deps['children'] = false;
470 $deps['parent'] = false;
471 $this->_children
[] = new Adherent($this->zdb
, (int)$row->$id, $deps);
474 } catch (Throwable
$e) {
476 'Cannot load children for member #' . $this->_id
. ' | ' .
489 public function loadGroups(): void
491 $this->_groups
= Groups
::loadGroups($this->_id
);
492 $this->_managed_groups
= Groups
::loadManagedGroups($this->_id
);
496 * Load member social network/contact information
500 public function loadSocials(): void
502 $this->_socials
= Social
::getListForMember($this->_id
);
506 * Retrieve status from preferences
511 private function getDefaultStatus(): int
514 if ($preferences->pref_statut
!= '') {
515 return $preferences->pref_statut
;
518 'Unable to get pref_statut; is it defined in preferences?',
521 return Status
::DEFAULT_STATUS
;
526 * Check for dues status
530 private function checkDues(): void
532 //how many days since our beloved member has been created
533 $now = new \
DateTime();
534 $this->_oldness
= $now->diff(
535 new \
DateTime($this->_creation_date
)
538 if ($this->isDueFree()) {
539 //no fee required, we don't care about dates
540 $this->_row_classes
.= ' cotis-exempt';
542 //ok, fee is required. Let's check the dates
543 if ($this->_due_date
== '') {
544 $this->_row_classes
.= ' cotis-never';
546 // To count the days remaining, the next begin date is required.
547 $due_date = new \
DateTime($this->_due_date
);
548 $next_begin_date = clone $due_date;
549 $next_begin_date->add(new \
DateInterval('P1D'));
550 $date_diff = $now->diff($next_begin_date);
551 $this->_days_remaining
= $date_diff->days
;
553 if ($date_diff->invert
== 0 && $date_diff->days
>= 0) {
554 $this->_days_remaining
= $date_diff->days
;
555 if ($this->_days_remaining
<= 30) {
556 if ($date_diff->days
== 0) {
557 $this->_row_classes
.= ' cotis-lastday';
559 $this->_row_classes
.= ' cotis-soon';
561 $this->_row_classes
.= ' cotis-ok';
564 } elseif ($date_diff->invert
== 1 && $date_diff->days
>= 0) {
565 $this->_days_remaining
= $date_diff->days
;
566 //check if member is still active
567 $this->_row_classes
.= $this->isActive() ?
' cotis-late' : ' cotis-old';
578 public function isAdmin(): bool
580 return $this->_admin
;
584 * Is user member of staff?
588 public function isStaff(): bool
590 return $this->_staff
;
594 * Is member freed of dues?
598 public function isDueFree(): bool
600 return $this->_due_free
;
604 * Is member in specified group?
606 * @param string $group_name Group name
610 public function isGroupMember(string $group_name): bool
612 if (!$this->isDepEnabled('groups')) {
616 foreach ($this->_groups
as $g) {
617 if ($g->getName() == $group_name) {
625 * Is member manager of specified group?
627 * @param string $group_name Group name
631 public function isGroupManager(string $group_name): bool
633 if (!$this->isDepEnabled('groups')) {
637 foreach ($this->_managed_groups
as $mg) {
638 if ($mg->getName() == $group_name) {
646 * Does current member represents a company?
650 public function isCompany(): bool
652 return trim($this->_company_name ??
'') != '';
656 * Is current member a man?
660 public function isMan(): bool
662 return (int)$this->_gender
=== self
::MAN
;
666 * Is current member a woman?
670 public function isWoman(): bool
672 return (int)$this->_gender
=== self
::WOMAN
;
677 * Can member appears in public members list?
681 public function appearsInMembersList(): bool
683 return $this->_appears_in_list
;
691 public function isActive(): bool
693 return $this->_active
;
697 * Does member have uploaded a picture?
701 public function hasPicture(): bool
703 return $this->_picture
->hasPicture();
707 * Does member have a parent?
711 public function hasParent(): bool
713 return !empty($this->_parent
);
717 * Does member have children?
721 public function hasChildren(): bool
723 if ($this->_children
=== null) {
726 'Children has not been loaded!',
732 return count($this->_children
) > 0;
737 * Get row class related to current fee status
739 * @param boolean $public we want the class for public pages
741 * @return string the class to apply
743 public function getRowClass(bool $public = false): string
745 $strclass = ($this->isActive()) ?
'active-account' : 'inactive-account';
746 if ($public === false) {
747 $strclass .= $this->_row_classes
;
753 * Get current member due status
755 * @return string i18n string representing state of due
757 public function getDues(): string
760 $never_contributed = false;
761 $now = new \
DateTime();
762 // To count the days remaining, the next begin date is required.
763 if ($this->_due_date
=== null) {
764 $this->_due_date
= $now->format('Y-m-d');
765 $never_contributed = true;
767 $due_date = new \
DateTime($this->_due_date
);
768 $next_begin_date = clone $due_date;
769 $next_begin_date->add(new \
DateInterval('P1D'));
770 $date_diff = $now->diff($next_begin_date);
771 if ($this->isDueFree()) {
772 $ret = _T("Freed of dues");
773 } elseif ($never_contributed === true) {
774 $patterns = array('/%days/', '/%date/');
775 $cdate = new \
DateTime($this->_creation_date
);
778 $cdate->format(__("Y-m-d"))
780 if ($this->_active
) {
784 _T("Never contributed: Registered %days days ago (since %date)")
787 $ret = _T("Never contributed");
789 // Last active or first expired day
790 } elseif ($this->_days_remaining
== 0) {
791 if ($date_diff->invert
== 0) {
792 $ret = _T("Last day!");
794 $ret = _T("Late since today!");
797 } elseif ($date_diff->invert
== 0 && $this->_days_remaining
> 0) {
798 $patterns = array('/%days/', '/%date/');
800 $this->_days_remaining
,
801 $due_date->format(__("Y-m-d"))
806 _T("%days days remaining (ending on %date)")
809 } elseif ($date_diff->invert
== 1 && $this->_days_remaining
> 0) {
810 $patterns = array('/%days/', '/%date/');
812 // We need the number of days expired, not the number of days remaining.
813 $this->_days_remaining +
1,
814 $due_date->format(__("Y-m-d"))
816 if ($this->_active
) {
820 _T("Late of %days days (since %date)")
823 $ret = _T("No longer member");
830 * Retrieve Full name and surname for the specified member id
832 * @param Db $zdb Database instance
833 * @param integer $id Member id
834 * @param boolean $wid Add member id
835 * @param boolean $wnick Add member nickname
837 * @return string formatted Name and Surname
839 public static function getSName(Db
$zdb, int $id, bool $wid = false, bool $wnick = false): string
842 $select = $zdb->select(self
::TABLE
);
843 $select->where([self
::PK
=> $id]);
845 $results = $zdb->execute($select);
846 $row = $results->current();
847 return self
::getNameWithCase(
851 ($wid === true ?
$row->id_adh
: false),
852 ($wnick === true ?
$row->pseudo_adh
: false)
854 } catch (Throwable
$e) {
856 'Cannot get formatted name for member form id `' . $id . '` | ' .
865 * Get member name with correct case
867 * @param string $name Member name
868 * @param string $surname Member surname
869 * @param false|Title $title Member title to show or false
870 * @param false|integer $id Member id to display or false
871 * @param false|string $nick Member nickname to display or false
875 public static function getNameWithCase(
884 if ($title instanceof Title
) {
885 $str .= $title->tshort
. ' ';
888 $str .= mb_strtoupper($name ??
'', 'UTF-8') . ' ' .
889 ucwords(mb_strtolower($surname ??
'', 'UTF-8'), " \t\r\n\f\v-_|");
891 if ($id !== false ||
!empty($nick)) {
903 if ($id !== false ||
!empty($nick)) {
906 return strip_tags($str);
910 * Change password for a given user
912 * @param Db $zdb Database instance
913 * @param integer $id_adh Member identifier
914 * @param string $pass New password
918 public static function updatePassword(Db
$zdb, int $id_adh, string $pass): bool
921 $cpass = password_hash($pass, PASSWORD_BCRYPT
);
923 $update = $zdb->update(self
::TABLE
);
925 array('mdp_adh' => $cpass)
926 )->where([self
::PK
=> $id_adh]);
927 $zdb->execute($update);
929 'Password for `' . $id_adh . '` has been updated.',
933 } catch (Throwable
$e) {
935 'An error occurred while updating password for `' . $id_adh .
936 '` | ' . $e->getMessage(),
946 * @param string $field Field name
950 private function getFieldLabel(string $field): string
952 $label = $this->fields
[$field]['label'] ??
'';
954 $label = str_replace(' ', ' ', $label);
955 //remove trailing ':' and then trim
956 $label = trim(trim($label, ':'));
961 * Retrieve fields from database
963 * @param Db $zdb Database instance
967 public static function getDbFields(Db
$zdb): array
969 $columns = $zdb->getColumns(self
::TABLE
);
971 foreach ($columns as $col) {
972 $fields[] = $col->getName();
978 * Mark as self membership
982 public function setSelfMembership(): void
984 $this->_self_adh
= true;
988 * Is member up to date?
992 public function isUp2Date(): bool
994 if (!$this->isDepEnabled('dues')) {
998 if ($this->isDueFree()) {
999 //member is due free, he's up to date.
1002 //let's check from due date, if present
1003 if ($this->_due_date
== null) {
1006 $due_date = new \
DateTime($this->_due_date
);
1007 $now = new \
DateTime();
1008 $now->setTime(0, 0, 0);
1009 return $due_date >= $now;
1017 * @param Preferences $preferences Preferences instance
1018 * @param array $fields Members fields configuration
1019 * @param History $history History instance
1023 public function setDependencies(
1024 Preferences
$preferences,
1028 $this->preferences
= $preferences;
1029 $this->fields
= $fields;
1030 $this->history
= $history;
1034 * Check posted values validity
1036 * @param array $values All values to check, basically the $_POST array
1037 * after sending the form
1038 * @param array $required Array of required fields
1039 * @param array $disabled Array of disabled fields
1041 * @return true|array
1043 public function check(array $values, array $required, array $disabled)
1047 $this->errors
= array();
1050 foreach ($values as &$rawvalue) {
1051 if (is_string($rawvalue)) {
1052 $rawvalue = strip_tags($rawvalue);
1056 $fields = self
::getDbFields($this->zdb
);
1058 //reset company name if needed
1059 if (!isset($values['is_company'])) {
1060 unset($values['is_company']);
1061 $values['societe_adh'] = '';
1064 //no parent if checkbox was unchecked
1066 !isset($values['attach'])
1067 && empty($this->_id
)
1068 && isset($values['parent_id'])
1070 unset($values['parent_id']);
1073 if (isset($values['duplicate'])) {
1074 //if we're duplicating, keep a trace (if an error occurs)
1075 $this->_duplicate
= true;
1078 foreach ($fields as $key) {
1079 //first, let's sanitize values
1080 $key = strtolower($key);
1081 $prop = '_' . $this->fields
[$key]['propname'];
1083 if (isset($values[$key])) {
1084 $value = $values[$key];
1085 if ($value !== true && $value !== false) {
1086 //@phpstan-ignore-next-line
1087 $value = trim($value ??
'');
1089 } elseif (empty($this->_id
)) {
1091 case 'bool_admin_adh':
1092 case 'bool_exempt_adh':
1093 case 'bool_display_info':
1096 case 'activite_adh':
1097 //values that are set at object instantiation
1100 case 'date_crea_adh':
1106 //values that are set at object instantiation
1107 $value = $this->$prop;
1117 //keep stored value on update
1118 if ($prop != '_password' ||
isset($values['mdp_adh']) && isset($values['mdp_adh2'])) {
1119 $value = $this->$prop;
1125 // if the field is enabled, check it
1126 if (!isset($disabled[$key])) {
1127 // fill up the adherent structure
1128 if ($value !== null && $value !== true && $value !== false && !is_object($value)) {
1129 $value = stripslashes($value);
1131 $this->$prop = $value;
1133 // now, check validity
1134 if ($value !== null && $value != '') {
1135 if ($key !== 'mdp_adh') {
1136 $this->validate($key, $value, $values);
1138 } elseif (empty($this->_id
)) {
1139 //ensure login and password are not empty
1140 if (($key == 'login_adh' ||
$key == 'mdp_adh') && !isset($required[$key])) {
1141 $p = new Password($this->zdb
);
1142 $generated_value = $p->makeRandomPassword(15);
1143 if ($key == 'login_adh') {
1144 //'@' is not permitted in logins
1145 $this->$prop = str_replace('@', 'a', $generated_value);
1147 $this->$prop = $generated_value;
1154 //password checks need data to be previously set
1155 if (isset($values['mdp_adh'])) {
1156 $this->validate('mdp_adh', $values['mdp_adh'], $values);
1159 // missing required fields?
1160 foreach ($required as $key => $val) {
1161 $prop = '_' . $this->fields
[$key]['propname'];
1163 if (!isset($disabled[$key])) {
1164 $mandatory_missing = false;
1165 if (!isset($this->$prop) ||
$this->$prop == '') {
1166 $mandatory_missing = true;
1167 } elseif ($key === 'titre_adh' && $this->$prop == '-1') {
1168 $mandatory_missing = true;
1171 if ($mandatory_missing === true) {
1172 $this->errors
[] = str_replace(
1174 '<a href="#' . $key . '">' . $this->getFieldLabel($key) . '</a>',
1175 _T("- Mandatory field %field empty.")
1181 //attach to/detach from parent
1182 if (isset($values['detach_parent'])) {
1183 $this->_parent
= null;
1186 if ($login->isGroupManager() && !$login->isAdmin() && !$login->isStaff() && $this->parent_id
!== $login->id
) {
1187 if (!isset($values['groups_adh'])) {
1188 $this->errors
[] = _T('You have to select a group you own!');
1190 $owned_group = false;
1191 foreach ($values['groups_adh'] as $group) {
1192 list($gid) = explode('|', $group);
1193 if ($login->isGroupManager($gid)) {
1194 $owned_group = true;
1197 if ($owned_group === false) {
1198 $this->errors
[] = _T('You have to select a group you own!');
1203 $this->dynamicsCheck($values, $required, $disabled);
1204 $this->checkSocials($values);
1206 if (count($this->errors
) > 0) {
1208 'Some errors has been thew attempting to edit/store a member' . "\n" .
1209 print_r($this->errors
, true),
1212 return $this->errors
;
1217 'Member checked successfully.',
1225 * Validate data for given key
1226 * Set valid data in current object, also resets errors list
1228 * @param string $field Field name
1229 * @param mixed $value Value we want to set
1230 * @param array $values All values, for some references
1234 public function validate(string $field, $value, array $values): void
1236 global $preferences;
1238 $prop = '_' . $this->fields
[$field]['propname'];
1240 if ($value === null ||
(is_string($value) && trim($value) == '')) {
1241 //empty values are OK
1242 $this->$prop = $value;
1248 case 'date_crea_adh':
1249 case 'date_modif_adh_':
1251 case 'date_echeance':
1253 $d = \DateTime
::createFromFormat(__("Y-m-d"), $value);
1255 //try with non localized date
1256 $d = \DateTime
::createFromFormat("Y-m-d", $value);
1258 throw new \
Exception('Incorrect format');
1262 if ($field === 'ddn_adh') {
1263 $now = new \
DateTime();
1264 $now->setTime(0, 0, 0);
1265 $d->setTime(0, 0, 0);
1267 $diff = $now->diff($d);
1268 $days = (int)$diff->format('%R%a');
1270 $this->errors
[] = _T('- Birthdate must be set in the past!');
1273 $years = (int)$diff->format('%R%Y');
1274 if ($years <= -200) {
1275 $this->errors
[] = str_replace(
1278 _T('- Members must be less than 200 years old (currently %years)!')
1282 $this->$prop = $d->format('Y-m-d');
1283 } catch (Throwable
$e) {
1285 'Wrong date format. field: ' . $field .
1286 ', value: ' . $value . ', expected fmt: ' .
1287 __("Y-m-d") . ' | ' . $e->getMessage(),
1290 $this->errors
[] = str_replace(
1297 $this->getFieldLabel($field)
1299 _T("- Wrong date format (%date_format) for %field!")
1304 if ($value !== null && $value !== '') {
1305 if ($value == '-1') {
1306 $this->$prop = null;
1307 } elseif (!$value instanceof Title
) {
1308 $this->$prop = new Title((int)$value);
1311 $this->$prop = null;
1315 if (!GaletteMail
::isValidEmail($value)) {
1316 $this->errors
[] = _T("- Non-valid E-Mail address!") .
1317 ' (' . $this->getFieldLabel($field) . ')';
1321 $select = $this->zdb
->select(self
::TABLE
);
1324 )->where(array('email_adh' => $value));
1325 if (!empty($this->_id
)) {
1326 $select->where
->notEqualTo(
1332 $results = $this->zdb
->execute($select);
1333 if ($results->count() !== 0) {
1334 $this->errors
[] = _T("- This E-Mail address is already used by another member!");
1336 } catch (Throwable
$e) {
1338 'An error occurred checking member email uniqueness.',
1341 $this->errors
[] = _T("An error has occurred while looking if login already exists.");
1345 /** FIXME: add a preference for login length */
1346 if (strlen($value) < 2) {
1347 $this->errors
[] = str_replace(
1350 _T("- The username must be composed of at least %i characters!")
1353 //check if login does not contain the @ character
1354 if (strpos($value, '@') != false) {
1355 $this->errors
[] = _T("- The username cannot contain the @ character");
1357 //check if login is already taken
1359 $select = $this->zdb
->select(self
::TABLE
);
1362 )->where(array('login_adh' => $value));
1363 if (!empty($this->_id
)) {
1364 $select->where
->notEqualTo(
1370 $results = $this->zdb
->execute($select);
1372 $results->count() !== 0
1373 ||
$value == $preferences->pref_admin_login
1375 $this->errors
[] = _T("- This username is already in use, please choose another one!");
1377 } catch (Throwable
$e) {
1379 'An error occurred checking member login uniqueness.',
1382 $this->errors
[] = _T("An error has occurred while looking if login already exists.");
1389 $this->_self_adh
!== true
1390 && (!isset($values['mdp_adh2'])
1391 ||
$values['mdp_adh2'] != $value)
1393 $this->errors
[] = _T("- The passwords don't match!");
1395 $this->_self_adh
=== true
1396 && !crypt($value, $values['mdp_crypt']) == $values['mdp_crypt']
1398 $this->errors
[] = _T("Password misrepeated: ");
1400 $pinfos = password_get_info($value);
1401 //check if value is already a hash
1402 if ($pinfos['algo'] == 0) {
1403 $this->$prop = password_hash(
1408 $pwcheck = new \Galette\Util\
Password($preferences);
1409 $pwcheck->setAdherent($this);
1410 if (!$pwcheck->isValid($value)) {
1411 $this->errors
= array_merge(
1413 $pwcheck->getErrors()
1421 $this->$prop = (int)$value;
1422 //check if status exists
1423 $select = $this->zdb
->select(Status
::TABLE
);
1424 $select->where([Status
::PK
=> $value]);
1426 $results = $this->zdb
->execute($select);
1427 $result = $results->current();
1429 $this->errors
[] = str_replace(
1432 _T("Status #%id does not exists in database.")
1436 } catch (Throwable
$e) {
1438 'An error occurred checking status existence: ' . $e->getMessage(),
1441 $this->errors
[] = _T("An error has occurred while looking if status does exists.");
1445 if (in_array($value, [self
::NC
, self
::MAN
, self
::WOMAN
])) {
1446 $this->$prop = (int)$value;
1448 $this->errors
[] = _T("Gender %gender does not exists!");
1452 $this->$prop = ($value instanceof Adherent
) ?
(int)$value->id
: (int)$value;
1453 $this->loadParent();
1463 public function store(): bool
1465 global $hist, $emitter, $login;
1468 if (!$login->isAdmin() && !$login->isStaff() && !$login->isGroupManager() && $this->id
== '') {
1469 if ($this->preferences
->pref_bool_create_member
) {
1470 $this->_parent
= $login->id
;
1476 $fields = self
::getDbFields($this->zdb
);
1478 foreach ($fields as $field) {
1480 $field !== 'date_modif_adh'
1481 ||
empty($this->_id
)
1483 $prop = '_' . $this->fields
[$field]['propname'];
1485 ($field === 'bool_admin_adh'
1486 ||
$field === 'bool_exempt_adh'
1487 ||
$field === 'bool_display_info'
1488 ||
$field === 'activite_adh')
1489 && $this->$prop === false
1491 //Handle booleans for postgres ; bugs #18899 and #19354
1492 $values[$field] = $this->zdb
->isPostgres() ?
'false' : 0;
1493 } elseif ($field === 'parent_id') {
1495 if ($this->_parent
=== null) {
1496 $values['parent_id'] = new Expression('NULL');
1497 } elseif ($this->parent
instanceof Adherent
) {
1498 $values['parent_id'] = $this->_parent
->id
;
1500 $values['parent_id'] = $this->_parent
;
1503 $values[$field] = $this->$prop;
1508 //an empty value will cause date to be set to 1901-01-01, a null
1509 //will result in 0000-00-00. We want a database NULL value here.
1510 if (!$this->_birthdate
) {
1511 $values['ddn_adh'] = new Expression('NULL');
1513 if (!$this->_due_date
) {
1514 $values['date_echeance'] = new Expression('NULL');
1517 if ($this->_title
instanceof Title
) {
1518 $values['titre_adh'] = $this->_title
->id
;
1520 $values['titre_adh'] = new Expression('NULL');
1523 if (!$this->_parent
) {
1524 $values['parent_id'] = new Expression('NULL');
1527 if (!$this->_number
) {
1528 $values['num_adh'] = new Expression('NULL');
1531 //fields that cannot be null
1533 '_surname' => 'prenom_adh',
1534 '_nickname' => 'pseudo_adh',
1535 '_address' => 'adresse_adh',
1536 '_zipcode' => 'cp_adh',
1537 '_town' => 'ville_adh'
1539 foreach ($notnull as $prop => $field) {
1540 if ($this->$prop === null) {
1541 $values[$field] = '';
1545 if (empty($this->_id
)) {
1546 //we're inserting a new member
1547 unset($values[self
::PK
]);
1548 //set modification date
1549 $this->_modification_date
= date('Y-m-d');
1550 $values['date_modif_adh'] = $this->_modification_date
;
1552 $insert = $this->zdb
->insert(self
::TABLE
);
1553 $insert->values($values);
1554 $add = $this->zdb
->execute($insert);
1555 if ($add->count() > 0) {
1556 $this->_id
= $this->zdb
->getLastGeneratedValue($this);
1557 $this->_picture
= new Picture($this->_id
);
1559 if ($this->_self_adh
) {
1561 _T("Self_subscription as a member: ") .
1562 $this->getNameWithCase($this->_name
, $this->_surname
),
1567 _T("Member card added"),
1572 $event = 'member.add';
1574 $hist->add(_T("Fail to add new member."));
1575 throw new \
Exception(
1576 'An error occurred inserting new member!'
1580 //we're editing an existing member
1581 if (!$this->isDueFree()) {
1583 $due_date = Contribution
::getDueDate($this->zdb
, $this->_id
);
1585 $values['date_echeance'] = $due_date;
1589 if (!$this->_password
) {
1590 unset($values['mdp_adh']);
1593 $update = $this->zdb
->update(self
::TABLE
);
1594 $update->set($values);
1595 $update->where([self
::PK
=> $this->_id
]);
1597 $edit = $this->zdb
->execute($update);
1599 //edit == 0 does not mean there were an error, but that there
1600 //were nothing to change
1601 if ($edit->count() > 0) {
1602 $this->updateModificationDate();
1604 _T("Member card updated"),
1608 $event = 'member.edit';
1612 $this->dynamicsStore();
1613 $this->storeSocials($this->id
);
1615 //send event at the end of process, once all has been stored
1616 if ($event !== null) {
1617 $emitter->dispatch(new GaletteEvent($event, $this));
1620 } catch (Throwable
$e) {
1622 'Something went wrong :\'( | ' . $e->getMessage() . "\n" .
1623 $e->getTraceAsString(),
1631 * Update member modification date
1635 private function updateModificationDate(): void
1638 $modif_date = date('Y-m-d');
1639 $update = $this->zdb
->update(self
::TABLE
);
1641 array('date_modif_adh' => $modif_date)
1642 )->where([self
::PK
=> $this->_id
]);
1644 $this->zdb
->execute($update);
1645 $this->_modification_date
= $modif_date;
1646 } catch (Throwable
$e) {
1648 'Something went wrong updating modif date :\'( | ' .
1649 $e->getMessage() . "\n" . $e->getTraceAsString(),
1657 * Global getter method
1659 * @param string $name name of the property we want to retrieve
1663 public function __get(string $name)
1666 'admin', 'staff', 'due_free', 'appears_in_list', 'active',
1667 'row_classes', 'oldness', 'duplicate', 'groups', 'managed_groups'
1669 if (!defined('GALETTE_TESTS')) {
1670 $forbidden[] = 'password'; //keep that for tests only
1674 'sadmin', 'sstaff', 'sdue_free', 'sappears_in_list', 'sactive',
1675 'stitle', 'sstatus', 'sfullname', 'sname', 'saddress',
1676 'rbirthdate', 'sgender', 'contribstatus',
1679 $socials = array('website', 'msn', 'jabber', 'icq');
1681 if (in_array($name, $forbidden)) {
1683 'Calling property "' . $name . '" directly is discouraged.',
1688 return $this->isAdmin();
1690 return $this->isStaff();
1692 return $this->isDueFree();
1693 case 'appears_in_list':
1694 return $this->appearsInMembersList();
1696 return $this->isActive();
1698 return $this->isDuplicate();
1700 return $this->getGroups();
1701 case 'managed_groups':
1702 return $this->getManagedGroups();
1704 throw new \
RuntimeException("Call to __get for '$name' is forbidden!");
1708 if (in_array($name, $virtuals)) {
1709 if (substr($name, 0, 1) !== '_') {
1710 $real = '_' . substr($name, 1);
1716 return (($this->isAdmin()) ?
_T("Yes") : _T("No"));
1718 return (($this->isDueFree()) ?
_T("Yes") : _T("No"));
1719 case 'sappears_in_list':
1720 return (($this->appearsInMembersList()) ?
_T("Yes") : _T("No"));
1722 return (($this->$real) ?
_T("Yes") : _T("No"));
1724 return (($this->isActive()) ?
_T("Active") : _T("Inactive"));
1726 if (isset($this->_title
) && $this->_title
instanceof Title
) {
1727 return $this->_title
->tshort
;
1732 $status = new Status($this->zdb
);
1733 return $status->getLabel($this->_status
);
1735 return $this->getNameWithCase(
1738 (isset($this->_title
) ?
$this->title
: false)
1741 $address = $this->_address
;
1744 return $this->getNameWithCase($this->_name
, $this->_surname
);
1746 return $this->_birthdate
;
1748 switch ($this->gender
) {
1754 return _T('Unspecified');
1756 case 'contribstatus':
1757 return $this->getDues();
1761 //for backward compatibility
1762 if (in_array($name, $socials)) {
1763 $values = Social
::getListForMember($this->_id
, $name);
1764 return $values[0] ??
null;
1767 if (substr($name, 0, 1) !== '_') {
1768 $rname = '_' . $name;
1776 if ($this->$rname !== null) {
1777 return (int)$this->$rname;
1782 return $this->$rname ??
'';
1784 case 'creation_date':
1785 case 'modification_date':
1787 if ($this->$rname != '') {
1789 $d = new \
DateTime($this->$rname);
1790 return $d->format(__("Y-m-d"));
1791 } catch (Throwable
$e) {
1792 //oops, we've got a bad date :/
1794 'Bad date (' . $this->$rname . ') | ' .
1798 return $this->$rname;
1803 return ($this->_parent
instanceof Adherent
) ?
(int)$this->_parent
->id
: (int)$this->_parent
;
1805 if (!property_exists($this, $rname)) {
1807 "Unknown property '$rname'",
1812 return $this->$rname;
1818 * Global isset method
1819 * Required for twig to access properties via __get
1821 * @param string $name name of the property we want to retrieve
1825 public function __isset(string $name)
1828 'admin', 'staff', 'due_free', 'appears_in_list', 'active',
1829 'row_classes', 'oldness', 'duplicate', 'groups', 'managed_groups'
1831 if (!defined('GALETTE_TESTS')) {
1832 $forbidden[] = 'password'; //keep that for tests only
1836 'sadmin', 'sstaff', 'sdue_free', 'sappears_in_list', 'sactive',
1837 'stitle', 'sstatus', 'sfullname', 'sname', 'saddress',
1838 'rbirthdate', 'sgender', 'contribstatus',
1841 $socials = array('website', 'msn', 'jabber', 'icq');
1843 if (in_array($name, $forbidden)) {
1845 'Calling property "' . $name . '" directly is discouraged.',
1852 case 'appears_in_list':
1856 case 'managed_groups':
1863 if (in_array($name, $virtuals)) {
1867 //for backward compatibility
1868 if (in_array($name, $socials)) {
1872 if (substr($name, 0, 1) !== '_') {
1873 $rname = '_' . $name;
1883 case 'creation_date':
1884 case 'modification_date':
1889 return property_exists($this, $rname);
1895 * If member does not have an email address, but is attached to
1896 * another member, we'll take information from its parent.
1900 public function getEmail(): string
1902 $email = $this->_email
;
1903 if (empty($email) && $this->hasParent()) {
1904 $this->loadParent();
1905 $email = $this->parent
->email
;
1908 return $email ??
'';
1912 * Get member address.
1913 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1917 public function getAddress(): string
1919 $address = $this->_address
;
1920 if (empty($address) && $this->hasParent()) {
1921 $this->loadParent();
1922 $address = $this->parent
->address
;
1925 return $address ??
'';
1929 * Get member zipcode.
1930 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1934 public function getZipcode(): string
1936 $address = $this->_address
;
1937 $zip = $this->_zipcode
;
1938 if (empty($address) && $this->hasParent()) {
1939 $this->loadParent();
1940 $zip = $this->parent
->zipcode
;
1948 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1952 public function getTown(): string
1954 $address = $this->_address
;
1955 $town = $this->_town
;
1956 if (empty($address) && $this->hasParent()) {
1957 $this->loadParent();
1958 $town = $this->parent
->town
;
1965 * Get member country.
1966 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1970 public function getCountry(): string
1972 $address = $this->_address
;
1973 $country = $this->_country
;
1974 if (empty($address) && $this->hasParent()) {
1975 $this->loadParent();
1976 $country = $this->parent
->country
;
1979 return $country ??
'';
1987 public function getAge(): string
1989 if ($this->_birthdate
== null) {
1993 $d = \DateTime
::createFromFormat('Y-m-d', $this->_birthdate
);
1996 'Invalid birthdate: ' . $this->_birthdate
,
2004 $d->diff(new \
DateTime())->y
,
2005 _T(' (%age years old)')
2010 * Get parent inherited fields
2014 public function getParentFields(): array
2016 return $this->parent_fields
;
2020 * Handle files (photo and dynamics files)
2022 * @param array $files Files sent
2023 * @param array $cropping Cropping properties
2025 * @return array|true
2027 public function handleFiles(array $files, array $cropping = null)
2031 if (isset($files['photo'])) {
2032 if ($files['photo']['error'] === UPLOAD_ERR_OK
) {
2033 if ($files['photo']['tmp_name'] != '') {
2034 if (is_uploaded_file($files['photo']['tmp_name'])) {
2035 if ($this->preferences
->pref_force_picture_ratio
== 1 && isset($cropping)) {
2036 $res = $this->picture
->store($files['photo'], false, $cropping);
2038 $res = $this->picture
->store($files['photo']);
2042 = $this->picture
->getErrorMessage($res);
2046 } elseif ($files['photo']['error'] !== UPLOAD_ERR_NO_FILE
) {
2048 $this->picture
->getPhpErrorMessage($files['photo']['error']),
2051 $this->errors
[] = $this->picture
->getPhpErrorMessage(
2052 $files['photo']['error']
2056 $this->dynamicsFiles($files);
2058 if (count($this->errors
) > 0) {
2060 'Some errors has been thew attempting to edit/store a member files' . "\n" .
2061 print_r($this->errors
, true),
2064 return $this->errors
;
2071 * Set member as duplicate
2075 public function setDuplicate(): void
2077 //mark as duplicated
2078 $this->_duplicate
= true;
2079 $infos = $this->_others_infos_admin
;
2080 $this->_others_infos_admin
= str_replace(
2082 [$this->sname
, $this->_id
],
2083 _T('Duplicated from %name (%id)')
2085 if (!empty($infos)) {
2086 $this->_others_infos_admin
.= "\n" . $infos;
2090 //drop email, must be unique
2091 $this->_email
= null;
2092 //drop creation date
2093 $this->_creation_date
= date("Y-m-d");
2095 $this->_login
= null;
2097 $this->_picture
= new Picture();
2099 $this->_birthdate
= null;
2101 $this->_surname
= null;
2103 $this->_admin
= false;
2105 $this->_due_free
= false;
2109 * Get current errors
2113 public function getErrors(): array
2115 return $this->errors
;
2123 public function getGroups(): array
2125 if (!$this->isDepEnabled('groups')) {
2126 $this->loadGroups();
2128 return $this->_groups
;
2132 * Get user managed groups
2136 public function getManagedGroups(): array
2138 if (!$this->isDepEnabled('groups')) {
2139 $this->loadGroups();
2141 return $this->_managed_groups
;
2145 * Can current logged-in user create member
2147 * @param Login $login Login instance
2151 public function canCreate(Login
$login): bool
2153 global $preferences;
2155 if ($this->id
&& $login->id
== $this->id ||
$login->isAdmin() ||
$login->isStaff()) {
2159 if ($preferences->pref_bool_groupsmanagers_create_member
&& $login->isGroupManager()) {
2163 if ($preferences->pref_bool_create_member
&& $login->isLogged()) {
2171 * Can current logged-in user edit member
2173 * @param Login $login Login instance
2177 public function canEdit(Login
$login): bool
2179 global $preferences;
2181 //admin and staff users can edit, as well as member itself
2182 if ($this->id
&& $login->id
== $this->id ||
$login->isAdmin() ||
$login->isStaff()) {
2186 //parent can edit their child cards
2187 if ($this->hasParent() && $this->parent_id
=== $login->id
) {
2191 //group managers can edit members of groups they manage when pref is on
2192 if ($preferences->pref_bool_groupsmanagers_edit_member
&& $login->isGroupManager()) {
2193 foreach ($this->getGroups() as $g) {
2194 if ($login->isGroupManager($g->getId())) {
2204 * Can current logged-in user display member
2206 * @param Login $login Login instance
2210 public function canShow(Login
$login): bool
2212 //group managers can show members of groups they manage
2213 if ($login->isGroupManager()) {
2214 foreach ($this->getGroups() as $g) {
2215 if ($login->isGroupManager($g->getId())) {
2221 return $this->canEdit($login);
2225 * Are we currently duplicated a member?
2229 public function isDuplicate(): bool
2231 return $this->_duplicate
;
2235 * Flag creation mail sending
2237 * @param boolean $send True (default) to send creation email
2241 public function setSendmail(bool $send = true): self
2243 $this->sendmail
= $send;
2248 * Should we send administrative emails to member?
2252 public function sendEMail(): bool
2254 return $this->sendmail
;
2260 * @param integer $id Parent identifier
2264 public function setParent(int $id): self
2266 $this->_parent
= $id;
2267 $this->loadParent();