3 /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
6 * Member class for galette
10 * Copyright © 2009-2021 The Galette Team
12 * This file is part of Galette (http://galette.tuxfamily.org).
14 * Galette is free software: you can redistribute it and/or modify
15 * it under the terms of the GNU General Public License as published by
16 * the Free Software Foundation, either version 3 of the License, or
17 * (at your option) any later version.
19 * Galette is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 * GNU General Public License for more details.
24 * You should have received a copy of the GNU General Public License
25 * along with Galette. If not, see <http://www.gnu.org/licenses/>.
30 * @author Johan Cwiklinski <johan@x-tnd.be>
31 * @copyright 2009-2021 The Galette Team
32 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL License 3.0 or (at your option) any later version
33 * @link http://galette.tuxfamily.org
34 * @since Available since 0.7dev - 2009-06-02
37 namespace Galette\Entity
;
39 use Galette\Features\Socials
;
42 use Laminas\Db\Sql\Expression
;
44 use Galette\Core\Picture
;
45 use Galette\Core\GaletteMail
;
46 use Galette\Core\Password
;
47 use Galette\Core\Preferences
;
48 use Galette\Core\History
;
49 use Galette\Repository\Groups
;
50 use Galette\Core\Login
;
51 use Galette\Repository\Members
;
52 use Galette\Features\Dynamics
;
55 * Member class for galette
60 * @author Johan Cwiklinski <johan@x-tnd.be>
61 * @copyright 2009-2021 The Galette Team
62 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL License 3.0 or (at your option) any later version
63 * @link http://galette.tuxfamily.org
64 * @since Available since 0.7dev - 02-06-2009
66 * @property integer $id
67 * @property integer|Title $title Either a title id or an instance of Title
68 * @property string $stitle Title label
69 * @property string company_name
70 * @property string $name
71 * @property string $surname
72 * @property string $nickname
73 * @property string $birthdate Localized birth date
74 * @property string $rbirthdate Raw birth date
75 * @property string $birth_place
76 * @property integer $gender
77 * @property string $sgender Gender label
78 * @property string $job
79 * @property string $language
80 * @property integer $status
81 * @property string $sstatus Status label
82 * @property string $address
83 * @property string $address_continuation
84 * @property string $zipcode
85 * @property string $town
86 * @property string $country
87 * @property string $phone
88 * @property string $gsm
89 * @property string $email
90 * @property string $gnupgid
91 * @property string $fingerprint
92 * @property string $login
93 * @property string $creation_date Localized creation date
94 * @property string $modification_date Localized modification date
95 * @property string $due_date Localized due date
96 * @property string $others_infos
97 * @property string $others_infos_admin
98 * @property Picture $picture
99 * @property array $groups
100 * @property array $managed_groups
101 * @property integer|Adherent $parent Parent id if parent dep is not loaded, Adherent instance otherwise
102 * @property array $children
103 * @property boolean $admin better to rely on isAdmin()
104 * @property boolean $staff better to rely on isStaff()
105 * @property boolean $due_free better to rely on isDueFree()
106 * @property boolean $appears_in_list better to rely on appearsInMembersList()
107 * @property boolean $active better to rely on isActive()
108 * @property boolean $duplicate better to rely on isDuplicate()
109 * @property string $sadmin yes/no
110 * @property string $sstaff yes/no
111 * @property string $sdue_free yes/no
112 * @property string $sappears_in_list yes/no
113 * @property string $sactive yes/no
114 * @property string $sfullname
115 * @property string $sname
116 * @property string $saddress Concatened address and continuation
117 * @property string $contribstatus State of member contributions
118 * @property string $days_remaining
119 * @property-read integer $parent_id
120 * @property Social $social Social networks/Contact
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 $_fingerprint;
167 //Galette relative information
168 private $_appears_in_list;
174 private $_creation_date;
175 private $_modification_date;
177 private $_others_infos;
178 private $_others_infos_admin;
181 private $_days_remaining;
183 private $_managed_groups;
186 private $_duplicate = false;
189 private $_row_classes;
191 private $_self_adh = false;
192 private $_deps = array(
203 private $preferences;
207 private $parent_fields = [
215 private $errors = [];
217 private $sendmail = false;
220 * Default constructor
222 * @param Db $zdb Database instance
223 * @param mixed $args Either a ResultSet row, its id or its
224 * login or its email for to load s specific
225 * member, or null to just instantiate object
226 * @param false|array $deps Dependencies configuration, see Adherent::$_deps
228 public function __construct(Db
$zdb, $args = null, $deps = null)
234 if ($deps !== null) {
235 if (is_array($deps)) {
236 $this->_deps
= array_merge(
240 } elseif ($deps === false) {
242 $this->_deps
= array_fill_keys(
243 array_keys($this->_deps
),
248 '$deps should be an array, ' . gettype($deps) . ' given!',
254 if ($args == null ||
is_int($args)) {
255 if (is_int($args) && $args > 0) {
258 $this->_active
= true;
259 $this->_language
= $i18n->getID();
260 $this->_creation_date
= date("Y-m-d");
261 $this->_status
= $this->getDefaultStatus();
262 $this->_title
= null;
263 $this->_gender
= self
::NC
;
264 $gp = new Password($this->zdb
);
265 $this->_password
= $gp->makeRandomPassword();
266 $this->_picture
= new Picture();
267 $this->_admin
= false;
268 $this->_staff
= false;
269 $this->_due_free
= false;
270 $this->_appears_in_list
= false;
271 $this->_parent
= null;
273 if ($this->_deps
['dynamics'] === true) {
274 $this->loadDynamicFields();
277 } elseif (is_object($args)) {
278 $this->loadFromRS($args);
279 } elseif (is_string($args)) {
280 $this->loadFromLoginOrMail($args);
285 * Loads a member from its id
287 * @param int $id the identifier for the member to load
289 * @return bool true if query succeed, false otherwise
291 public function load($id)
294 $select = $this->zdb
->select(self
::TABLE
, 'a');
297 array('b' => PREFIX_DB
. Status
::TABLE
),
298 'a.' . Status
::PK
. '=b.' . Status
::PK
,
299 array('priorite_statut')
300 )->where(array(self
::PK
=> $id));
302 $results = $this->zdb
->execute($select);
304 if ($results->count() === 0) {
308 $this->loadFromRS($results->current());
310 } catch (Throwable
$e) {
312 'Cannot load member form id `' . $id . '` | ' . $e->getMessage(),
320 * Loads a member from its login
322 * @param string $login login for the member to load
324 * @return bool true if query succeed, false otherwise
326 public function loadFromLoginOrMail($login)
329 $select = $this->zdb
->select(self
::TABLE
);
330 if (GaletteMail
::isValidEmail($login)) {
331 //we got a valid email address, use it
332 $select->where(array('email_adh' => $login));
334 ///we did not get an email address, consider using login
335 $select->where(array('login_adh' => $login));
338 $results = $this->zdb
->execute($select);
339 $result = $results->current();
341 $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)
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) ?
true : false;
380 $this->_status
= (int)$r->id_statut
;
381 //Contact information
382 $this->_address
= $r->adresse_adh
;
383 /** TODO: remove and merge with address */
384 $this->_address_continuation
= $r->adresse2_adh
;
385 $this->_zipcode
= $r->cp_adh
;
386 $this->_town
= $r->ville_adh
;
387 $this->_country
= $r->pays_adh
;
388 $this->_phone
= $r->tel_adh
;
389 $this->_gsm
= $r->gsm_adh
;
390 $this->_email
= $r->email_adh
;
391 $this->_gnupgid
= $r->gpgid
;
392 $this->_fingerprint
= $r->fingerprint
;
393 //Galette relative information
394 $this->_appears_in_list
= ($r->bool_display_info
== 1) ?
true : false;
395 $this->_admin
= ($r->bool_admin_adh
== 1) ?
true : false;
397 isset($r->priorite_statut
)
398 && $r->priorite_statut
< Members
::NON_STAFF_MEMBERS
400 $this->_staff
= true;
402 $this->_due_free
= ($r->bool_exempt_adh
== 1) ?
true : false;
403 $this->_login
= $r->login_adh
;
404 $this->_password
= $r->mdp_adh
;
405 $this->_creation_date
= $r->date_crea_adh
;
406 if ($r->date_modif_adh
!= '1901-01-01') {
407 $this->_modification_date
= $r->date_modif_adh
;
409 $this->_modification_date
= $this->_creation_date
;
411 $this->_due_date
= $r->date_echeance
;
412 $this->_others_infos
= $r->info_public_adh
;
413 $this->_others_infos_admin
= $r->info_adh
;
415 if ($r->parent_id
!== null) {
416 $this->_parent
= (int)$r->parent_id
;
417 if ($this->_deps
['parent'] === true) {
422 if ($this->_deps
['children'] === true) {
423 $this->loadChildren();
426 if ($this->_deps
['picture'] === true) {
427 $this->_picture
= new Picture($this->_id
);
430 if ($this->_deps
['groups'] === true) {
434 if ($this->_deps
['dues'] === true) {
438 if ($this->_deps
['dynamics'] === true) {
439 $this->loadDynamicFields();
442 if ($this->_deps
['socials'] === true) {
443 $this->loadSocials();
452 private function loadParent()
454 if (!$this->_parent
instanceof Adherent
) {
455 $deps = array_fill_keys(array_keys($this->_deps
), false);
456 $this->_parent
= new Adherent($this->zdb
, (int)$this->_parent
, $deps);
461 * Load member children
465 private function loadChildren()
467 $this->_children
= array();
470 $select = $this->zdb
->select(self
::TABLE
);
474 'parent_id = ' . $this->_id
477 $results = $this->zdb
->execute($select);
479 if ($results->count() > 0) {
480 foreach ($results as $row) {
481 $deps = $this->_deps
;
482 $deps['children'] = false;
483 $deps['parent'] = false;
484 $this->_children
[] = new Adherent($this->zdb
, (int)$row->$id, $deps);
487 } catch (Throwable
$e) {
489 'Cannot load children for member #' . $this->_id
. ' | ' .
502 public function loadGroups()
504 $this->_groups
= Groups
::loadGroups($this->_id
);
505 $this->_managed_groups
= Groups
::loadManagedGroups($this->_id
);
509 * Load member social network/contact information
513 public function loadSocials()
515 $this->_socials
= Social
::getListForMember($this->_id
);
519 * Retrieve status from preferences
521 * @return pref_statut
524 private function getDefaultStatus()
527 if ($preferences->pref_statut
!= '') {
528 return $preferences->pref_statut
;
531 'Unable to get pref_statut; is it defined in preferences?',
534 return Status
::DEFAULT_STATUS
;
539 * Check for dues status
543 private function checkDues()
545 //how many days since our beloved member has been created
546 $date_now = new \
DateTime();
547 $this->_oldness
= $date_now->diff(
548 new \
DateTime($this->_creation_date
)
551 if ($this->isDueFree()) {
552 //no fee required, we don't care about dates
553 $this->_row_classes
.= ' cotis-exempt';
555 //ok, fee is required. Let's check the dates
556 if ($this->_due_date
== '') {
557 $this->_row_classes
.= ' cotis-never';
559 $date_end = new \
DateTime($this->_due_date
);
560 $date_diff = $date_now->diff($date_end);
561 $this->_days_remaining
= ($date_diff->invert
== 1)
562 ?
$date_diff->days
* -1
565 if ($this->_days_remaining
== 0) {
566 $this->_row_classes
.= ' cotis-lastday';
567 } elseif ($this->_days_remaining
< 0) {
568 //check if member is still active
569 $this->_row_classes
.= $this->isActive() ?
' cotis-late' : ' cotis-old';
570 } elseif ($this->_days_remaining
< 30) {
571 $this->_row_classes
.= ' cotis-soon';
573 $this->_row_classes
.= ' cotis-ok';
584 public function isAdmin()
586 return $this->_admin
;
590 * Is user member of staff?
594 public function isStaff()
596 return $this->_staff
;
600 * Is member freed of dues?
604 public function isDueFree()
606 return $this->_due_free
;
610 * Is member in specified group?
612 * @param string $group_name Group name
616 public function isGroupMember($group_name)
618 if (is_array($this->_groups
)) {
619 foreach ($this->_groups
as $g) {
620 if ($g->getName() == $group_name) {
627 'Calling ' . __METHOD__
. ' without groups loaded!',
635 * Is member manager of specified group?
637 * @param string $group_name Group name
641 public function isGroupManager($group_name)
643 if (is_array($this->_managed_groups
)) {
644 foreach ($this->_managed_groups
as $mg) {
645 if ($mg->getName() == $group_name) {
652 'Calling ' . __METHOD__
. ' without groups loaded!',
660 * Does current member represents a company?
664 public function isCompany()
666 return trim($this->_company_name ??
'') != '';
670 * Is current member a man?
674 public function isMan()
676 return (int)$this->_gender
=== self
::MAN
;
680 * Is current member a woman?
684 public function isWoman()
686 return (int)$this->_gender
=== self
::WOMAN
;
691 * Can member appears in public members list?
695 public function appearsInMembersList()
697 return $this->_appears_in_list
;
705 public function isActive()
707 return $this->_active
;
711 * Does member have uploaded a picture?
715 public function hasPicture()
717 return $this->_picture
->hasPicture();
721 * Does member have a parent?
725 public function hasParent()
727 return !empty($this->_parent
);
731 * Does member have children?
735 public function hasChildren()
737 if ($this->_children
=== null) {
740 'Children has not been loaded!',
746 return count($this->_children
) > 0;
751 * Get row class related to current fee status
753 * @param boolean $public we want the class for public pages
755 * @return string the class to apply
757 public function getRowClass($public = false)
759 $strclass = ($this->isActive()) ?
'active' : 'inactive';
760 if ($public === false) {
761 $strclass .= $this->_row_classes
;
767 * Get current member due status
769 * @return string i18n string representing state of due
771 public function getDues()
774 $date_now = new \
DateTime();
775 if ($this->isDueFree()) {
776 $ret = _T("Freed of dues");
777 } elseif ($this->_due_date
== '') {
778 $patterns = array('/%days/', '/%date/');
779 $cdate = new \
DateTime($this->_creation_date
);
782 $cdate->format(__("Y-m-d"))
784 if ($this->_active
) {
788 _T("Never contributed: Registered %days days ago (since %date)")
791 $ret = _T("Never contributed");
793 } elseif ($this->_days_remaining
== 0) {
794 $ddate = new \
DateTime($this->_due_date
);
795 $date_diff = $date_now->diff($ddate);
796 if ($date_diff->invert
== 0) {
797 $ret = _T("Last day!");
799 $ret = _T("Late since today!");
801 } elseif ($this->_days_remaining
< 0) {
802 $ddate = new \
DateTime($this->_due_date
);
803 $patterns = array('/%days/', '/%date/');
805 $this->_days_remaining
* -1,
806 $ddate->format(__("Y-m-d"))
808 if ($this->_active
) {
812 _T("Late of %days days (since %date)")
815 $ret = _T("No longer member");
818 $ddate = new \
DateTime($this->_due_date
);
819 $patterns = array('/%days/', '/%date/');
821 $this->_days_remaining
,
822 $ddate->format(__("Y-m-d"))
827 _T("%days days remaining (ending on %date)")
834 * Retrieve Full name and surname for the specified member id
836 * @param Db $zdb Database instance
837 * @param integer $id Member id
838 * @param boolean $wid Add member id
839 * @param boolean $wnick Add member nickname
841 * @return string formatted Name and Surname
843 public static function getSName($zdb, $id, $wid = false, $wnick = false)
846 $select = $zdb->select(self
::TABLE
);
847 $select->where(self
::PK
. ' = ' . $id);
849 $results = $zdb->execute($select);
850 $row = $results->current();
851 return self
::getNameWithCase(
855 ($wid === true ?
$row->id_adh
: false),
856 ($wnick === true ?
$row->pseudo_adh
: false)
858 } catch (Throwable
$e) {
860 'Cannot get formatted name for member form id `' . $id . '` | ' .
869 * Get member name with correct case
871 * @param string $name Member name
872 * @param string $surname Mmeber surname
873 * @param false|Title $title Member title to show or false
874 * @param false|integer $id Member id to display or false
875 * @param false|string $nick Member nickname to display or false
879 public static function getNameWithCase($name, $surname, $title = false, $id = false, $nick = false)
883 if ($title !== false && $title instanceof Title
) {
884 $str .= $title->tshort
. ' ';
887 $str .= mb_strtoupper($name ??
'', 'UTF-8') . ' ' .
888 ucwords(mb_strtolower($surname ??
'', 'UTF-8'), " \t\r\n\f\v-_|");
890 if ($id !== false ||
$nick !== false) {
893 if ($nick !== false) {
897 if ($nick !== false && !empty($nick)) {
902 if ($id !== false ||
$nick !== false) {
905 return strip_tags($str);
909 * Change password for a given user
911 * @param Db $zdb Database instance
912 * @param string $id_adh Member identifier
913 * @param string $pass New password
917 public static function updatePassword(Db
$zdb, $id_adh, $pass)
920 $cpass = password_hash($pass, PASSWORD_BCRYPT
);
922 $update = $zdb->update(self
::TABLE
);
924 array('mdp_adh' => $cpass)
925 )->where(self
::PK
. ' = ' . $id_adh);
926 $zdb->execute($update);
928 'Password for `' . $id_adh . '` has been updated.',
932 } catch (Throwable
$e) {
934 'An error occurred while updating password for `' . $id_adh .
935 '` | ' . $e->getMessage(),
945 * @param string $field Field name
949 private function getFieldLabel($field)
951 $label = $this->fields
[$field]['label'];
953 $label = str_replace(' ', ' ', $label);
954 //remove trailing ':' and then trim
955 $label = trim(trim($label ??
'', ':'));
960 * Retrieve fields from database
962 * @param Db $zdb Database instance
966 public static function getDbFields(Db
$zdb)
968 $columns = $zdb->getColumns(self
::TABLE
);
970 foreach ($columns as $col) {
971 $fields[] = $col->getName();
977 * Mark as self membership
981 public function setSelfMembership()
983 $this->_self_adh
= true;
987 * Is member up to date?
991 public function isUp2Date()
993 if ($this->_deps
['dues']) {
994 if ($this->isDueFree()) {
995 //member is due free, he's up to date.
998 //let's check from end date, if present
999 if ($this->_due_date
== null) {
1002 $ech = new \
DateTime($this->_due_date
);
1003 $now = new \
DateTime();
1004 $now->setTime(0, 0, 0);
1005 return $ech >= $now;
1009 throw new \
RuntimeException(
1010 'Cannot check if member is up to date, dues deps is disabled!'
1018 * @param Preferences $preferences Preferences instance
1019 * @param array $fields Members fields configuration
1020 * @param History $history History instance
1024 public function setDependencies(
1025 Preferences
$preferences,
1029 $this->preferences
= $preferences;
1030 $this->fields
= $fields;
1031 $this->history
= $history;
1035 * Check posted values validity
1037 * @param array $values All values to check, basically the $_POST array
1038 * after sending the form
1039 * @param array $required Array of required fields
1040 * @param array $disabled Array of disabled fields
1042 * @return true|array
1044 public function check($values, $required, $disabled)
1046 $this->errors
= array();
1049 foreach ($values as &$rawvalue) {
1050 if (is_string($rawvalue)) {
1051 $rawvalue = strip_tags($rawvalue);
1055 $fields = self
::getDbFields($this->zdb
);
1057 //reset company name if needed
1058 if (!isset($values['is_company'])) {
1059 unset($values['is_company']);
1060 $values['societe_adh'] = '';
1063 //no parent if checkbox was unchecked
1065 !isset($values['attach'])
1066 && empty($this->_id
)
1067 && isset($values['parent_id'])
1069 unset($values['parent_id']);
1072 if (isset($values['duplicate'])) {
1073 //if we're duplicating, keep a trace (if an error occurs)
1074 $this->_duplicate
= true;
1077 foreach ($fields as $key) {
1078 //first, let's sanitize values
1079 $key = strtolower($key);
1080 $prop = '_' . $this->fields
[$key]['propname'];
1082 if (isset($values[$key])) {
1083 $value = $values[$key];
1084 if ($value !== true && $value !== false) {
1085 $value = trim($value ??
'');
1087 } elseif (empty($this->_id
)) {
1089 case 'bool_admin_adh':
1090 case 'bool_exempt_adh':
1091 case 'bool_display_info':
1094 case 'activite_adh':
1095 //values that are set at object instantiation
1098 case 'date_crea_adh':
1104 //values that are set at object instantiation
1105 $value = $this->$prop;
1115 //keep stored value on update
1116 if ($prop != '_password' ||
isset($values['mdp_adh']) && isset($values['mdp_adh2'])) {
1117 $value = $this->$prop;
1123 // if the field is enabled, check it
1124 if (!isset($disabled[$key])) {
1125 // fill up the adherent structure
1126 if ($value !== null && $value !== true && $value !== false && !is_object($value)) {
1127 $value = stripslashes($value);
1129 $this->$prop = $value;
1131 // now, check validity
1132 if ($value !== null && $value != '') {
1133 if ($key !== 'mdp_adh') {
1134 $this->validate($key, $value, $values);
1136 } elseif (empty($this->_id
)) {
1137 //ensure login and password are not empty
1138 if (($key == 'login_adh' ||
$key == 'mdp_adh') && !isset($required[$key])) {
1139 $p = new Password($this->zdb
);
1140 $generated_value = $p->makeRandomPassword(15);
1141 if ($key == 'login_adh') {
1142 //'@' is not permitted in logins
1143 $this->$prop = str_replace('@', 'a', $generated_value);
1145 $this->$prop = $generated_value;
1152 //password checks need data to be previously set
1153 if (isset($values['mdp_adh'])) {
1154 $this->validate('mdp_adh', $values['mdp_adh'], $values);
1157 // missing required fields?
1158 foreach ($required as $key => $val) {
1159 $prop = '_' . $this->fields
[$key]['propname'];
1161 if (!isset($disabled[$key])) {
1162 $mandatory_missing = false;
1163 if (!isset($this->$prop) ||
$this->$prop == '') {
1164 $mandatory_missing = true;
1165 } elseif ($key === 'titre_adh' && $this->$prop == '-1') {
1166 $mandatory_missing = true;
1169 if ($mandatory_missing === true) {
1170 $this->errors
[] = str_replace(
1172 '<a href="#' . $key . '">' . $this->getFieldLabel($key) . '</a>',
1173 _T("- Mandatory field %field empty.")
1179 //attach to/detach from parent
1180 if (isset($values['detach_parent'])) {
1181 $this->_parent
= null;
1184 $this->dynamicsCheck($values, $required, $disabled);
1185 $this->checkSocials($values);
1187 if (count($this->errors
) > 0) {
1189 'Some errors has been thew attempting to edit/store a member' . "\n" .
1190 print_r($this->errors
, true),
1193 return $this->errors
;
1198 'Member checked successfully.',
1206 * Validate data for given key
1207 * Set valid data in current object, also resets errors list
1209 * @param string $field Field name
1210 * @param mixed $value Value we want to set
1211 * @param array $values All values, for some references
1215 public function validate($field, $value, $values)
1217 global $preferences;
1219 $prop = '_' . $this->fields
[$field]['propname'];
1221 if ($value === null ||
(is_string($value) && trim($value) == '')) {
1222 //empty values are OK
1223 $this->$prop = $value;
1229 case 'date_crea_adh':
1230 case 'date_modif_adh_':
1232 case 'date_echeance':
1234 $d = \DateTime
::createFromFormat(__("Y-m-d"), $value);
1236 //try with non localized date
1237 $d = \DateTime
::createFromFormat("Y-m-d", $value);
1239 throw new \
Exception('Incorrect format');
1243 if ($field === 'ddn_adh') {
1244 $now = new \
DateTime();
1245 $now->setTime(0, 0, 0);
1246 $d->setTime(0, 0, 0);
1248 $diff = $now->diff($d);
1249 $days = (int)$diff->format('%R%a');
1251 $this->errors
[] = _T('- Birthdate must be set in the past!');
1254 $years = (int)$diff->format('%R%Y');
1255 if ($years <= -200) {
1256 $this->errors
[] = str_replace(
1259 _T('- Members must be less than 200 years old (currently %years)!')
1263 $this->$prop = $d->format('Y-m-d');
1264 } catch (Throwable
$e) {
1266 'Wrong date format. field: ' . $field .
1267 ', value: ' . $value . ', expected fmt: ' .
1268 __("Y-m-d") . ' | ' . $e->getMessage(),
1271 $this->errors
[] = str_replace(
1278 $this->getFieldLabel($field)
1280 _T("- Wrong date format (%date_format) for %field!")
1285 if ($value !== null && $value !== '') {
1286 if ($value == '-1') {
1287 $this->$prop = null;
1288 } elseif (!$value instanceof Title
) {
1289 $this->$prop = new Title((int)$value);
1292 $this->$prop = null;
1296 if (!GaletteMail
::isValidEmail($value)) {
1297 $this->errors
[] = _T("- Non-valid E-Mail address!") .
1298 ' (' . $this->getFieldLabel($field) . ')';
1300 if ($field == 'email_adh') {
1302 $select = $this->zdb
->select(self
::TABLE
);
1305 )->where(array('email_adh' => $value));
1306 if (!empty($this->_id
)) {
1308 self
::PK
. ' != ' . $this->_id
1312 $results = $this->zdb
->execute($select);
1313 if ($results->count() !== 0) {
1314 $this->errors
[] = _T("- This E-Mail address is already used by another member!");
1316 } catch (Throwable
$e) {
1318 'An error occurred checking member email unicity.',
1321 $this->errors
[] = _T("An error has occurred while looking if login already exists.");
1326 /** FIXME: add a preference for login length */
1327 if (strlen($value) < 2) {
1328 $this->errors
[] = str_replace(
1331 _T("- The username must be composed of at least %i characters!")
1334 //check if login does not contain the @ character
1335 if (strpos($value, '@') != false) {
1336 $this->errors
[] = _T("- The username cannot contain the @ character");
1338 //check if login is already taken
1340 $select = $this->zdb
->select(self
::TABLE
);
1343 )->where(array('login_adh' => $value));
1344 if (!empty($this->_id
)) {
1346 self
::PK
. ' != ' . $this->_id
1350 $results = $this->zdb
->execute($select);
1352 $results->count() !== 0
1353 ||
$value == $preferences->pref_admin_login
1355 $this->errors
[] = _T("- This username is already in use, please choose another one!");
1357 } catch (Throwable
$e) {
1359 'An error occurred checking member login uniqueness.',
1362 $this->errors
[] = _T("An error has occurred while looking if login already exists.");
1369 $this->_self_adh
!== true
1370 && (!isset($values['mdp_adh2'])
1371 ||
$values['mdp_adh2'] != $value)
1373 $this->errors
[] = _T("- The passwords don't match!");
1375 $this->_self_adh
=== true
1376 && !crypt($value, $values['mdp_crypt']) == $values['mdp_crypt']
1378 $this->errors
[] = _T("Password misrepeated: ");
1380 $pinfos = password_get_info($value);
1381 //check if value is already a hash
1382 if ($pinfos['algo'] == 0) {
1383 $this->$prop = password_hash(
1388 $pwcheck = new \Galette\Util\
Password($preferences);
1389 $pwcheck->setAdherent($this);
1390 if (!$pwcheck->isValid($value)) {
1391 $this->errors
= array_merge(
1393 $pwcheck->getErrors()
1401 $this->$prop = (int)$value;
1402 //check if status exists
1403 $select = $this->zdb
->select(Status
::TABLE
);
1404 $select->where(Status
::PK
. '= ' . $value);
1406 $results = $this->zdb
->execute($select);
1407 $result = $results->current();
1409 $this->errors
[] = str_replace(
1412 _T("Status #%id does not exists in database.")
1416 } catch (Throwable
$e) {
1418 'An error occurred checking status existence: ' . $e->getMessage(),
1421 $this->errors
[] = _T("An error has occurred while looking if status does exists.");
1425 if (in_array($value, [self
::NC
, self
::MAN
, self
::WOMAN
])) {
1426 $this->$prop = (int)$value;
1428 $this->errors
[] = _T("Gender %gender does not exists!");
1432 $this->$prop = ($value instanceof Adherent
) ?
(int)$value->id
: (int)$value;
1433 $this->loadParent();
1443 public function store()
1445 global $hist, $emitter, $login;
1448 if (!$login->isAdmin() && !$login->isStaff() && !$login->isGroupManager() && $this->id
== '') {
1449 if ($this->preferences
->pref_bool_create_member
) {
1450 $this->_parent
= $login->id
;
1456 $fields = self
::getDbFields($this->zdb
);
1458 foreach ($fields as $field) {
1460 $field !== 'date_modif_adh'
1461 ||
empty($this->_id
)
1463 $prop = '_' . $this->fields
[$field]['propname'];
1465 ($field === 'bool_admin_adh'
1466 ||
$field === 'bool_exempt_adh'
1467 ||
$field === 'bool_display_info'
1468 ||
$field === 'activite_adh')
1469 && $this->$prop === false
1471 //Handle booleans for postgres ; bugs #18899 and #19354
1472 $values[$field] = $this->zdb
->isPostgres() ?
'false' : 0;
1473 } elseif ($field === 'parent_id') {
1475 if ($this->_parent
=== null) {
1476 $values['parent_id'] = new Expression('NULL');
1477 } elseif ($this->parent
instanceof Adherent
) {
1478 $values['parent_id'] = $this->_parent
->id
;
1480 $values['parent_id'] = $this->_parent
;
1483 $values[$field] = $this->$prop;
1488 //an empty value will cause date to be set to 1901-01-01, a null
1489 //will result in 0000-00-00. We want a database NULL value here.
1490 if (!$this->_birthdate
) {
1491 $values['ddn_adh'] = new Expression('NULL');
1493 if (!$this->_due_date
) {
1494 $values['date_echeance'] = new Expression('NULL');
1497 if ($this->_title
instanceof Title
) {
1498 $values['titre_adh'] = $this->_title
->id
;
1500 $values['titre_adh'] = new Expression('NULL');
1503 if (!$this->_parent
) {
1504 $values['parent_id'] = new Expression('NULL');
1507 //fields that cannot be null
1509 '_surname' => 'prenom_adh',
1510 '_nickname' => 'pseudo_adh',
1511 '_address' => 'adresse_adh',
1512 '_zipcode' => 'cp_adh',
1513 '_town' => 'ville_adh'
1515 foreach ($notnull as $prop => $field) {
1516 if ($this->$prop === null) {
1517 $values[$field] = '';
1522 if (empty($this->_id
)) {
1523 //we're inserting a new member
1524 unset($values[self
::PK
]);
1525 //set modification date
1526 $this->_modification_date
= date('Y-m-d');
1527 $values['date_modif_adh'] = $this->_modification_date
;
1529 $insert = $this->zdb
->insert(self
::TABLE
);
1530 $insert->values($values);
1531 $add = $this->zdb
->execute($insert);
1532 if ($add->count() > 0) {
1533 $this->_id
= $this->zdb
->getLastGeneratedValue($this);
1534 $this->_picture
= new Picture($this->_id
);
1536 if ($this->_self_adh
) {
1538 _T("Self_subscription as a member: ") .
1539 $this->getNameWithCase($this->_name
, $this->_surname
),
1544 _T("Member card added"),
1550 $event = 'member.add';
1552 $hist->add(_T("Fail to add new member."));
1553 throw new \
Exception(
1554 'An error occurred inserting new member!'
1558 //we're editing an existing member
1559 if (!$this->isDueFree()) {
1561 $due_date = Contribution
::getDueDate($this->zdb
, $this->_id
);
1563 $values['date_echeance'] = $due_date;
1567 if (!$this->_password
) {
1568 unset($values['mdp_adh']);
1571 $update = $this->zdb
->update(self
::TABLE
);
1572 $update->set($values);
1574 self
::PK
. '=' . $this->_id
1577 $edit = $this->zdb
->execute($update);
1579 //edit == 0 does not mean there were an error, but that there
1580 //were nothing to change
1581 if ($edit->count() > 0) {
1582 $this->updateModificationDate();
1584 _T("Member card updated"),
1589 $event = 'member.edit';
1594 $success = $this->dynamicsStore();
1595 $this->storeSocials($this->id
);
1598 //send event at the end of process, once all has been stored
1599 if ($event !== null) {
1600 $emitter->emit($event, $this);
1603 } catch (Throwable
$e) {
1605 'Something went wrong :\'( | ' . $e->getMessage() . "\n" .
1606 $e->getTraceAsString(),
1614 * Update member modification date
1618 private function updateModificationDate()
1621 $modif_date = date('Y-m-d');
1622 $update = $this->zdb
->update(self
::TABLE
);
1624 array('date_modif_adh' => $modif_date)
1625 )->where(self
::PK
. '=' . $this->_id
);
1627 $edit = $this->zdb
->execute($update);
1628 $this->_modification_date
= $modif_date;
1629 } catch (Throwable
$e) {
1631 'Something went wrong updating modif date :\'( | ' .
1632 $e->getMessage() . "\n" . $e->getTraceAsString(),
1640 * Global getter method
1642 * @param string $name name of the property we want to retrieve
1644 * @return false|object the called property
1646 public function __get($name)
1649 'admin', 'staff', 'due_free', 'appears_in_list', 'active',
1650 'row_classes', 'oldness', 'duplicate'
1652 if (!defined('GALETTE_TESTS')) {
1653 $forbidden[] = 'password'; //keep that for tests only
1657 'sadmin', 'sstaff', 'sdue_free', 'sappears_in_list', 'sactive',
1658 'stitle', 'sstatus', 'sfullname', 'sname', 'saddress',
1659 'rbirthdate', 'sgender', 'contribstatus',
1662 $socials = array('website', 'msn', 'jabber', 'icq');
1664 if (in_array($name, $forbidden)) {
1667 return $this->isAdmin();
1669 return $this->isStaff();
1671 return $this->isDueFree();
1672 case 'appears_in_list':
1673 return $this->appearsInMembersList();
1675 return $this->isActive();
1677 return $this->isDuplicate();
1679 throw new \
RuntimeException("Call to __get for '$name' is forbidden!");
1683 if (in_array($name, $virtuals)) {
1684 if (substr($name, 0, 1) !== '_') {
1685 $real = '_' . substr($name, 1);
1692 case 'sappears_in_list':
1694 return (($this->$real) ?
_T("Yes") : _T("No"));
1697 return (($this->$real) ?
_T("Active") : _T("Inactive"));
1700 if (isset($this->_title
) && $this->_title
instanceof Title
) {
1701 return $this->_title
->tshort
;
1707 $status = new Status($this->zdb
);
1708 return $status->getLabel($this->_status
);
1711 return $this->getNameWithCase(
1714 (isset($this->_title
) ?
$this->title
: false)
1718 $address = $this->_address
;
1719 if ($this->_address_continuation
!== '' && $this->_address_continuation
!== null) {
1720 $address .= "\n" . $this->_address_continuation
;
1722 return htmlspecialchars($address, ENT_QUOTES
);
1725 return $this->getNameWithCase($this->_name
, $this->_surname
);
1728 return $this->_birthdate
;
1731 switch ($this->gender
) {
1737 return _T('Unspecified');
1740 case 'contribstatus':
1741 return $this->getDues();
1746 //for backward compatibility
1747 if (in_array($name, $socials)) {
1748 $values = Social
::getListForMember($this->_id
, $name);
1749 return $values[0] ??
null;
1752 if (substr($name, 0, 1) !== '_') {
1753 $rname = '_' . $name;
1761 if ($this->$rname !== null) {
1762 return (int)$this->$rname;
1768 case 'address_continuation':
1769 return $this->$rname ??
'';
1772 case 'creation_date':
1773 case 'modification_date':
1775 if ($this->$rname != '') {
1777 $d = new \
DateTime($this->$rname);
1778 return $d->format(__("Y-m-d"));
1779 } catch (Throwable
$e) {
1780 //oops, we've got a bad date :/
1782 'Bad date (' . $this->$rname . ') | ' .
1786 return $this->$rname;
1791 return ($this->_parent
instanceof Adherent
) ?
(int)$this->_parent
->id
: (int)$this->_parent
;
1794 if (!property_exists($this, $rname)) {
1796 "Unknown property '$rname'",
1801 return $this->$rname;
1809 * If member does not have an email address, but is attached to
1810 * another member, we'll take information from its parent.
1814 public function getEmail()
1816 $email = $this->_email
;
1817 if (empty($email)) {
1818 $this->loadParent();
1819 $email = $this->parent
->email
;
1826 * Get member address.
1827 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1831 public function getAddress()
1833 $address = $this->_address
;
1834 if (empty($address) && $this->hasParent()) {
1835 $this->loadParent();
1836 $address = $this->parent
->address
;
1843 * Get member address continuation.
1844 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1848 public function getAddressContinuation()
1850 $address = $this->_address
;
1851 $address_continuation = $this->_address_continuation
;
1852 if (empty($address) && $this->hasParent()) {
1853 $this->loadParent();
1854 $address_continuation = $this->parent
->address_continuation
;
1857 return $address_continuation;
1861 * Get member zipcode.
1862 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1866 public function getZipcode()
1868 $address = $this->_address
;
1869 $zip = $this->_zipcode
;
1870 if (empty($address) && $this->hasParent()) {
1871 $this->loadParent();
1872 $zip = $this->parent
->zipcode
;
1880 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1884 public function getTown()
1886 $address = $this->_address
;
1887 $town = $this->_town
;
1888 if (empty($address) && $this->hasParent()) {
1889 $this->loadParent();
1890 $town = $this->parent
->town
;
1897 * Get member country.
1898 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1902 public function getCountry()
1904 $address = $this->_address
;
1905 $country = $this->_country
;
1906 if (empty($address) && $this->hasParent()) {
1907 $this->loadParent();
1908 $country = $this->parent
->country
;
1919 public function getAge()
1921 if ($this->_birthdate
== null) {
1925 $d = \DateTime
::createFromFormat('Y-m-d', $this->_birthdate
);
1928 'Invalid birthdate: ' . $this->_birthdate
,
1936 $d->diff(new \
DateTime())->y
,
1937 _T(' (%age years old)')
1942 * Get parent inherited fields
1946 public function getParentFields()
1948 return $this->parent_fields
;
1952 * Handle files (photo and dynamics files)
1954 * @param array $files Files sent
1956 * @return array|true
1958 public function handleFiles($files)
1962 if (isset($files['photo'])) {
1963 if ($files['photo']['error'] === UPLOAD_ERR_OK
) {
1964 if ($files['photo']['tmp_name'] != '') {
1965 if (is_uploaded_file($files['photo']['tmp_name'])) {
1966 $res = $this->picture
->store($files['photo']);
1969 = $this->picture
->getErrorMessage($res);
1973 } elseif ($files['photo']['error'] !== UPLOAD_ERR_NO_FILE
) {
1975 $this->picture
->getPhpErrorMessage($files['photo']['error']),
1978 $this->errors
[] = $this->picture
->getPhpErrorMessage(
1979 $files['photo']['error']
1983 $this->dynamicsFiles($files);
1985 if (count($this->errors
) > 0) {
1987 'Some errors has been thew attempting to edit/store a member files' . "\n" .
1988 print_r($this->errors
, true),
1991 return $this->errors
;
1998 * Set member as duplicate
2002 public function setDuplicate()
2004 //mark as duplicated
2005 $this->_duplicate
= true;
2006 $infos = $this->_others_infos_admin
;
2007 $this->_others_infos_admin
= str_replace(
2009 [$this->sname
, $this->_id
],
2010 _T('Duplicated from %name (%id)')
2012 if (!empty($infos)) {
2013 $this->_others_infos_admin
.= "\n" . $infos;
2017 //drop email, must be unique
2018 $this->_email
= null;
2019 //drop creation date
2020 $this->_creation_date
= date("Y-m-d");
2022 $this->_login
= null;
2024 $this->_picture
= new Picture();
2026 $this->_birthdate
= null;
2028 $this->_surname
= null;
2030 $this->_admin
= false;
2032 $this->_due_free
= false;
2036 * Get current errors
2040 public function getErrors()
2042 return $this->errors
;
2050 public function getGroups()
2052 return $this->_groups
;
2056 * Get user managed groups
2060 public function getManagedGroups()
2062 return $this->_managed_groups
;
2066 * Can current logged-in user create member
2068 * @param Login $login Login instance
2072 public function canCreate(Login
$login): bool
2074 global $preferences;
2076 if ($this->id
&& $login->id
== $this->id ||
$login->isAdmin() ||
$login->isStaff()) {
2080 if ($preferences->pref_bool_create_member
&& $login->isLogged()) {
2088 * Can current logged-in user edit member
2090 * @param Login $login Login instance
2094 public function canEdit(Login
$login): bool
2096 //admin and staff users can edit, as well as member itself
2097 if ($this->id
&& $login->id
== $this->id ||
$login->isAdmin() ||
$login->isStaff()) {
2101 //parent can edit their child cards
2102 if ($this->hasParent() && $this->parent_id
=== $login->id
) {
2106 //group managers can edit members of groups they manage
2107 if ($login->isGroupManager()) {
2108 foreach ($this->getGroups() as $g) {
2109 if ($login->isGroupManager($g->getId())) {
2119 * Can current logged-in user display member
2121 * @param Login $login Login instance
2125 public function canShow(Login
$login): bool
2127 return $this->canEdit($login);
2131 * Are we currently duplicated a member?
2135 public function isDuplicate(): bool
2137 return $this->_duplicate
;
2141 * Flag creation mail sending
2143 * @param boolean $send True (default) to send creation email
2147 public function setSendmail($send = true): self
2149 $this->sendmail
= $send;
2154 * Should we send administrative emails to member?
2158 public function sendEMail()
2160 return $this->sendmail
;
2166 * @param integer $id Parent identifier
2170 public function setParent(int $id): self
2172 $this->_parent
= $id;
2173 $this->loadParent();
2178 * Reset dependencies to load
2182 public function disableAllDeps(): self
2184 foreach ($this->_deps
as &$dep) {
2191 * Enable all dependencies to load
2195 public function enableAllDeps(): self
2197 foreach ($this->_deps
as &$dep) {
2204 * Enable a load dependency
2206 * @param string $name Dependency name
2210 public function enableDep(string $name): self
2212 if (!isset($this->_deps
[$name])) {
2214 'dependency ' . $name . ' does not exists!',
2218 $this->_deps
[$name] = true;
2225 * Enable a load dependency
2227 * @param string $name Dependency name
2231 public function disableDep(string $name): self
2233 if (!isset($this->_deps
[$name])) {
2235 'dependency ' . $name . ' does not exists!',
2239 $this->_deps
[$name] = false;