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
;
53 * Member class for galette
58 * @author Johan Cwiklinski <johan@x-tnd.be>
59 * @copyright 2009-2021 The Galette Team
60 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL License 3.0 or (at your option) any later version
61 * @link http://galette.tuxfamily.org
62 * @since Available since 0.7dev - 02-06-2009
64 * @property integer $id
65 * @property integer|Title $title Either a title id or an instance of Title
66 * @property string $stitle Title label
67 * @property string company_name
68 * @property string $name
69 * @property string $surname
70 * @property string $nickname
71 * @property string $birthdate Localized birth date
72 * @property string $rbirthdate Raw birth date
73 * @property string $birth_place
74 * @property integer $gender
75 * @property string $sgender Gender label
76 * @property string $job
77 * @property string $language
78 * @property integer $status
79 * @property string $sstatus Status label
80 * @property string $address
81 * @property string $address_continuation
82 * @property string $zipcode
83 * @property string $town
84 * @property string $country
85 * @property string $phone
86 * @property string $gsm
87 * @property string $email
88 * @property string $website
89 * @property string $msn
90 * @property string $icq
91 * @property string $jabber
92 * @property string $gnupgid
93 * @property string $fingerprint
94 * @property string $login
95 * @property string $creation_date Localized creation date
96 * @property string $modification_date Localized modification date
97 * @property string $due_date Localized due date
98 * @property string $others_infos
99 * @property string $others_infos_admin
100 * @property Picture $picture
101 * @property array $groups
102 * @property array $managed_groups
103 * @property integer|Adherent $parent Parent id if parent dep is not loaded, Adherent instance otherwise
104 * @property array $children
105 * @property boolean $admin better to rely on isAdmin()
106 * @property boolean $staff better to rely on isStaff()
107 * @property boolean $due_free better to rely on isDueFree()
108 * @property boolean $appears_in_list better to rely on appearsInMembersList()
109 * @property boolean $active better to rely on isActive()
110 * @property boolean $duplicate better to rely on isDuplicate()
111 * @property string $sadmin yes/no
112 * @property string $sstaff yes/no
113 * @property string $sdue_free yes/no
114 * @property string $sappears_in_list yes/no
115 * @property string $sactive yes/no
116 * @property string $sfullname
117 * @property string $sname
118 * @property string $saddress Concatened address and continuation
119 * @property string $contribstatus State of member contributions
120 * @property string $days_remaining
121 * @property-read integer $parent_id
127 public const TABLE
= 'adherents';
128 public const PK
= 'id_adh';
131 public const MAN
= 1;
132 public const WOMAN
= 2;
134 public const AFTER_ADD_DEFAULT
= 0;
135 public const AFTER_ADD_TRANS
= 1;
136 public const AFTER_ADD_NEW
= 2;
137 public const AFTER_ADD_SHOW
= 3;
138 public const AFTER_ADD_LIST
= 4;
139 public const AFTER_ADD_HOME
= 5;
144 private $_company_name;
149 private $_birth_place;
155 //Contact information
157 private $_address_continuation; /** TODO: remove */
165 private $_msn; /** TODO: remove */
166 private $_icq; /** TODO: remove */
167 private $_jabber; /** TODO: remove */
168 private $_gnupgid; /** TODO: remove */
169 private $_fingerprint; /** TODO: remove */
170 //Galette relative information
171 private $_appears_in_list;
177 private $_creation_date;
178 private $_modification_date;
180 private $_others_infos;
181 private $_others_infos_admin;
184 private $_days_remaining;
186 private $_managed_groups;
189 private $_duplicate = false;
191 private $_row_classes;
193 private $_self_adh = false;
194 private $_deps = array(
204 private $preferences;
208 private $parent_fields = [
216 private $errors = [];
218 private $sendmail = false;
221 * Default constructor
223 * @param Db $zdb Database instance
224 * @param mixed $args Either a ResultSet row, its id or its
225 * login or its email for to load s specific
226 * member, or null to just instanciate object
227 * @param false|array $deps Dependencies configuration, see Adherent::$_deps
229 public function __construct(Db
$zdb, $args = null, $deps = null)
235 if ($deps !== null) {
236 if (is_array($deps)) {
237 $this->_deps
= array_merge(
241 } elseif ($deps === false) {
243 $this->_deps
= array_fill_keys(
244 array_keys($this->_deps
),
249 '$deps shoud be an array, ' . gettype($deps) . ' given!',
255 if ($args == null ||
is_int($args)) {
256 if (is_int($args) && $args > 0) {
259 $this->_active
= true;
260 $this->_language
= $i18n->getID();
261 $this->_creation_date
= date("Y-m-d");
262 $this->_status
= $this->getDefaultStatus();
263 $this->_title
= null;
264 $this->_gender
= self
::NC
;
265 $gp = new Password($this->zdb
);
266 $this->_password
= $gp->makeRandomPassword();
267 $this->_picture
= new Picture();
268 $this->_admin
= false;
269 $this->_staff
= false;
270 $this->_due_free
= false;
271 $this->_appears_in_list
= false;
272 $this->_parent
= null;
274 if ($this->_deps
['dynamics'] === true) {
275 $this->loadDynamicFields();
278 } elseif (is_object($args)) {
279 $this->loadFromRS($args);
280 } elseif (is_string($args)) {
281 $this->loadFromLoginOrMail($args);
286 * Loads a member from its id
288 * @param int $id the identifier for the member to load
290 * @return bool true if query succeed, false otherwise
292 public function load($id)
295 $select = $this->zdb
->select(self
::TABLE
, 'a');
298 array('b' => PREFIX_DB
. Status
::TABLE
),
299 'a.' . Status
::PK
. '=b.' . Status
::PK
,
300 array('priorite_statut')
301 )->where(array(self
::PK
=> $id));
303 $results = $this->zdb
->execute($select);
305 if ($results->count() === 0) {
309 $this->loadFromRS($results->current());
311 } catch (Throwable
$e) {
313 'Cannot load member form id `' . $id . '` | ' . $e->getMessage(),
321 * Loads a member from its login
323 * @param string $login login for the member to load
325 * @return bool true if query succeed, false otherwise
327 public function loadFromLoginOrMail($login)
330 $select = $this->zdb
->select(self
::TABLE
);
331 if (GaletteMail
::isValidEmail($login)) {
332 //we got a valid email address, use it
333 $select->where(array('email_adh' => $login));
335 ///we did not get an email address, consider using login
336 $select->where(array('login_adh' => $login));
339 $results = $this->zdb
->execute($select);
340 $result = $results->current();
342 $this->loadFromRS($result);
344 } catch (Throwable
$e) {
346 'Cannot load member form login `' . $login . '` | ' .
355 * Populate object from a resultset row
357 * @param ResultSet $r the resultset row
361 private function loadFromRS($r)
363 $this->_self_adh
= false;
364 $this->_id
= $r->id_adh
;
366 if ($r->titre_adh
!== null) {
367 $this->_title
= new Title((int)$r->titre_adh
);
369 $this->_company_name
= $r->societe_adh
;
370 $this->_name
= $r->nom_adh
;
371 $this->_surname
= $r->prenom_adh
;
372 $this->_nickname
= $r->pseudo_adh
;
373 if ($r->ddn_adh
!= '1901-01-01') {
374 $this->_birthdate
= $r->ddn_adh
;
376 $this->_birth_place
= $r->lieu_naissance
;
377 $this->_gender
= (int)$r->sexe_adh
;
378 $this->_job
= $r->prof_adh
;
379 $this->_language
= $r->pref_lang
;
380 $this->_active
= ($r->activite_adh
== 1) ?
true : false;
381 $this->_status
= (int)$r->id_statut
;
382 //Contact information
383 $this->_address
= $r->adresse_adh
;
384 /** TODO: remove and merge with address */
385 $this->_address_continuation
= $r->adresse2_adh
;
386 $this->_zipcode
= $r->cp_adh
;
387 $this->_town
= $r->ville_adh
;
388 $this->_country
= $r->pays_adh
;
389 $this->_phone
= $r->tel_adh
;
390 $this->_gsm
= $r->gsm_adh
;
391 $this->_email
= $r->email_adh
;
392 $this->_website
= $r->url_adh
;
394 $this->_msn
= $r->msn_adh
;
396 $this->_icq
= $r->icq_adh
;
398 $this->_jabber
= $r->jabber_adh
;
400 $this->_gnupgid
= $r->gpgid
;
402 $this->_fingerprint
= $r->fingerprint
;
403 //Galette relative information
404 $this->_appears_in_list
= ($r->bool_display_info
== 1) ?
true : false;
405 $this->_admin
= ($r->bool_admin_adh
== 1) ?
true : false;
407 isset($r->priorite_statut
)
408 && $r->priorite_statut
< Members
::NON_STAFF_MEMBERS
410 $this->_staff
= true;
412 $this->_due_free
= ($r->bool_exempt_adh
== 1) ?
true : false;
413 $this->_login
= $r->login_adh
;
414 $this->_password
= $r->mdp_adh
;
415 $this->_creation_date
= $r->date_crea_adh
;
416 if ($r->date_modif_adh
!= '1901-01-01') {
417 $this->_modification_date
= $r->date_modif_adh
;
419 $this->_modification_date
= $this->_creation_date
;
421 $this->_due_date
= $r->date_echeance
;
422 $this->_others_infos
= $r->info_public_adh
;
423 $this->_others_infos_admin
= $r->info_adh
;
425 if ($r->parent_id
!== null) {
426 $this->_parent
= (int)$r->parent_id
;
427 if ($this->_deps
['parent'] === true) {
432 if ($this->_deps
['children'] === true) {
433 $this->loadChildren();
436 if ($this->_deps
['picture'] === true) {
437 $this->_picture
= new Picture($this->_id
);
440 if ($this->_deps
['groups'] === true) {
444 if ($this->_deps
['dues'] === true) {
448 if ($this->_deps
['dynamics'] === true) {
449 $this->loadDynamicFields();
458 private function loadParent()
460 if (!$this->_parent
instanceof Adherent
) {
461 $deps = array_fill_keys(array_keys($this->_deps
), false);
462 $this->_parent
= new Adherent($this->zdb
, (int)$this->_parent
, $deps);
467 * Load member children
471 private function loadChildren()
473 $this->_children
= array();
476 $select = $this->zdb
->select(self
::TABLE
);
480 'parent_id = ' . $this->_id
483 $results = $this->zdb
->execute($select);
485 if ($results->count() > 0) {
486 foreach ($results as $row) {
487 $deps = $this->_deps
;
488 $deps['children'] = false;
489 $deps['parent'] = false;
490 $this->_children
[] = new Adherent($this->zdb
, (int)$row->$id, $deps);
493 } catch (Throwable
$e) {
495 'Cannot load children for member #' . $this->_id
. ' | ' .
508 public function loadGroups()
510 $this->_groups
= Groups
::loadGroups($this->_id
);
511 $this->_managed_groups
= Groups
::loadManagedGroups($this->_id
);
515 * Retrieve status from preferences
517 * @return pref_statut
520 private function getDefaultStatus()
523 if ($preferences->pref_statut
!= '') {
524 return $preferences->pref_statut
;
527 'Unable to get pref_statut; is it defined in preferences?',
530 return Status
::DEFAULT_STATUS
;
535 * Check for dues status
539 private function checkDues()
541 //how many days since our beloved member has been created
542 $date_now = new \
DateTime();
543 $this->_oldness
= $date_now->diff(
544 new \
DateTime($this->_creation_date
)
547 if ($this->isDueFree()) {
548 //no fee required, we don't care about dates
549 $this->_row_classes
.= ' cotis-exempt';
551 //ok, fee is required. Let's check the dates
552 if ($this->_due_date
== '') {
553 $this->_row_classes
.= ' cotis-never';
555 $date_end = new \
DateTime($this->_due_date
);
556 $date_diff = $date_now->diff($date_end);
557 $this->_days_remaining
= ($date_diff->invert
== 1)
558 ?
$date_diff->days
* -1
561 if ($this->_days_remaining
== 0) {
562 $this->_row_classes
.= ' cotis-lastday';
563 } elseif ($this->_days_remaining
< 0) {
564 //check if member is still active
565 $this->_row_classes
.= $this->isActive() ?
' cotis-late' : ' cotis-old';
566 } elseif ($this->_days_remaining
< 30) {
567 $this->_row_classes
.= ' cotis-soon';
569 $this->_row_classes
.= ' cotis-ok';
580 public function isAdmin()
582 return $this->_admin
;
586 * Is user member of staff?
590 public function isStaff()
592 return $this->_staff
;
596 * Is member freed of dues?
600 public function isDueFree()
602 return $this->_due_free
;
606 * Is member in specified group?
608 * @param string $group_name Group name
612 public function isGroupMember($group_name)
614 if (is_array($this->_groups
)) {
615 foreach ($this->_groups
as $g) {
616 if ($g->getName() == $group_name) {
623 'Calling ' . __METHOD__
. ' without groups loaded!',
631 * Is member manager of specified group?
633 * @param string $group_name Group name
637 public function isGroupManager($group_name)
639 if (is_array($this->_managed_groups
)) {
640 foreach ($this->_managed_groups
as $mg) {
641 if ($mg->getName() == $group_name) {
648 'Calling ' . __METHOD__
. ' without groups loaded!',
656 * Does current member represents a company?
660 public function isCompany()
662 return trim($this->_company_name ??
'') != '';
666 * Is current member a man?
670 public function isMan()
672 return (int)$this->_gender
=== self
::MAN
;
676 * Is current member a woman?
680 public function isWoman()
682 return (int)$this->_gender
=== self
::WOMAN
;
687 * Can member appears in public members list?
691 public function appearsInMembersList()
693 return $this->_appears_in_list
;
701 public function isActive()
703 return $this->_active
;
707 * Does member have uploaded a picture?
711 public function hasPicture()
713 return $this->_picture
->hasPicture();
717 * Does member have a parent?
721 public function hasParent()
723 return !empty($this->_parent
);
727 * Does member have children?
731 public function hasChildren()
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($public = false)
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()
770 $date_now = new \
DateTime();
771 $ddate = new \
DateTime($this->_due_date
);
772 $date_diff = $date_now->diff($ddate);
773 if ($this->isDueFree()) {
774 $ret = _T("Freed of dues");
775 } elseif ($this->_due_date
== '') {
776 $patterns = array('/%days/', '/%date/');
777 $cdate = new \
DateTime($this->_creation_date
);
780 $cdate->format(__("Y-m-d"))
782 if ($this->_active
) {
786 _T("Never contributed: Registered %days days ago (since %date)")
789 $ret = _T("Never contributed");
791 } elseif ($this->_days_remaining
== 0) {
792 if ($date_diff->invert
== 0) {
793 $ret = _T("Last day!");
795 $ret = _T("Late since today!");
797 } elseif ($this->_days_remaining
< 0) {
798 $patterns = array('/%days/', '/%date/');
800 $this->_days_remaining
* -1,
801 $ddate->format(__("Y-m-d"))
803 if ($this->_active
) {
807 _T("Late of %days days (since %date)")
810 $ret = _T("No longer member");
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($zdb, $id, $wid = false, $wnick = false)
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 Mmeber 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($name, $surname, $title = false, $id = false, $nick = false)
877 if ($title !== false && $title instanceof Title
) {
878 $str .= $title->tshort
. ' ';
881 $str .= mb_strtoupper($name ??
'', 'UTF-8') . ' ' .
882 ucwords(mb_strtolower($surname ??
'', 'UTF-8'), " \t\r\n\f\v-_|");
884 if ($id !== false ||
$nick !== false) {
887 if ($nick !== false) {
891 if ($nick !== false && !empty($nick)) {
896 if ($id !== false ||
$nick !== false) {
899 return strip_tags($str);
903 * Change password for a given user
905 * @param Db $zdb Database instance
906 * @param string $id_adh Member identifier
907 * @param string $pass New password
911 public static function updatePassword(Db
$zdb, $id_adh, $pass)
914 $cpass = password_hash($pass, PASSWORD_BCRYPT
);
916 $update = $zdb->update(self
::TABLE
);
918 array('mdp_adh' => $cpass)
919 )->where(self
::PK
. ' = ' . $id_adh);
920 $zdb->execute($update);
922 'Password for `' . $id_adh . '` has been updated.',
926 } catch (Throwable
$e) {
928 'An error occurred while updating password for `' . $id_adh .
929 '` | ' . $e->getMessage(),
939 * @param string $field Field name
943 private function getFieldLabel($field)
945 $label = $this->fields
[$field]['label'];
946 //remove trailing ':' and then nbsp (for french at least)
947 $label = trim(trim($label ??
'', ':'), ' ');
952 * Retrieve fields from database
954 * @param Db $zdb Database instance
958 public static function getDbFields(Db
$zdb)
960 $columns = $zdb->getColumns(self
::TABLE
);
962 foreach ($columns as $col) {
963 $fields[] = $col->getName();
969 * Mark as self membership
973 public function setSelfMembership()
975 $this->_self_adh
= true;
979 * Is member up to date?
983 public function isUp2Date()
985 if ($this->_deps
['dues']) {
986 if ($this->isDueFree()) {
987 //member is due free, he's up to date.
990 //let's check from end date, if present
991 if ($this->_due_date
== null) {
994 $ech = new \
DateTime($this->_due_date
);
995 $now = new \
DateTime();
996 $now->setTime(0, 0, 0);
1001 throw new \
RuntimeException(
1002 'Cannot check if member is up to date, dues deps is disabled!'
1010 * @param Preferences $preferences Preferences instance
1011 * @param array $fields Members fields configuration
1012 * @param History $history History instance
1016 public function setDependencies(
1017 Preferences
$preferences,
1021 $this->preferences
= $preferences;
1022 $this->fields
= $fields;
1023 $this->history
= $history;
1027 * Check posted values validity
1029 * @param array $values All values to check, basically the $_POST array
1030 * after sending the form
1031 * @param array $required Array of required fields
1032 * @param array $disabled Array of disabled fields
1034 * @return true|array
1036 public function check($values, $required, $disabled)
1038 $this->errors
= array();
1041 foreach ($values as &$rawvalue) {
1042 if (is_string($rawvalue)) {
1043 $rawvalue = strip_tags($rawvalue);
1047 $fields = self
::getDbFields($this->zdb
);
1049 //reset company name if needed
1050 if (!isset($values['is_company'])) {
1051 unset($values['is_company']);
1052 $values['societe_adh'] = '';
1055 //no parent if checkbox was unchecked
1057 !isset($values['attach'])
1058 && empty($this->_id
)
1059 && isset($values['parent_id'])
1061 unset($values['parent_id']);
1064 if (isset($values['duplicate'])) {
1065 //if we're duplicating, keep a trace (if an error occurs)
1066 $this->_duplicate
= true;
1069 foreach ($fields as $key) {
1070 //first, let's sanitize values
1071 $key = strtolower($key);
1072 $prop = '_' . $this->fields
[$key]['propname'];
1074 if (isset($values[$key])) {
1075 $value = $values[$key];
1076 if ($value !== true && $value !== false) {
1077 $value = trim($value ??
'');
1079 } elseif (empty($this->_id
)) {
1081 case 'bool_admin_adh':
1082 case 'bool_exempt_adh':
1083 case 'bool_display_info':
1086 case 'activite_adh':
1087 //values that are set at object instantiation
1090 case 'date_crea_adh':
1096 //values that are set at object instantiation
1097 $value = $this->$prop;
1104 //keep stored value on update
1105 if ($prop != '_password' ||
isset($values['mdp_adh']) && isset($values['mdp_adh2'])) {
1106 $value = $this->$prop;
1112 // if the field is enabled, check it
1113 if (!isset($disabled[$key])) {
1114 // fill up the adherent structure
1115 if ($value !== null && $value !== true && $value !== false && !is_object($value)) {
1116 $value = stripslashes($value);
1118 $this->$prop = $value;
1120 // now, check validity
1121 if ($value !== null && $value != '') {
1122 $this->validate($key, $value, $values);
1123 } elseif (empty($this->_id
)) {
1124 //ensure login and password are not empty
1125 if (($key == 'login_adh' ||
$key == 'mdp_adh') && !isset($required[$key])) {
1126 $p = new Password($this->zdb
);
1127 $generated_value = $p->makeRandomPassword(15);
1128 if ($key == 'login_adh') {
1129 //'@' is not permitted in logins
1130 $this->$prop = str_replace('@', 'a', $generated_value);
1132 $this->$prop = $generated_value;
1139 // missing required fields?
1140 foreach ($required as $key => $val) {
1141 $prop = '_' . $this->fields
[$key]['propname'];
1143 if (!isset($disabled[$key])) {
1144 $mandatory_missing = false;
1145 if (!isset($this->$prop) ||
$this->$prop == '') {
1146 $mandatory_missing = true;
1147 } elseif ($key === 'titre_adh' && $this->$prop == '-1') {
1148 $mandatory_missing = true;
1151 if ($mandatory_missing === true) {
1152 $this->errors
[] = str_replace(
1154 '<a href="#' . $key . '">' . $this->getFieldLabel($key) . '</a>',
1155 _T("- Mandatory field %field empty.")
1161 //attach to/detach from parent
1162 if (isset($values['detach_parent'])) {
1163 $this->_parent
= null;
1166 $this->dynamicsCheck($values, $required, $disabled);
1168 if (count($this->errors
) > 0) {
1170 'Some errors has been thew attempting to edit/store a member' . "\n" .
1171 print_r($this->errors
, true),
1174 return $this->errors
;
1179 'Member checked successfully.',
1187 * Validate data for given key
1188 * Set valid data in current object, also resets errors list
1190 * @param string $field Field name
1191 * @param mixed $value Value we want to set
1192 * @param array $values All values, for some references
1196 public function validate($field, $value, $values)
1198 global $preferences;
1200 $prop = '_' . $this->fields
[$field]['propname'];
1202 if ($value === null ||
(is_string($value) && trim($value) == '')) {
1203 //empty values are OK
1204 $this->$prop = $value;
1210 case 'date_crea_adh':
1211 case 'date_modif_adh_':
1213 case 'date_echeance':
1215 $d = \DateTime
::createFromFormat(__("Y-m-d"), $value);
1217 //try with non localized date
1218 $d = \DateTime
::createFromFormat("Y-m-d", $value);
1220 throw new \
Exception('Incorrect format');
1224 if ($field === 'ddn_adh') {
1225 $now = new \
DateTime();
1226 $now->setTime(0, 0, 0);
1227 $d->setTime(0, 0, 0);
1229 $diff = $now->diff($d);
1230 $days = (int)$diff->format('%R%a');
1232 $this->errors
[] = _T('- Birthdate must be set in the past!');
1235 $years = (int)$diff->format('%R%Y');
1236 if ($years <= -200) {
1237 $this->errors
[] = str_replace(
1240 _T('- Members must be less than 200 years old (currently %years)!')
1244 $this->$prop = $d->format('Y-m-d');
1245 } catch (Throwable
$e) {
1247 'Wrong date format. field: ' . $field .
1248 ', value: ' . $value . ', expected fmt: ' .
1249 __("Y-m-d") . ' | ' . $e->getMessage(),
1252 $this->errors
[] = str_replace(
1259 $this->getFieldLabel($field)
1261 _T("- Wrong date format (%date_format) for %field!")
1266 if ($value !== null && $value !== '') {
1267 if ($value == '-1') {
1268 $this->$prop = null;
1269 } elseif (!$value instanceof Title
) {
1270 $this->$prop = new Title((int)$value);
1273 $this->$prop = null;
1278 if (!GaletteMail
::isValidEmail($value)) {
1279 $this->errors
[] = _T("- Non-valid E-Mail address!") .
1280 ' (' . $this->getFieldLabel($field) . ')';
1282 if ($field == 'email_adh') {
1284 $select = $this->zdb
->select(self
::TABLE
);
1287 )->where(array('email_adh' => $value));
1288 if (!empty($this->_id
)) {
1290 self
::PK
. ' != ' . $this->_id
1294 $results = $this->zdb
->execute($select);
1295 if ($results->count() !== 0) {
1296 $this->errors
[] = _T("- This E-Mail address is already used by another member!");
1298 } catch (Throwable
$e) {
1300 'An error occurred checking member email unicity.',
1303 $this->errors
[] = _T("An error has occurred while looking if login already exists.");
1308 if ($value == 'http://') {
1310 } elseif (!isValidWebUrl($value)) {
1311 $this->errors
[] = _T("- Non-valid Website address! Maybe you've skipped the http://?");
1315 /** FIXME: add a preference for login lenght */
1316 if (strlen($value) < 2) {
1317 $this->errors
[] = str_replace(
1320 _T("- The username must be composed of at least %i characters!")
1323 //check if login does not contain the @ character
1324 if (strpos($value, '@') != false) {
1325 $this->errors
[] = _T("- The username cannot contain the @ character");
1327 //check if login is already taken
1329 $select = $this->zdb
->select(self
::TABLE
);
1332 )->where(array('login_adh' => $value));
1333 if (!empty($this->_id
)) {
1335 self
::PK
. ' != ' . $this->_id
1339 $results = $this->zdb
->execute($select);
1341 $results->count() !== 0
1342 ||
$value == $preferences->pref_admin_login
1344 $this->errors
[] = _T("- This username is already in use, please choose another one!");
1346 } catch (Throwable
$e) {
1348 'An error occurred checking member login unicity.',
1351 $this->errors
[] = _T("An error has occurred while looking if login already exists.");
1358 $this->_self_adh
!== true
1359 && (!isset($values['mdp_adh2'])
1360 ||
$values['mdp_adh2'] != $value)
1362 $this->errors
[] = _T("- The passwords don't match!");
1364 $this->_self_adh
=== true
1365 && !crypt($value, $values['mdp_crypt']) == $values['mdp_crypt']
1367 $this->errors
[] = _T("Password misrepeated: ");
1369 $pinfos = password_get_info($value);
1370 //check if value is already a hash
1371 if ($pinfos['algo'] == 0) {
1372 $this->$prop = password_hash(
1377 $pwcheck = new \Galette\Util\
Password($preferences);
1378 $pwcheck->setAdherent($this);
1379 if (!$pwcheck->isValid($value)) {
1380 $this->errors
= array_merge(
1382 $pwcheck->getErrors()
1390 $this->$prop = (int)$value;
1391 //check if status exists
1392 $select = $this->zdb
->select(Status
::TABLE
);
1393 $select->where(Status
::PK
. '= ' . $value);
1395 $results = $this->zdb
->execute($select);
1396 $result = $results->current();
1398 $this->errors
[] = str_replace(
1401 _T("Status #%id does not exists in database.")
1405 } catch (Throwable
$e) {
1407 'An error occurred checking status existance: ' . $e->getMessage(),
1410 $this->errors
[] = _T("An error has occurred while looking if status does exists.");
1414 if (in_array($value, [self
::NC
, self
::MAN
, self
::WOMAN
])) {
1415 $this->$prop = (int)$value;
1417 $this->errors
[] = _T("Gender %gender does not exists!");
1421 $this->$prop = ($value instanceof Adherent
) ?
(int)$value->id
: (int)$value;
1422 $this->loadParent();
1432 public function store()
1434 global $hist, $emitter, $login;
1437 if (!$login->isAdmin() && !$login->isStaff() && !$login->isGroupManager() && $this->id
== '') {
1438 if ($this->preferences
->pref_bool_create_member
) {
1439 $this->_parent
= $login->id
;
1445 $fields = self
::getDbFields($this->zdb
);
1447 foreach ($fields as $field) {
1449 $field !== 'date_modif_adh'
1450 ||
empty($this->_id
)
1452 $prop = '_' . $this->fields
[$field]['propname'];
1454 ($field === 'bool_admin_adh'
1455 ||
$field === 'bool_exempt_adh'
1456 ||
$field === 'bool_display_info'
1457 ||
$field === 'activite_adh')
1458 && $this->$prop === false
1460 //Handle booleans for postgres ; bugs #18899 and #19354
1461 $values[$field] = $this->zdb
->isPostgres() ?
'false' : 0;
1462 } elseif ($field === 'parent_id') {
1464 if ($this->_parent
=== null) {
1465 $values['parent_id'] = new Expression('NULL');
1466 } elseif ($this->parent
instanceof Adherent
) {
1467 $values['parent_id'] = $this->_parent
->id
;
1469 $values['parent_id'] = $this->_parent
;
1472 $values[$field] = $this->$prop;
1477 //an empty value will cause date to be set to 1901-01-01, a null
1478 //will result in 0000-00-00. We want a database NULL value here.
1479 if (!$this->_birthdate
) {
1480 $values['ddn_adh'] = new Expression('NULL');
1482 if (!$this->_due_date
) {
1483 $values['date_echeance'] = new Expression('NULL');
1486 if ($this->_title
instanceof Title
) {
1487 $values['titre_adh'] = $this->_title
->id
;
1489 $values['titre_adh'] = new Expression('NULL');
1492 if (!$this->_parent
) {
1493 $values['parent_id'] = new Expression('NULL');
1496 //fields that cannot be null
1498 '_surname' => 'prenom_adh',
1499 '_nickname' => 'pseudo_adh',
1500 '_address' => 'adresse_adh',
1501 '_zipcode' => 'cp_adh',
1502 '_town' => 'ville_adh'
1504 foreach ($notnull as $prop => $field) {
1505 if ($this->$prop === null) {
1506 $values[$field] = '';
1511 if (empty($this->_id
)) {
1512 //we're inserting a new member
1513 unset($values[self
::PK
]);
1514 //set modification date
1515 $this->_modification_date
= date('Y-m-d');
1516 $values['date_modif_adh'] = $this->_modification_date
;
1518 $insert = $this->zdb
->insert(self
::TABLE
);
1519 $insert->values($values);
1520 $add = $this->zdb
->execute($insert);
1521 if ($add->count() > 0) {
1522 $this->_id
= $this->zdb
->getLastGeneratedValue($this);
1523 $this->_picture
= new Picture($this->_id
);
1525 if ($this->_self_adh
) {
1527 _T("Self_subscription as a member: ") .
1528 $this->getNameWithCase($this->_name
, $this->_surname
),
1533 _T("Member card added"),
1539 $event = 'member.add';
1541 $hist->add(_T("Fail to add new member."));
1542 throw new \
Exception(
1543 'An error occurred inserting new member!'
1547 //we're editing an existing member
1548 if (!$this->isDueFree()) {
1550 $due_date = Contribution
::getDueDate($this->zdb
, $this->_id
);
1552 $values['date_echeance'] = $due_date;
1556 if (!$this->_password
) {
1557 unset($values['mdp_adh']);
1560 $update = $this->zdb
->update(self
::TABLE
);
1561 $update->set($values);
1563 self
::PK
. '=' . $this->_id
1566 $edit = $this->zdb
->execute($update);
1568 //edit == 0 does not mean there were an error, but that there
1569 //were nothing to change
1570 if ($edit->count() > 0) {
1571 $this->updateModificationDate();
1573 _T("Member card updated"),
1578 $event = 'member.edit';
1583 $success = $this->dynamicsStore();
1586 //send event at the end of process, once all has been stored
1587 if ($event !== null) {
1588 $emitter->emit($event, $this);
1591 } catch (Throwable
$e) {
1593 'Something went wrong :\'( | ' . $e->getMessage() . "\n" .
1594 $e->getTraceAsString(),
1602 * Update member modification date
1606 private function updateModificationDate()
1609 $modif_date = date('Y-m-d');
1610 $update = $this->zdb
->update(self
::TABLE
);
1612 array('date_modif_adh' => $modif_date)
1613 )->where(self
::PK
. '=' . $this->_id
);
1615 $edit = $this->zdb
->execute($update);
1616 $this->_modification_date
= $modif_date;
1617 } catch (Throwable
$e) {
1619 'Something went wrong updating modif date :\'( | ' .
1620 $e->getMessage() . "\n" . $e->getTraceAsString(),
1627 * Global getter method
1629 * @param string $name name of the property we want to retrive
1631 * @return false|object the called property
1633 public function __get($name)
1636 'admin', 'staff', 'due_free', 'appears_in_list', 'active',
1637 'row_classes', 'oldness', 'duplicate'
1639 if (!defined('GALETTE_TESTS')) {
1640 $forbidden[] = 'password'; //keep that for tests only
1644 'sadmin', 'sstaff', 'sdue_free', 'sappears_in_list', 'sactive',
1645 'stitle', 'sstatus', 'sfullname', 'sname', 'saddress',
1646 'rbirthdate', 'sgender', 'contribstatus'
1649 if (in_array($name, $forbidden)) {
1652 return $this->isAdmin();
1654 return $this->isStaff();
1656 return $this->isDueFree();
1657 case 'appears_in_list':
1658 return $this->appearsInMembersList();
1660 return $this->isActive();
1662 return $this->isDuplicate();
1664 throw new \
RuntimeException("Call to __get for '$name' is forbidden!");
1667 if (in_array($name, $virtuals)) {
1668 if (substr($name, 0, 1) !== '_') {
1669 $real = '_' . substr($name, 1);
1676 case 'sappears_in_list':
1678 return (($this->$real) ?
_T("Yes") : _T("No"));
1681 return (($this->$real) ?
_T("Active") : _T("Inactive"));
1684 if (isset($this->_title
) && $this->_title
instanceof Title
) {
1685 return $this->_title
->tshort
;
1691 $status = new Status($this->zdb
);
1692 return $status->getLabel($this->_status
);
1695 return $this->getNameWithCase(
1698 (isset($this->_title
) ?
$this->title
: false)
1702 $address = $this->_address
;
1703 if ($this->_address_continuation
!== '' && $this->_address_continuation
!== null) {
1704 $address .= "\n" . $this->_address_continuation
;
1706 return htmlspecialchars($address, ENT_QUOTES
);
1709 return $this->getNameWithCase($this->_name
, $this->_surname
);
1712 return $this->_birthdate
;
1715 switch ($this->gender
) {
1721 return _T('Unspecified');
1724 case 'contribstatus':
1725 return $this->getDues();
1729 if (substr($name, 0, 1) !== '_') {
1730 $rname = '_' . $name;
1738 if ($this->$rname !== null) {
1739 return (int)$this->$rname;
1745 case 'address_continuation':
1746 return $this->$rname ??
'';
1749 case 'creation_date':
1750 case 'modification_date':
1752 if ($this->$rname != '') {
1754 $d = new \
DateTime($this->$rname);
1755 return $d->format(__("Y-m-d"));
1756 } catch (Throwable
$e) {
1757 //oops, we've got a bad date :/
1759 'Bad date (' . $this->$rname . ') | ' .
1763 return $this->$rname;
1768 return ($this->_parent
instanceof Adherent
) ?
(int)$this->_parent
->id
: (int)$this->_parent
;
1771 if (!property_exists($this, $rname)) {
1773 "Unknown property '$rname'",
1778 return $this->$rname;
1788 * If member does not have an email address, but is attached to
1789 * another member, we'll take information from its parent.
1793 public function getEmail()
1795 $email = $this->_email
;
1796 if (empty($email)) {
1797 $this->loadParent();
1798 $email = $this->parent
->email
;
1805 * Get member address.
1806 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1810 public function getAddress()
1812 $address = $this->_address
;
1813 if (empty($address) && $this->hasParent()) {
1814 $this->loadParent();
1815 $address = $this->parent
->address
;
1822 * Get member address continuation.
1823 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1827 public function getAddressContinuation()
1829 $address = $this->_address
;
1830 $address_continuation = $this->_address_continuation
;
1831 if (empty($address) && $this->hasParent()) {
1832 $this->loadParent();
1833 $address_continuation = $this->parent
->address_continuation
;
1836 return $address_continuation;
1840 * Get member zipcode.
1841 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1845 public function getZipcode()
1847 $address = $this->_address
;
1848 $zip = $this->_zipcode
;
1849 if (empty($address) && $this->hasParent()) {
1850 $this->loadParent();
1851 $zip = $this->parent
->zipcode
;
1859 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1863 public function getTown()
1865 $address = $this->_address
;
1866 $town = $this->_town
;
1867 if (empty($address) && $this->hasParent()) {
1868 $this->loadParent();
1869 $town = $this->parent
->town
;
1876 * Get member country.
1877 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1881 public function getCountry()
1883 $address = $this->_address
;
1884 $country = $this->_country
;
1885 if (empty($address) && $this->hasParent()) {
1886 $this->loadParent();
1887 $country = $this->parent
->country
;
1898 public function getAge()
1900 if ($this->_birthdate
== null) {
1904 $d = \DateTime
::createFromFormat('Y-m-d', $this->_birthdate
);
1907 'Invalid birthdate: ' . $this->_birthdate
,
1915 $d->diff(new \
DateTime())->y
,
1916 _T(' (%age years old)')
1921 * Get parent inherited fields
1925 public function getParentFields()
1927 return $this->parent_fields
;
1931 * Handle files (photo and dynamics files)
1933 * @param array $files Files sent
1935 * @return array|true
1937 public function handleFiles($files)
1941 if (isset($files['photo'])) {
1942 if ($files['photo']['error'] === UPLOAD_ERR_OK
) {
1943 if ($files['photo']['tmp_name'] != '') {
1944 if (is_uploaded_file($files['photo']['tmp_name'])) {
1945 $res = $this->picture
->store($files['photo']);
1948 = $this->picture
->getErrorMessage($res);
1952 } elseif ($files['photo']['error'] !== UPLOAD_ERR_NO_FILE
) {
1954 $this->picture
->getPhpErrorMessage($files['photo']['error']),
1957 $this->errors
[] = $this->picture
->getPhpErrorMessage(
1958 $files['photo']['error']
1962 $this->dynamicsFiles($files);
1964 if (count($this->errors
) > 0) {
1966 'Some errors has been thew attempting to edit/store a member files' . "\n" .
1967 print_r($this->errors
, true),
1970 return $this->errors
;
1977 * Set member as duplicate
1981 public function setDuplicate()
1983 //mark as duplicated
1984 $this->_duplicate
= true;
1985 $infos = $this->_others_infos_admin
;
1986 $this->_others_infos_admin
= str_replace(
1988 [$this->sname
, $this->_id
],
1989 _T('Duplicated from %name (%id)')
1991 if (!empty($infos)) {
1992 $this->_others_infos_admin
.= "\n" . $infos;
1996 //drop email, must be unique
1997 $this->_email
= null;
1998 //drop creation date
1999 $this->_creation_date
= date("Y-m-d");
2001 $this->_login
= null;
2003 $this->_picture
= new Picture();
2005 $this->_birthdate
= null;
2007 $this->_surname
= null;
2009 $this->_admin
= false;
2011 $this->_due_free
= false;
2015 * Get current errors
2019 public function getErrors()
2021 return $this->errors
;
2029 public function getGroups()
2031 return $this->_groups
;
2035 * Get user managed groups
2039 public function getManagedGroups()
2041 return $this->_managed_groups
;
2045 * Can current logged-in user create member
2047 * @param Login $login Login instance
2051 public function canCreate(Login
$login): bool
2053 global $preferences;
2055 if ($this->id
&& $login->id
== $this->id ||
$login->isAdmin() ||
$login->isStaff()) {
2059 if ($preferences->pref_bool_create_member
&& $login->isLogged()) {
2067 * Can current logged-in user edit member
2069 * @param Login $login Login instance
2073 public function canEdit(Login
$login): bool
2075 //admin and staff users can edit, as well as member itself
2076 if ($this->id
&& $login->id
== $this->id ||
$login->isAdmin() ||
$login->isStaff()) {
2080 //parent can edit their child cards
2081 if ($this->hasParent() && $this->parent_id
=== $login->id
) {
2085 //group managers can edit members of groups they manage
2086 if ($login->isGroupManager()) {
2087 foreach ($this->getGroups() as $g) {
2088 if ($login->isGroupManager($g->getId())) {
2098 * Can current logged-in user display member
2100 * @param Login $login Login instance
2104 public function canShow(Login
$login): bool
2106 return $this->canEdit($login);
2110 * Are we currently duplicated a member?
2114 public function isDuplicate(): bool
2116 return $this->_duplicate
;
2120 * Flag creation mail sending
2122 * @param boolean $send True (default) to send creation email
2126 public function setSendmail($send = true): self
2128 $this->sendmail
= $send;
2133 * Should we send administrative emails to member?
2137 public function sendEMail()
2139 return $this->sendmail
;
2145 * @param integer $id Parent identifier
2149 public function setParent(int $id): self
2151 $this->_parent
= $id;
2152 $this->loadParent();
2157 * Reset dependencies to load
2161 public function disableAllDeps(): self
2163 foreach ($this->_deps
as &$dep) {
2170 * Enable all dependencies to load
2174 public function enableAllDeps(): self
2176 foreach ($this->_deps
as &$dep) {
2183 * Enable a load dependency
2185 * @param string $name Dependency name
2189 public function enableDep(string $name): self
2191 if (!isset($this->_deps
[$name])) {
2193 'dependency ' . $name . ' does not exists!',
2197 $this->_deps
[$name] = true;
2204 * Enable a load dependency
2206 * @param string $name Dependency name
2210 public function disableDep(string $name): self
2212 if (!isset($this->_deps
[$name])) {
2214 'dependency ' . $name . ' does not exists!',
2218 $this->_deps
[$name] = false;