3 /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
6 * Member class for galette
10 * Copyright © 2009-2021 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-2021 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-2021 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 birth date
74 * @property string $rbirthdate Raw birth date
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 $address_continuation
84 * @property string $zipcode
85 * @property string $town
86 * @property string $country
87 * @property string $phone
88 * @property string $gsm
89 * @property string $email
90 * @property string $gnupgid
91 * @property string $fingerprint
92 * @property string $login
93 * @property string $creation_date Localized creation date
94 * @property string $modification_date Localized modification date
95 * @property string $due_date Localized due date
96 * @property string $others_infos
97 * @property string $others_infos_admin
98 * @property Picture $picture
99 * @property array $groups
100 * @property array $managed_groups
101 * @property integer|Adherent $parent Parent id if parent dep is not loaded, Adherent instance otherwise
102 * @property array $children
103 * @property boolean $admin better to rely on isAdmin()
104 * @property boolean $staff better to rely on isStaff()
105 * @property boolean $due_free better to rely on isDueFree()
106 * @property boolean $appears_in_list better to rely on appearsInMembersList()
107 * @property boolean $active better to rely on isActive()
108 * @property boolean $duplicate better to rely on isDuplicate()
109 * @property string $sadmin yes/no
110 * @property string $sstaff yes/no
111 * @property string $sdue_free yes/no
112 * @property string $sappears_in_list yes/no
113 * @property string $sactive yes/no
114 * @property string $sfullname
115 * @property string $sname
116 * @property string $saddress Concatened address and continuation
117 * @property string $contribstatus State of member contributions
118 * @property string $days_remaining
119 * @property-read integer $parent_id
120 * @property Social $social Social networks/Contact
121 * @property string $number Member number
129 public const TABLE
= 'adherents';
130 public const PK
= 'id_adh';
133 public const MAN
= 1;
134 public const WOMAN
= 2;
136 public const AFTER_ADD_DEFAULT
= 0;
137 public const AFTER_ADD_TRANS
= 1;
138 public const AFTER_ADD_NEW
= 2;
139 public const AFTER_ADD_SHOW
= 3;
140 public const AFTER_ADD_LIST
= 4;
141 public const AFTER_ADD_HOME
= 5;
146 private $_company_name;
151 private $_birth_place;
157 //Contact information
159 private $_address_continuation; /** TODO: remove */
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 = [];
187 private $_duplicate = false;
191 private $_row_classes;
193 private $_self_adh = false;
194 private $_deps = array(
205 private $preferences;
209 private $parent_fields = [
217 private $errors = [];
219 private $sendmail = false;
222 * Default constructor
224 * @param Db $zdb Database instance
225 * @param mixed $args Either a ResultSet row, its id or its
226 * login or its email for to load s specific
227 * member, or null to just instantiate object
228 * @param false|array|null $deps Dependencies configuration, see Adherent::$_deps
230 public function __construct(Db
$zdb, $args = null, $deps = null)
236 if ($deps !== null) {
237 if (is_array($deps)) {
238 $this->_deps
= array_merge(
242 } elseif ($deps === false) {
244 $this->_deps
= array_fill_keys(
245 array_keys($this->_deps
),
250 '$deps should be an array, ' . gettype($deps) . ' given!',
256 if ($args == null ||
is_int($args)) {
257 if (is_int($args) && $args > 0) {
260 $this->_active
= true;
261 $this->_language
= $i18n->getID();
262 $this->_creation_date
= date("Y-m-d");
263 $this->_status
= $this->getDefaultStatus();
264 $this->_title
= null;
265 $this->_gender
= self
::NC
;
266 $gp = new Password($this->zdb
);
267 $this->_password
= $gp->makeRandomPassword();
268 $this->_picture
= new Picture();
269 $this->_admin
= false;
270 $this->_staff
= false;
271 $this->_due_free
= false;
272 $this->_appears_in_list
= false;
273 $this->_parent
= null;
275 if ($this->_deps
['dynamics'] === true) {
276 $this->loadDynamicFields();
279 } elseif (is_object($args)) {
280 $this->loadFromRS($args);
281 } elseif (is_string($args)) {
282 $this->loadFromLoginOrMail($args);
287 * Loads a member from its id
289 * @param int $id the identifier for the member to load
291 * @return bool true if query succeed, false otherwise
293 public function load(int $id): bool
296 $select = $this->zdb
->select(self
::TABLE
, 'a');
299 array('b' => PREFIX_DB
. Status
::TABLE
),
300 'a.' . Status
::PK
. '=b.' . Status
::PK
,
301 array('priorite_statut')
302 )->where(array(self
::PK
=> $id));
304 $results = $this->zdb
->execute($select);
306 if ($results->count() === 0) {
310 $this->loadFromRS($results->current());
312 } catch (Throwable
$e) {
314 'Cannot load member form id `' . $id . '` | ' . $e->getMessage(),
322 * Loads a member from its login
324 * @param string $login login for the member to load
328 public function loadFromLoginOrMail(string $login): bool
331 $select = $this->zdb
->select(self
::TABLE
);
332 if (GaletteMail
::isValidEmail($login)) {
333 //we got a valid email address, use it
334 $select->where(array('email_adh' => $login));
336 ///we did not get an email address, consider using login
337 $select->where(array('login_adh' => $login));
340 $results = $this->zdb
->execute($select);
341 $result = $results->current();
343 $this->loadFromRS($result);
346 } catch (Throwable
$e) {
348 'Cannot load member form login `' . $login . '` | ' .
357 * Populate object from a resultset row
359 * @param ResultSet $r the resultset row
363 private function loadFromRS($r): void
365 $this->_self_adh
= false;
366 $this->_id
= $r->id_adh
;
368 if ($r->titre_adh
!== null) {
369 $this->_title
= new Title((int)$r->titre_adh
);
371 $this->_company_name
= $r->societe_adh
;
372 $this->_name
= $r->nom_adh
;
373 $this->_surname
= $r->prenom_adh
;
374 $this->_nickname
= $r->pseudo_adh
;
375 if ($r->ddn_adh
!= '1901-01-01') {
376 $this->_birthdate
= $r->ddn_adh
;
378 $this->_birth_place
= $r->lieu_naissance
;
379 $this->_gender
= (int)$r->sexe_adh
;
380 $this->_job
= $r->prof_adh
;
381 $this->_language
= $r->pref_lang
;
382 $this->_active
= $r->activite_adh
== 1;
383 $this->_status
= (int)$r->id_statut
;
384 //Contact information
385 $this->_address
= $r->adresse_adh
;
386 /** TODO: remove and merge with address */
387 $this->_address_continuation
= $r->adresse2_adh
;
388 $this->_zipcode
= $r->cp_adh
;
389 $this->_town
= $r->ville_adh
;
390 $this->_country
= $r->pays_adh
;
391 $this->_phone
= $r->tel_adh
;
392 $this->_gsm
= $r->gsm_adh
;
393 $this->_email
= $r->email_adh
;
394 $this->_gnupgid
= $r->gpgid
;
395 $this->_fingerprint
= $r->fingerprint
;
396 //Galette relative information
397 $this->_appears_in_list
= $r->bool_display_info
== 1;
398 $this->_admin
= $r->bool_admin_adh
== 1;
400 isset($r->priorite_statut
)
401 && $r->priorite_statut
< Members
::NON_STAFF_MEMBERS
403 $this->_staff
= true;
405 $this->_due_free
= $r->bool_exempt_adh
== 1;
406 $this->_login
= $r->login_adh
;
407 $this->_password
= $r->mdp_adh
;
408 $this->_creation_date
= $r->date_crea_adh
;
409 if ($r->date_modif_adh
!= '1901-01-01') {
410 $this->_modification_date
= $r->date_modif_adh
;
412 $this->_modification_date
= $this->_creation_date
;
414 $this->_due_date
= $r->date_echeance
;
415 $this->_others_infos
= $r->info_public_adh
;
416 $this->_others_infos_admin
= $r->info_adh
;
417 $this->_number
= $r->num_adh
;
419 if ($r->parent_id
!== null) {
420 $this->_parent
= (int)$r->parent_id
;
421 if ($this->_deps
['parent'] === true) {
426 if ($this->_deps
['children'] === true) {
427 $this->loadChildren();
430 if ($this->_deps
['picture'] === true) {
431 $this->_picture
= new Picture($this->_id
);
434 if ($this->_deps
['groups'] === true) {
438 if ($this->_deps
['dues'] === true) {
442 if ($this->_deps
['dynamics'] === true) {
443 $this->loadDynamicFields();
446 if ($this->_deps
['socials'] === true) {
447 $this->loadSocials();
456 private function loadParent(): void
458 if (!$this->_parent
instanceof Adherent
) {
459 $deps = array_fill_keys(array_keys($this->_deps
), false);
460 $this->_parent
= new Adherent($this->zdb
, (int)$this->_parent
, $deps);
465 * Load member children
469 private function loadChildren(): void
471 $this->_children
= array();
474 $select = $this->zdb
->select(self
::TABLE
);
477 )->where(['parent_id' => $this->_id
]);
479 $results = $this->zdb
->execute($select);
481 if ($results->count() > 0) {
482 foreach ($results as $row) {
483 $deps = $this->_deps
;
484 $deps['children'] = false;
485 $deps['parent'] = false;
486 $this->_children
[] = new Adherent($this->zdb
, (int)$row->$id, $deps);
489 } catch (Throwable
$e) {
491 'Cannot load children for member #' . $this->_id
. ' | ' .
504 public function loadGroups(): void
506 $this->_groups
= Groups
::loadGroups($this->_id
);
507 $this->_managed_groups
= Groups
::loadManagedGroups($this->_id
);
511 * Load member social network/contact information
515 public function loadSocials(): void
517 $this->_socials
= Social
::getListForMember($this->_id
);
521 * Retrieve status from preferences
526 private function getDefaultStatus(): int
529 if ($preferences->pref_statut
!= '') {
530 return $preferences->pref_statut
;
533 'Unable to get pref_statut; is it defined in preferences?',
536 return Status
::DEFAULT_STATUS
;
541 * Check for dues status
545 private function checkDues(): void
547 //how many days since our beloved member has been created
548 $date_now = new \
DateTime();
549 $this->_oldness
= $date_now->diff(
550 new \
DateTime($this->_creation_date
)
553 if ($this->isDueFree()) {
554 //no fee required, we don't care about dates
555 $this->_row_classes
.= ' cotis-exempt';
557 //ok, fee is required. Let's check the dates
558 if ($this->_due_date
== '') {
559 $this->_row_classes
.= ' cotis-never';
561 $date_end = new \
DateTime($this->_due_date
);
562 $date_diff = $date_now->diff($date_end);
563 $this->_days_remaining
= ($date_diff->invert
== 1)
564 ?
$date_diff->days
* -1
567 if ($this->_days_remaining
== 0) {
568 $this->_row_classes
.= ' cotis-lastday';
569 } elseif ($this->_days_remaining
< 0) {
570 //check if member is still active
571 $this->_row_classes
.= $this->isActive() ?
' cotis-late' : ' cotis-old';
572 } elseif ($this->_days_remaining
< 30) {
573 $this->_row_classes
.= ' cotis-soon';
575 $this->_row_classes
.= ' cotis-ok';
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' : 'inactive';
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 $date_now = new \
DateTime();
769 if ($this->isDueFree()) {
770 $ret = _T("Freed of dues");
771 } elseif ($this->_due_date
== '') {
772 $patterns = array('/%days/', '/%date/');
773 $cdate = new \
DateTime($this->_creation_date
);
776 $cdate->format(__("Y-m-d"))
778 if ($this->_active
) {
782 _T("Never contributed: Registered %days days ago (since %date)")
785 $ret = _T("Never contributed");
787 } elseif ($this->_days_remaining
== 0) {
788 $ddate = new \
DateTime($this->_due_date
);
789 $date_diff = $date_now->diff($ddate);
790 if ($date_diff->invert
== 0) {
791 $ret = _T("Last day!");
793 $ret = _T("Late since today!");
795 } elseif ($this->_days_remaining
< 0) {
796 $ddate = new \
DateTime($this->_due_date
);
797 $patterns = array('/%days/', '/%date/');
799 $this->_days_remaining
* -1,
800 $ddate->format(__("Y-m-d"))
802 if ($this->_active
) {
806 _T("Late of %days days (since %date)")
809 $ret = _T("No longer member");
812 $ddate = new \
DateTime($this->_due_date
);
813 $patterns = array('/%days/', '/%date/');
815 $this->_days_remaining
,
816 $ddate->format(__("Y-m-d"))
821 _T("%days days remaining (ending on %date)")
828 * Retrieve Full name and surname for the specified member id
830 * @param Db $zdb Database instance
831 * @param integer $id Member id
832 * @param boolean $wid Add member id
833 * @param boolean $wnick Add member nickname
835 * @return string formatted Name and Surname
837 public static function getSName(Db
$zdb, int $id, bool $wid = false, bool $wnick = false): string
840 $select = $zdb->select(self
::TABLE
);
841 $select->where([self
::PK
=> $id]);
843 $results = $zdb->execute($select);
844 $row = $results->current();
845 return self
::getNameWithCase(
849 ($wid === true ?
$row->id_adh
: false),
850 ($wnick === true ?
$row->pseudo_adh
: false)
852 } catch (Throwable
$e) {
854 'Cannot get formatted name for member form id `' . $id . '` | ' .
863 * Get member name with correct case
865 * @param string $name Member name
866 * @param string $surname Member surname
867 * @param false|Title $title Member title to show or false
868 * @param false|integer $id Member id to display or false
869 * @param false|string $nick Member nickname to display or false
873 public static function getNameWithCase(
882 if ($title instanceof Title
) {
883 $str .= $title->tshort
. ' ';
886 $str .= mb_strtoupper($name ??
'', 'UTF-8') . ' ' .
887 ucwords(mb_strtolower($surname ??
'', 'UTF-8'), " \t\r\n\f\v-_|");
889 if ($id !== false ||
!empty($nick)) {
901 if ($id !== false ||
!empty($nick)) {
904 return strip_tags($str);
908 * Change password for a given user
910 * @param Db $zdb Database instance
911 * @param integer $id_adh Member identifier
912 * @param string $pass New password
916 public static function updatePassword(Db
$zdb, int $id_adh, string $pass): bool
919 $cpass = password_hash($pass, PASSWORD_BCRYPT
);
921 $update = $zdb->update(self
::TABLE
);
923 array('mdp_adh' => $cpass)
924 )->where([self
::PK
=> $id_adh]);
925 $zdb->execute($update);
927 'Password for `' . $id_adh . '` has been updated.',
931 } catch (Throwable
$e) {
933 'An error occurred while updating password for `' . $id_adh .
934 '` | ' . $e->getMessage(),
944 * @param string $field Field name
948 private function getFieldLabel(string $field): string
950 $label = $this->fields
[$field]['label'];
952 $label = str_replace(' ', ' ', $label);
953 //remove trailing ':' and then trim
954 $label = trim(trim($label ??
'', ':'));
959 * Retrieve fields from database
961 * @param Db $zdb Database instance
965 public static function getDbFields(Db
$zdb): array
967 $columns = $zdb->getColumns(self
::TABLE
);
969 foreach ($columns as $col) {
970 $fields[] = $col->getName();
976 * Mark as self membership
980 public function setSelfMembership(): void
982 $this->_self_adh
= true;
986 * Is member up to date?
990 public function isUp2Date(): bool
992 if (!$this->isDepEnabled('dues')) {
996 if ($this->isDueFree()) {
997 //member is due free, he's up to date.
1000 //let's check from end date, if present
1001 if ($this->_due_date
== null) {
1004 $ech = new \
DateTime($this->_due_date
);
1005 $now = new \
DateTime();
1006 $now->setTime(0, 0, 0);
1007 return $ech >= $now;
1015 * @param Preferences $preferences Preferences instance
1016 * @param array $fields Members fields configuration
1017 * @param History $history History instance
1021 public function setDependencies(
1022 Preferences
$preferences,
1026 $this->preferences
= $preferences;
1027 $this->fields
= $fields;
1028 $this->history
= $history;
1032 * Check posted values validity
1034 * @param array $values All values to check, basically the $_POST array
1035 * after sending the form
1036 * @param array $required Array of required fields
1037 * @param array $disabled Array of disabled fields
1039 * @return true|array
1041 public function check(array $values, array $required, array $disabled)
1043 $this->errors
= array();
1046 foreach ($values as &$rawvalue) {
1047 if (is_string($rawvalue)) {
1048 $rawvalue = strip_tags($rawvalue);
1052 $fields = self
::getDbFields($this->zdb
);
1054 //reset company name if needed
1055 if (!isset($values['is_company'])) {
1056 unset($values['is_company']);
1057 $values['societe_adh'] = '';
1060 //no parent if checkbox was unchecked
1062 !isset($values['attach'])
1063 && empty($this->_id
)
1064 && isset($values['parent_id'])
1066 unset($values['parent_id']);
1069 if (isset($values['duplicate'])) {
1070 //if we're duplicating, keep a trace (if an error occurs)
1071 $this->_duplicate
= true;
1074 foreach ($fields as $key) {
1075 //first, let's sanitize values
1076 $key = strtolower($key);
1077 $prop = '_' . $this->fields
[$key]['propname'];
1079 if (isset($values[$key])) {
1080 $value = $values[$key];
1081 if ($value !== true && $value !== false) {
1082 $value = trim($value ??
'');
1084 } elseif (empty($this->_id
)) {
1086 case 'bool_admin_adh':
1087 case 'bool_exempt_adh':
1088 case 'bool_display_info':
1091 case 'activite_adh':
1092 //values that are set at object instantiation
1095 case 'date_crea_adh':
1101 //values that are set at object instantiation
1102 $value = $this->$prop;
1112 //keep stored value on update
1113 if ($prop != '_password' ||
isset($values['mdp_adh']) && isset($values['mdp_adh2'])) {
1114 $value = $this->$prop;
1120 // if the field is enabled, check it
1121 if (!isset($disabled[$key])) {
1122 // fill up the adherent structure
1123 if ($value !== null && $value !== true && $value !== false && !is_object($value)) {
1124 $value = stripslashes($value);
1126 $this->$prop = $value;
1128 // now, check validity
1129 if ($value !== null && $value != '') {
1130 if ($key !== 'mdp_adh') {
1131 $this->validate($key, $value, $values);
1133 } elseif (empty($this->_id
)) {
1134 //ensure login and password are not empty
1135 if (($key == 'login_adh' ||
$key == 'mdp_adh') && !isset($required[$key])) {
1136 $p = new Password($this->zdb
);
1137 $generated_value = $p->makeRandomPassword(15);
1138 if ($key == 'login_adh') {
1139 //'@' is not permitted in logins
1140 $this->$prop = str_replace('@', 'a', $generated_value);
1142 $this->$prop = $generated_value;
1149 //password checks need data to be previously set
1150 if (isset($values['mdp_adh'])) {
1151 $this->validate('mdp_adh', $values['mdp_adh'], $values);
1154 // missing required fields?
1155 foreach ($required as $key => $val) {
1156 $prop = '_' . $this->fields
[$key]['propname'];
1158 if (!isset($disabled[$key])) {
1159 $mandatory_missing = false;
1160 if (!isset($this->$prop) ||
$this->$prop == '') {
1161 $mandatory_missing = true;
1162 } elseif ($key === 'titre_adh' && $this->$prop == '-1') {
1163 $mandatory_missing = true;
1166 if ($mandatory_missing === true) {
1167 $this->errors
[] = str_replace(
1169 '<a href="#' . $key . '">' . $this->getFieldLabel($key) . '</a>',
1170 _T("- Mandatory field %field empty.")
1176 //attach to/detach from parent
1177 if (isset($values['detach_parent'])) {
1178 $this->_parent
= null;
1181 $this->dynamicsCheck($values, $required, $disabled);
1182 $this->checkSocials($values);
1184 if (count($this->errors
) > 0) {
1186 'Some errors has been thew attempting to edit/store a member' . "\n" .
1187 print_r($this->errors
, true),
1190 return $this->errors
;
1195 'Member checked successfully.',
1203 * Validate data for given key
1204 * Set valid data in current object, also resets errors list
1206 * @param string $field Field name
1207 * @param mixed $value Value we want to set
1208 * @param array $values All values, for some references
1212 public function validate(string $field, $value, array $values): void
1214 global $preferences;
1216 $prop = '_' . $this->fields
[$field]['propname'];
1218 if ($value === null ||
(is_string($value) && trim($value) == '')) {
1219 //empty values are OK
1220 $this->$prop = $value;
1226 case 'date_crea_adh':
1227 case 'date_modif_adh_':
1229 case 'date_echeance':
1231 $d = \DateTime
::createFromFormat(__("Y-m-d"), $value);
1233 //try with non localized date
1234 $d = \DateTime
::createFromFormat("Y-m-d", $value);
1236 throw new \
Exception('Incorrect format');
1240 if ($field === 'ddn_adh') {
1241 $now = new \
DateTime();
1242 $now->setTime(0, 0, 0);
1243 $d->setTime(0, 0, 0);
1245 $diff = $now->diff($d);
1246 $days = (int)$diff->format('%R%a');
1248 $this->errors
[] = _T('- Birthdate must be set in the past!');
1251 $years = (int)$diff->format('%R%Y');
1252 if ($years <= -200) {
1253 $this->errors
[] = str_replace(
1256 _T('- Members must be less than 200 years old (currently %years)!')
1260 $this->$prop = $d->format('Y-m-d');
1261 } catch (Throwable
$e) {
1263 'Wrong date format. field: ' . $field .
1264 ', value: ' . $value . ', expected fmt: ' .
1265 __("Y-m-d") . ' | ' . $e->getMessage(),
1268 $this->errors
[] = str_replace(
1275 $this->getFieldLabel($field)
1277 _T("- Wrong date format (%date_format) for %field!")
1282 if ($value !== null && $value !== '') {
1283 if ($value == '-1') {
1284 $this->$prop = null;
1285 } elseif (!$value instanceof Title
) {
1286 $this->$prop = new Title((int)$value);
1289 $this->$prop = null;
1293 if (!GaletteMail
::isValidEmail($value)) {
1294 $this->errors
[] = _T("- Non-valid E-Mail address!") .
1295 ' (' . $this->getFieldLabel($field) . ')';
1297 if ($field == 'email_adh') {
1299 $select = $this->zdb
->select(self
::TABLE
);
1302 )->where(array('email_adh' => $value));
1303 if (!empty($this->_id
)) {
1304 $select->where
->notEqualTo(
1310 $results = $this->zdb
->execute($select);
1311 if ($results->count() !== 0) {
1312 $this->errors
[] = _T("- This E-Mail address is already used by another member!");
1314 } catch (Throwable
$e) {
1316 'An error occurred checking member email unicity.',
1319 $this->errors
[] = _T("An error has occurred while looking if login already exists.");
1324 /** FIXME: add a preference for login length */
1325 if (strlen($value) < 2) {
1326 $this->errors
[] = str_replace(
1329 _T("- The username must be composed of at least %i characters!")
1332 //check if login does not contain the @ character
1333 if (strpos($value, '@') != false) {
1334 $this->errors
[] = _T("- The username cannot contain the @ character");
1336 //check if login is already taken
1338 $select = $this->zdb
->select(self
::TABLE
);
1341 )->where(array('login_adh' => $value));
1342 if (!empty($this->_id
)) {
1343 $select->where
->notEqualTo(
1349 $results = $this->zdb
->execute($select);
1351 $results->count() !== 0
1352 ||
$value == $preferences->pref_admin_login
1354 $this->errors
[] = _T("- This username is already in use, please choose another one!");
1356 } catch (Throwable
$e) {
1358 'An error occurred checking member login uniqueness.',
1361 $this->errors
[] = _T("An error has occurred while looking if login already exists.");
1368 $this->_self_adh
!== true
1369 && (!isset($values['mdp_adh2'])
1370 ||
$values['mdp_adh2'] != $value)
1372 $this->errors
[] = _T("- The passwords don't match!");
1374 $this->_self_adh
=== true
1375 && !crypt($value, $values['mdp_crypt']) == $values['mdp_crypt']
1377 $this->errors
[] = _T("Password misrepeated: ");
1379 $pinfos = password_get_info($value);
1380 //check if value is already a hash
1381 if ($pinfos['algo'] == 0) {
1382 $this->$prop = password_hash(
1387 $pwcheck = new \Galette\Util\
Password($preferences);
1388 $pwcheck->setAdherent($this);
1389 if (!$pwcheck->isValid($value)) {
1390 $this->errors
= array_merge(
1392 $pwcheck->getErrors()
1400 $this->$prop = (int)$value;
1401 //check if status exists
1402 $select = $this->zdb
->select(Status
::TABLE
);
1403 $select->where([Status
::PK
=> $value]);
1405 $results = $this->zdb
->execute($select);
1406 $result = $results->current();
1408 $this->errors
[] = str_replace(
1411 _T("Status #%id does not exists in database.")
1415 } catch (Throwable
$e) {
1417 'An error occurred checking status existence: ' . $e->getMessage(),
1420 $this->errors
[] = _T("An error has occurred while looking if status does exists.");
1424 if (in_array($value, [self
::NC
, self
::MAN
, self
::WOMAN
])) {
1425 $this->$prop = (int)$value;
1427 $this->errors
[] = _T("Gender %gender does not exists!");
1431 $this->$prop = ($value instanceof Adherent
) ?
(int)$value->id
: (int)$value;
1432 $this->loadParent();
1442 public function store(): bool
1444 global $hist, $emitter, $login;
1447 if (!$login->isAdmin() && !$login->isStaff() && !$login->isGroupManager() && $this->id
== '') {
1448 if ($this->preferences
->pref_bool_create_member
) {
1449 $this->_parent
= $login->id
;
1455 $fields = self
::getDbFields($this->zdb
);
1457 foreach ($fields as $field) {
1459 $field !== 'date_modif_adh'
1460 ||
empty($this->_id
)
1462 $prop = '_' . $this->fields
[$field]['propname'];
1464 ($field === 'bool_admin_adh'
1465 ||
$field === 'bool_exempt_adh'
1466 ||
$field === 'bool_display_info'
1467 ||
$field === 'activite_adh')
1468 && $this->$prop === false
1470 //Handle booleans for postgres ; bugs #18899 and #19354
1471 $values[$field] = $this->zdb
->isPostgres() ?
'false' : 0;
1472 } elseif ($field === 'parent_id') {
1474 if ($this->_parent
=== null) {
1475 $values['parent_id'] = new Expression('NULL');
1476 } elseif ($this->parent
instanceof Adherent
) {
1477 $values['parent_id'] = $this->_parent
->id
;
1479 $values['parent_id'] = $this->_parent
;
1482 $values[$field] = $this->$prop;
1487 //an empty value will cause date to be set to 1901-01-01, a null
1488 //will result in 0000-00-00. We want a database NULL value here.
1489 if (!$this->_birthdate
) {
1490 $values['ddn_adh'] = new Expression('NULL');
1492 if (!$this->_due_date
) {
1493 $values['date_echeance'] = new Expression('NULL');
1496 if ($this->_title
instanceof Title
) {
1497 $values['titre_adh'] = $this->_title
->id
;
1499 $values['titre_adh'] = new Expression('NULL');
1502 if (!$this->_parent
) {
1503 $values['parent_id'] = new Expression('NULL');
1506 if (!$this->_number
) {
1507 $values['num_adh'] = new Expression('NULL');
1510 //fields that cannot be null
1512 '_surname' => 'prenom_adh',
1513 '_nickname' => 'pseudo_adh',
1514 '_address' => 'adresse_adh',
1515 '_zipcode' => 'cp_adh',
1516 '_town' => 'ville_adh'
1518 foreach ($notnull as $prop => $field) {
1519 if ($this->$prop === null) {
1520 $values[$field] = '';
1525 if (empty($this->_id
)) {
1526 //we're inserting a new member
1527 unset($values[self
::PK
]);
1528 //set modification date
1529 $this->_modification_date
= date('Y-m-d');
1530 $values['date_modif_adh'] = $this->_modification_date
;
1532 $insert = $this->zdb
->insert(self
::TABLE
);
1533 $insert->values($values);
1534 $add = $this->zdb
->execute($insert);
1535 if ($add->count() > 0) {
1536 $this->_id
= $this->zdb
->getLastGeneratedValue($this);
1537 $this->_picture
= new Picture($this->_id
);
1539 if ($this->_self_adh
) {
1541 _T("Self_subscription as a member: ") .
1542 $this->getNameWithCase($this->_name
, $this->_surname
),
1547 _T("Member card added"),
1553 $event = 'member.add';
1555 $hist->add(_T("Fail to add new member."));
1556 throw new \
Exception(
1557 'An error occurred inserting new member!'
1561 //we're editing an existing member
1562 if (!$this->isDueFree()) {
1564 $due_date = Contribution
::getDueDate($this->zdb
, $this->_id
);
1566 $values['date_echeance'] = $due_date;
1570 if (!$this->_password
) {
1571 unset($values['mdp_adh']);
1574 $update = $this->zdb
->update(self
::TABLE
);
1575 $update->set($values);
1576 $update->where([self
::PK
=> $this->_id
]);
1578 $edit = $this->zdb
->execute($update);
1580 //edit == 0 does not mean there were an error, but that there
1581 //were nothing to change
1582 if ($edit->count() > 0) {
1583 $this->updateModificationDate();
1585 _T("Member card updated"),
1590 $event = 'member.edit';
1595 $success = $this->dynamicsStore();
1596 $this->storeSocials($this->id
);
1599 //send event at the end of process, once all has been stored
1600 if ($event !== null) {
1601 $emitter->emit($event, $this);
1604 } catch (Throwable
$e) {
1606 'Something went wrong :\'( | ' . $e->getMessage() . "\n" .
1607 $e->getTraceAsString(),
1615 * Update member modification date
1619 private function updateModificationDate(): void
1622 $modif_date = date('Y-m-d');
1623 $update = $this->zdb
->update(self
::TABLE
);
1625 array('date_modif_adh' => $modif_date)
1626 )->where([self
::PK
=> $this->_id
]);
1628 $edit = $this->zdb
->execute($update);
1629 $this->_modification_date
= $modif_date;
1630 } catch (Throwable
$e) {
1632 'Something went wrong updating modif date :\'( | ' .
1633 $e->getMessage() . "\n" . $e->getTraceAsString(),
1641 * Global getter method
1643 * @param string $name name of the property we want to retrieve
1647 public function __get(string $name)
1650 'admin', 'staff', 'due_free', 'appears_in_list', 'active',
1651 'row_classes', 'oldness', 'duplicate', 'groups', 'managed_groups'
1653 if (!defined('GALETTE_TESTS')) {
1654 $forbidden[] = 'password'; //keep that for tests only
1658 'sadmin', 'sstaff', 'sdue_free', 'sappears_in_list', 'sactive',
1659 'stitle', 'sstatus', 'sfullname', 'sname', 'saddress',
1660 'rbirthdate', 'sgender', 'contribstatus',
1663 $socials = array('website', 'msn', 'jabber', 'icq');
1665 if (in_array($name, $forbidden)) {
1667 'Calling property "' . $name . '" directly is discouraged.',
1672 return $this->isAdmin();
1674 return $this->isStaff();
1676 return $this->isDueFree();
1677 case 'appears_in_list':
1678 return $this->appearsInMembersList();
1680 return $this->isActive();
1682 return $this->isDuplicate();
1684 return $this->getGroups();
1685 case 'managed_groups':
1686 return $this->getManagedGroups();
1688 throw new \
RuntimeException("Call to __get for '$name' is forbidden!");
1692 if (in_array($name, $virtuals)) {
1693 if (substr($name, 0, 1) !== '_') {
1694 $real = '_' . substr($name, 1);
1701 case 'sappears_in_list':
1703 return (($this->$real) ?
_T("Yes") : _T("No"));
1706 return (($this->$real) ?
_T("Active") : _T("Inactive"));
1709 if (isset($this->_title
) && $this->_title
instanceof Title
) {
1710 return $this->_title
->tshort
;
1716 $status = new Status($this->zdb
);
1717 return $status->getLabel($this->_status
);
1720 return $this->getNameWithCase(
1723 (isset($this->_title
) ?
$this->title
: false)
1727 $address = $this->_address
;
1728 if ($this->_address_continuation
!== '' && $this->_address_continuation
!== null) {
1729 $address .= "\n" . $this->_address_continuation
;
1734 return $this->getNameWithCase($this->_name
, $this->_surname
);
1737 return $this->_birthdate
;
1740 switch ($this->gender
) {
1746 return _T('Unspecified');
1749 case 'contribstatus':
1750 return $this->getDues();
1755 //for backward compatibility
1756 if (in_array($name, $socials)) {
1757 $values = Social
::getListForMember($this->_id
, $name);
1758 return $values[0] ??
null;
1761 if (substr($name, 0, 1) !== '_') {
1762 $rname = '_' . $name;
1770 if ($this->$rname !== null) {
1771 return (int)$this->$rname;
1777 case 'address_continuation':
1778 return $this->$rname ??
'';
1781 case 'creation_date':
1782 case 'modification_date':
1784 if ($this->$rname != '') {
1786 $d = new \
DateTime($this->$rname);
1787 return $d->format(__("Y-m-d"));
1788 } catch (Throwable
$e) {
1789 //oops, we've got a bad date :/
1791 'Bad date (' . $this->$rname . ') | ' .
1795 return $this->$rname;
1800 return ($this->_parent
instanceof Adherent
) ?
(int)$this->_parent
->id
: (int)$this->_parent
;
1803 if (!property_exists($this, $rname)) {
1805 "Unknown property '$rname'",
1810 return $this->$rname;
1818 * If member does not have an email address, but is attached to
1819 * another member, we'll take information from its parent.
1823 public function getEmail(): string
1825 $email = $this->_email
;
1826 if (empty($email)) {
1827 $this->loadParent();
1828 $email = $this->parent
->email
;
1835 * Get member address.
1836 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1840 public function getAddress(): string
1842 $address = $this->_address
;
1843 if (empty($address) && $this->hasParent()) {
1844 $this->loadParent();
1845 $address = $this->parent
->address
;
1852 * Get member address continuation.
1853 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1857 public function getAddressContinuation(): string
1859 $address = $this->_address
;
1860 $address_continuation = $this->_address_continuation
;
1861 if (empty($address) && $this->hasParent()) {
1862 $this->loadParent();
1863 $address_continuation = $this->parent
->address_continuation
;
1866 return $address_continuation;
1870 * Get member zipcode.
1871 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1875 public function getZipcode(): string
1877 $address = $this->_address
;
1878 $zip = $this->_zipcode
;
1879 if (empty($address) && $this->hasParent()) {
1880 $this->loadParent();
1881 $zip = $this->parent
->zipcode
;
1889 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1893 public function getTown(): string
1895 $address = $this->_address
;
1896 $town = $this->_town
;
1897 if (empty($address) && $this->hasParent()) {
1898 $this->loadParent();
1899 $town = $this->parent
->town
;
1906 * Get member country.
1907 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1911 public function getCountry(): string
1913 $address = $this->_address
;
1914 $country = $this->_country
;
1915 if (empty($address) && $this->hasParent()) {
1916 $this->loadParent();
1917 $country = $this->parent
->country
;
1928 public function getAge(): string
1930 if ($this->_birthdate
== null) {
1934 $d = \DateTime
::createFromFormat('Y-m-d', $this->_birthdate
);
1937 'Invalid birthdate: ' . $this->_birthdate
,
1945 $d->diff(new \
DateTime())->y
,
1946 _T(' (%age years old)')
1951 * Get parent inherited fields
1955 public function getParentFields(): array
1957 return $this->parent_fields
;
1961 * Handle files (photo and dynamics files)
1963 * @param array $files Files sent
1965 * @return array|true
1967 public function handleFiles(array $files)
1971 if (isset($files['photo'])) {
1972 if ($files['photo']['error'] === UPLOAD_ERR_OK
) {
1973 if ($files['photo']['tmp_name'] != '') {
1974 if (is_uploaded_file($files['photo']['tmp_name'])) {
1975 $res = $this->picture
->store($files['photo']);
1978 = $this->picture
->getErrorMessage($res);
1982 } elseif ($files['photo']['error'] !== UPLOAD_ERR_NO_FILE
) {
1984 $this->picture
->getPhpErrorMessage($files['photo']['error']),
1987 $this->errors
[] = $this->picture
->getPhpErrorMessage(
1988 $files['photo']['error']
1992 $this->dynamicsFiles($files);
1994 if (count($this->errors
) > 0) {
1996 'Some errors has been thew attempting to edit/store a member files' . "\n" .
1997 print_r($this->errors
, true),
2000 return $this->errors
;
2007 * Set member as duplicate
2011 public function setDuplicate(): void
2013 //mark as duplicated
2014 $this->_duplicate
= true;
2015 $infos = $this->_others_infos_admin
;
2016 $this->_others_infos_admin
= str_replace(
2018 [$this->sname
, $this->_id
],
2019 _T('Duplicated from %name (%id)')
2021 if (!empty($infos)) {
2022 $this->_others_infos_admin
.= "\n" . $infos;
2026 //drop email, must be unique
2027 $this->_email
= null;
2028 //drop creation date
2029 $this->_creation_date
= date("Y-m-d");
2031 $this->_login
= null;
2033 $this->_picture
= new Picture();
2035 $this->_birthdate
= null;
2037 $this->_surname
= null;
2039 $this->_admin
= false;
2041 $this->_due_free
= false;
2045 * Get current errors
2049 public function getErrors(): array
2051 return $this->errors
;
2059 public function getGroups(): array
2061 if (!$this->isDepEnabled('groups')) {
2062 $this->loadGroups();
2064 return $this->_groups
;
2068 * Get user managed groups
2072 public function getManagedGroups(): array
2074 if (!$this->isDepEnabled('groups')) {
2075 $this->loadGroups();
2077 return $this->_managed_groups
;
2081 * Can current logged-in user create member
2083 * @param Login $login Login instance
2087 public function canCreate(Login
$login): bool
2089 global $preferences;
2091 if ($this->id
&& $login->id
== $this->id ||
$login->isAdmin() ||
$login->isStaff()) {
2095 if ($preferences->pref_bool_create_member
&& $login->isLogged()) {
2103 * Can current logged-in user edit member
2105 * @param Login $login Login instance
2109 public function canEdit(Login
$login): bool
2111 //admin and staff users can edit, as well as member itself
2112 if ($this->id
&& $login->id
== $this->id ||
$login->isAdmin() ||
$login->isStaff()) {
2116 //parent can edit their child cards
2117 if ($this->hasParent() && $this->parent_id
=== $login->id
) {
2121 //group managers can edit members of groups they manage
2122 if ($login->isGroupManager()) {
2123 foreach ($this->getGroups() as $g) {
2124 if ($login->isGroupManager($g->getId())) {
2134 * Can current logged-in user display member
2136 * @param Login $login Login instance
2140 public function canShow(Login
$login): bool
2142 return $this->canEdit($login);
2146 * Are we currently duplicated a member?
2150 public function isDuplicate(): bool
2152 return $this->_duplicate
;
2156 * Flag creation mail sending
2158 * @param boolean $send True (default) to send creation email
2162 public function setSendmail(bool $send = true): self
2164 $this->sendmail
= $send;
2169 * Should we send administrative emails to member?
2173 public function sendEMail(): bool
2175 return $this->sendmail
;
2181 * @param integer $id Parent identifier
2185 public function setParent(int $id): self
2187 $this->_parent
= $id;
2188 $this->loadParent();
2193 * Reset dependencies to load
2197 public function disableAllDeps(): self
2199 foreach ($this->_deps
as &$dep) {
2206 * Enable all dependencies to load
2210 public function enableAllDeps(): self
2212 foreach ($this->_deps
as &$dep) {
2219 * Enable a load dependency
2221 * @param string $name Dependency name
2225 public function enableDep(string $name): self
2227 if (!isset($this->_deps
[$name])) {
2229 'dependency ' . $name . ' does not exists!',
2233 $this->_deps
[$name] = true;
2240 * Enable a load dependency
2242 * @param string $name Dependency name
2246 public function disableDep(string $name): self
2248 if (!isset($this->_deps
[$name])) {
2250 'dependency ' . $name . ' does not exists!',
2254 $this->_deps
[$name] = false;
2261 * Is load dependency enabled?
2263 * @param string $name Dependency name
2267 protected function isDepEnabled(string $name): bool
2269 return $this->_deps
[$name];