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 $now = new \
DateTime();
771 // To count the days remaining, the next begin date is required.
772 if ($this->_due_date
=== null) {
773 $this->_due_date
= $now->format('Y-m-d');
775 $due_date = new \
DateTime($this->_due_date
);
776 $next_begin_date = clone $due_date;
777 $next_begin_date->add(new \
DateInterval('P1D'));
778 $date_diff = $now->diff($next_begin_date);
779 if ($this->isDueFree()) {
780 $ret = _T("Freed of dues");
781 } elseif ($this->_due_date
== '') {
782 $patterns = array('/%days/', '/%date/');
783 $cdate = new \
DateTime($this->_creation_date
);
786 $cdate->format(__("Y-m-d"))
788 if ($this->_active
) {
792 _T("Never contributed: Registered %days days ago (since %date)")
795 $ret = _T("Never contributed");
797 // Last active or first expired day
798 } elseif ($this->_days_remaining
== 0) {
799 if ($date_diff->invert
== 0) {
800 $ret = _T("Last day!");
802 $ret = _T("Late since today!");
805 } elseif ($date_diff->invert
== 0 && $this->_days_remaining
> 0) {
806 $patterns = array('/%days/', '/%date/');
808 $this->_days_remaining
,
809 $due_date->format(__("Y-m-d"))
814 _T("%days days remaining (ending on %date)")
817 } elseif ($date_diff->invert
== 1 && $this->_days_remaining
> 0) {
818 $patterns = array('/%days/', '/%date/');
820 // We need the number of days expired, not the number of days remaining.
821 $this->_days_remaining +
1,
822 $due_date->format(__("Y-m-d"))
824 if ($this->_active
) {
828 _T("Late of %days days (since %date)")
831 $ret = _T("No longer member");
838 * Retrieve Full name and surname for the specified member id
840 * @param Db $zdb Database instance
841 * @param integer $id Member id
842 * @param boolean $wid Add member id
843 * @param boolean $wnick Add member nickname
845 * @return string formatted Name and Surname
847 public static function getSName(Db
$zdb, int $id, bool $wid = false, bool $wnick = false): string
850 $select = $zdb->select(self
::TABLE
);
851 $select->where([self
::PK
=> $id]);
853 $results = $zdb->execute($select);
854 $row = $results->current();
855 return self
::getNameWithCase(
859 ($wid === true ?
$row->id_adh
: false),
860 ($wnick === true ?
$row->pseudo_adh
: false)
862 } catch (Throwable
$e) {
864 'Cannot get formatted name for member form id `' . $id . '` | ' .
873 * Get member name with correct case
875 * @param string $name Member name
876 * @param string $surname Member surname
877 * @param false|Title $title Member title to show or false
878 * @param false|integer $id Member id to display or false
879 * @param false|string $nick Member nickname to display or false
883 public static function getNameWithCase(
892 if ($title instanceof Title
) {
893 $str .= $title->tshort
. ' ';
896 $str .= mb_strtoupper($name ??
'', 'UTF-8') . ' ' .
897 ucwords(mb_strtolower($surname ??
'', 'UTF-8'), " \t\r\n\f\v-_|");
899 if ($id !== false ||
!empty($nick)) {
911 if ($id !== false ||
!empty($nick)) {
914 return strip_tags($str);
918 * Change password for a given user
920 * @param Db $zdb Database instance
921 * @param integer $id_adh Member identifier
922 * @param string $pass New password
926 public static function updatePassword(Db
$zdb, int $id_adh, string $pass): bool
929 $cpass = password_hash($pass, PASSWORD_BCRYPT
);
931 $update = $zdb->update(self
::TABLE
);
933 array('mdp_adh' => $cpass)
934 )->where([self
::PK
=> $id_adh]);
935 $zdb->execute($update);
937 'Password for `' . $id_adh . '` has been updated.',
941 } catch (Throwable
$e) {
943 'An error occurred while updating password for `' . $id_adh .
944 '` | ' . $e->getMessage(),
954 * @param string $field Field name
958 private function getFieldLabel(string $field): string
960 $label = $this->fields
[$field]['label'];
962 $label = str_replace(' ', ' ', $label);
963 //remove trailing ':' and then trim
964 $label = trim(trim($label ??
'', ':'));
969 * Retrieve fields from database
971 * @param Db $zdb Database instance
975 public static function getDbFields(Db
$zdb): array
977 $columns = $zdb->getColumns(self
::TABLE
);
979 foreach ($columns as $col) {
980 $fields[] = $col->getName();
986 * Mark as self membership
990 public function setSelfMembership(): void
992 $this->_self_adh
= true;
996 * Is member up to date?
1000 public function isUp2Date(): bool
1002 if (!$this->isDepEnabled('dues')) {
1006 if ($this->isDueFree()) {
1007 //member is due free, he's up to date.
1010 //let's check from due date, if present
1011 if ($this->_due_date
== null) {
1014 $due_date = new \
DateTime($this->_due_date
);
1015 $now = new \
DateTime();
1016 $now->setTime(0, 0, 0);
1017 return $due_date >= $now;
1025 * @param Preferences $preferences Preferences instance
1026 * @param array $fields Members fields configuration
1027 * @param History $history History instance
1031 public function setDependencies(
1032 Preferences
$preferences,
1036 $this->preferences
= $preferences;
1037 $this->fields
= $fields;
1038 $this->history
= $history;
1042 * Check posted values validity
1044 * @param array $values All values to check, basically the $_POST array
1045 * after sending the form
1046 * @param array $required Array of required fields
1047 * @param array $disabled Array of disabled fields
1049 * @return true|array
1051 public function check(array $values, array $required, array $disabled)
1055 $this->errors
= array();
1058 foreach ($values as &$rawvalue) {
1059 if (is_string($rawvalue)) {
1060 $rawvalue = strip_tags($rawvalue);
1064 $fields = self
::getDbFields($this->zdb
);
1066 //reset company name if needed
1067 if (!isset($values['is_company'])) {
1068 unset($values['is_company']);
1069 $values['societe_adh'] = '';
1072 //no parent if checkbox was unchecked
1074 !isset($values['attach'])
1075 && empty($this->_id
)
1076 && isset($values['parent_id'])
1078 unset($values['parent_id']);
1081 if (isset($values['duplicate'])) {
1082 //if we're duplicating, keep a trace (if an error occurs)
1083 $this->_duplicate
= true;
1086 foreach ($fields as $key) {
1087 //first, let's sanitize values
1088 $key = strtolower($key);
1089 $prop = '_' . $this->fields
[$key]['propname'];
1091 if (isset($values[$key])) {
1092 $value = $values[$key];
1093 if ($value !== true && $value !== false) {
1094 $value = trim($value ??
'');
1096 } elseif (empty($this->_id
)) {
1098 case 'bool_admin_adh':
1099 case 'bool_exempt_adh':
1100 case 'bool_display_info':
1103 case 'activite_adh':
1104 //values that are set at object instantiation
1107 case 'date_crea_adh':
1113 //values that are set at object instantiation
1114 $value = $this->$prop;
1124 //keep stored value on update
1125 if ($prop != '_password' ||
isset($values['mdp_adh']) && isset($values['mdp_adh2'])) {
1126 $value = $this->$prop;
1132 // if the field is enabled, check it
1133 if (!isset($disabled[$key])) {
1134 // fill up the adherent structure
1135 if ($value !== null && $value !== true && $value !== false && !is_object($value)) {
1136 $value = stripslashes($value);
1138 $this->$prop = $value;
1140 // now, check validity
1141 if ($value !== null && $value != '') {
1142 if ($key !== 'mdp_adh') {
1143 $this->validate($key, $value, $values);
1145 } elseif (empty($this->_id
)) {
1146 //ensure login and password are not empty
1147 if (($key == 'login_adh' ||
$key == 'mdp_adh') && !isset($required[$key])) {
1148 $p = new Password($this->zdb
);
1149 $generated_value = $p->makeRandomPassword(15);
1150 if ($key == 'login_adh') {
1151 //'@' is not permitted in logins
1152 $this->$prop = str_replace('@', 'a', $generated_value);
1154 $this->$prop = $generated_value;
1161 //password checks need data to be previously set
1162 if (isset($values['mdp_adh'])) {
1163 $this->validate('mdp_adh', $values['mdp_adh'], $values);
1166 // missing required fields?
1167 foreach ($required as $key => $val) {
1168 $prop = '_' . $this->fields
[$key]['propname'];
1170 if (!isset($disabled[$key])) {
1171 $mandatory_missing = false;
1172 if (!isset($this->$prop) ||
$this->$prop == '') {
1173 $mandatory_missing = true;
1174 } elseif ($key === 'titre_adh' && $this->$prop == '-1') {
1175 $mandatory_missing = true;
1178 if ($mandatory_missing === true) {
1179 $this->errors
[] = str_replace(
1181 '<a href="#' . $key . '">' . $this->getFieldLabel($key) . '</a>',
1182 _T("- Mandatory field %field empty.")
1188 //attach to/detach from parent
1189 if (isset($values['detach_parent'])) {
1190 $this->_parent
= null;
1193 if ($login->isGroupManager() && !$login->isAdmin() && !$login->isStaff()) {
1194 if (!isset($values['groups_adh'])) {
1195 $this->errors
[] = _T('You have to select a group you own!');
1197 foreach ($values['groups_adh'] as $group) {
1198 list($gid) = explode('|', $group);
1199 if (!$login->isGroupManager($gid)) {
1200 $this->errors
[] = _T('You have to select a group you own!');
1206 $this->dynamicsCheck($values, $required, $disabled);
1207 $this->checkSocials($values);
1209 if (count($this->errors
) > 0) {
1211 'Some errors has been thew attempting to edit/store a member' . "\n" .
1212 print_r($this->errors
, true),
1215 return $this->errors
;
1220 'Member checked successfully.',
1228 * Validate data for given key
1229 * Set valid data in current object, also resets errors list
1231 * @param string $field Field name
1232 * @param mixed $value Value we want to set
1233 * @param array $values All values, for some references
1237 public function validate(string $field, $value, array $values): void
1239 global $preferences;
1241 $prop = '_' . $this->fields
[$field]['propname'];
1243 if ($value === null ||
(is_string($value) && trim($value) == '')) {
1244 //empty values are OK
1245 $this->$prop = $value;
1251 case 'date_crea_adh':
1252 case 'date_modif_adh_':
1254 case 'date_echeance':
1256 $d = \DateTime
::createFromFormat(__("Y-m-d"), $value);
1258 //try with non localized date
1259 $d = \DateTime
::createFromFormat("Y-m-d", $value);
1261 throw new \
Exception('Incorrect format');
1265 if ($field === 'ddn_adh') {
1266 $now = new \
DateTime();
1267 $now->setTime(0, 0, 0);
1268 $d->setTime(0, 0, 0);
1270 $diff = $now->diff($d);
1271 $days = (int)$diff->format('%R%a');
1273 $this->errors
[] = _T('- Birthdate must be set in the past!');
1276 $years = (int)$diff->format('%R%Y');
1277 if ($years <= -200) {
1278 $this->errors
[] = str_replace(
1281 _T('- Members must be less than 200 years old (currently %years)!')
1285 $this->$prop = $d->format('Y-m-d');
1286 } catch (Throwable
$e) {
1288 'Wrong date format. field: ' . $field .
1289 ', value: ' . $value . ', expected fmt: ' .
1290 __("Y-m-d") . ' | ' . $e->getMessage(),
1293 $this->errors
[] = str_replace(
1300 $this->getFieldLabel($field)
1302 _T("- Wrong date format (%date_format) for %field!")
1307 if ($value !== null && $value !== '') {
1308 if ($value == '-1') {
1309 $this->$prop = null;
1310 } elseif (!$value instanceof Title
) {
1311 $this->$prop = new Title((int)$value);
1314 $this->$prop = null;
1318 if (!GaletteMail
::isValidEmail($value)) {
1319 $this->errors
[] = _T("- Non-valid E-Mail address!") .
1320 ' (' . $this->getFieldLabel($field) . ')';
1322 if ($field == 'email_adh') {
1324 $select = $this->zdb
->select(self
::TABLE
);
1327 )->where(array('email_adh' => $value));
1328 if (!empty($this->_id
)) {
1329 $select->where
->notEqualTo(
1335 $results = $this->zdb
->execute($select);
1336 if ($results->count() !== 0) {
1337 $this->errors
[] = _T("- This E-Mail address is already used by another member!");
1339 } catch (Throwable
$e) {
1341 'An error occurred checking member email uniqueness.',
1344 $this->errors
[] = _T("An error has occurred while looking if login already exists.");
1349 /** FIXME: add a preference for login length */
1350 if (strlen($value) < 2) {
1351 $this->errors
[] = str_replace(
1354 _T("- The username must be composed of at least %i characters!")
1357 //check if login does not contain the @ character
1358 if (strpos($value, '@') != false) {
1359 $this->errors
[] = _T("- The username cannot contain the @ character");
1361 //check if login is already taken
1363 $select = $this->zdb
->select(self
::TABLE
);
1366 )->where(array('login_adh' => $value));
1367 if (!empty($this->_id
)) {
1368 $select->where
->notEqualTo(
1374 $results = $this->zdb
->execute($select);
1376 $results->count() !== 0
1377 ||
$value == $preferences->pref_admin_login
1379 $this->errors
[] = _T("- This username is already in use, please choose another one!");
1381 } catch (Throwable
$e) {
1383 'An error occurred checking member login uniqueness.',
1386 $this->errors
[] = _T("An error has occurred while looking if login already exists.");
1393 $this->_self_adh
!== true
1394 && (!isset($values['mdp_adh2'])
1395 ||
$values['mdp_adh2'] != $value)
1397 $this->errors
[] = _T("- The passwords don't match!");
1399 $this->_self_adh
=== true
1400 && !crypt($value, $values['mdp_crypt']) == $values['mdp_crypt']
1402 $this->errors
[] = _T("Password misrepeated: ");
1404 $pinfos = password_get_info($value);
1405 //check if value is already a hash
1406 if ($pinfos['algo'] == 0) {
1407 $this->$prop = password_hash(
1412 $pwcheck = new \Galette\Util\
Password($preferences);
1413 $pwcheck->setAdherent($this);
1414 if (!$pwcheck->isValid($value)) {
1415 $this->errors
= array_merge(
1417 $pwcheck->getErrors()
1425 $this->$prop = (int)$value;
1426 //check if status exists
1427 $select = $this->zdb
->select(Status
::TABLE
);
1428 $select->where([Status
::PK
=> $value]);
1430 $results = $this->zdb
->execute($select);
1431 $result = $results->current();
1433 $this->errors
[] = str_replace(
1436 _T("Status #%id does not exists in database.")
1440 } catch (Throwable
$e) {
1442 'An error occurred checking status existence: ' . $e->getMessage(),
1445 $this->errors
[] = _T("An error has occurred while looking if status does exists.");
1449 if (in_array($value, [self
::NC
, self
::MAN
, self
::WOMAN
])) {
1450 $this->$prop = (int)$value;
1452 $this->errors
[] = _T("Gender %gender does not exists!");
1456 $this->$prop = ($value instanceof Adherent
) ?
(int)$value->id
: (int)$value;
1457 $this->loadParent();
1467 public function store(): bool
1469 global $hist, $emitter, $login;
1472 if (!$login->isAdmin() && !$login->isStaff() && !$login->isGroupManager() && $this->id
== '') {
1473 if ($this->preferences
->pref_bool_create_member
) {
1474 $this->_parent
= $login->id
;
1480 $fields = self
::getDbFields($this->zdb
);
1482 foreach ($fields as $field) {
1484 $field !== 'date_modif_adh'
1485 ||
empty($this->_id
)
1487 $prop = '_' . $this->fields
[$field]['propname'];
1489 ($field === 'bool_admin_adh'
1490 ||
$field === 'bool_exempt_adh'
1491 ||
$field === 'bool_display_info'
1492 ||
$field === 'activite_adh')
1493 && $this->$prop === false
1495 //Handle booleans for postgres ; bugs #18899 and #19354
1496 $values[$field] = $this->zdb
->isPostgres() ?
'false' : 0;
1497 } elseif ($field === 'parent_id') {
1499 if ($this->_parent
=== null) {
1500 $values['parent_id'] = new Expression('NULL');
1501 } elseif ($this->parent
instanceof Adherent
) {
1502 $values['parent_id'] = $this->_parent
->id
;
1504 $values['parent_id'] = $this->_parent
;
1507 $values[$field] = $this->$prop;
1512 //an empty value will cause date to be set to 1901-01-01, a null
1513 //will result in 0000-00-00. We want a database NULL value here.
1514 if (!$this->_birthdate
) {
1515 $values['ddn_adh'] = new Expression('NULL');
1517 if (!$this->_due_date
) {
1518 $values['date_echeance'] = new Expression('NULL');
1521 if ($this->_title
instanceof Title
) {
1522 $values['titre_adh'] = $this->_title
->id
;
1524 $values['titre_adh'] = new Expression('NULL');
1527 if (!$this->_parent
) {
1528 $values['parent_id'] = new Expression('NULL');
1531 if (!$this->_number
) {
1532 $values['num_adh'] = new Expression('NULL');
1535 //fields that cannot be null
1537 '_surname' => 'prenom_adh',
1538 '_nickname' => 'pseudo_adh',
1539 '_address' => 'adresse_adh',
1540 '_zipcode' => 'cp_adh',
1541 '_town' => 'ville_adh'
1543 foreach ($notnull as $prop => $field) {
1544 if ($this->$prop === null) {
1545 $values[$field] = '';
1550 if (empty($this->_id
)) {
1551 //we're inserting a new member
1552 unset($values[self
::PK
]);
1553 //set modification date
1554 $this->_modification_date
= date('Y-m-d');
1555 $values['date_modif_adh'] = $this->_modification_date
;
1557 $insert = $this->zdb
->insert(self
::TABLE
);
1558 $insert->values($values);
1559 $add = $this->zdb
->execute($insert);
1560 if ($add->count() > 0) {
1561 $this->_id
= $this->zdb
->getLastGeneratedValue($this);
1562 $this->_picture
= new Picture($this->_id
);
1564 if ($this->_self_adh
) {
1566 _T("Self_subscription as a member: ") .
1567 $this->getNameWithCase($this->_name
, $this->_surname
),
1572 _T("Member card added"),
1578 $event = 'member.add';
1580 $hist->add(_T("Fail to add new member."));
1581 throw new \
Exception(
1582 'An error occurred inserting new member!'
1586 //we're editing an existing member
1587 if (!$this->isDueFree()) {
1589 $due_date = Contribution
::getDueDate($this->zdb
, $this->_id
);
1591 $values['date_echeance'] = $due_date;
1595 if (!$this->_password
) {
1596 unset($values['mdp_adh']);
1599 $update = $this->zdb
->update(self
::TABLE
);
1600 $update->set($values);
1601 $update->where([self
::PK
=> $this->_id
]);
1603 $edit = $this->zdb
->execute($update);
1605 //edit == 0 does not mean there were an error, but that there
1606 //were nothing to change
1607 if ($edit->count() > 0) {
1608 $this->updateModificationDate();
1610 _T("Member card updated"),
1615 $event = 'member.edit';
1620 $success = $this->dynamicsStore();
1621 $this->storeSocials($this->id
);
1624 //send event at the end of process, once all has been stored
1625 if ($event !== null) {
1626 $emitter->emit($event, $this);
1629 } catch (Throwable
$e) {
1631 'Something went wrong :\'( | ' . $e->getMessage() . "\n" .
1632 $e->getTraceAsString(),
1640 * Update member modification date
1644 private function updateModificationDate(): void
1647 $modif_date = date('Y-m-d');
1648 $update = $this->zdb
->update(self
::TABLE
);
1650 array('date_modif_adh' => $modif_date)
1651 )->where([self
::PK
=> $this->_id
]);
1653 $edit = $this->zdb
->execute($update);
1654 $this->_modification_date
= $modif_date;
1655 } catch (Throwable
$e) {
1657 'Something went wrong updating modif date :\'( | ' .
1658 $e->getMessage() . "\n" . $e->getTraceAsString(),
1666 * Global getter method
1668 * @param string $name name of the property we want to retrieve
1672 public function __get(string $name)
1675 'admin', 'staff', 'due_free', 'appears_in_list', 'active',
1676 'row_classes', 'oldness', 'duplicate', 'groups', 'managed_groups'
1678 if (!defined('GALETTE_TESTS')) {
1679 $forbidden[] = 'password'; //keep that for tests only
1683 'sadmin', 'sstaff', 'sdue_free', 'sappears_in_list', 'sactive',
1684 'stitle', 'sstatus', 'sfullname', 'sname', 'saddress',
1685 'rbirthdate', 'sgender', 'contribstatus',
1688 $socials = array('website', 'msn', 'jabber', 'icq');
1690 if (in_array($name, $forbidden)) {
1692 'Calling property "' . $name . '" directly is discouraged.',
1697 return $this->isAdmin();
1699 return $this->isStaff();
1701 return $this->isDueFree();
1702 case 'appears_in_list':
1703 return $this->appearsInMembersList();
1705 return $this->isActive();
1707 return $this->isDuplicate();
1709 return $this->getGroups();
1710 case 'managed_groups':
1711 return $this->getManagedGroups();
1713 throw new \
RuntimeException("Call to __get for '$name' is forbidden!");
1717 if (in_array($name, $virtuals)) {
1718 if (substr($name, 0, 1) !== '_') {
1719 $real = '_' . substr($name, 1);
1726 case 'sappears_in_list':
1728 return (($this->$real) ?
_T("Yes") : _T("No"));
1731 return (($this->$real) ?
_T("Active") : _T("Inactive"));
1734 if (isset($this->_title
) && $this->_title
instanceof Title
) {
1735 return $this->_title
->tshort
;
1741 $status = new Status($this->zdb
);
1742 return $status->getLabel($this->_status
);
1744 return $this->getNameWithCase(
1747 (isset($this->_title
) ?
$this->title
: false)
1750 $address = $this->_address
;
1753 return $this->getNameWithCase($this->_name
, $this->_surname
);
1755 return $this->_birthdate
;
1757 switch ($this->gender
) {
1763 return _T('Unspecified');
1765 case 'contribstatus':
1766 return $this->getDues();
1770 //for backward compatibility
1771 if (in_array($name, $socials)) {
1772 $values = Social
::getListForMember($this->_id
, $name);
1773 return $values[0] ??
null;
1776 if (substr($name, 0, 1) !== '_') {
1777 $rname = '_' . $name;
1785 if ($this->$rname !== null) {
1786 return (int)$this->$rname;
1791 return $this->$rname ??
'';
1793 case 'creation_date':
1794 case 'modification_date':
1796 if ($this->$rname != '') {
1798 $d = new \
DateTime($this->$rname);
1799 return $d->format(__("Y-m-d"));
1800 } catch (Throwable
$e) {
1801 //oops, we've got a bad date :/
1803 'Bad date (' . $this->$rname . ') | ' .
1807 return $this->$rname;
1812 return ($this->_parent
instanceof Adherent
) ?
(int)$this->_parent
->id
: (int)$this->_parent
;
1814 if (!property_exists($this, $rname)) {
1816 "Unknown property '$rname'",
1821 return $this->$rname;
1828 * If member does not have an email address, but is attached to
1829 * another member, we'll take information from its parent.
1833 public function getEmail(): string
1835 $email = $this->_email
;
1836 if (empty($email)) {
1837 $this->loadParent();
1838 $email = $this->parent
->email
;
1841 return $email ??
'';
1845 * Get member address.
1846 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1850 public function getAddress(): string
1852 $address = $this->_address
;
1853 if (empty($address) && $this->hasParent()) {
1854 $this->loadParent();
1855 $address = $this->parent
->address
;
1858 return $address ??
'';
1862 * Get member zipcode.
1863 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1867 public function getZipcode(): string
1869 $address = $this->_address
;
1870 $zip = $this->_zipcode
;
1871 if (empty($address) && $this->hasParent()) {
1872 $this->loadParent();
1873 $zip = $this->parent
->zipcode
;
1881 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1885 public function getTown(): string
1887 $address = $this->_address
;
1888 $town = $this->_town
;
1889 if (empty($address) && $this->hasParent()) {
1890 $this->loadParent();
1891 $town = $this->parent
->town
;
1898 * Get member country.
1899 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1903 public function getCountry(): string
1905 $address = $this->_address
;
1906 $country = $this->_country
;
1907 if (empty($address) && $this->hasParent()) {
1908 $this->loadParent();
1909 $country = $this->parent
->country
;
1912 return $country ??
'';
1920 public function getAge(): string
1922 if ($this->_birthdate
== null) {
1926 $d = \DateTime
::createFromFormat('Y-m-d', $this->_birthdate
);
1929 'Invalid birthdate: ' . $this->_birthdate
,
1937 $d->diff(new \
DateTime())->y
,
1938 _T(' (%age years old)')
1943 * Get parent inherited fields
1947 public function getParentFields(): array
1949 return $this->parent_fields
;
1953 * Handle files (photo and dynamics files)
1955 * @param array $files Files sent
1957 * @return array|true
1959 public function handleFiles(array $files)
1963 if (isset($files['photo'])) {
1964 if ($files['photo']['error'] === UPLOAD_ERR_OK
) {
1965 if ($files['photo']['tmp_name'] != '') {
1966 if (is_uploaded_file($files['photo']['tmp_name'])) {
1967 $res = $this->picture
->store($files['photo']);
1970 = $this->picture
->getErrorMessage($res);
1974 } elseif ($files['photo']['error'] !== UPLOAD_ERR_NO_FILE
) {
1976 $this->picture
->getPhpErrorMessage($files['photo']['error']),
1979 $this->errors
[] = $this->picture
->getPhpErrorMessage(
1980 $files['photo']['error']
1984 $this->dynamicsFiles($files);
1986 if (count($this->errors
) > 0) {
1988 'Some errors has been thew attempting to edit/store a member files' . "\n" .
1989 print_r($this->errors
, true),
1992 return $this->errors
;
1999 * Set member as duplicate
2003 public function setDuplicate(): void
2005 //mark as duplicated
2006 $this->_duplicate
= true;
2007 $infos = $this->_others_infos_admin
;
2008 $this->_others_infos_admin
= str_replace(
2010 [$this->sname
, $this->_id
],
2011 _T('Duplicated from %name (%id)')
2013 if (!empty($infos)) {
2014 $this->_others_infos_admin
.= "\n" . $infos;
2018 //drop email, must be unique
2019 $this->_email
= null;
2020 //drop creation date
2021 $this->_creation_date
= date("Y-m-d");
2023 $this->_login
= null;
2025 $this->_picture
= new Picture();
2027 $this->_birthdate
= null;
2029 $this->_surname
= null;
2031 $this->_admin
= false;
2033 $this->_due_free
= false;
2037 * Get current errors
2041 public function getErrors(): array
2043 return $this->errors
;
2051 public function getGroups(): array
2053 if (!$this->isDepEnabled('groups')) {
2054 $this->loadGroups();
2056 return $this->_groups
;
2060 * Get user managed groups
2064 public function getManagedGroups(): array
2066 if (!$this->isDepEnabled('groups')) {
2067 $this->loadGroups();
2069 return $this->_managed_groups
;
2073 * Can current logged-in user create member
2075 * @param Login $login Login instance
2079 public function canCreate(Login
$login): bool
2081 global $preferences;
2083 if ($this->id
&& $login->id
== $this->id ||
$login->isAdmin() ||
$login->isStaff()) {
2087 if ($preferences->pref_bool_groupsmanagers_create_member
&& $login->isGroupManager()) {
2091 if ($preferences->pref_bool_create_member
&& $login->isLogged()) {
2099 * Can current logged-in user edit member
2101 * @param Login $login Login instance
2105 public function canEdit(Login
$login): bool
2107 global $preferences;
2109 //admin and staff users can edit, as well as member itself
2110 if ($this->id
&& $login->id
== $this->id ||
$login->isAdmin() ||
$login->isStaff()) {
2114 //parent can edit their child cards
2115 if ($this->hasParent() && $this->parent_id
=== $login->id
) {
2119 //group managers can edit members of groups they manage when pref is on
2120 if ($preferences->pref_bool_groupsmanagers_edit_member
&& $login->isGroupManager()) {
2121 foreach ($this->getGroups() as $g) {
2122 if ($login->isGroupManager($g->getId())) {
2132 * Can current logged-in user display member
2134 * @param Login $login Login instance
2138 public function canShow(Login
$login): bool
2140 //group managers can show members of groups they manage
2141 if ($login->isGroupManager()) {
2142 foreach ($this->getGroups() as $g) {
2143 if ($login->isGroupManager($g->getId())) {
2149 return $this->canEdit($login);
2153 * Are we currently duplicated a member?
2157 public function isDuplicate(): bool
2159 return $this->_duplicate
;
2163 * Flag creation mail sending
2165 * @param boolean $send True (default) to send creation email
2169 public function setSendmail(bool $send = true): self
2171 $this->sendmail
= $send;
2176 * Should we send administrative emails to member?
2180 public function sendEMail(): bool
2182 return $this->sendmail
;
2188 * @param integer $id Parent identifier
2192 public function setParent(int $id): self
2194 $this->_parent
= $id;
2195 $this->loadParent();
2200 * Reset dependencies to load
2204 public function disableAllDeps(): self
2206 foreach ($this->_deps
as &$dep) {
2213 * Enable all dependencies to load
2217 public function enableAllDeps(): self
2219 foreach ($this->_deps
as &$dep) {
2226 * Enable a load dependency
2228 * @param string $name Dependency name
2232 public function enableDep(string $name): self
2234 if (!isset($this->_deps
[$name])) {
2236 'dependency ' . $name . ' does not exists!',
2240 $this->_deps
[$name] = true;
2247 * Enable a load dependency
2249 * @param string $name Dependency name
2253 public function disableDep(string $name): self
2255 if (!isset($this->_deps
[$name])) {
2257 'dependency ' . $name . ' does not exists!',
2261 $this->_deps
[$name] = false;
2268 * Is load dependency enabled?
2270 * @param string $name Dependency name
2274 protected function isDepEnabled(string $name): bool
2276 return $this->_deps
[$name];