3 /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
6 * Member class for galette
10 * Copyright © 2009-2022 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-2022 The Galette Team
32 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL License 3.0 or (at your option) any later version
33 * @link http://galette.tuxfamily.org
34 * @since Available since 0.7dev - 2009-06-02
37 namespace Galette\Entity
;
39 use Galette\Features\Socials
;
42 use Laminas\Db\Sql\Expression
;
44 use Galette\Core\Picture
;
45 use Galette\Core\GaletteMail
;
46 use Galette\Core\Password
;
47 use Galette\Core\Preferences
;
48 use Galette\Core\History
;
49 use Galette\Repository\Groups
;
50 use Galette\Core\Login
;
51 use Galette\Repository\Members
;
52 use Galette\Features\Dynamics
;
55 * Member class for galette
60 * @author Johan Cwiklinski <johan@x-tnd.be>
61 * @copyright 2009-2022 The Galette Team
62 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL License 3.0 or (at your option) any later version
63 * @link http://galette.tuxfamily.org
64 * @since Available since 0.7dev - 02-06-2009
66 * @property integer $id
67 * @property integer|Title $title Either a title id or an instance of Title
68 * @property string $stitle Title label
69 * @property string company_name
70 * @property string $name
71 * @property string $surname
72 * @property string $nickname
73 * @property string $birthdate Localized birthdate
74 * @property string $rbirthdate Raw birthdate
75 * @property string $birth_place
76 * @property integer $gender
77 * @property string $sgender Gender label
78 * @property string $job
79 * @property string $language
80 * @property integer $status
81 * @property string $sstatus Status label
82 * @property string $address
83 * @property string $zipcode
84 * @property string $town
85 * @property string $country
86 * @property string $phone
87 * @property string $gsm
88 * @property string $email
89 * @property string $gnupgid
90 * @property string $fingerprint
91 * @property string $login
92 * @property string $creation_date Localized creation date
93 * @property string $modification_date Localized modification date
94 * @property string $due_date Localized due date
95 * @property string $others_infos
96 * @property string $others_infos_admin
97 * @property Picture $picture
98 * @property array $groups
99 * @property array $managed_groups
100 * @property integer|Adherent $parent Parent id if parent dep is not loaded, Adherent instance otherwise
101 * @property array $children
102 * @property boolean $admin better to rely on isAdmin()
103 * @property boolean $staff better to rely on isStaff()
104 * @property boolean $due_free better to rely on isDueFree()
105 * @property boolean $appears_in_list better to rely on appearsInMembersList()
106 * @property boolean $active better to rely on isActive()
107 * @property boolean $duplicate better to rely on isDuplicate()
108 * @property string $sadmin yes/no
109 * @property string $sstaff yes/no
110 * @property string $sdue_free yes/no
111 * @property string $sappears_in_list yes/no
112 * @property string $sactive yes/no
113 * @property string $sfullname
114 * @property string $sname
115 * @property string $saddress
116 * @property string $contribstatus State of member contributions
117 * @property string $days_remaining
118 * @property-read integer $parent_id
119 * @property Social $social Social networks/Contact
120 * @property string $number Member number
128 public const TABLE
= 'adherents';
129 public const PK
= 'id_adh';
132 public const MAN
= 1;
133 public const WOMAN
= 2;
135 public const AFTER_ADD_DEFAULT
= 0;
136 public const AFTER_ADD_TRANS
= 1;
137 public const AFTER_ADD_NEW
= 2;
138 public const AFTER_ADD_SHOW
= 3;
139 public const AFTER_ADD_LIST
= 4;
140 public const AFTER_ADD_HOME
= 5;
145 private $_company_name;
150 private $_birth_place;
156 //Contact information
165 private $_fingerprint;
166 //Galette relative information
167 private $_appears_in_list;
169 private $_staff = false;
173 private $_creation_date;
174 private $_modification_date;
176 private $_others_infos;
177 private $_others_infos_admin;
180 private $_days_remaining;
181 private $_groups = [];
182 private $_managed_groups = [];
185 private $_duplicate = false;
189 private $_row_classes;
191 private $_self_adh = false;
192 private $_deps = array(
203 private $preferences;
207 private $parent_fields = [
214 private $errors = [];
216 private $sendmail = false;
219 * Default constructor
221 * @param Db $zdb Database instance
222 * @param mixed $args Either a ResultSet row, its id or its
223 * login or its email for to load s specific
224 * member, or null to just instantiate object
225 * @param false|array|null $deps Dependencies configuration, see Adherent::$_deps
227 public function __construct(Db
$zdb, $args = null, $deps = null)
233 if ($deps !== null) {
234 if (is_array($deps)) {
235 $this->_deps
= array_merge(
239 } elseif ($deps === false) {
241 $this->_deps
= array_fill_keys(
242 array_keys($this->_deps
),
247 '$deps should be an array, ' . gettype($deps) . ' given!',
253 if ($args == null ||
is_int($args)) {
254 if (is_int($args) && $args > 0) {
257 $this->_active
= true;
258 $this->_language
= $i18n->getID();
259 $this->_creation_date
= date("Y-m-d");
260 $this->_status
= $this->getDefaultStatus();
261 $this->_title
= null;
262 $this->_gender
= self
::NC
;
263 $gp = new Password($this->zdb
);
264 $this->_password
= $gp->makeRandomPassword();
265 $this->_picture
= new Picture();
266 $this->_admin
= false;
267 $this->_staff
= false;
268 $this->_due_free
= false;
269 $this->_appears_in_list
= false;
270 $this->_parent
= null;
272 if ($this->_deps
['dynamics'] === true) {
273 $this->loadDynamicFields();
276 } elseif (is_object($args)) {
277 $this->loadFromRS($args);
278 } elseif (is_string($args)) {
279 $this->loadFromLoginOrMail($args);
284 * Loads a member from its id
286 * @param int $id the identifier for the member to load
288 * @return bool true if query succeed, false otherwise
290 public function load(int $id): bool
293 $select = $this->zdb
->select(self
::TABLE
, 'a');
296 array('b' => PREFIX_DB
. Status
::TABLE
),
297 'a.' . Status
::PK
. '=b.' . Status
::PK
,
298 array('priorite_statut')
299 )->where(array(self
::PK
=> $id));
301 $results = $this->zdb
->execute($select);
303 if ($results->count() === 0) {
307 $this->loadFromRS($results->current());
309 } catch (Throwable
$e) {
311 'Cannot load member form id `' . $id . '` | ' . $e->getMessage(),
319 * Loads a member from its login
321 * @param string $login login for the member to load
325 public function loadFromLoginOrMail(string $login): bool
328 $select = $this->zdb
->select(self
::TABLE
);
329 if (GaletteMail
::isValidEmail($login)) {
330 //we got a valid email address, use it
331 $select->where(array('email_adh' => $login));
333 ///we did not get an email address, consider using login
334 $select->where(array('login_adh' => $login));
337 $results = $this->zdb
->execute($select);
338 $result = $results->current();
340 $this->loadFromRS($result);
343 } catch (Throwable
$e) {
345 'Cannot load member form login `' . $login . '` | ' .
354 * Populate object from a resultset row
356 * @param ResultSet $r the resultset row
360 private function loadFromRS($r): void
362 $this->_self_adh
= false;
363 $this->_id
= $r->id_adh
;
365 if ($r->titre_adh
!== null) {
366 $this->_title
= new Title((int)$r->titre_adh
);
368 $this->_company_name
= $r->societe_adh
;
369 $this->_name
= $r->nom_adh
;
370 $this->_surname
= $r->prenom_adh
;
371 $this->_nickname
= $r->pseudo_adh
;
372 if ($r->ddn_adh
!= '1901-01-01') {
373 $this->_birthdate
= $r->ddn_adh
;
375 $this->_birth_place
= $r->lieu_naissance
;
376 $this->_gender
= (int)$r->sexe_adh
;
377 $this->_job
= $r->prof_adh
;
378 $this->_language
= $r->pref_lang
;
379 $this->_active
= $r->activite_adh
== 1;
380 $this->_status
= (int)$r->id_statut
;
381 //Contact information
382 $this->_address
= $r->adresse_adh
;
383 $this->_zipcode
= $r->cp_adh
;
384 $this->_town
= $r->ville_adh
;
385 $this->_country
= $r->pays_adh
;
386 $this->_phone
= $r->tel_adh
;
387 $this->_gsm
= $r->gsm_adh
;
388 $this->_email
= $r->email_adh
;
389 $this->_gnupgid
= $r->gpgid
;
390 $this->_fingerprint
= $r->fingerprint
;
391 //Galette relative information
392 $this->_appears_in_list
= $r->bool_display_info
== 1;
393 $this->_admin
= $r->bool_admin_adh
== 1;
395 isset($r->priorite_statut
)
396 && $r->priorite_statut
< Members
::NON_STAFF_MEMBERS
398 $this->_staff
= true;
400 $this->_due_free
= $r->bool_exempt_adh
== 1;
401 $this->_login
= $r->login_adh
;
402 $this->_password
= $r->mdp_adh
;
403 $this->_creation_date
= $r->date_crea_adh
;
404 if ($r->date_modif_adh
!= '1901-01-01') {
405 $this->_modification_date
= $r->date_modif_adh
;
407 $this->_modification_date
= $this->_creation_date
;
409 $this->_due_date
= $r->date_echeance
;
410 $this->_others_infos
= $r->info_public_adh
;
411 $this->_others_infos_admin
= $r->info_adh
;
412 $this->_number
= $r->num_adh
;
414 if ($r->parent_id
!== null) {
415 $this->_parent
= (int)$r->parent_id
;
416 if ($this->_deps
['parent'] === true) {
421 if ($this->_deps
['children'] === true) {
422 $this->loadChildren();
425 if ($this->_deps
['picture'] === true) {
426 $this->_picture
= new Picture($this->_id
);
429 if ($this->_deps
['groups'] === true) {
433 if ($this->_deps
['dues'] === true) {
437 if ($this->_deps
['dynamics'] === true) {
438 $this->loadDynamicFields();
441 if ($this->_deps
['socials'] === true) {
442 $this->loadSocials();
451 private function loadParent(): void
453 if (!$this->_parent
instanceof Adherent
) {
454 $deps = array_fill_keys(array_keys($this->_deps
), false);
455 $this->_parent
= new Adherent($this->zdb
, (int)$this->_parent
, $deps);
460 * Load member children
464 private function loadChildren(): void
466 $this->_children
= array();
469 $select = $this->zdb
->select(self
::TABLE
);
472 )->where(['parent_id' => $this->_id
]);
474 $results = $this->zdb
->execute($select);
476 if ($results->count() > 0) {
477 foreach ($results as $row) {
478 $deps = $this->_deps
;
479 $deps['children'] = false;
480 $deps['parent'] = false;
481 $this->_children
[] = new Adherent($this->zdb
, (int)$row->$id, $deps);
484 } catch (Throwable
$e) {
486 'Cannot load children for member #' . $this->_id
. ' | ' .
499 public function loadGroups(): void
501 $this->_groups
= Groups
::loadGroups($this->_id
);
502 $this->_managed_groups
= Groups
::loadManagedGroups($this->_id
);
506 * Load member social network/contact information
510 public function loadSocials(): void
512 $this->_socials
= Social
::getListForMember($this->_id
);
516 * Retrieve status from preferences
521 private function getDefaultStatus(): int
524 if ($preferences->pref_statut
!= '') {
525 return $preferences->pref_statut
;
528 'Unable to get pref_statut; is it defined in preferences?',
531 return Status
::DEFAULT_STATUS
;
536 * Check for dues status
540 private function checkDues(): void
542 //how many days since our beloved member has been created
543 $now = new \
DateTime();
544 $this->_oldness
= $now->diff(
545 new \
DateTime($this->_creation_date
)
548 if ($this->isDueFree()) {
549 //no fee required, we don't care about dates
550 $this->_row_classes
.= ' cotis-exempt';
552 //ok, fee is required. Let's check the dates
553 if ($this->_due_date
== '') {
554 $this->_row_classes
.= ' cotis-never';
556 // To count the days remaining, the next begin date is required.
557 $due_date = new \
DateTime($this->_due_date
);
558 $next_begin_date = clone $due_date;
559 $next_begin_date->add(new \
DateInterval('P1D'));
560 $date_diff = $now->diff($next_begin_date);
561 $this->_days_remaining
= $date_diff->days
;
563 if ($date_diff->invert
== 0 && $date_diff->days
>= 0) {
564 $this->_days_remaining
= $date_diff->days
;
565 if ($this->_days_remaining
<= 30) {
566 if ($date_diff->days
== 0) {
567 $this->_row_classes
.= ' cotis-lastday';
569 $this->_row_classes
.= ' cotis-soon';
571 $this->_row_classes
.= ' cotis-ok';
574 } elseif ($date_diff->invert
== 1 && $date_diff->days
>= 0) {
575 $this->_days_remaining
= $date_diff->days
;
576 //check if member is still active
577 $this->_row_classes
.= $this->isActive() ?
' cotis-late' : ' cotis-old';
588 public function isAdmin(): bool
590 return $this->_admin
;
594 * Is user member of staff?
598 public function isStaff(): bool
600 return $this->_staff
;
604 * Is member freed of dues?
608 public function isDueFree(): bool
610 return $this->_due_free
;
614 * Is member in specified group?
616 * @param string $group_name Group name
620 public function isGroupMember(string $group_name): bool
622 if (!$this->isDepEnabled('groups')) {
626 foreach ($this->_groups
as $g) {
627 if ($g->getName() == $group_name) {
635 * Is member manager of specified group?
637 * @param string $group_name Group name
641 public function isGroupManager(string $group_name): bool
643 if (!$this->isDepEnabled('groups')) {
647 foreach ($this->_managed_groups
as $mg) {
648 if ($mg->getName() == $group_name) {
656 * Does current member represents a company?
660 public function isCompany(): bool
662 return trim($this->_company_name ??
'') != '';
666 * Is current member a man?
670 public function isMan(): bool
672 return (int)$this->_gender
=== self
::MAN
;
676 * Is current member a woman?
680 public function isWoman(): bool
682 return (int)$this->_gender
=== self
::WOMAN
;
687 * Can member appears in public members list?
691 public function appearsInMembersList(): bool
693 return $this->_appears_in_list
;
701 public function isActive(): bool
703 return $this->_active
;
707 * Does member have uploaded a picture?
711 public function hasPicture(): bool
713 return $this->_picture
->hasPicture();
717 * Does member have a parent?
721 public function hasParent(): bool
723 return !empty($this->_parent
);
727 * Does member have children?
731 public function hasChildren(): bool
733 if ($this->_children
=== null) {
736 'Children has not been loaded!',
742 return count($this->_children
) > 0;
747 * Get row class related to current fee status
749 * @param boolean $public we want the class for public pages
751 * @return string the class to apply
753 public function getRowClass(bool $public = false): string
755 $strclass = ($this->isActive()) ?
'active' : 'inactive';
756 if ($public === false) {
757 $strclass .= $this->_row_classes
;
763 * Get current member due status
765 * @return string i18n string representing state of due
767 public function getDues(): string
770 $never_contributed = false;
771 $now = new \
DateTime();
772 // To count the days remaining, the next begin date is required.
773 if ($this->_due_date
=== null) {
774 $this->_due_date
= $now->format('Y-m-d');
775 $never_contributed = true;
777 $due_date = new \
DateTime($this->_due_date
);
778 $next_begin_date = clone $due_date;
779 $next_begin_date->add(new \
DateInterval('P1D'));
780 $date_diff = $now->diff($next_begin_date);
781 if ($this->isDueFree()) {
782 $ret = _T("Freed of dues");
783 } elseif ($never_contributed === true) {
784 $patterns = array('/%days/', '/%date/');
785 $cdate = new \
DateTime($this->_creation_date
);
788 $cdate->format(__("Y-m-d"))
790 if ($this->_active
) {
794 _T("Never contributed: Registered %days days ago (since %date)")
797 $ret = _T("Never contributed");
799 // Last active or first expired day
800 } elseif ($this->_days_remaining
== 0) {
801 if ($date_diff->invert
== 0) {
802 $ret = _T("Last day!");
804 $ret = _T("Late since today!");
807 } elseif ($date_diff->invert
== 0 && $this->_days_remaining
> 0) {
808 $patterns = array('/%days/', '/%date/');
810 $this->_days_remaining
,
811 $due_date->format(__("Y-m-d"))
816 _T("%days days remaining (ending on %date)")
819 } elseif ($date_diff->invert
== 1 && $this->_days_remaining
> 0) {
820 $patterns = array('/%days/', '/%date/');
822 // We need the number of days expired, not the number of days remaining.
823 $this->_days_remaining +
1,
824 $due_date->format(__("Y-m-d"))
826 if ($this->_active
) {
830 _T("Late of %days days (since %date)")
833 $ret = _T("No longer member");
840 * Retrieve Full name and surname for the specified member id
842 * @param Db $zdb Database instance
843 * @param integer $id Member id
844 * @param boolean $wid Add member id
845 * @param boolean $wnick Add member nickname
847 * @return string formatted Name and Surname
849 public static function getSName(Db
$zdb, int $id, bool $wid = false, bool $wnick = false): string
852 $select = $zdb->select(self
::TABLE
);
853 $select->where([self
::PK
=> $id]);
855 $results = $zdb->execute($select);
856 $row = $results->current();
857 return self
::getNameWithCase(
861 ($wid === true ?
$row->id_adh
: false),
862 ($wnick === true ?
$row->pseudo_adh
: false)
864 } catch (Throwable
$e) {
866 'Cannot get formatted name for member form id `' . $id . '` | ' .
875 * Get member name with correct case
877 * @param string $name Member name
878 * @param string $surname Member surname
879 * @param false|Title $title Member title to show or false
880 * @param false|integer $id Member id to display or false
881 * @param false|string $nick Member nickname to display or false
885 public static function getNameWithCase(
894 if ($title instanceof Title
) {
895 $str .= $title->tshort
. ' ';
898 $str .= mb_strtoupper($name ??
'', 'UTF-8') . ' ' .
899 ucwords(mb_strtolower($surname ??
'', 'UTF-8'), " \t\r\n\f\v-_|");
901 if ($id !== false ||
!empty($nick)) {
913 if ($id !== false ||
!empty($nick)) {
916 return strip_tags($str);
920 * Change password for a given user
922 * @param Db $zdb Database instance
923 * @param integer $id_adh Member identifier
924 * @param string $pass New password
928 public static function updatePassword(Db
$zdb, int $id_adh, string $pass): bool
931 $cpass = password_hash($pass, PASSWORD_BCRYPT
);
933 $update = $zdb->update(self
::TABLE
);
935 array('mdp_adh' => $cpass)
936 )->where([self
::PK
=> $id_adh]);
937 $zdb->execute($update);
939 'Password for `' . $id_adh . '` has been updated.',
943 } catch (Throwable
$e) {
945 'An error occurred while updating password for `' . $id_adh .
946 '` | ' . $e->getMessage(),
956 * @param string $field Field name
960 private function getFieldLabel(string $field): string
962 $label = $this->fields
[$field]['label'];
964 $label = str_replace(' ', ' ', $label);
965 //remove trailing ':' and then trim
966 $label = trim(trim($label ??
'', ':'));
971 * Retrieve fields from database
973 * @param Db $zdb Database instance
977 public static function getDbFields(Db
$zdb): array
979 $columns = $zdb->getColumns(self
::TABLE
);
981 foreach ($columns as $col) {
982 $fields[] = $col->getName();
988 * Mark as self membership
992 public function setSelfMembership(): void
994 $this->_self_adh
= true;
998 * Is member up to date?
1002 public function isUp2Date(): bool
1004 if (!$this->isDepEnabled('dues')) {
1008 if ($this->isDueFree()) {
1009 //member is due free, he's up to date.
1012 //let's check from due date, if present
1013 if ($this->_due_date
== null) {
1016 $due_date = new \
DateTime($this->_due_date
);
1017 $now = new \
DateTime();
1018 $now->setTime(0, 0, 0);
1019 return $due_date >= $now;
1027 * @param Preferences $preferences Preferences instance
1028 * @param array $fields Members fields configuration
1029 * @param History $history History instance
1033 public function setDependencies(
1034 Preferences
$preferences,
1038 $this->preferences
= $preferences;
1039 $this->fields
= $fields;
1040 $this->history
= $history;
1044 * Check posted values validity
1046 * @param array $values All values to check, basically the $_POST array
1047 * after sending the form
1048 * @param array $required Array of required fields
1049 * @param array $disabled Array of disabled fields
1051 * @return true|array
1053 public function check(array $values, array $required, array $disabled)
1057 $this->errors
= array();
1060 foreach ($values as &$rawvalue) {
1061 if (is_string($rawvalue)) {
1062 $rawvalue = strip_tags($rawvalue);
1066 $fields = self
::getDbFields($this->zdb
);
1068 //reset company name if needed
1069 if (!isset($values['is_company'])) {
1070 unset($values['is_company']);
1071 $values['societe_adh'] = '';
1074 //no parent if checkbox was unchecked
1076 !isset($values['attach'])
1077 && empty($this->_id
)
1078 && isset($values['parent_id'])
1080 unset($values['parent_id']);
1083 if (isset($values['duplicate'])) {
1084 //if we're duplicating, keep a trace (if an error occurs)
1085 $this->_duplicate
= true;
1088 foreach ($fields as $key) {
1089 //first, let's sanitize values
1090 $key = strtolower($key);
1091 $prop = '_' . $this->fields
[$key]['propname'];
1093 if (isset($values[$key])) {
1094 $value = $values[$key];
1095 if ($value !== true && $value !== false) {
1096 $value = trim($value ??
'');
1098 } elseif (empty($this->_id
)) {
1100 case 'bool_admin_adh':
1101 case 'bool_exempt_adh':
1102 case 'bool_display_info':
1105 case 'activite_adh':
1106 //values that are set at object instantiation
1109 case 'date_crea_adh':
1115 //values that are set at object instantiation
1116 $value = $this->$prop;
1126 //keep stored value on update
1127 if ($prop != '_password' ||
isset($values['mdp_adh']) && isset($values['mdp_adh2'])) {
1128 $value = $this->$prop;
1134 // if the field is enabled, check it
1135 if (!isset($disabled[$key])) {
1136 // fill up the adherent structure
1137 if ($value !== null && $value !== true && $value !== false && !is_object($value)) {
1138 $value = stripslashes($value);
1140 $this->$prop = $value;
1142 // now, check validity
1143 if ($value !== null && $value != '') {
1144 if ($key !== 'mdp_adh') {
1145 $this->validate($key, $value, $values);
1147 } elseif (empty($this->_id
)) {
1148 //ensure login and password are not empty
1149 if (($key == 'login_adh' ||
$key == 'mdp_adh') && !isset($required[$key])) {
1150 $p = new Password($this->zdb
);
1151 $generated_value = $p->makeRandomPassword(15);
1152 if ($key == 'login_adh') {
1153 //'@' is not permitted in logins
1154 $this->$prop = str_replace('@', 'a', $generated_value);
1156 $this->$prop = $generated_value;
1163 //password checks need data to be previously set
1164 if (isset($values['mdp_adh'])) {
1165 $this->validate('mdp_adh', $values['mdp_adh'], $values);
1168 // missing required fields?
1169 foreach ($required as $key => $val) {
1170 $prop = '_' . $this->fields
[$key]['propname'];
1172 if (!isset($disabled[$key])) {
1173 $mandatory_missing = false;
1174 if (!isset($this->$prop) ||
$this->$prop == '') {
1175 $mandatory_missing = true;
1176 } elseif ($key === 'titre_adh' && $this->$prop == '-1') {
1177 $mandatory_missing = true;
1180 if ($mandatory_missing === true) {
1181 $this->errors
[] = str_replace(
1183 '<a href="#' . $key . '">' . $this->getFieldLabel($key) . '</a>',
1184 _T("- Mandatory field %field empty.")
1190 //attach to/detach from parent
1191 if (isset($values['detach_parent'])) {
1192 $this->_parent
= null;
1195 if ($login->isGroupManager() && !$login->isAdmin() && !$login->isStaff() && $this->parent_id
!== $login->id
) {
1196 if (!isset($values['groups_adh'])) {
1197 $this->errors
[] = _T('You have to select a group you own!');
1199 $owned_group = false;
1200 foreach ($values['groups_adh'] as $group) {
1201 list($gid) = explode('|', $group);
1202 if ($login->isGroupManager($gid)) {
1203 $owned_group = true;
1206 if ($owned_group === false) {
1207 $this->errors
[] = _T('You have to select a group you own!');
1212 $this->dynamicsCheck($values, $required, $disabled);
1213 $this->checkSocials($values);
1215 if (count($this->errors
) > 0) {
1217 'Some errors has been thew attempting to edit/store a member' . "\n" .
1218 print_r($this->errors
, true),
1221 return $this->errors
;
1226 'Member checked successfully.',
1234 * Validate data for given key
1235 * Set valid data in current object, also resets errors list
1237 * @param string $field Field name
1238 * @param mixed $value Value we want to set
1239 * @param array $values All values, for some references
1243 public function validate(string $field, $value, array $values): void
1245 global $preferences;
1247 $prop = '_' . $this->fields
[$field]['propname'];
1249 if ($value === null ||
(is_string($value) && trim($value) == '')) {
1250 //empty values are OK
1251 $this->$prop = $value;
1257 case 'date_crea_adh':
1258 case 'date_modif_adh_':
1260 case 'date_echeance':
1262 $d = \DateTime
::createFromFormat(__("Y-m-d"), $value);
1264 //try with non localized date
1265 $d = \DateTime
::createFromFormat("Y-m-d", $value);
1267 throw new \
Exception('Incorrect format');
1271 if ($field === 'ddn_adh') {
1272 $now = new \
DateTime();
1273 $now->setTime(0, 0, 0);
1274 $d->setTime(0, 0, 0);
1276 $diff = $now->diff($d);
1277 $days = (int)$diff->format('%R%a');
1279 $this->errors
[] = _T('- Birthdate must be set in the past!');
1282 $years = (int)$diff->format('%R%Y');
1283 if ($years <= -200) {
1284 $this->errors
[] = str_replace(
1287 _T('- Members must be less than 200 years old (currently %years)!')
1291 $this->$prop = $d->format('Y-m-d');
1292 } catch (Throwable
$e) {
1294 'Wrong date format. field: ' . $field .
1295 ', value: ' . $value . ', expected fmt: ' .
1296 __("Y-m-d") . ' | ' . $e->getMessage(),
1299 $this->errors
[] = str_replace(
1306 $this->getFieldLabel($field)
1308 _T("- Wrong date format (%date_format) for %field!")
1313 if ($value !== null && $value !== '') {
1314 if ($value == '-1') {
1315 $this->$prop = null;
1316 } elseif (!$value instanceof Title
) {
1317 $this->$prop = new Title((int)$value);
1320 $this->$prop = null;
1324 if (!GaletteMail
::isValidEmail($value)) {
1325 $this->errors
[] = _T("- Non-valid E-Mail address!") .
1326 ' (' . $this->getFieldLabel($field) . ')';
1328 if ($field == 'email_adh') {
1330 $select = $this->zdb
->select(self
::TABLE
);
1333 )->where(array('email_adh' => $value));
1334 if (!empty($this->_id
)) {
1335 $select->where
->notEqualTo(
1341 $results = $this->zdb
->execute($select);
1342 if ($results->count() !== 0) {
1343 $this->errors
[] = _T("- This E-Mail address is already used by another member!");
1345 } catch (Throwable
$e) {
1347 'An error occurred checking member email uniqueness.',
1350 $this->errors
[] = _T("An error has occurred while looking if login already exists.");
1355 /** FIXME: add a preference for login length */
1356 if (strlen($value) < 2) {
1357 $this->errors
[] = str_replace(
1360 _T("- The username must be composed of at least %i characters!")
1363 //check if login does not contain the @ character
1364 if (strpos($value, '@') != false) {
1365 $this->errors
[] = _T("- The username cannot contain the @ character");
1367 //check if login is already taken
1369 $select = $this->zdb
->select(self
::TABLE
);
1372 )->where(array('login_adh' => $value));
1373 if (!empty($this->_id
)) {
1374 $select->where
->notEqualTo(
1380 $results = $this->zdb
->execute($select);
1382 $results->count() !== 0
1383 ||
$value == $preferences->pref_admin_login
1385 $this->errors
[] = _T("- This username is already in use, please choose another one!");
1387 } catch (Throwable
$e) {
1389 'An error occurred checking member login uniqueness.',
1392 $this->errors
[] = _T("An error has occurred while looking if login already exists.");
1399 $this->_self_adh
!== true
1400 && (!isset($values['mdp_adh2'])
1401 ||
$values['mdp_adh2'] != $value)
1403 $this->errors
[] = _T("- The passwords don't match!");
1405 $this->_self_adh
=== true
1406 && !crypt($value, $values['mdp_crypt']) == $values['mdp_crypt']
1408 $this->errors
[] = _T("Password misrepeated: ");
1410 $pinfos = password_get_info($value);
1411 //check if value is already a hash
1412 if ($pinfos['algo'] == 0) {
1413 $this->$prop = password_hash(
1418 $pwcheck = new \Galette\Util\
Password($preferences);
1419 $pwcheck->setAdherent($this);
1420 if (!$pwcheck->isValid($value)) {
1421 $this->errors
= array_merge(
1423 $pwcheck->getErrors()
1431 $this->$prop = (int)$value;
1432 //check if status exists
1433 $select = $this->zdb
->select(Status
::TABLE
);
1434 $select->where([Status
::PK
=> $value]);
1436 $results = $this->zdb
->execute($select);
1437 $result = $results->current();
1439 $this->errors
[] = str_replace(
1442 _T("Status #%id does not exists in database.")
1446 } catch (Throwable
$e) {
1448 'An error occurred checking status existence: ' . $e->getMessage(),
1451 $this->errors
[] = _T("An error has occurred while looking if status does exists.");
1455 if (in_array($value, [self
::NC
, self
::MAN
, self
::WOMAN
])) {
1456 $this->$prop = (int)$value;
1458 $this->errors
[] = _T("Gender %gender does not exists!");
1462 $this->$prop = ($value instanceof Adherent
) ?
(int)$value->id
: (int)$value;
1463 $this->loadParent();
1473 public function store(): bool
1475 global $hist, $emitter, $login;
1478 if (!$login->isAdmin() && !$login->isStaff() && !$login->isGroupManager() && $this->id
== '') {
1479 if ($this->preferences
->pref_bool_create_member
) {
1480 $this->_parent
= $login->id
;
1486 $fields = self
::getDbFields($this->zdb
);
1488 foreach ($fields as $field) {
1490 $field !== 'date_modif_adh'
1491 ||
empty($this->_id
)
1493 $prop = '_' . $this->fields
[$field]['propname'];
1495 ($field === 'bool_admin_adh'
1496 ||
$field === 'bool_exempt_adh'
1497 ||
$field === 'bool_display_info'
1498 ||
$field === 'activite_adh')
1499 && $this->$prop === false
1501 //Handle booleans for postgres ; bugs #18899 and #19354
1502 $values[$field] = $this->zdb
->isPostgres() ?
'false' : 0;
1503 } elseif ($field === 'parent_id') {
1505 if ($this->_parent
=== null) {
1506 $values['parent_id'] = new Expression('NULL');
1507 } elseif ($this->parent
instanceof Adherent
) {
1508 $values['parent_id'] = $this->_parent
->id
;
1510 $values['parent_id'] = $this->_parent
;
1513 $values[$field] = $this->$prop;
1518 //an empty value will cause date to be set to 1901-01-01, a null
1519 //will result in 0000-00-00. We want a database NULL value here.
1520 if (!$this->_birthdate
) {
1521 $values['ddn_adh'] = new Expression('NULL');
1523 if (!$this->_due_date
) {
1524 $values['date_echeance'] = new Expression('NULL');
1527 if ($this->_title
instanceof Title
) {
1528 $values['titre_adh'] = $this->_title
->id
;
1530 $values['titre_adh'] = new Expression('NULL');
1533 if (!$this->_parent
) {
1534 $values['parent_id'] = new Expression('NULL');
1537 if (!$this->_number
) {
1538 $values['num_adh'] = new Expression('NULL');
1541 //fields that cannot be null
1543 '_surname' => 'prenom_adh',
1544 '_nickname' => 'pseudo_adh',
1545 '_address' => 'adresse_adh',
1546 '_zipcode' => 'cp_adh',
1547 '_town' => 'ville_adh'
1549 foreach ($notnull as $prop => $field) {
1550 if ($this->$prop === null) {
1551 $values[$field] = '';
1556 if (empty($this->_id
)) {
1557 //we're inserting a new member
1558 unset($values[self
::PK
]);
1559 //set modification date
1560 $this->_modification_date
= date('Y-m-d');
1561 $values['date_modif_adh'] = $this->_modification_date
;
1563 $insert = $this->zdb
->insert(self
::TABLE
);
1564 $insert->values($values);
1565 $add = $this->zdb
->execute($insert);
1566 if ($add->count() > 0) {
1567 $this->_id
= $this->zdb
->getLastGeneratedValue($this);
1568 $this->_picture
= new Picture($this->_id
);
1570 if ($this->_self_adh
) {
1572 _T("Self_subscription as a member: ") .
1573 $this->getNameWithCase($this->_name
, $this->_surname
),
1578 _T("Member card added"),
1584 $event = 'member.add';
1586 $hist->add(_T("Fail to add new member."));
1587 throw new \
Exception(
1588 'An error occurred inserting new member!'
1592 //we're editing an existing member
1593 if (!$this->isDueFree()) {
1595 $due_date = Contribution
::getDueDate($this->zdb
, $this->_id
);
1597 $values['date_echeance'] = $due_date;
1601 if (!$this->_password
) {
1602 unset($values['mdp_adh']);
1605 $update = $this->zdb
->update(self
::TABLE
);
1606 $update->set($values);
1607 $update->where([self
::PK
=> $this->_id
]);
1609 $edit = $this->zdb
->execute($update);
1611 //edit == 0 does not mean there were an error, but that there
1612 //were nothing to change
1613 if ($edit->count() > 0) {
1614 $this->updateModificationDate();
1616 _T("Member card updated"),
1621 $event = 'member.edit';
1626 $success = $this->dynamicsStore();
1627 $this->storeSocials($this->id
);
1630 //send event at the end of process, once all has been stored
1631 if ($event !== null) {
1632 $emitter->emit($event, $this);
1635 } catch (Throwable
$e) {
1637 'Something went wrong :\'( | ' . $e->getMessage() . "\n" .
1638 $e->getTraceAsString(),
1646 * Update member modification date
1650 private function updateModificationDate(): void
1653 $modif_date = date('Y-m-d');
1654 $update = $this->zdb
->update(self
::TABLE
);
1656 array('date_modif_adh' => $modif_date)
1657 )->where([self
::PK
=> $this->_id
]);
1659 $edit = $this->zdb
->execute($update);
1660 $this->_modification_date
= $modif_date;
1661 } catch (Throwable
$e) {
1663 'Something went wrong updating modif date :\'( | ' .
1664 $e->getMessage() . "\n" . $e->getTraceAsString(),
1672 * Global getter method
1674 * @param string $name name of the property we want to retrieve
1678 public function __get(string $name)
1681 'admin', 'staff', 'due_free', 'appears_in_list', 'active',
1682 'row_classes', 'oldness', 'duplicate', 'groups', 'managed_groups'
1684 if (!defined('GALETTE_TESTS')) {
1685 $forbidden[] = 'password'; //keep that for tests only
1689 'sadmin', 'sstaff', 'sdue_free', 'sappears_in_list', 'sactive',
1690 'stitle', 'sstatus', 'sfullname', 'sname', 'saddress',
1691 'rbirthdate', 'sgender', 'contribstatus',
1694 $socials = array('website', 'msn', 'jabber', 'icq');
1696 if (in_array($name, $forbidden)) {
1698 'Calling property "' . $name . '" directly is discouraged.',
1703 return $this->isAdmin();
1705 return $this->isStaff();
1707 return $this->isDueFree();
1708 case 'appears_in_list':
1709 return $this->appearsInMembersList();
1711 return $this->isActive();
1713 return $this->isDuplicate();
1715 return $this->getGroups();
1716 case 'managed_groups':
1717 return $this->getManagedGroups();
1719 throw new \
RuntimeException("Call to __get for '$name' is forbidden!");
1723 if (in_array($name, $virtuals)) {
1724 if (substr($name, 0, 1) !== '_') {
1725 $real = '_' . substr($name, 1);
1732 case 'sappears_in_list':
1734 return (($this->$real) ?
_T("Yes") : _T("No"));
1737 return (($this->$real) ?
_T("Active") : _T("Inactive"));
1740 if (isset($this->_title
) && $this->_title
instanceof Title
) {
1741 return $this->_title
->tshort
;
1747 $status = new Status($this->zdb
);
1748 return $status->getLabel($this->_status
);
1750 return $this->getNameWithCase(
1753 (isset($this->_title
) ?
$this->title
: false)
1756 $address = $this->_address
;
1759 return $this->getNameWithCase($this->_name
, $this->_surname
);
1761 return $this->_birthdate
;
1763 switch ($this->gender
) {
1769 return _T('Unspecified');
1771 case 'contribstatus':
1772 return $this->getDues();
1776 //for backward compatibility
1777 if (in_array($name, $socials)) {
1778 $values = Social
::getListForMember($this->_id
, $name);
1779 return $values[0] ??
null;
1782 if (substr($name, 0, 1) !== '_') {
1783 $rname = '_' . $name;
1791 if ($this->$rname !== null) {
1792 return (int)$this->$rname;
1797 return $this->$rname ??
'';
1799 case 'creation_date':
1800 case 'modification_date':
1802 if ($this->$rname != '') {
1804 $d = new \
DateTime($this->$rname);
1805 return $d->format(__("Y-m-d"));
1806 } catch (Throwable
$e) {
1807 //oops, we've got a bad date :/
1809 'Bad date (' . $this->$rname . ') | ' .
1813 return $this->$rname;
1818 return ($this->_parent
instanceof Adherent
) ?
(int)$this->_parent
->id
: (int)$this->_parent
;
1820 if (!property_exists($this, $rname)) {
1822 "Unknown property '$rname'",
1827 return $this->$rname;
1833 * Global isset method
1834 * Required for twig to access properties via __get
1836 * @param string $name name of the property we want to retrieve
1840 public function __isset(string $name)
1843 'admin', 'staff', 'due_free', 'appears_in_list', 'active',
1844 'row_classes', 'oldness', 'duplicate', 'groups', 'managed_groups'
1846 if (!defined('GALETTE_TESTS')) {
1847 $forbidden[] = 'password'; //keep that for tests only
1851 'sadmin', 'sstaff', 'sdue_free', 'sappears_in_list', 'sactive',
1852 'stitle', 'sstatus', 'sfullname', 'sname', 'saddress',
1853 'rbirthdate', 'sgender', 'contribstatus',
1856 $socials = array('website', 'msn', 'jabber', 'icq');
1858 if (in_array($name, $forbidden)) {
1860 'Calling property "' . $name . '" directly is discouraged.',
1867 case 'appears_in_list':
1871 case 'managed_groups':
1878 if (in_array($name, $virtuals)) {
1882 //for backward compatibility
1883 if (in_array($name, $socials)) {
1887 if (substr($name, 0, 1) !== '_') {
1888 $rname = '_' . $name;
1898 case 'creation_date':
1899 case 'modification_date':
1904 return property_exists($this, $rname);
1912 * If member does not have an email address, but is attached to
1913 * another member, we'll take information from its parent.
1917 public function getEmail(): string
1919 $email = $this->_email
;
1920 if (empty($email)) {
1921 $this->loadParent();
1922 $email = $this->parent
->email
;
1925 return $email ??
'';
1929 * Get member address.
1930 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1934 public function getAddress(): string
1936 $address = $this->_address
;
1937 if (empty($address) && $this->hasParent()) {
1938 $this->loadParent();
1939 $address = $this->parent
->address
;
1942 return $address ??
'';
1946 * Get member zipcode.
1947 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1951 public function getZipcode(): string
1953 $address = $this->_address
;
1954 $zip = $this->_zipcode
;
1955 if (empty($address) && $this->hasParent()) {
1956 $this->loadParent();
1957 $zip = $this->parent
->zipcode
;
1965 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1969 public function getTown(): string
1971 $address = $this->_address
;
1972 $town = $this->_town
;
1973 if (empty($address) && $this->hasParent()) {
1974 $this->loadParent();
1975 $town = $this->parent
->town
;
1982 * Get member country.
1983 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1987 public function getCountry(): string
1989 $address = $this->_address
;
1990 $country = $this->_country
;
1991 if (empty($address) && $this->hasParent()) {
1992 $this->loadParent();
1993 $country = $this->parent
->country
;
1996 return $country ??
'';
2004 public function getAge(): string
2006 if ($this->_birthdate
== null) {
2010 $d = \DateTime
::createFromFormat('Y-m-d', $this->_birthdate
);
2013 'Invalid birthdate: ' . $this->_birthdate
,
2021 $d->diff(new \
DateTime())->y
,
2022 _T(' (%age years old)')
2027 * Get parent inherited fields
2031 public function getParentFields(): array
2033 return $this->parent_fields
;
2037 * Handle files (photo and dynamics files)
2039 * @param array $files Files sent
2041 * @return array|true
2043 public function handleFiles(array $files)
2047 if (isset($files['photo'])) {
2048 if ($files['photo']['error'] === UPLOAD_ERR_OK
) {
2049 if ($files['photo']['tmp_name'] != '') {
2050 if (is_uploaded_file($files['photo']['tmp_name'])) {
2051 $res = $this->picture
->store($files['photo']);
2054 = $this->picture
->getErrorMessage($res);
2058 } elseif ($files['photo']['error'] !== UPLOAD_ERR_NO_FILE
) {
2060 $this->picture
->getPhpErrorMessage($files['photo']['error']),
2063 $this->errors
[] = $this->picture
->getPhpErrorMessage(
2064 $files['photo']['error']
2068 $this->dynamicsFiles($files);
2070 if (count($this->errors
) > 0) {
2072 'Some errors has been thew attempting to edit/store a member files' . "\n" .
2073 print_r($this->errors
, true),
2076 return $this->errors
;
2083 * Set member as duplicate
2087 public function setDuplicate(): void
2089 //mark as duplicated
2090 $this->_duplicate
= true;
2091 $infos = $this->_others_infos_admin
;
2092 $this->_others_infos_admin
= str_replace(
2094 [$this->sname
, $this->_id
],
2095 _T('Duplicated from %name (%id)')
2097 if (!empty($infos)) {
2098 $this->_others_infos_admin
.= "\n" . $infos;
2102 //drop email, must be unique
2103 $this->_email
= null;
2104 //drop creation date
2105 $this->_creation_date
= date("Y-m-d");
2107 $this->_login
= null;
2109 $this->_picture
= new Picture();
2111 $this->_birthdate
= null;
2113 $this->_surname
= null;
2115 $this->_admin
= false;
2117 $this->_due_free
= false;
2121 * Get current errors
2125 public function getErrors(): array
2127 return $this->errors
;
2135 public function getGroups(): array
2137 if (!$this->isDepEnabled('groups')) {
2138 $this->loadGroups();
2140 return $this->_groups
;
2144 * Get user managed groups
2148 public function getManagedGroups(): array
2150 if (!$this->isDepEnabled('groups')) {
2151 $this->loadGroups();
2153 return $this->_managed_groups
;
2157 * Can current logged-in user create member
2159 * @param Login $login Login instance
2163 public function canCreate(Login
$login): bool
2165 global $preferences;
2167 if ($this->id
&& $login->id
== $this->id ||
$login->isAdmin() ||
$login->isStaff()) {
2171 if ($preferences->pref_bool_groupsmanagers_create_member
&& $login->isGroupManager()) {
2175 if ($preferences->pref_bool_create_member
&& $login->isLogged()) {
2183 * Can current logged-in user edit member
2185 * @param Login $login Login instance
2189 public function canEdit(Login
$login): bool
2191 global $preferences;
2193 //admin and staff users can edit, as well as member itself
2194 if ($this->id
&& $login->id
== $this->id ||
$login->isAdmin() ||
$login->isStaff()) {
2198 //parent can edit their child cards
2199 if ($this->hasParent() && $this->parent_id
=== $login->id
) {
2203 //group managers can edit members of groups they manage when pref is on
2204 if ($preferences->pref_bool_groupsmanagers_edit_member
&& $login->isGroupManager()) {
2205 foreach ($this->getGroups() as $g) {
2206 if ($login->isGroupManager($g->getId())) {
2216 * Can current logged-in user display member
2218 * @param Login $login Login instance
2222 public function canShow(Login
$login): bool
2224 //group managers can show members of groups they manage
2225 if ($login->isGroupManager()) {
2226 foreach ($this->getGroups() as $g) {
2227 if ($login->isGroupManager($g->getId())) {
2233 return $this->canEdit($login);
2237 * Are we currently duplicated a member?
2241 public function isDuplicate(): bool
2243 return $this->_duplicate
;
2247 * Flag creation mail sending
2249 * @param boolean $send True (default) to send creation email
2253 public function setSendmail(bool $send = true): self
2255 $this->sendmail
= $send;
2260 * Should we send administrative emails to member?
2264 public function sendEMail(): bool
2266 return $this->sendmail
;
2272 * @param integer $id Parent identifier
2276 public function setParent(int $id): self
2278 $this->_parent
= $id;
2279 $this->loadParent();
2284 * Reset dependencies to load
2288 public function disableAllDeps(): self
2290 foreach ($this->_deps
as &$dep) {
2297 * Enable all dependencies to load
2301 public function enableAllDeps(): self
2303 foreach ($this->_deps
as &$dep) {
2310 * Enable a load dependency
2312 * @param string $name Dependency name
2316 public function enableDep(string $name): self
2318 if (!isset($this->_deps
[$name])) {
2320 'dependency ' . $name . ' does not exists!',
2324 $this->_deps
[$name] = true;
2331 * Enable a load dependency
2333 * @param string $name Dependency name
2337 public function disableDep(string $name): self
2339 if (!isset($this->_deps
[$name])) {
2341 'dependency ' . $name . ' does not exists!',
2345 $this->_deps
[$name] = false;
2352 * Is load dependency enabled?
2354 * @param string $name Dependency name
2358 protected function isDepEnabled(string $name): bool
2360 return $this->_deps
[$name];