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 */
169 private $_fingerprint;
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 instantiate 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 should 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 if ($this->isDueFree()) {
772 $ret = _T("Freed of dues");
773 } elseif ($this->_due_date
== '') {
774 $patterns = array('/%days/', '/%date/');
775 $cdate = new \
DateTime($this->_creation_date
);
778 $cdate->format(__("Y-m-d"))
780 if ($this->_active
) {
784 _T("Never contributed: Registered %days days ago (since %date)")
787 $ret = _T("Never contributed");
789 } elseif ($this->_days_remaining
== 0) {
790 $ddate = new \
DateTime($this->_due_date
);
791 $date_diff = $date_now->diff($ddate);
792 if ($date_diff->invert
== 0) {
793 $ret = _T("Last day!");
795 $ret = _T("Late since today!");
797 } elseif ($this->_days_remaining
< 0) {
798 $ddate = new \
DateTime($this->_due_date
);
799 $patterns = array('/%days/', '/%date/');
801 $this->_days_remaining
* -1,
802 $ddate->format(__("Y-m-d"))
804 if ($this->_active
) {
808 _T("Late of %days days (since %date)")
811 $ret = _T("No longer member");
814 $ddate = new \
DateTime($this->_due_date
);
815 $patterns = array('/%days/', '/%date/');
817 $this->_days_remaining
,
818 $ddate->format(__("Y-m-d"))
823 _T("%days days remaining (ending on %date)")
830 * Retrieve Full name and surname for the specified member id
832 * @param Db $zdb Database instance
833 * @param integer $id Member id
834 * @param boolean $wid Add member id
835 * @param boolean $wnick Add member nickname
837 * @return string formatted Name and Surname
839 public static function getSName($zdb, $id, $wid = false, $wnick = false)
842 $select = $zdb->select(self
::TABLE
);
843 $select->where(self
::PK
. ' = ' . $id);
845 $results = $zdb->execute($select);
846 $row = $results->current();
847 return self
::getNameWithCase(
851 ($wid === true ?
$row->id_adh
: false),
852 ($wnick === true ?
$row->pseudo_adh
: false)
854 } catch (Throwable
$e) {
856 'Cannot get formatted name for member form id `' . $id . '` | ' .
865 * Get member name with correct case
867 * @param string $name Member name
868 * @param string $surname Mmeber surname
869 * @param false|Title $title Member title to show or false
870 * @param false|integer $id Member id to display or false
871 * @param false|string $nick Member nickname to display or false
875 public static function getNameWithCase($name, $surname, $title = false, $id = false, $nick = false)
879 if ($title !== false && $title instanceof Title
) {
880 $str .= $title->tshort
. ' ';
883 $str .= mb_strtoupper($name ??
'', 'UTF-8') . ' ' .
884 ucwords(mb_strtolower($surname ??
'', 'UTF-8'), " \t\r\n\f\v-_|");
886 if ($id !== false ||
$nick !== false) {
889 if ($nick !== false) {
893 if ($nick !== false && !empty($nick)) {
898 if ($id !== false ||
$nick !== false) {
901 return strip_tags($str);
905 * Change password for a given user
907 * @param Db $zdb Database instance
908 * @param string $id_adh Member identifier
909 * @param string $pass New password
913 public static function updatePassword(Db
$zdb, $id_adh, $pass)
916 $cpass = password_hash($pass, PASSWORD_BCRYPT
);
918 $update = $zdb->update(self
::TABLE
);
920 array('mdp_adh' => $cpass)
921 )->where(self
::PK
. ' = ' . $id_adh);
922 $zdb->execute($update);
924 'Password for `' . $id_adh . '` has been updated.',
928 } catch (Throwable
$e) {
930 'An error occurred while updating password for `' . $id_adh .
931 '` | ' . $e->getMessage(),
941 * @param string $field Field name
945 private function getFieldLabel($field)
947 $label = $this->fields
[$field]['label'];
949 $label = str_replace(' ', ' ', $label);
950 //remove trailing ':' and then trim
951 $label = trim(trim($label ??
'', ':'));
956 * Retrieve fields from database
958 * @param Db $zdb Database instance
962 public static function getDbFields(Db
$zdb)
964 $columns = $zdb->getColumns(self
::TABLE
);
966 foreach ($columns as $col) {
967 $fields[] = $col->getName();
973 * Mark as self membership
977 public function setSelfMembership()
979 $this->_self_adh
= true;
983 * Is member up to date?
987 public function isUp2Date()
989 if ($this->_deps
['dues']) {
990 if ($this->isDueFree()) {
991 //member is due free, he's up to date.
994 //let's check from end date, if present
995 if ($this->_due_date
== null) {
998 $ech = new \
DateTime($this->_due_date
);
999 $now = new \
DateTime();
1000 $now->setTime(0, 0, 0);
1001 return $ech >= $now;
1005 throw new \
RuntimeException(
1006 'Cannot check if member is up to date, dues deps is disabled!'
1014 * @param Preferences $preferences Preferences instance
1015 * @param array $fields Members fields configuration
1016 * @param History $history History instance
1020 public function setDependencies(
1021 Preferences
$preferences,
1025 $this->preferences
= $preferences;
1026 $this->fields
= $fields;
1027 $this->history
= $history;
1031 * Check posted values validity
1033 * @param array $values All values to check, basically the $_POST array
1034 * after sending the form
1035 * @param array $required Array of required fields
1036 * @param array $disabled Array of disabled fields
1038 * @return true|array
1040 public function check($values, $required, $disabled)
1042 $this->errors
= array();
1045 foreach ($values as &$rawvalue) {
1046 if (is_string($rawvalue)) {
1047 $rawvalue = strip_tags($rawvalue);
1051 $fields = self
::getDbFields($this->zdb
);
1053 //reset company name if needed
1054 if (!isset($values['is_company'])) {
1055 unset($values['is_company']);
1056 $values['societe_adh'] = '';
1059 //no parent if checkbox was unchecked
1061 !isset($values['attach'])
1062 && empty($this->_id
)
1063 && isset($values['parent_id'])
1065 unset($values['parent_id']);
1068 if (isset($values['duplicate'])) {
1069 //if we're duplicating, keep a trace (if an error occurs)
1070 $this->_duplicate
= true;
1073 foreach ($fields as $key) {
1074 //first, let's sanitize values
1075 $key = strtolower($key);
1076 $prop = '_' . $this->fields
[$key]['propname'];
1078 if (isset($values[$key])) {
1079 $value = $values[$key];
1080 if ($value !== true && $value !== false) {
1081 $value = trim($value ??
'');
1083 } elseif (empty($this->_id
)) {
1085 case 'bool_admin_adh':
1086 case 'bool_exempt_adh':
1087 case 'bool_display_info':
1090 case 'activite_adh':
1091 //values that are set at object instantiation
1094 case 'date_crea_adh':
1100 //values that are set at object instantiation
1101 $value = $this->$prop;
1111 //keep stored value on update
1112 if ($prop != '_password' ||
isset($values['mdp_adh']) && isset($values['mdp_adh2'])) {
1113 $value = $this->$prop;
1119 // if the field is enabled, check it
1120 if (!isset($disabled[$key])) {
1121 // fill up the adherent structure
1122 if ($value !== null && $value !== true && $value !== false && !is_object($value)) {
1123 $value = stripslashes($value);
1125 $this->$prop = $value;
1127 // now, check validity
1128 if ($value !== null && $value != '') {
1129 $this->validate($key, $value, $values);
1130 } elseif (empty($this->_id
)) {
1131 //ensure login and password are not empty
1132 if (($key == 'login_adh' ||
$key == 'mdp_adh') && !isset($required[$key])) {
1133 $p = new Password($this->zdb
);
1134 $generated_value = $p->makeRandomPassword(15);
1135 if ($key == 'login_adh') {
1136 //'@' is not permitted in logins
1137 $this->$prop = str_replace('@', 'a', $generated_value);
1139 $this->$prop = $generated_value;
1146 // missing required fields?
1147 foreach ($required as $key => $val) {
1148 $prop = '_' . $this->fields
[$key]['propname'];
1150 if (!isset($disabled[$key])) {
1151 $mandatory_missing = false;
1152 if (!isset($this->$prop) ||
$this->$prop == '') {
1153 $mandatory_missing = true;
1154 } elseif ($key === 'titre_adh' && $this->$prop == '-1') {
1155 $mandatory_missing = true;
1158 if ($mandatory_missing === true) {
1159 $this->errors
[] = str_replace(
1161 '<a href="#' . $key . '">' . $this->getFieldLabel($key) . '</a>',
1162 _T("- Mandatory field %field empty.")
1168 //attach to/detach from parent
1169 if (isset($values['detach_parent'])) {
1170 $this->_parent
= null;
1173 $this->dynamicsCheck($values, $required, $disabled);
1175 if (count($this->errors
) > 0) {
1177 'Some errors has been thew attempting to edit/store a member' . "\n" .
1178 print_r($this->errors
, true),
1181 return $this->errors
;
1186 'Member checked successfully.',
1194 * Validate data for given key
1195 * Set valid data in current object, also resets errors list
1197 * @param string $field Field name
1198 * @param mixed $value Value we want to set
1199 * @param array $values All values, for some references
1203 public function validate($field, $value, $values)
1205 global $preferences;
1207 $prop = '_' . $this->fields
[$field]['propname'];
1209 if ($value === null ||
(is_string($value) && trim($value) == '')) {
1210 //empty values are OK
1211 $this->$prop = $value;
1217 case 'date_crea_adh':
1218 case 'date_modif_adh_':
1220 case 'date_echeance':
1222 $d = \DateTime
::createFromFormat(__("Y-m-d"), $value);
1224 //try with non localized date
1225 $d = \DateTime
::createFromFormat("Y-m-d", $value);
1227 throw new \
Exception('Incorrect format');
1231 if ($field === 'ddn_adh') {
1232 $now = new \
DateTime();
1233 $now->setTime(0, 0, 0);
1234 $d->setTime(0, 0, 0);
1236 $diff = $now->diff($d);
1237 $days = (int)$diff->format('%R%a');
1239 $this->errors
[] = _T('- Birthdate must be set in the past!');
1242 $years = (int)$diff->format('%R%Y');
1243 if ($years <= -200) {
1244 $this->errors
[] = str_replace(
1247 _T('- Members must be less than 200 years old (currently %years)!')
1251 $this->$prop = $d->format('Y-m-d');
1252 } catch (Throwable
$e) {
1254 'Wrong date format. field: ' . $field .
1255 ', value: ' . $value . ', expected fmt: ' .
1256 __("Y-m-d") . ' | ' . $e->getMessage(),
1259 $this->errors
[] = str_replace(
1266 $this->getFieldLabel($field)
1268 _T("- Wrong date format (%date_format) for %field!")
1273 if ($value !== null && $value !== '') {
1274 if ($value == '-1') {
1275 $this->$prop = null;
1276 } elseif (!$value instanceof Title
) {
1277 $this->$prop = new Title((int)$value);
1280 $this->$prop = null;
1285 if (!GaletteMail
::isValidEmail($value)) {
1286 $this->errors
[] = _T("- Non-valid E-Mail address!") .
1287 ' (' . $this->getFieldLabel($field) . ')';
1289 if ($field == 'email_adh') {
1291 $select = $this->zdb
->select(self
::TABLE
);
1294 )->where(array('email_adh' => $value));
1295 if (!empty($this->_id
)) {
1297 self
::PK
. ' != ' . $this->_id
1301 $results = $this->zdb
->execute($select);
1302 if ($results->count() !== 0) {
1303 $this->errors
[] = _T("- This E-Mail address is already used by another member!");
1305 } catch (Throwable
$e) {
1307 'An error occurred checking member email unicity.',
1310 $this->errors
[] = _T("An error has occurred while looking if login already exists.");
1315 if ($value == 'http://' ||
$value == 'https://') {
1317 } elseif (!isValidWebUrl($value)) {
1318 $this->errors
[] = _T("- Non-valid Website address! Maybe you've skipped the http://?");
1322 /** FIXME: add a preference for login length */
1323 if (strlen($value) < 2) {
1324 $this->errors
[] = str_replace(
1327 _T("- The username must be composed of at least %i characters!")
1330 //check if login does not contain the @ character
1331 if (strpos($value, '@') != false) {
1332 $this->errors
[] = _T("- The username cannot contain the @ character");
1334 //check if login is already taken
1336 $select = $this->zdb
->select(self
::TABLE
);
1339 )->where(array('login_adh' => $value));
1340 if (!empty($this->_id
)) {
1342 self
::PK
. ' != ' . $this->_id
1346 $results = $this->zdb
->execute($select);
1348 $results->count() !== 0
1349 ||
$value == $preferences->pref_admin_login
1351 $this->errors
[] = _T("- This username is already in use, please choose another one!");
1353 } catch (Throwable
$e) {
1355 'An error occurred checking member login uniqueness.',
1358 $this->errors
[] = _T("An error has occurred while looking if login already exists.");
1365 $this->_self_adh
!== true
1366 && (!isset($values['mdp_adh2'])
1367 ||
$values['mdp_adh2'] != $value)
1369 $this->errors
[] = _T("- The passwords don't match!");
1371 $this->_self_adh
=== true
1372 && !crypt($value, $values['mdp_crypt']) == $values['mdp_crypt']
1374 $this->errors
[] = _T("Password misrepeated: ");
1376 $pinfos = password_get_info($value);
1377 //check if value is already a hash
1378 if ($pinfos['algo'] == 0) {
1379 $this->$prop = password_hash(
1384 $pwcheck = new \Galette\Util\
Password($preferences);
1385 $pwcheck->setAdherent($this);
1386 if (!$pwcheck->isValid($value)) {
1387 $this->errors
= array_merge(
1389 $pwcheck->getErrors()
1397 $this->$prop = (int)$value;
1398 //check if status exists
1399 $select = $this->zdb
->select(Status
::TABLE
);
1400 $select->where(Status
::PK
. '= ' . $value);
1402 $results = $this->zdb
->execute($select);
1403 $result = $results->current();
1405 $this->errors
[] = str_replace(
1408 _T("Status #%id does not exists in database.")
1412 } catch (Throwable
$e) {
1414 'An error occurred checking status existence: ' . $e->getMessage(),
1417 $this->errors
[] = _T("An error has occurred while looking if status does exists.");
1421 if (in_array($value, [self
::NC
, self
::MAN
, self
::WOMAN
])) {
1422 $this->$prop = (int)$value;
1424 $this->errors
[] = _T("Gender %gender does not exists!");
1428 $this->$prop = ($value instanceof Adherent
) ?
(int)$value->id
: (int)$value;
1429 $this->loadParent();
1439 public function store()
1441 global $hist, $emitter, $login;
1444 if (!$login->isAdmin() && !$login->isStaff() && !$login->isGroupManager() && $this->id
== '') {
1445 if ($this->preferences
->pref_bool_create_member
) {
1446 $this->_parent
= $login->id
;
1452 $fields = self
::getDbFields($this->zdb
);
1454 foreach ($fields as $field) {
1456 $field !== 'date_modif_adh'
1457 ||
empty($this->_id
)
1459 $prop = '_' . $this->fields
[$field]['propname'];
1461 ($field === 'bool_admin_adh'
1462 ||
$field === 'bool_exempt_adh'
1463 ||
$field === 'bool_display_info'
1464 ||
$field === 'activite_adh')
1465 && $this->$prop === false
1467 //Handle booleans for postgres ; bugs #18899 and #19354
1468 $values[$field] = $this->zdb
->isPostgres() ?
'false' : 0;
1469 } elseif ($field === 'parent_id') {
1471 if ($this->_parent
=== null) {
1472 $values['parent_id'] = new Expression('NULL');
1473 } elseif ($this->parent
instanceof Adherent
) {
1474 $values['parent_id'] = $this->_parent
->id
;
1476 $values['parent_id'] = $this->_parent
;
1479 $values[$field] = $this->$prop;
1484 //an empty value will cause date to be set to 1901-01-01, a null
1485 //will result in 0000-00-00. We want a database NULL value here.
1486 if (!$this->_birthdate
) {
1487 $values['ddn_adh'] = new Expression('NULL');
1489 if (!$this->_due_date
) {
1490 $values['date_echeance'] = new Expression('NULL');
1493 if ($this->_title
instanceof Title
) {
1494 $values['titre_adh'] = $this->_title
->id
;
1496 $values['titre_adh'] = new Expression('NULL');
1499 if (!$this->_parent
) {
1500 $values['parent_id'] = new Expression('NULL');
1503 //fields that cannot be null
1505 '_surname' => 'prenom_adh',
1506 '_nickname' => 'pseudo_adh',
1507 '_address' => 'adresse_adh',
1508 '_zipcode' => 'cp_adh',
1509 '_town' => 'ville_adh'
1511 foreach ($notnull as $prop => $field) {
1512 if ($this->$prop === null) {
1513 $values[$field] = '';
1518 if (empty($this->_id
)) {
1519 //we're inserting a new member
1520 unset($values[self
::PK
]);
1521 //set modification date
1522 $this->_modification_date
= date('Y-m-d');
1523 $values['date_modif_adh'] = $this->_modification_date
;
1525 $insert = $this->zdb
->insert(self
::TABLE
);
1526 $insert->values($values);
1527 $add = $this->zdb
->execute($insert);
1528 if ($add->count() > 0) {
1529 $this->_id
= $this->zdb
->getLastGeneratedValue($this);
1530 $this->_picture
= new Picture($this->_id
);
1532 if ($this->_self_adh
) {
1534 _T("Self_subscription as a member: ") .
1535 $this->getNameWithCase($this->_name
, $this->_surname
),
1540 _T("Member card added"),
1546 $event = 'member.add';
1548 $hist->add(_T("Fail to add new member."));
1549 throw new \
Exception(
1550 'An error occurred inserting new member!'
1554 //we're editing an existing member
1555 if (!$this->isDueFree()) {
1557 $due_date = Contribution
::getDueDate($this->zdb
, $this->_id
);
1559 $values['date_echeance'] = $due_date;
1563 if (!$this->_password
) {
1564 unset($values['mdp_adh']);
1567 $update = $this->zdb
->update(self
::TABLE
);
1568 $update->set($values);
1570 self
::PK
. '=' . $this->_id
1573 $edit = $this->zdb
->execute($update);
1575 //edit == 0 does not mean there were an error, but that there
1576 //were nothing to change
1577 if ($edit->count() > 0) {
1578 $this->updateModificationDate();
1580 _T("Member card updated"),
1585 $event = 'member.edit';
1590 $success = $this->dynamicsStore();
1593 //send event at the end of process, once all has been stored
1594 if ($event !== null) {
1595 $emitter->emit($event, $this);
1598 } catch (Throwable
$e) {
1600 'Something went wrong :\'( | ' . $e->getMessage() . "\n" .
1601 $e->getTraceAsString(),
1609 * Update member modification date
1613 private function updateModificationDate()
1616 $modif_date = date('Y-m-d');
1617 $update = $this->zdb
->update(self
::TABLE
);
1619 array('date_modif_adh' => $modif_date)
1620 )->where(self
::PK
. '=' . $this->_id
);
1622 $edit = $this->zdb
->execute($update);
1623 $this->_modification_date
= $modif_date;
1624 } catch (Throwable
$e) {
1626 'Something went wrong updating modif date :\'( | ' .
1627 $e->getMessage() . "\n" . $e->getTraceAsString(),
1634 * Global getter method
1636 * @param string $name name of the property we want to retrieve
1638 * @return false|object the called property
1640 public function __get($name)
1643 'admin', 'staff', 'due_free', 'appears_in_list', 'active',
1644 'row_classes', 'oldness', 'duplicate'
1646 if (!defined('GALETTE_TESTS')) {
1647 $forbidden[] = 'password'; //keep that for tests only
1651 'sadmin', 'sstaff', 'sdue_free', 'sappears_in_list', 'sactive',
1652 'stitle', 'sstatus', 'sfullname', 'sname', 'saddress',
1653 'rbirthdate', 'sgender', 'contribstatus'
1656 if (in_array($name, $forbidden)) {
1659 return $this->isAdmin();
1661 return $this->isStaff();
1663 return $this->isDueFree();
1664 case 'appears_in_list':
1665 return $this->appearsInMembersList();
1667 return $this->isActive();
1669 return $this->isDuplicate();
1671 throw new \
RuntimeException("Call to __get for '$name' is forbidden!");
1674 if (in_array($name, $virtuals)) {
1675 if (substr($name, 0, 1) !== '_') {
1676 $real = '_' . substr($name, 1);
1683 case 'sappears_in_list':
1685 return (($this->$real) ?
_T("Yes") : _T("No"));
1688 return (($this->$real) ?
_T("Active") : _T("Inactive"));
1691 if (isset($this->_title
) && $this->_title
instanceof Title
) {
1692 return $this->_title
->tshort
;
1698 $status = new Status($this->zdb
);
1699 return $status->getLabel($this->_status
);
1702 return $this->getNameWithCase(
1705 (isset($this->_title
) ?
$this->title
: false)
1709 $address = $this->_address
;
1710 if ($this->_address_continuation
!== '' && $this->_address_continuation
!== null) {
1711 $address .= "\n" . $this->_address_continuation
;
1713 return htmlspecialchars($address, ENT_QUOTES
);
1716 return $this->getNameWithCase($this->_name
, $this->_surname
);
1719 return $this->_birthdate
;
1722 switch ($this->gender
) {
1728 return _T('Unspecified');
1731 case 'contribstatus':
1732 return $this->getDues();
1736 if (substr($name, 0, 1) !== '_') {
1737 $rname = '_' . $name;
1745 if ($this->$rname !== null) {
1746 return (int)$this->$rname;
1752 case 'address_continuation':
1753 return $this->$rname ??
'';
1756 case 'creation_date':
1757 case 'modification_date':
1759 if ($this->$rname != '') {
1761 $d = new \
DateTime($this->$rname);
1762 return $d->format(__("Y-m-d"));
1763 } catch (Throwable
$e) {
1764 //oops, we've got a bad date :/
1766 'Bad date (' . $this->$rname . ') | ' .
1770 return $this->$rname;
1775 return ($this->_parent
instanceof Adherent
) ?
(int)$this->_parent
->id
: (int)$this->_parent
;
1778 if (!property_exists($this, $rname)) {
1780 "Unknown property '$rname'",
1785 return $this->$rname;
1795 * If member does not have an email address, but is attached to
1796 * another member, we'll take information from its parent.
1800 public function getEmail()
1802 $email = $this->_email
;
1803 if (empty($email)) {
1804 $this->loadParent();
1805 $email = $this->parent
->email
;
1812 * Get member address.
1813 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1817 public function getAddress()
1819 $address = $this->_address
;
1820 if (empty($address) && $this->hasParent()) {
1821 $this->loadParent();
1822 $address = $this->parent
->address
;
1829 * Get member address continuation.
1830 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1834 public function getAddressContinuation()
1836 $address = $this->_address
;
1837 $address_continuation = $this->_address_continuation
;
1838 if (empty($address) && $this->hasParent()) {
1839 $this->loadParent();
1840 $address_continuation = $this->parent
->address_continuation
;
1843 return $address_continuation;
1847 * Get member zipcode.
1848 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1852 public function getZipcode()
1854 $address = $this->_address
;
1855 $zip = $this->_zipcode
;
1856 if (empty($address) && $this->hasParent()) {
1857 $this->loadParent();
1858 $zip = $this->parent
->zipcode
;
1866 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1870 public function getTown()
1872 $address = $this->_address
;
1873 $town = $this->_town
;
1874 if (empty($address) && $this->hasParent()) {
1875 $this->loadParent();
1876 $town = $this->parent
->town
;
1883 * Get member country.
1884 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1888 public function getCountry()
1890 $address = $this->_address
;
1891 $country = $this->_country
;
1892 if (empty($address) && $this->hasParent()) {
1893 $this->loadParent();
1894 $country = $this->parent
->country
;
1905 public function getAge()
1907 if ($this->_birthdate
== null) {
1911 $d = \DateTime
::createFromFormat('Y-m-d', $this->_birthdate
);
1914 'Invalid birthdate: ' . $this->_birthdate
,
1922 $d->diff(new \
DateTime())->y
,
1923 _T(' (%age years old)')
1928 * Get parent inherited fields
1932 public function getParentFields()
1934 return $this->parent_fields
;
1938 * Handle files (photo and dynamics files)
1940 * @param array $files Files sent
1942 * @return array|true
1944 public function handleFiles($files)
1948 if (isset($files['photo'])) {
1949 if ($files['photo']['error'] === UPLOAD_ERR_OK
) {
1950 if ($files['photo']['tmp_name'] != '') {
1951 if (is_uploaded_file($files['photo']['tmp_name'])) {
1952 $res = $this->picture
->store($files['photo']);
1955 = $this->picture
->getErrorMessage($res);
1959 } elseif ($files['photo']['error'] !== UPLOAD_ERR_NO_FILE
) {
1961 $this->picture
->getPhpErrorMessage($files['photo']['error']),
1964 $this->errors
[] = $this->picture
->getPhpErrorMessage(
1965 $files['photo']['error']
1969 $this->dynamicsFiles($files);
1971 if (count($this->errors
) > 0) {
1973 'Some errors has been thew attempting to edit/store a member files' . "\n" .
1974 print_r($this->errors
, true),
1977 return $this->errors
;
1984 * Set member as duplicate
1988 public function setDuplicate()
1990 //mark as duplicated
1991 $this->_duplicate
= true;
1992 $infos = $this->_others_infos_admin
;
1993 $this->_others_infos_admin
= str_replace(
1995 [$this->sname
, $this->_id
],
1996 _T('Duplicated from %name (%id)')
1998 if (!empty($infos)) {
1999 $this->_others_infos_admin
.= "\n" . $infos;
2003 //drop email, must be unique
2004 $this->_email
= null;
2005 //drop creation date
2006 $this->_creation_date
= date("Y-m-d");
2008 $this->_login
= null;
2010 $this->_picture
= new Picture();
2012 $this->_birthdate
= null;
2014 $this->_surname
= null;
2016 $this->_admin
= false;
2018 $this->_due_free
= false;
2022 * Get current errors
2026 public function getErrors()
2028 return $this->errors
;
2036 public function getGroups()
2038 return $this->_groups
;
2042 * Get user managed groups
2046 public function getManagedGroups()
2048 return $this->_managed_groups
;
2052 * Can current logged-in user create member
2054 * @param Login $login Login instance
2058 public function canCreate(Login
$login): bool
2060 global $preferences;
2062 if ($this->id
&& $login->id
== $this->id ||
$login->isAdmin() ||
$login->isStaff()) {
2066 if ($preferences->pref_bool_create_member
&& $login->isLogged()) {
2074 * Can current logged-in user edit member
2076 * @param Login $login Login instance
2080 public function canEdit(Login
$login): bool
2082 //admin and staff users can edit, as well as member itself
2083 if ($this->id
&& $login->id
== $this->id ||
$login->isAdmin() ||
$login->isStaff()) {
2087 //parent can edit their child cards
2088 if ($this->hasParent() && $this->parent_id
=== $login->id
) {
2092 //group managers can edit members of groups they manage
2093 if ($login->isGroupManager()) {
2094 foreach ($this->getGroups() as $g) {
2095 if ($login->isGroupManager($g->getId())) {
2105 * Can current logged-in user display member
2107 * @param Login $login Login instance
2111 public function canShow(Login
$login): bool
2113 return $this->canEdit($login);
2117 * Are we currently duplicated a member?
2121 public function isDuplicate(): bool
2123 return $this->_duplicate
;
2127 * Flag creation mail sending
2129 * @param boolean $send True (default) to send creation email
2133 public function setSendmail($send = true): self
2135 $this->sendmail
= $send;
2140 * Should we send administrative emails to member?
2144 public function sendEMail()
2146 return $this->sendmail
;
2152 * @param integer $id Parent identifier
2156 public function setParent(int $id): self
2158 $this->_parent
= $id;
2159 $this->loadParent();
2164 * Reset dependencies to load
2168 public function disableAllDeps(): self
2170 foreach ($this->_deps
as &$dep) {
2177 * Enable all dependencies to load
2181 public function enableAllDeps(): self
2183 foreach ($this->_deps
as &$dep) {
2190 * Enable a load dependency
2192 * @param string $name Dependency name
2196 public function enableDep(string $name): self
2198 if (!isset($this->_deps
[$name])) {
2200 'dependency ' . $name . ' does not exists!',
2204 $this->_deps
[$name] = true;
2211 * Enable a load dependency
2213 * @param string $name Dependency name
2217 public function disableDep(string $name): self
2219 if (!isset($this->_deps
[$name])) {
2221 'dependency ' . $name . ' does not exists!',
2225 $this->_deps
[$name] = false;