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
;
41 use Laminas\Db\Sql\Expression
;
43 use Galette\Core\Picture
;
44 use Galette\Core\GaletteMail
;
45 use Galette\Core\Password
;
46 use Galette\Core\Preferences
;
47 use Galette\Core\History
;
48 use Galette\Repository\Groups
;
49 use Galette\Core\Login
;
50 use Galette\Repository\Members
;
51 use Galette\Features\Dynamics
;
54 * Member class for galette
59 * @author Johan Cwiklinski <johan@x-tnd.be>
60 * @copyright 2009-2021 The Galette Team
61 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL License 3.0 or (at your option) any later version
62 * @link http://galette.tuxfamily.org
63 * @since Available since 0.7dev - 02-06-2009
65 * @property integer $id
66 * @property integer|Title $title Either a title id or an instance of Title
67 * @property string $stitle Title label
68 * @property string company_name
69 * @property string $name
70 * @property string $surname
71 * @property string $nickname
72 * @property string $birthdate Localized birth date
73 * @property string $rbirthdate Raw birth date
74 * @property string $birth_place
75 * @property integer $gender
76 * @property string $sgender Gender label
77 * @property string $job
78 * @property string $language
79 * @property integer $status
80 * @property string $sstatus Status label
81 * @property string $address
82 * @property string $address_continuation
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 $website
90 * @property string $msn
91 * @property string $icq
92 * @property string $jabber
93 * @property string $gnupgid
94 * @property string $fingerprint
95 * @property string $login
96 * @property string $creation_date Localized creation date
97 * @property string $modification_date Localized modification date
98 * @property string $due_date Localized due date
99 * @property string $others_infos
100 * @property string $others_infos_admin
101 * @property Picture $picture
102 * @property array $groups
103 * @property array $managed_groups
104 * @property integer|Adherent $parent Parent id if parent dep is not loaded, Adherent instance otherwise
105 * @property array $children
106 * @property boolean $admin better to rely on isAdmin()
107 * @property boolean $staff better to rely on isStaff()
108 * @property boolean $due_free better to rely on isDueFree()
109 * @property boolean $appears_in_list better to rely on appearsInMembersList()
110 * @property boolean $active better to rely on isActive()
111 * @property boolean $duplicate better to rely on isDuplicate()
112 * @property string $sadmin yes/no
113 * @property string $sstaff yes/no
114 * @property string $sdue_free yes/no
115 * @property string $sappears_in_list yes/no
116 * @property string $sactive yes/no
117 * @property string $sfullname
118 * @property string $sname
119 * @property string $saddress Concatened address and continuation
120 * @property string $contribstatus State of member contributions
121 * @property string $days_remaining
122 * @property-read integer $parent_id
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
158 private $_address_continuation; /** TODO: remove */
166 private $_msn; /** TODO: remove */
167 private $_icq; /** TODO: remove */
168 private $_jabber; /** TODO: remove */
170 private $_fingerprint;
171 //Galette relative information
172 private $_appears_in_list;
178 private $_creation_date;
179 private $_modification_date;
181 private $_others_infos;
182 private $_others_infos_admin;
185 private $_days_remaining;
187 private $_managed_groups;
190 private $_duplicate = false;
192 private $_row_classes;
194 private $_self_adh = false;
195 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 $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($id)
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
326 * @return bool true if query succeed, false otherwise
328 public function loadFromLoginOrMail($login)
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);
345 } catch (Throwable
$e) {
347 'Cannot load member form login `' . $login . '` | ' .
356 * Populate object from a resultset row
358 * @param ResultSet $r the resultset row
362 private function loadFromRS($r)
364 $this->_self_adh
= false;
365 $this->_id
= $r->id_adh
;
367 if ($r->titre_adh
!== null) {
368 $this->_title
= new Title((int)$r->titre_adh
);
370 $this->_company_name
= $r->societe_adh
;
371 $this->_name
= $r->nom_adh
;
372 $this->_surname
= $r->prenom_adh
;
373 $this->_nickname
= $r->pseudo_adh
;
374 if ($r->ddn_adh
!= '1901-01-01') {
375 $this->_birthdate
= $r->ddn_adh
;
377 $this->_birth_place
= $r->lieu_naissance
;
378 $this->_gender
= (int)$r->sexe_adh
;
379 $this->_job
= $r->prof_adh
;
380 $this->_language
= $r->pref_lang
;
381 $this->_active
= ($r->activite_adh
== 1) ?
true : false;
382 $this->_status
= (int)$r->id_statut
;
383 //Contact information
384 $this->_address
= $r->adresse_adh
;
385 /** TODO: remove and merge with address */
386 $this->_address_continuation
= $r->adresse2_adh
;
387 $this->_zipcode
= $r->cp_adh
;
388 $this->_town
= $r->ville_adh
;
389 $this->_country
= $r->pays_adh
;
390 $this->_phone
= $r->tel_adh
;
391 $this->_gsm
= $r->gsm_adh
;
392 $this->_email
= $r->email_adh
;
393 $this->_website
= $r->url_adh
;
395 $this->_msn
= $r->msn_adh
;
397 $this->_icq
= $r->icq_adh
;
399 $this->_jabber
= $r->jabber_adh
;
401 $this->_gnupgid
= $r->gpgid
;
403 $this->_fingerprint
= $r->fingerprint
;
404 //Galette relative information
405 $this->_appears_in_list
= ($r->bool_display_info
== 1) ?
true : false;
406 $this->_admin
= ($r->bool_admin_adh
== 1) ?
true : false;
408 isset($r->priorite_statut
)
409 && $r->priorite_statut
< Members
::NON_STAFF_MEMBERS
411 $this->_staff
= true;
413 $this->_due_free
= ($r->bool_exempt_adh
== 1) ?
true : false;
414 $this->_login
= $r->login_adh
;
415 $this->_password
= $r->mdp_adh
;
416 $this->_creation_date
= $r->date_crea_adh
;
417 if ($r->date_modif_adh
!= '1901-01-01') {
418 $this->_modification_date
= $r->date_modif_adh
;
420 $this->_modification_date
= $this->_creation_date
;
422 $this->_due_date
= $r->date_echeance
;
423 $this->_others_infos
= $r->info_public_adh
;
424 $this->_others_infos_admin
= $r->info_adh
;
426 if ($r->parent_id
!== null) {
427 $this->_parent
= (int)$r->parent_id
;
428 if ($this->_deps
['parent'] === true) {
433 if ($this->_deps
['children'] === true) {
434 $this->loadChildren();
437 if ($this->_deps
['picture'] === true) {
438 $this->_picture
= new Picture($this->_id
);
441 if ($this->_deps
['groups'] === true) {
445 if ($this->_deps
['dues'] === true) {
449 if ($this->_deps
['dynamics'] === true) {
450 $this->loadDynamicFields();
459 private function loadParent()
461 if (!$this->_parent
instanceof Adherent
) {
462 $deps = array_fill_keys(array_keys($this->_deps
), false);
463 $this->_parent
= new Adherent($this->zdb
, (int)$this->_parent
, $deps);
468 * Load member children
472 private function loadChildren()
474 $this->_children
= array();
477 $select = $this->zdb
->select(self
::TABLE
);
481 'parent_id = ' . $this->_id
484 $results = $this->zdb
->execute($select);
486 if ($results->count() > 0) {
487 foreach ($results as $row) {
488 $deps = $this->_deps
;
489 $deps['children'] = false;
490 $deps['parent'] = false;
491 $this->_children
[] = new Adherent($this->zdb
, (int)$row->$id, $deps);
494 } catch (Throwable
$e) {
496 'Cannot load children for member #' . $this->_id
. ' | ' .
509 public function loadGroups()
511 $this->_groups
= Groups
::loadGroups($this->_id
);
512 $this->_managed_groups
= Groups
::loadManagedGroups($this->_id
);
516 * Retrieve status from preferences
518 * @return pref_statut
521 private function getDefaultStatus()
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()
542 //how many days since our beloved member has been created
543 $date_now = new \
DateTime();
544 $this->_oldness
= $date_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 $date_end = new \
DateTime($this->_due_date
);
557 $date_diff = $date_now->diff($date_end);
558 $this->_days_remaining
= ($date_diff->invert
== 1)
559 ?
$date_diff->days
* -1
562 if ($this->_days_remaining
== 0) {
563 $this->_row_classes
.= ' cotis-lastday';
564 } elseif ($this->_days_remaining
< 0) {
565 //check if member is still active
566 $this->_row_classes
.= $this->isActive() ?
' cotis-late' : ' cotis-old';
567 } elseif ($this->_days_remaining
< 30) {
568 $this->_row_classes
.= ' cotis-soon';
570 $this->_row_classes
.= ' cotis-ok';
581 public function isAdmin()
583 return $this->_admin
;
587 * Is user member of staff?
591 public function isStaff()
593 return $this->_staff
;
597 * Is member freed of dues?
601 public function isDueFree()
603 return $this->_due_free
;
607 * Is member in specified group?
609 * @param string $group_name Group name
613 public function isGroupMember($group_name)
615 if (is_array($this->_groups
)) {
616 foreach ($this->_groups
as $g) {
617 if ($g->getName() == $group_name) {
624 'Calling ' . __METHOD__
. ' without groups loaded!',
632 * Is member manager of specified group?
634 * @param string $group_name Group name
638 public function isGroupManager($group_name)
640 if (is_array($this->_managed_groups
)) {
641 foreach ($this->_managed_groups
as $mg) {
642 if ($mg->getName() == $group_name) {
649 'Calling ' . __METHOD__
. ' without groups loaded!',
657 * Does current member represents a company?
661 public function isCompany()
663 return trim($this->_company_name ??
'') != '';
667 * Is current member a man?
671 public function isMan()
673 return (int)$this->_gender
=== self
::MAN
;
677 * Is current member a woman?
681 public function isWoman()
683 return (int)$this->_gender
=== self
::WOMAN
;
688 * Can member appears in public members list?
692 public function appearsInMembersList()
694 return $this->_appears_in_list
;
702 public function isActive()
704 return $this->_active
;
708 * Does member have uploaded a picture?
712 public function hasPicture()
714 return $this->_picture
->hasPicture();
718 * Does member have a parent?
722 public function hasParent()
724 return !empty($this->_parent
);
728 * Does member have children?
732 public function hasChildren()
734 if ($this->_children
=== null) {
737 'Children has not been loaded!',
743 return count($this->_children
) > 0;
748 * Get row class related to current fee status
750 * @param boolean $public we want the class for public pages
752 * @return string the class to apply
754 public function getRowClass($public = false)
756 $strclass = ($this->isActive()) ?
'active' : 'inactive';
757 if ($public === false) {
758 $strclass .= $this->_row_classes
;
764 * Get current member due status
766 * @return string i18n string representing state of due
768 public function getDues()
771 $date_now = new \
DateTime();
772 if ($this->isDueFree()) {
773 $ret = _T("Freed of dues");
774 } elseif ($this->_due_date
== '') {
775 $patterns = array('/%days/', '/%date/');
776 $cdate = new \
DateTime($this->_creation_date
);
779 $cdate->format(__("Y-m-d"))
781 if ($this->_active
) {
785 _T("Never contributed: Registered %days days ago (since %date)")
788 $ret = _T("Never contributed");
790 } elseif ($this->_days_remaining
== 0) {
791 $ddate = new \
DateTime($this->_due_date
);
792 $date_diff = $date_now->diff($ddate);
793 if ($date_diff->invert
== 0) {
794 $ret = _T("Last day!");
796 $ret = _T("Late since today!");
798 } elseif ($this->_days_remaining
< 0) {
799 $ddate = new \
DateTime($this->_due_date
);
800 $patterns = array('/%days/', '/%date/');
802 $this->_days_remaining
* -1,
803 $ddate->format(__("Y-m-d"))
805 if ($this->_active
) {
809 _T("Late of %days days (since %date)")
812 $ret = _T("No longer member");
815 $ddate = new \
DateTime($this->_due_date
);
816 $patterns = array('/%days/', '/%date/');
818 $this->_days_remaining
,
819 $ddate->format(__("Y-m-d"))
824 _T("%days days remaining (ending on %date)")
831 * Retrieve Full name and surname for the specified member id
833 * @param Db $zdb Database instance
834 * @param integer $id Member id
835 * @param boolean $wid Add member id
836 * @param boolean $wnick Add member nickname
838 * @return string formatted Name and Surname
840 public static function getSName($zdb, $id, $wid = false, $wnick = false)
843 $select = $zdb->select(self
::TABLE
);
844 $select->where(self
::PK
. ' = ' . $id);
846 $results = $zdb->execute($select);
847 $row = $results->current();
848 return self
::getNameWithCase(
852 ($wid === true ?
$row->id_adh
: false),
853 ($wnick === true ?
$row->pseudo_adh
: false)
855 } catch (Throwable
$e) {
857 'Cannot get formatted name for member form id `' . $id . '` | ' .
866 * Get member name with correct case
868 * @param string $name Member name
869 * @param string $surname Mmeber surname
870 * @param false|Title $title Member title to show or false
871 * @param false|integer $id Member id to display or false
872 * @param false|string $nick Member nickname to display or false
876 public static function getNameWithCase($name, $surname, $title = false, $id = false, $nick = false)
880 if ($title !== false && $title instanceof Title
) {
881 $str .= $title->tshort
. ' ';
884 $str .= mb_strtoupper($name ??
'', 'UTF-8') . ' ' .
885 ucwords(mb_strtolower($surname ??
'', 'UTF-8'), " \t\r\n\f\v-_|");
887 if ($id !== false ||
$nick !== false) {
890 if ($nick !== false) {
894 if ($nick !== false && !empty($nick)) {
899 if ($id !== false ||
$nick !== false) {
902 return strip_tags($str);
906 * Change password for a given user
908 * @param Db $zdb Database instance
909 * @param string $id_adh Member identifier
910 * @param string $pass New password
914 public static function updatePassword(Db
$zdb, $id_adh, $pass)
917 $cpass = password_hash($pass, PASSWORD_BCRYPT
);
919 $update = $zdb->update(self
::TABLE
);
921 array('mdp_adh' => $cpass)
922 )->where(self
::PK
. ' = ' . $id_adh);
923 $zdb->execute($update);
925 'Password for `' . $id_adh . '` has been updated.',
929 } catch (Throwable
$e) {
931 'An error occurred while updating password for `' . $id_adh .
932 '` | ' . $e->getMessage(),
942 * @param string $field Field name
946 private function getFieldLabel($field)
948 $label = $this->fields
[$field]['label'];
950 $label = str_replace(' ', ' ', $label);
951 //remove trailing ':' and then trim
952 $label = trim(trim($label ??
'', ':'));
957 * Retrieve fields from database
959 * @param Db $zdb Database instance
963 public static function getDbFields(Db
$zdb)
965 $columns = $zdb->getColumns(self
::TABLE
);
967 foreach ($columns as $col) {
968 $fields[] = $col->getName();
974 * Mark as self membership
978 public function setSelfMembership()
980 $this->_self_adh
= true;
984 * Is member up to date?
988 public function isUp2Date()
990 if ($this->_deps
['dues']) {
991 if ($this->isDueFree()) {
992 //member is due free, he's up to date.
995 //let's check from end date, if present
996 if ($this->_due_date
== null) {
999 $ech = new \
DateTime($this->_due_date
);
1000 $now = new \
DateTime();
1001 $now->setTime(0, 0, 0);
1002 return $ech >= $now;
1006 throw new \
RuntimeException(
1007 'Cannot check if member is up to date, dues deps is disabled!'
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($values, $required, $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 $this->validate($key, $value, $values);
1131 } elseif (empty($this->_id
)) {
1132 //ensure login and password are not empty
1133 if (($key == 'login_adh' ||
$key == 'mdp_adh') && !isset($required[$key])) {
1134 $p = new Password($this->zdb
);
1135 $generated_value = $p->makeRandomPassword(15);
1136 if ($key == 'login_adh') {
1137 //'@' is not permitted in logins
1138 $this->$prop = str_replace('@', 'a', $generated_value);
1140 $this->$prop = $generated_value;
1147 // missing required fields?
1148 foreach ($required as $key => $val) {
1149 $prop = '_' . $this->fields
[$key]['propname'];
1151 if (!isset($disabled[$key])) {
1152 $mandatory_missing = false;
1153 if (!isset($this->$prop) ||
$this->$prop == '') {
1154 $mandatory_missing = true;
1155 } elseif ($key === 'titre_adh' && $this->$prop == '-1') {
1156 $mandatory_missing = true;
1159 if ($mandatory_missing === true) {
1160 $this->errors
[] = str_replace(
1162 '<a href="#' . $key . '">' . $this->getFieldLabel($key) . '</a>',
1163 _T("- Mandatory field %field empty.")
1169 //attach to/detach from parent
1170 if (isset($values['detach_parent'])) {
1171 $this->_parent
= null;
1174 $this->dynamicsCheck($values, $required, $disabled);
1176 if (count($this->errors
) > 0) {
1178 'Some errors has been thew attempting to edit/store a member' . "\n" .
1179 print_r($this->errors
, true),
1182 return $this->errors
;
1187 'Member checked successfully.',
1195 * Validate data for given key
1196 * Set valid data in current object, also resets errors list
1198 * @param string $field Field name
1199 * @param mixed $value Value we want to set
1200 * @param array $values All values, for some references
1204 public function validate($field, $value, $values)
1206 global $preferences;
1208 $prop = '_' . $this->fields
[$field]['propname'];
1210 if ($value === null ||
(is_string($value) && trim($value) == '')) {
1211 //empty values are OK
1212 $this->$prop = $value;
1218 case 'date_crea_adh':
1219 case 'date_modif_adh_':
1221 case 'date_echeance':
1223 $d = \DateTime
::createFromFormat(__("Y-m-d"), $value);
1225 //try with non localized date
1226 $d = \DateTime
::createFromFormat("Y-m-d", $value);
1228 throw new \
Exception('Incorrect format');
1232 if ($field === 'ddn_adh') {
1233 $now = new \
DateTime();
1234 $now->setTime(0, 0, 0);
1235 $d->setTime(0, 0, 0);
1237 $diff = $now->diff($d);
1238 $days = (int)$diff->format('%R%a');
1240 $this->errors
[] = _T('- Birthdate must be set in the past!');
1243 $years = (int)$diff->format('%R%Y');
1244 if ($years <= -200) {
1245 $this->errors
[] = str_replace(
1248 _T('- Members must be less than 200 years old (currently %years)!')
1252 $this->$prop = $d->format('Y-m-d');
1253 } catch (Throwable
$e) {
1255 'Wrong date format. field: ' . $field .
1256 ', value: ' . $value . ', expected fmt: ' .
1257 __("Y-m-d") . ' | ' . $e->getMessage(),
1260 $this->errors
[] = str_replace(
1267 $this->getFieldLabel($field)
1269 _T("- Wrong date format (%date_format) for %field!")
1274 if ($value !== null && $value !== '') {
1275 if ($value == '-1') {
1276 $this->$prop = null;
1277 } elseif (!$value instanceof Title
) {
1278 $this->$prop = new Title((int)$value);
1281 $this->$prop = null;
1286 if (!GaletteMail
::isValidEmail($value)) {
1287 $this->errors
[] = _T("- Non-valid E-Mail address!") .
1288 ' (' . $this->getFieldLabel($field) . ')';
1290 if ($field == 'email_adh') {
1292 $select = $this->zdb
->select(self
::TABLE
);
1295 )->where(array('email_adh' => $value));
1296 if (!empty($this->_id
)) {
1298 self
::PK
. ' != ' . $this->_id
1302 $results = $this->zdb
->execute($select);
1303 if ($results->count() !== 0) {
1304 $this->errors
[] = _T("- This E-Mail address is already used by another member!");
1306 } catch (Throwable
$e) {
1308 'An error occurred checking member email unicity.',
1311 $this->errors
[] = _T("An error has occurred while looking if login already exists.");
1316 if ($value == 'http://' ||
$value == 'https://') {
1318 } elseif (!isValidWebUrl($value)) {
1319 $this->errors
[] = _T("- Non-valid Website address! Maybe you've skipped the http://?");
1323 /** FIXME: add a preference for login length */
1324 if (strlen($value) < 2) {
1325 $this->errors
[] = str_replace(
1328 _T("- The username must be composed of at least %i characters!")
1331 //check if login does not contain the @ character
1332 if (strpos($value, '@') != false) {
1333 $this->errors
[] = _T("- The username cannot contain the @ character");
1335 //check if login is already taken
1337 $select = $this->zdb
->select(self
::TABLE
);
1340 )->where(array('login_adh' => $value));
1341 if (!empty($this->_id
)) {
1343 self
::PK
. ' != ' . $this->_id
1347 $results = $this->zdb
->execute($select);
1349 $results->count() !== 0
1350 ||
$value == $preferences->pref_admin_login
1352 $this->errors
[] = _T("- This username is already in use, please choose another one!");
1354 } catch (Throwable
$e) {
1356 'An error occurred checking member login uniqueness.',
1359 $this->errors
[] = _T("An error has occurred while looking if login already exists.");
1366 $this->_self_adh
!== true
1367 && (!isset($values['mdp_adh2'])
1368 ||
$values['mdp_adh2'] != $value)
1370 $this->errors
[] = _T("- The passwords don't match!");
1372 $this->_self_adh
=== true
1373 && !crypt($value, $values['mdp_crypt']) == $values['mdp_crypt']
1375 $this->errors
[] = _T("Password misrepeated: ");
1377 $pinfos = password_get_info($value);
1378 //check if value is already a hash
1379 if ($pinfos['algo'] == 0) {
1380 $this->$prop = password_hash(
1385 $pwcheck = new \Galette\Util\
Password($preferences);
1386 $pwcheck->setAdherent($this);
1387 if (!$pwcheck->isValid($value)) {
1388 $this->errors
= array_merge(
1390 $pwcheck->getErrors()
1398 $this->$prop = (int)$value;
1399 //check if status exists
1400 $select = $this->zdb
->select(Status
::TABLE
);
1401 $select->where(Status
::PK
. '= ' . $value);
1403 $results = $this->zdb
->execute($select);
1404 $result = $results->current();
1406 $this->errors
[] = str_replace(
1409 _T("Status #%id does not exists in database.")
1413 } catch (Throwable
$e) {
1415 'An error occurred checking status existence: ' . $e->getMessage(),
1418 $this->errors
[] = _T("An error has occurred while looking if status does exists.");
1422 if (in_array($value, [self
::NC
, self
::MAN
, self
::WOMAN
])) {
1423 $this->$prop = (int)$value;
1425 $this->errors
[] = _T("Gender %gender does not exists!");
1429 $this->$prop = ($value instanceof Adherent
) ?
(int)$value->id
: (int)$value;
1430 $this->loadParent();
1440 public function store()
1442 global $hist, $emitter, $login;
1445 if (!$login->isAdmin() && !$login->isStaff() && !$login->isGroupManager() && $this->id
== '') {
1446 if ($this->preferences
->pref_bool_create_member
) {
1447 $this->_parent
= $login->id
;
1453 $fields = self
::getDbFields($this->zdb
);
1455 foreach ($fields as $field) {
1457 $field !== 'date_modif_adh'
1458 ||
empty($this->_id
)
1460 $prop = '_' . $this->fields
[$field]['propname'];
1462 ($field === 'bool_admin_adh'
1463 ||
$field === 'bool_exempt_adh'
1464 ||
$field === 'bool_display_info'
1465 ||
$field === 'activite_adh')
1466 && $this->$prop === false
1468 //Handle booleans for postgres ; bugs #18899 and #19354
1469 $values[$field] = $this->zdb
->isPostgres() ?
'false' : 0;
1470 } elseif ($field === 'parent_id') {
1472 if ($this->_parent
=== null) {
1473 $values['parent_id'] = new Expression('NULL');
1474 } elseif ($this->parent
instanceof Adherent
) {
1475 $values['parent_id'] = $this->_parent
->id
;
1477 $values['parent_id'] = $this->_parent
;
1480 $values[$field] = $this->$prop;
1485 //an empty value will cause date to be set to 1901-01-01, a null
1486 //will result in 0000-00-00. We want a database NULL value here.
1487 if (!$this->_birthdate
) {
1488 $values['ddn_adh'] = new Expression('NULL');
1490 if (!$this->_due_date
) {
1491 $values['date_echeance'] = new Expression('NULL');
1494 if ($this->_title
instanceof Title
) {
1495 $values['titre_adh'] = $this->_title
->id
;
1497 $values['titre_adh'] = new Expression('NULL');
1500 if (!$this->_parent
) {
1501 $values['parent_id'] = new Expression('NULL');
1504 //fields that cannot be null
1506 '_surname' => 'prenom_adh',
1507 '_nickname' => 'pseudo_adh',
1508 '_address' => 'adresse_adh',
1509 '_zipcode' => 'cp_adh',
1510 '_town' => 'ville_adh'
1512 foreach ($notnull as $prop => $field) {
1513 if ($this->$prop === null) {
1514 $values[$field] = '';
1519 if (empty($this->_id
)) {
1520 //we're inserting a new member
1521 unset($values[self
::PK
]);
1522 //set modification date
1523 $this->_modification_date
= date('Y-m-d');
1524 $values['date_modif_adh'] = $this->_modification_date
;
1526 $insert = $this->zdb
->insert(self
::TABLE
);
1527 $insert->values($values);
1528 $add = $this->zdb
->execute($insert);
1529 if ($add->count() > 0) {
1530 $this->_id
= $this->zdb
->getLastGeneratedValue($this);
1531 $this->_picture
= new Picture($this->_id
);
1533 if ($this->_self_adh
) {
1535 _T("Self_subscription as a member: ") .
1536 $this->getNameWithCase($this->_name
, $this->_surname
),
1541 _T("Member card added"),
1547 $event = 'member.add';
1549 $hist->add(_T("Fail to add new member."));
1550 throw new \
Exception(
1551 'An error occurred inserting new member!'
1555 //we're editing an existing member
1556 if (!$this->isDueFree()) {
1558 $due_date = Contribution
::getDueDate($this->zdb
, $this->_id
);
1560 $values['date_echeance'] = $due_date;
1564 if (!$this->_password
) {
1565 unset($values['mdp_adh']);
1568 $update = $this->zdb
->update(self
::TABLE
);
1569 $update->set($values);
1571 self
::PK
. '=' . $this->_id
1574 $edit = $this->zdb
->execute($update);
1576 //edit == 0 does not mean there were an error, but that there
1577 //were nothing to change
1578 if ($edit->count() > 0) {
1579 $this->updateModificationDate();
1581 _T("Member card updated"),
1586 $event = 'member.edit';
1591 $success = $this->dynamicsStore();
1594 //send event at the end of process, once all has been stored
1595 if ($event !== null) {
1596 $emitter->emit($event, $this);
1599 } catch (Throwable
$e) {
1601 'Something went wrong :\'( | ' . $e->getMessage() . "\n" .
1602 $e->getTraceAsString(),
1610 * Update member modification date
1614 private function updateModificationDate()
1617 $modif_date = date('Y-m-d');
1618 $update = $this->zdb
->update(self
::TABLE
);
1620 array('date_modif_adh' => $modif_date)
1621 )->where(self
::PK
. '=' . $this->_id
);
1623 $edit = $this->zdb
->execute($update);
1624 $this->_modification_date
= $modif_date;
1625 } catch (Throwable
$e) {
1627 'Something went wrong updating modif date :\'( | ' .
1628 $e->getMessage() . "\n" . $e->getTraceAsString(),
1635 * Global getter method
1637 * @param string $name name of the property we want to retrieve
1639 * @return false|object the called property
1641 public function __get($name)
1644 'admin', 'staff', 'due_free', 'appears_in_list', 'active',
1645 'row_classes', 'oldness', 'duplicate'
1647 if (!defined('GALETTE_TESTS')) {
1648 $forbidden[] = 'password'; //keep that for tests only
1652 'sadmin', 'sstaff', 'sdue_free', 'sappears_in_list', 'sactive',
1653 'stitle', 'sstatus', 'sfullname', 'sname', 'saddress',
1654 'rbirthdate', 'sgender', 'contribstatus'
1657 if (in_array($name, $forbidden)) {
1660 return $this->isAdmin();
1662 return $this->isStaff();
1664 return $this->isDueFree();
1665 case 'appears_in_list':
1666 return $this->appearsInMembersList();
1668 return $this->isActive();
1670 return $this->isDuplicate();
1672 throw new \
RuntimeException("Call to __get for '$name' is forbidden!");
1676 if (in_array($name, $virtuals)) {
1677 if (substr($name, 0, 1) !== '_') {
1678 $real = '_' . substr($name, 1);
1685 case 'sappears_in_list':
1687 return (($this->$real) ?
_T("Yes") : _T("No"));
1690 return (($this->$real) ?
_T("Active") : _T("Inactive"));
1693 if (isset($this->_title
) && $this->_title
instanceof Title
) {
1694 return $this->_title
->tshort
;
1700 $status = new Status($this->zdb
);
1701 return $status->getLabel($this->_status
);
1704 return $this->getNameWithCase(
1707 (isset($this->_title
) ?
$this->title
: false)
1711 $address = $this->_address
;
1712 if ($this->_address_continuation
!== '' && $this->_address_continuation
!== null) {
1713 $address .= "\n" . $this->_address_continuation
;
1715 return htmlspecialchars($address, ENT_QUOTES
);
1718 return $this->getNameWithCase($this->_name
, $this->_surname
);
1721 return $this->_birthdate
;
1724 switch ($this->gender
) {
1730 return _T('Unspecified');
1733 case 'contribstatus':
1734 return $this->getDues();
1739 if (substr($name, 0, 1) !== '_') {
1740 $rname = '_' . $name;
1748 if ($this->$rname !== null) {
1749 return (int)$this->$rname;
1755 case 'address_continuation':
1756 return $this->$rname ??
'';
1759 case 'creation_date':
1760 case 'modification_date':
1762 if ($this->$rname != '') {
1764 $d = new \
DateTime($this->$rname);
1765 return $d->format(__("Y-m-d"));
1766 } catch (Throwable
$e) {
1767 //oops, we've got a bad date :/
1769 'Bad date (' . $this->$rname . ') | ' .
1773 return $this->$rname;
1778 return ($this->_parent
instanceof Adherent
) ?
(int)$this->_parent
->id
: (int)$this->_parent
;
1781 if (!property_exists($this, $rname)) {
1783 "Unknown property '$rname'",
1788 return $this->$rname;
1796 * If member does not have an email address, but is attached to
1797 * another member, we'll take information from its parent.
1801 public function getEmail()
1803 $email = $this->_email
;
1804 if (empty($email)) {
1805 $this->loadParent();
1806 $email = $this->parent
->email
;
1813 * Get member address.
1814 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1818 public function getAddress()
1820 $address = $this->_address
;
1821 if (empty($address) && $this->hasParent()) {
1822 $this->loadParent();
1823 $address = $this->parent
->address
;
1830 * Get member address continuation.
1831 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1835 public function getAddressContinuation()
1837 $address = $this->_address
;
1838 $address_continuation = $this->_address_continuation
;
1839 if (empty($address) && $this->hasParent()) {
1840 $this->loadParent();
1841 $address_continuation = $this->parent
->address_continuation
;
1844 return $address_continuation;
1848 * Get member zipcode.
1849 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1853 public function getZipcode()
1855 $address = $this->_address
;
1856 $zip = $this->_zipcode
;
1857 if (empty($address) && $this->hasParent()) {
1858 $this->loadParent();
1859 $zip = $this->parent
->zipcode
;
1867 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1871 public function getTown()
1873 $address = $this->_address
;
1874 $town = $this->_town
;
1875 if (empty($address) && $this->hasParent()) {
1876 $this->loadParent();
1877 $town = $this->parent
->town
;
1884 * Get member country.
1885 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1889 public function getCountry()
1891 $address = $this->_address
;
1892 $country = $this->_country
;
1893 if (empty($address) && $this->hasParent()) {
1894 $this->loadParent();
1895 $country = $this->parent
->country
;
1906 public function getAge()
1908 if ($this->_birthdate
== null) {
1912 $d = \DateTime
::createFromFormat('Y-m-d', $this->_birthdate
);
1915 'Invalid birthdate: ' . $this->_birthdate
,
1923 $d->diff(new \
DateTime())->y
,
1924 _T(' (%age years old)')
1929 * Get parent inherited fields
1933 public function getParentFields()
1935 return $this->parent_fields
;
1939 * Handle files (photo and dynamics files)
1941 * @param array $files Files sent
1943 * @return array|true
1945 public function handleFiles($files)
1949 if (isset($files['photo'])) {
1950 if ($files['photo']['error'] === UPLOAD_ERR_OK
) {
1951 if ($files['photo']['tmp_name'] != '') {
1952 if (is_uploaded_file($files['photo']['tmp_name'])) {
1953 $res = $this->picture
->store($files['photo']);
1956 = $this->picture
->getErrorMessage($res);
1960 } elseif ($files['photo']['error'] !== UPLOAD_ERR_NO_FILE
) {
1962 $this->picture
->getPhpErrorMessage($files['photo']['error']),
1965 $this->errors
[] = $this->picture
->getPhpErrorMessage(
1966 $files['photo']['error']
1970 $this->dynamicsFiles($files);
1972 if (count($this->errors
) > 0) {
1974 'Some errors has been thew attempting to edit/store a member files' . "\n" .
1975 print_r($this->errors
, true),
1978 return $this->errors
;
1985 * Set member as duplicate
1989 public function setDuplicate()
1991 //mark as duplicated
1992 $this->_duplicate
= true;
1993 $infos = $this->_others_infos_admin
;
1994 $this->_others_infos_admin
= str_replace(
1996 [$this->sname
, $this->_id
],
1997 _T('Duplicated from %name (%id)')
1999 if (!empty($infos)) {
2000 $this->_others_infos_admin
.= "\n" . $infos;
2004 //drop email, must be unique
2005 $this->_email
= null;
2006 //drop creation date
2007 $this->_creation_date
= date("Y-m-d");
2009 $this->_login
= null;
2011 $this->_picture
= new Picture();
2013 $this->_birthdate
= null;
2015 $this->_surname
= null;
2017 $this->_admin
= false;
2019 $this->_due_free
= false;
2023 * Get current errors
2027 public function getErrors()
2029 return $this->errors
;
2037 public function getGroups()
2039 return $this->_groups
;
2043 * Get user managed groups
2047 public function getManagedGroups()
2049 return $this->_managed_groups
;
2053 * Can current logged-in user create member
2055 * @param Login $login Login instance
2059 public function canCreate(Login
$login): bool
2061 global $preferences;
2063 if ($this->id
&& $login->id
== $this->id ||
$login->isAdmin() ||
$login->isStaff()) {
2067 if ($preferences->pref_bool_create_member
&& $login->isLogged()) {
2075 * Can current logged-in user edit member
2077 * @param Login $login Login instance
2081 public function canEdit(Login
$login): bool
2083 //admin and staff users can edit, as well as member itself
2084 if ($this->id
&& $login->id
== $this->id ||
$login->isAdmin() ||
$login->isStaff()) {
2088 //parent can edit their child cards
2089 if ($this->hasParent() && $this->parent_id
=== $login->id
) {
2093 //group managers can edit members of groups they manage
2094 if ($login->isGroupManager()) {
2095 foreach ($this->getGroups() as $g) {
2096 if ($login->isGroupManager($g->getId())) {
2106 * Can current logged-in user display member
2108 * @param Login $login Login instance
2112 public function canShow(Login
$login): bool
2114 return $this->canEdit($login);
2118 * Are we currently duplicated a member?
2122 public function isDuplicate(): bool
2124 return $this->_duplicate
;
2128 * Flag creation mail sending
2130 * @param boolean $send True (default) to send creation email
2134 public function setSendmail($send = true): self
2136 $this->sendmail
= $send;
2141 * Should we send administrative emails to member?
2145 public function sendEMail()
2147 return $this->sendmail
;
2153 * @param integer $id Parent identifier
2157 public function setParent(int $id): self
2159 $this->_parent
= $id;
2160 $this->loadParent();
2165 * Reset dependencies to load
2169 public function disableAllDeps(): self
2171 foreach ($this->_deps
as &$dep) {
2178 * Enable all dependencies to load
2182 public function enableAllDeps(): self
2184 foreach ($this->_deps
as &$dep) {
2191 * Enable a load dependency
2193 * @param string $name Dependency name
2197 public function enableDep(string $name): self
2199 if (!isset($this->_deps
[$name])) {
2201 'dependency ' . $name . ' does not exists!',
2205 $this->_deps
[$name] = true;
2212 * Enable a load dependency
2214 * @param string $name Dependency name
2218 public function disableDep(string $name): self
2220 if (!isset($this->_deps
[$name])) {
2222 'dependency ' . $name . ' does not exists!',
2226 $this->_deps
[$name] = false;