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\Repository\Members
;
52 * Member class for galette
57 * @author Johan Cwiklinski <johan@x-tnd.be>
58 * @copyright 2009-2021 The Galette Team
59 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL License 3.0 or (at your option) any later version
60 * @link http://galette.tuxfamily.org
61 * @since Available since 0.7dev - 02-06-2009
63 * @property integer $id
64 * @property integer|Title $title Either a title id or an instance of Title
65 * @property string $stitle Title label
66 * @property string company_name
67 * @property string $name
68 * @property string $surname
69 * @property string $nickname
70 * @property string $birthdate Localized birth date
71 * @property string $rbirthdate Raw birth date
72 * @property string $birth_place
73 * @property integer $gender
74 * @property string $sgender Gender label
75 * @property string $job
76 * @property string $language
77 * @property integer $status
78 * @property string $sstatus Status label
79 * @property string $address
80 * @property string $address_continuation
81 * @property string $zipcode
82 * @property string $town
83 * @property string $country
84 * @property string $phone
85 * @property string $gsm
86 * @property string $email
87 * @property string $website
88 * @property string $msn
89 * @property string $icq
90 * @property string $jabber
91 * @property string $gnupgid
92 * @property string $fingerprint
93 * @property string $login
94 * @property string $creation_date Localized creation date
95 * @property string $modification_date Localized modification date
96 * @property string $due_date Localized due date
97 * @property string $others_infos
98 * @property string $others_infos_admin
99 * @property Picture $picture
100 * @property array $groups
101 * @property array $managed_groups
102 * @property integer|Adherent $parent Parent id if parent dep is not loaded, Adherent instance otherwise
103 * @property array $children
104 * @property boolean $admin better to rely on isAdmin()
105 * @property boolean $staff better to rely on isStaff()
106 * @property boolean $due_free better to rely on isDueFree()
107 * @property boolean $appears_in_list better to rely on appearsInMembersList()
108 * @property boolean $active better to rely on isActive()
109 * @property boolean $duplicate better to rely on isDuplicate()
110 * @property string $sadmin yes/no
111 * @property string $sstaff yes/no
112 * @property string $sdue_free yes/no
113 * @property string $sappears_in_list yes/no
114 * @property string $sactive yes/no
115 * @property string $sfullname
116 * @property string $sname
117 * @property string $saddress Concatened address and continuation
118 * @property string $contribstatus State of member contributions
119 * @property string $days_remaining
125 public const TABLE
= 'adherents';
126 public const PK
= 'id_adh';
129 public const MAN
= 1;
130 public const WOMAN
= 2;
132 public const AFTER_ADD_DEFAULT
= 0;
133 public const AFTER_ADD_TRANS
= 1;
134 public const AFTER_ADD_NEW
= 2;
135 public const AFTER_ADD_SHOW
= 3;
136 public const AFTER_ADD_LIST
= 4;
137 public const AFTER_ADD_HOME
= 5;
142 private $_company_name;
147 private $_birth_place;
153 //Contact information
155 private $_address_continuation; /** TODO: remove */
163 private $_msn; /** TODO: remove */
164 private $_icq; /** TODO: remove */
165 private $_jabber; /** TODO: remove */
166 private $_gnupgid; /** TODO: remove */
167 private $_fingerprint; /** TODO: remove */
168 //Galette relative information
169 private $_appears_in_list;
175 private $_creation_date;
176 private $_modification_date;
178 private $_others_infos;
179 private $_others_infos_admin;
182 private $_days_remaining;
184 private $_managed_groups;
187 private $_duplicate = false;
189 private $_row_classes;
191 private $_self_adh = false;
192 private $_deps = array(
202 private $preferences;
206 private $parent_fields = [
214 private $errors = [];
216 private $sendmail = false;
219 * Default constructor
221 * @param Db $zdb Database instance
222 * @param mixed $args Either a ResultSet row, its id or its
223 * login or its email for to load s specific
224 * member, or null to just instanciate object
225 * @param false|array $deps Dependencies configuration, see Adherent::$_deps
227 public function __construct(Db
$zdb, $args = null, $deps = null)
233 if ($deps !== null) {
234 if (is_array($deps)) {
235 $this->_deps
= array_merge(
239 } elseif ($deps === false) {
241 $this->_deps
= array_fill_keys(
242 array_keys($this->_deps
),
247 '$deps shoud be an array, ' . gettype($deps) . ' given!',
253 if ($args == null ||
is_int($args)) {
254 if (is_int($args) && $args > 0) {
257 $this->_active
= true;
258 $this->_language
= $i18n->getID();
259 $this->_creation_date
= date("Y-m-d");
260 $this->_status
= $this->getDefaultStatus();
261 $this->_title
= null;
262 $this->_gender
= self
::NC
;
263 $gp = new Password($this->zdb
);
264 $this->_password
= $gp->makeRandomPassword();
265 $this->_picture
= new Picture();
266 $this->_admin
= false;
267 $this->_staff
= false;
268 $this->_due_free
= false;
269 $this->_appears_in_list
= false;
270 $this->_parent
= null;
272 if ($this->_deps
['dynamics'] === true) {
273 $this->loadDynamicFields();
276 } elseif (is_object($args)) {
277 $this->loadFromRS($args);
278 } elseif (is_string($args)) {
279 $this->loadFromLoginOrMail($args);
284 * Loads a member from its id
286 * @param int $id the identifiant for the member to load
288 * @return bool true if query succeed, false otherwise
290 public function load($id)
293 $select = $this->zdb
->select(self
::TABLE
, 'a');
296 array('b' => PREFIX_DB
. Status
::TABLE
),
297 'a.' . Status
::PK
. '=b.' . Status
::PK
,
298 array('priorite_statut')
299 )->where(array(self
::PK
=> $id));
301 $results = $this->zdb
->execute($select);
303 if ($results->count() === 0) {
307 $this->loadFromRS($results->current());
309 } catch (Throwable
$e) {
311 'Cannot load member form id `' . $id . '` | ' . $e->getMessage(),
319 * Loads a member from its login
321 * @param string $login login for the member to load
323 * @return bool true if query succeed, false otherwise
325 public function loadFromLoginOrMail($login)
328 $select = $this->zdb
->select(self
::TABLE
);
329 if (GaletteMail
::isValidEmail($login)) {
330 //we got a valid email address, use it
331 $select->where(array('email_adh' => $login));
333 ///we did not get an email address, consider using login
334 $select->where(array('login_adh' => $login));
337 $results = $this->zdb
->execute($select);
338 $result = $results->current();
340 $this->loadFromRS($result);
342 } catch (Throwable
$e) {
344 'Cannot load member form login `' . $login . '` | ' .
353 * Populate object from a resultset row
355 * @param ResultSet $r the resultset row
359 private function loadFromRS($r)
361 $this->_self_adh
= false;
362 $this->_id
= $r->id_adh
;
364 if ($r->titre_adh
!== null) {
365 $this->_title
= new Title((int)$r->titre_adh
);
367 $this->_company_name
= $r->societe_adh
;
368 $this->_name
= $r->nom_adh
;
369 $this->_surname
= $r->prenom_adh
;
370 $this->_nickname
= $r->pseudo_adh
;
371 if ($r->ddn_adh
!= '1901-01-01') {
372 $this->_birthdate
= $r->ddn_adh
;
374 $this->_birth_place
= $r->lieu_naissance
;
375 $this->_gender
= (int)$r->sexe_adh
;
376 $this->_job
= $r->prof_adh
;
377 $this->_language
= $r->pref_lang
;
378 $this->_active
= ($r->activite_adh
== 1) ?
true : false;
379 $this->_status
= (int)$r->id_statut
;
380 //Contact information
381 $this->_address
= $r->adresse_adh
;
382 /** TODO: remove and merge with address */
383 $this->_address_continuation
= $r->adresse2_adh
;
384 $this->_zipcode
= $r->cp_adh
;
385 $this->_town
= $r->ville_adh
;
386 $this->_country
= $r->pays_adh
;
387 $this->_phone
= $r->tel_adh
;
388 $this->_gsm
= $r->gsm_adh
;
389 $this->_email
= $r->email_adh
;
390 $this->_website
= $r->url_adh
;
392 $this->_msn
= $r->msn_adh
;
394 $this->_icq
= $r->icq_adh
;
396 $this->_jabber
= $r->jabber_adh
;
398 $this->_gnupgid
= $r->gpgid
;
400 $this->_fingerprint
= $r->fingerprint
;
401 //Galette relative information
402 $this->_appears_in_list
= ($r->bool_display_info
== 1) ?
true : false;
403 $this->_admin
= ($r->bool_admin_adh
== 1) ?
true : false;
405 isset($r->priorite_statut
)
406 && $r->priorite_statut
< Members
::NON_STAFF_MEMBERS
408 $this->_staff
= true;
410 $this->_due_free
= ($r->bool_exempt_adh
== 1) ?
true : false;
411 $this->_login
= $r->login_adh
;
412 $this->_password
= $r->mdp_adh
;
413 $this->_creation_date
= $r->date_crea_adh
;
414 if ($r->date_modif_adh
!= '1901-01-01') {
415 $this->_modification_date
= $r->date_modif_adh
;
417 $this->_modification_date
= $this->_creation_date
;
419 $this->_due_date
= $r->date_echeance
;
420 $this->_others_infos
= $r->info_public_adh
;
421 $this->_others_infos_admin
= $r->info_adh
;
423 if ($r->parent_id
!== null) {
424 $this->_parent
= (int)$r->parent_id
;
425 if ($this->_deps
['parent'] === true) {
426 $this->loadParent($r->parent_id
);
430 if ($this->_deps
['children'] === true) {
431 $this->loadChildren();
434 if ($this->_deps
['picture'] === true) {
435 $this->_picture
= new Picture($this->_id
);
438 if ($this->_deps
['groups'] === true) {
442 if ($this->_deps
['dues'] === true) {
446 if ($this->_deps
['dynamics'] === true) {
447 $this->loadDynamicFields();
456 private function loadParent()
458 if (!$this->_parent
instanceof Adherent
) {
459 $deps = array_fill_keys(array_keys($this->_deps
), false);
460 $this->_parent
= new Adherent($this->zdb
, (int)$this->_parent
, $deps);
465 * Load member children
469 private function loadChildren()
471 $this->_children
= array();
474 $select = $this->zdb
->select(self
::TABLE
);
478 'parent_id = ' . $this->_id
481 $results = $this->zdb
->execute($select);
483 if ($results->count() > 0) {
484 foreach ($results as $row) {
485 $deps = $this->_deps
;
486 $deps['children'] = false;
487 $deps['parent'] = false;
488 $this->_children
[] = new Adherent($this->zdb
, (int)$row->$id, $deps);
491 } catch (Throwable
$e) {
493 'Cannot load children for member #' . $this->_id
. ' | ' .
506 public function loadGroups()
508 $this->_groups
= Groups
::loadGroups($this->_id
);
509 $this->_managed_groups
= Groups
::loadManagedGroups($this->_id
);
513 * Retrieve status from preferences
515 * @return pref_statut
518 private function getDefaultStatus()
521 if ($preferences->pref_statut
!= '') {
522 return $preferences->pref_statut
;
525 'Unable to get pref_statut; is it defined in preferences?',
528 return Status
::DEFAULT_STATUS
;
533 * Check for dues status
537 private function checkDues()
539 //how many days since our beloved member has been created
540 $date_now = new \
DateTime();
541 $this->_oldness
= $date_now->diff(
542 new \
DateTime($this->_creation_date
)
545 if ($this->isDueFree()) {
546 //no fee required, we don't care about dates
547 $this->_row_classes
.= ' cotis-exempt';
549 //ok, fee is required. Let's check the dates
550 if ($this->_due_date
== '') {
551 $this->_row_classes
.= ' cotis-never';
553 $date_end = new \
DateTime($this->_due_date
);
554 $date_diff = $date_now->diff($date_end);
555 $this->_days_remaining
= ($date_diff->invert
== 1)
556 ?
$date_diff->days
* -1
559 if ($this->_days_remaining
== 0) {
560 $this->_row_classes
.= ' cotis-lastday';
561 } elseif ($this->_days_remaining
< 0) {
562 //check if member is still active
563 $this->_row_classes
.= $this->isActive() ?
' cotis-late' : ' cotis-old';
564 } elseif ($this->_days_remaining
< 30) {
565 $this->_row_classes
.= ' cotis-soon';
567 $this->_row_classes
.= ' cotis-ok';
578 public function isAdmin()
580 return $this->_admin
;
584 * Is user member of staff?
588 public function isStaff()
590 return $this->_staff
;
594 * Is member freed of dues?
598 public function isDueFree()
600 return $this->_due_free
;
604 * Is member in specified group?
606 * @param string $group_name Group name
610 public function isGroupMember($group_name)
612 if (is_array($this->_groups
)) {
613 foreach ($this->_groups
as $g) {
614 if ($g->getName() == $group_name) {
621 'Calling ' . __METHOD__
. ' without groups loaded!',
629 * Is member manager of specified group?
631 * @param string $group_name Group name
635 public function isGroupManager($group_name)
637 if (is_array($this->_managed_groups
)) {
638 foreach ($this->_managed_groups
as $mg) {
639 if ($mg->getName() == $group_name) {
646 'Calling ' . __METHOD__
. ' without groups loaded!',
654 * Does current member represents a company?
658 public function isCompany()
660 return trim($this->_company_name
) != '';
664 * Is current member a man?
668 public function isMan()
670 return (int)$this->_gender
=== self
::MAN
;
674 * Is current member a woman?
678 public function isWoman()
680 return (int)$this->_gender
=== self
::WOMAN
;
685 * Can member appears in public members list?
689 public function appearsInMembersList()
691 return $this->_appears_in_list
;
699 public function isActive()
701 return $this->_active
;
705 * Does member have uploaded a picture?
709 public function hasPicture()
711 return $this->_picture
->hasPicture();
715 * Does member have a parent?
719 public function hasParent()
721 return !empty($this->_parent
);
725 * Does member have children?
729 public function hasChildren()
731 if ($this->_children
=== null) {
734 'Children has not been loaded!',
740 return count($this->_children
) > 0;
745 * Get row class related to current fee status
747 * @param boolean $public we want the class for public pages
749 * @return string the class to apply
751 public function getRowClass($public = false)
753 $strclass = ($this->isActive()) ?
'active' : 'inactive';
754 if ($public === false) {
755 $strclass .= $this->_row_classes
;
761 * Get current member due status
763 * @return string i18n string representing state of due
765 public function getDues()
768 $date_now = new \
DateTime();
769 $ddate = new \
DateTime($this->_due_date
);
770 $date_diff = $date_now->diff($ddate);
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 if ($date_diff->invert
== 0) {
791 $ret = _T("Last day!");
793 $ret = _T("Late since today!");
795 } elseif ($this->_days_remaining
< 0) {
796 $patterns = array('/%days/', '/%date/');
798 $this->_days_remaining
* -1,
799 $ddate->format(__("Y-m-d"))
801 if ($this->_active
) {
805 _T("Late of %days days (since %date)")
808 $ret = _T("No longer member");
811 $patterns = array('/%days/', '/%date/');
813 $this->_days_remaining
,
814 $ddate->format(__("Y-m-d"))
819 _T("%days days remaining (ending on %date)")
826 * Retrieve Full name and surname for the specified member id
828 * @param Db $zdb Database instance
829 * @param integer $id Member id
830 * @param boolean $wid Add member id
831 * @param boolean $wnick Add member nickname
833 * @return string formatted Name and Surname
835 public static function getSName($zdb, $id, $wid = false, $wnick = false)
838 $select = $zdb->select(self
::TABLE
);
839 $select->where(self
::PK
. ' = ' . $id);
841 $results = $zdb->execute($select);
842 $row = $results->current();
843 return self
::getNameWithCase(
847 ($wid === true ?
$row->id_adh
: false),
848 ($wnick === true ?
$row->pseudo_adh
: false)
850 } catch (Throwable
$e) {
852 'Cannot get formatted name for member form id `' . $id . '` | ' .
861 * Get member name with correct case
863 * @param string $name Member name
864 * @param string $surname Mmeber surname
865 * @param false|Title $title Member title to show or false
866 * @param false|integer $id Member id to display or false
867 * @param false|string $nick Member nickname to display or false
871 public static function getNameWithCase($name, $surname, $title = false, $id = false, $nick = false)
875 if ($title !== false && $title instanceof Title
) {
876 $str .= $title->tshort
. ' ';
879 $str .= mb_strtoupper($name, 'UTF-8') . ' ' .
880 ucwords(mb_strtolower($surname, 'UTF-8'), " \t\r\n\f\v-_|");
882 if ($id !== false ||
$nick !== false) {
885 if ($nick !== false) {
889 if ($nick !== false && !empty($nick)) {
894 if ($id !== false ||
$nick !== false) {
897 return strip_tags($str);
901 * Change password for a given user
903 * @param Db $zdb Database instance
904 * @param string $id_adh Member identifier
905 * @param string $pass New password
909 public static function updatePassword(Db
$zdb, $id_adh, $pass)
912 $cpass = password_hash($pass, PASSWORD_BCRYPT
);
914 $update = $zdb->update(self
::TABLE
);
916 array('mdp_adh' => $cpass)
917 )->where(self
::PK
. ' = ' . $id_adh);
918 $zdb->execute($update);
920 'Password for `' . $id_adh . '` has been updated.',
924 } catch (Throwable
$e) {
926 'An error occurred while updating password for `' . $id_adh .
927 '` | ' . $e->getMessage(),
937 * @param string $field Field name
941 private function getFieldLabel($field)
943 $label = $this->fields
[$field]['label'];
944 //remove trailing ':' and then nbsp (for french at least)
945 $label = trim(trim($label, ':'), ' ');
950 * Retrieve fields from database
952 * @param Db $zdb Database instance
956 public static function getDbFields(Db
$zdb)
958 $columns = $zdb->getColumns(self
::TABLE
);
960 foreach ($columns as $col) {
961 $fields[] = $col->getName();
967 * Mark as self membership
971 public function setSelfMembership()
973 $this->_self_adh
= true;
977 * Is member up to date?
981 public function isUp2Date()
983 if ($this->_deps
['dues']) {
984 if ($this->isDueFree()) {
985 //member is due free, he's up to date.
988 //let's check from end date, if present
989 if ($this->_due_date
== null) {
992 $ech = new \
DateTime($this->_due_date
);
993 $now = new \
DateTime();
994 $now->setTime(0, 0, 0);
999 throw new \
RuntimeException(
1000 'Cannot check if member is up to date, dues deps is disabled!'
1008 * @param Preferences $preferences Preferences instance
1009 * @param array $fields Members fields configuration
1010 * @param History $history History instance
1014 public function setDependencies(
1015 Preferences
$preferences,
1019 $this->preferences
= $preferences;
1020 $this->fields
= $fields;
1021 $this->history
= $history;
1025 * Check posted values validity
1027 * @param array $values All values to check, basically the $_POST array
1028 * after sending the form
1029 * @param array $required Array of required fields
1030 * @param array $disabled Array of disabled fields
1032 * @return true|array
1034 public function check($values, $required, $disabled)
1036 $this->errors
= array();
1039 foreach ($values as &$rawvalue) {
1040 if (is_string($rawvalue)) {
1041 $rawvalue = strip_tags($rawvalue);
1045 $fields = self
::getDbFields($this->zdb
);
1047 //reset company name if needeed
1048 if (!isset($values['is_company'])) {
1049 unset($values['is_company']);
1050 $values['societe_adh'] = '';
1053 //no parent if checkbox was unchecked
1055 !isset($values['attach'])
1056 && empty($this->_id
)
1057 && isset($values['parent_id'])
1059 unset($values['parent_id']);
1062 if (isset($values['duplicate'])) {
1063 //if we're duplicating, keep a trace (if an error occurs)
1064 $this->_duplicate
= true;
1067 foreach ($fields as $key) {
1068 //first of all, let's sanitize values
1069 $key = strtolower($key);
1070 $prop = '_' . $this->fields
[$key]['propname'];
1072 if (isset($values[$key])) {
1073 $value = $values[$key];
1074 if ($value !== true && $value !== false) {
1075 $value = trim($value);
1077 } elseif (empty($this->_id
)) {
1079 case 'bool_admin_adh':
1080 case 'bool_exempt_adh':
1081 case 'bool_display_info':
1084 case 'activite_adh':
1085 //values that are setted at object instanciation
1088 case 'date_crea_adh':
1094 //values that are setted at object instanciation
1095 $value = $this->$prop;
1102 //keep stored value on update
1103 if ($prop != '_password' ||
isset($values['mdp_adh']) && isset($values['mdp_adh2'])) {
1104 $value = $this->$prop;
1110 // if the field is enabled, check it
1111 if (!isset($disabled[$key])) {
1112 // fill up the adherent structure
1113 if ($value !== null && $value !== true && $value !== false && !is_object($value)) {
1114 $value = stripslashes($value);
1116 $this->$prop = $value;
1118 // now, check validity
1119 if ($value !== null && $value != '') {
1120 $this->validate($key, $value, $values);
1121 } elseif (empty($this->_id
)) {
1122 //ensure login and password are not empty
1123 if (($key == 'login_adh' ||
$key == 'mdp_adh') && !isset($required[$key])) {
1124 $p = new Password($this->zdb
);
1125 $generated_value = $p->makeRandomPassword(15);
1126 if ($key == 'login_adh') {
1127 //'@' is not permitted in logins
1128 $this->$prop = str_replace('@', 'a', $generated_value);
1130 $this->$prop = $generated_value;
1137 // missing required fields?
1138 foreach ($required as $key => $val) {
1139 $prop = '_' . $this->fields
[$key]['propname'];
1141 if (!isset($disabled[$key])) {
1142 $mandatory_missing = false;
1143 if (!isset($this->$prop) ||
$this->$prop == '') {
1144 $mandatory_missing = true;
1145 } elseif ($key === 'titre_adh' && $this->$prop == '-1') {
1146 $mandatory_missing = true;
1149 if ($mandatory_missing === true) {
1150 $this->errors
[] = str_replace(
1152 '<a href="#' . $key . '">' . $this->getFieldLabel($key) . '</a>',
1153 _T("- Mandatory field %field empty.")
1159 //attach to/detach from parent
1160 if (isset($values['detach_parent'])) {
1161 $this->_parent
= null;
1164 $this->dynamicsCheck($values, $required, $disabled);
1166 if (count($this->errors
) > 0) {
1168 'Some errors has been throwed attempting to edit/store a member' . "\n" .
1169 print_r($this->errors
, true),
1172 return $this->errors
;
1177 'Member checked successfully.',
1185 * Validate data for given key
1186 * Set valid data in current object, also resets errors list
1188 * @param string $field Field name
1189 * @param mixed $value Value we want to set
1190 * @param array $values All values, for some references
1194 public function validate($field, $value, $values)
1196 global $preferences;
1198 $prop = '_' . $this->fields
[$field]['propname'];
1200 if ($value === null ||
(is_string($value) && trim($value) == '')) {
1201 //empty values are OK
1202 $this->$prop = $value;
1208 case 'date_crea_adh':
1209 case 'date_modif_adh_':
1211 case 'date_echeance':
1213 $d = \DateTime
::createFromFormat(__("Y-m-d"), $value);
1215 //try with non localized date
1216 $d = \DateTime
::createFromFormat("Y-m-d", $value);
1218 throw new \
Exception('Incorrect format');
1222 if ($field === 'ddn_adh') {
1223 $now = new \
DateTime();
1224 $now->setTime(0, 0, 0);
1225 $d->setTime(0, 0, 0);
1227 $diff = $now->diff($d);
1228 $days = (int)$diff->format('%R%a');
1230 $this->errors
[] = _T('- Birthdate must be set in the past!');
1233 $years = (int)$diff->format('%R%Y');
1234 if ($years <= -200) {
1235 $this->errors
[] = str_replace(
1238 _T('- Members must be less than 200 years old (currently %years)!')
1242 $this->$prop = $d->format('Y-m-d');
1243 } catch (Throwable
$e) {
1245 'Wrong date format. field: ' . $field .
1246 ', value: ' . $value . ', expected fmt: ' .
1247 __("Y-m-d") . ' | ' . $e->getMessage(),
1250 $this->errors
[] = str_replace(
1257 $this->getFieldLabel($field)
1259 _T("- Wrong date format (%date_format) for %field!")
1264 if ($value !== null && $value !== '') {
1265 if ($value == '-1') {
1266 $this->$prop = null;
1267 } elseif (!$value instanceof Title
) {
1268 $this->$prop = new Title((int)$value);
1271 $this->$prop = null;
1276 if (!GaletteMail
::isValidEmail($value)) {
1277 $this->errors
[] = _T("- Non-valid E-Mail address!") .
1278 ' (' . $this->getFieldLabel($field) . ')';
1280 if ($field == 'email_adh') {
1282 $select = $this->zdb
->select(self
::TABLE
);
1285 )->where(array('email_adh' => $value));
1286 if (!empty($this->_id
)) {
1288 self
::PK
. ' != ' . $this->_id
1292 $results = $this->zdb
->execute($select);
1293 if ($results->count() !== 0) {
1294 $this->errors
[] = _T("- This E-Mail address is already used by another member!");
1296 } catch (Throwable
$e) {
1298 'An error occurred checking member email unicity.',
1301 $this->errors
[] = _T("An error has occurred while looking if login already exists.");
1306 if ($value == 'http://') {
1308 } elseif (!isValidWebUrl($value)) {
1309 $this->errors
[] = _T("- Non-valid Website address! Maybe you've skipped the http://?");
1313 /** FIXME: add a preference for login lenght */
1314 if (strlen($value) < 2) {
1315 $this->errors
[] = str_replace(
1318 _T("- The username must be composed of at least %i characters!")
1321 //check if login does not contain the @ character
1322 if (strpos($value, '@') != false) {
1323 $this->errors
[] = _T("- The username cannot contain the @ character");
1325 //check if login is already taken
1327 $select = $this->zdb
->select(self
::TABLE
);
1330 )->where(array('login_adh' => $value));
1331 if (!empty($this->_id
)) {
1333 self
::PK
. ' != ' . $this->_id
1337 $results = $this->zdb
->execute($select);
1339 $results->count() !== 0
1340 ||
$value == $preferences->pref_admin_login
1342 $this->errors
[] = _T("- This username is already in use, please choose another one!");
1344 } catch (Throwable
$e) {
1346 'An error occurred checking member login unicity.',
1349 $this->errors
[] = _T("An error has occurred while looking if login already exists.");
1356 $this->_self_adh
!== true
1357 && (!isset($values['mdp_adh2'])
1358 ||
$values['mdp_adh2'] != $value)
1360 $this->errors
[] = _T("- The passwords don't match!");
1362 $this->_self_adh
=== true
1363 && !crypt($value, $values['mdp_crypt']) == $values['mdp_crypt']
1365 $this->errors
[] = _T("Password misrepeated: ");
1367 $pinfos = password_get_info($value);
1368 //check if value is already a hash
1369 if ($pinfos['algo'] == 0) {
1370 $this->$prop = password_hash(
1375 $pwcheck = new \Galette\Util\
Password($preferences);
1376 $pwcheck->setAdherent($this);
1377 if (!$pwcheck->isValid($value)) {
1378 $this->errors
= array_merge(
1380 $pwcheck->getErrors()
1388 $this->$prop = (int)$value;
1389 //check if status exists
1390 $select = $this->zdb
->select(Status
::TABLE
);
1391 $select->where(Status
::PK
. '= ' . $value);
1393 $results = $this->zdb
->execute($select);
1394 $result = $results->current();
1396 $this->errors
[] = str_replace(
1399 _T("Status #%id does not exists in database.")
1403 } catch (Throwable
$e) {
1405 'An error occurred checking status existance: ' . $e->getMessage(),
1408 $this->errors
[] = _T("An error has occurred while looking if status does exists.");
1412 if (in_array($value, [self
::NC
, self
::MAN
, self
::WOMAN
])) {
1413 $this->$prop = (int)$value;
1415 $this->errors
[] = _T("Gender %gender does not exists!");
1419 $this->$prop = ($value instanceof Adherent
) ?
(int)$value->id
: (int)$value;
1420 $this->loadParent();
1430 public function store()
1432 global $hist, $emitter;
1437 $fields = self
::getDbFields($this->zdb
);
1439 foreach ($fields as $field) {
1441 $field !== 'date_modif_adh'
1442 ||
empty($this->_id
)
1444 $prop = '_' . $this->fields
[$field]['propname'];
1446 ($field === 'bool_admin_adh'
1447 ||
$field === 'bool_exempt_adh'
1448 ||
$field === 'bool_display_info'
1449 ||
$field === 'activite_adh')
1450 && $this->$prop === false
1452 //Handle booleans for postgres ; bugs #18899 and #19354
1453 $values[$field] = $this->zdb
->isPostgres() ?
'false' : 0;
1454 } elseif ($field === 'parent_id') {
1456 if ($this->_parent
=== null) {
1457 $values['parent_id'] = new Expression('NULL');
1458 } elseif ($this->parent
instanceof Adherent
) {
1459 $values['parent_id'] = $this->_parent
->id
;
1461 $values['parent_id'] = $this->_parent
;
1464 $values[$field] = $this->$prop;
1469 //an empty value will cause date to be set to 1901-01-01, a null
1470 //will result in 0000-00-00. We want a database NULL value here.
1471 if (!$this->_birthdate
) {
1472 $values['ddn_adh'] = new Expression('NULL');
1474 if (!$this->_due_date
) {
1475 $values['date_echeance'] = new Expression('NULL');
1478 if ($this->_title
instanceof Title
) {
1479 $values['titre_adh'] = $this->_title
->id
;
1481 $values['titre_adh'] = new Expression('NULL');
1484 if (!$this->_parent
) {
1485 $values['parent_id'] = new Expression('NULL');
1488 //fields that cannot be null
1490 '_surname' => 'prenom_adh',
1491 '_nickname' => 'pseudo_adh',
1492 '_address' => 'adresse_adh',
1493 '_zipcode' => 'cp_adh',
1494 '_town' => 'ville_adh'
1496 foreach ($notnull as $prop => $field) {
1497 if ($this->$prop === null) {
1498 $values[$field] = '';
1503 if (empty($this->_id
)) {
1504 //we're inserting a new member
1505 unset($values[self
::PK
]);
1506 //set modification date
1507 $this->_modification_date
= date('Y-m-d');
1508 $values['date_modif_adh'] = $this->_modification_date
;
1510 $insert = $this->zdb
->insert(self
::TABLE
);
1511 $insert->values($values);
1512 $add = $this->zdb
->execute($insert);
1513 if ($add->count() > 0) {
1514 $this->_id
= $this->zdb
->getLastGeneratedValue($this);
1515 $this->_picture
= new Picture($this->_id
);
1517 if ($this->_self_adh
) {
1519 _T("Self_subscription as a member: ") .
1520 $this->getNameWithCase($this->_name
, $this->_surname
),
1525 _T("Member card added"),
1531 $event = 'member.add';
1533 $hist->add(_T("Fail to add new member."));
1534 throw new \
Exception(
1535 'An error occurred inserting new member!'
1539 //we're editing an existing member
1540 if (!$this->isDueFree()) {
1542 $due_date = Contribution
::getDueDate($this->zdb
, $this->_id
);
1544 $values['date_echeance'] = $due_date;
1548 if (!$this->_password
) {
1549 unset($values['mdp_adh']);
1552 $update = $this->zdb
->update(self
::TABLE
);
1553 $update->set($values);
1555 self
::PK
. '=' . $this->_id
1558 $edit = $this->zdb
->execute($update);
1560 //edit == 0 does not mean there were an error, but that there
1561 //were nothing to change
1562 if ($edit->count() > 0) {
1563 $this->updateModificationDate();
1565 _T("Member card updated"),
1571 $event = 'member.edit';
1576 $success = $this->dynamicsStore();
1579 //send event at the end of process, once all has been stored
1580 if ($event !== null) {
1581 $emitter->emit($event, $this);
1584 } catch (Throwable
$e) {
1586 'Something went wrong :\'( | ' . $e->getMessage() . "\n" .
1587 $e->getTraceAsString(),
1595 * Update member modification date
1599 private function updateModificationDate()
1602 $modif_date = date('Y-m-d');
1603 $update = $this->zdb
->update(self
::TABLE
);
1605 array('date_modif_adh' => $modif_date)
1606 )->where(self
::PK
. '=' . $this->_id
);
1608 $edit = $this->zdb
->execute($update);
1609 $this->_modification_date
= $modif_date;
1610 } catch (Throwable
$e) {
1612 'Something went wrong updating modif date :\'( | ' .
1613 $e->getMessage() . "\n" . $e->getTraceAsString(),
1620 * Global getter method
1622 * @param string $name name of the property we want to retrive
1624 * @return false|object the called property
1626 public function __get($name)
1629 'admin', 'staff', 'due_free', 'appears_in_list', 'active',
1630 'row_classes', 'oldness', 'duplicate'
1632 if (!defined('GALETTE_TESTS')) {
1633 $forbidden[] = 'password'; //keep that for tests only
1637 'sadmin', 'sstaff', 'sdue_free', 'sappears_in_list', 'sactive',
1638 'stitle', 'sstatus', 'sfullname', 'sname', 'saddress',
1639 'rbirthdate', 'sgender', 'contribstatus'
1642 if (in_array($name, $forbidden)) {
1645 return $this->isAdmin();
1647 return $this->isStaff();
1649 return $this->isDueFree();
1650 case 'appears_in_list':
1651 return $this->appearsInMembersList();
1653 return $this->isActive();
1655 return $this->isDuplicate();
1657 throw new \
RuntimeException("Call to __get for '$name' is forbidden!");
1660 if (in_array($name, $virtuals)) {
1661 if (substr($name, 0, 1) !== '_') {
1662 $real = '_' . substr($name, 1);
1669 case 'sappears_in_list':
1671 return (($this->$real) ?
_T("Yes") : _T("No"));
1674 return (($this->$real) ?
_T("Active") : _T("Inactive"));
1677 if (isset($this->_title
) && $this->_title
instanceof Title
) {
1678 return $this->_title
->tshort
;
1684 $status = new Status($this->zdb
);
1685 return $status->getLabel($this->_status
);
1688 return $this->getNameWithCase(
1691 (isset($this->_title
) ?
$this->title
: false)
1695 $address = $this->_address
;
1696 if ($this->_address_continuation
!== '' && $this->_address_continuation
!== null) {
1697 $address .= "\n" . $this->_address_continuation
;
1699 return htmlspecialchars($address, ENT_QUOTES
);
1702 return $this->getNameWithCase($this->_name
, $this->_surname
);
1705 return $this->_birthdate
;
1708 switch ($this->gender
) {
1714 return _T('Unspecified');
1717 case 'contribstatus':
1718 return $this->getDues();
1722 if (substr($name, 0, 1) !== '_') {
1723 $rname = '_' . $name;
1731 if ($this->$rname !== null) {
1732 return (int)$this->$rname;
1738 case 'creation_date':
1739 case 'modification_date':
1741 if ($this->$rname != '') {
1743 $d = new \
DateTime($this->$rname);
1744 return $d->format(__("Y-m-d"));
1745 } catch (Throwable
$e) {
1746 //oops, we've got a bad date :/
1748 'Bad date (' . $this->$rname . ') | ' .
1752 return $this->$rname;
1757 if (!property_exists($this, $rname)) {
1759 "Unknown property '$rname'",
1764 return $this->$rname;
1774 * If member does not have an email address, but is attached to
1775 * another member, we'll take information from its parent.
1779 public function getEmail()
1781 $email = $this->_email
;
1782 if (empty($email)) {
1783 $this->loadParent();
1784 $email = $this->parent
->email
;
1791 * Get member address.
1792 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1796 public function getAddress()
1798 $address = $this->_address
;
1799 if (empty($address) && $this->hasParent()) {
1800 $this->loadParent();
1801 $address = $this->parent
->address
;
1808 * Get member address continuation.
1809 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1813 public function getAddressContinuation()
1815 $address = $this->_address
;
1816 $address_continuation = $this->_address_continuation
;
1817 if (empty($address) && $this->hasParent()) {
1818 $this->loadParent();
1819 $address_continuation = $this->parent
->address_continuation
;
1822 return $address_continuation;
1826 * Get member zipcode.
1827 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1831 public function getZipcode()
1833 $address = $this->_address
;
1834 $zip = $this->_zipcode
;
1835 if (empty($address) && $this->hasParent()) {
1836 $this->loadParent();
1837 $zip = $this->parent
->zipcode
;
1845 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1849 public function getTown()
1851 $address = $this->_address
;
1852 $town = $this->_town
;
1853 if (empty($address) && $this->hasParent()) {
1854 $this->loadParent();
1855 $town = $this->parent
->town
;
1862 * Get member country.
1863 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1867 public function getCountry()
1869 $address = $this->_address
;
1870 $country = $this->_country
;
1871 if (empty($address) && $this->hasParent()) {
1872 $this->loadParent();
1873 $country = $this->parent
->country
;
1884 public function getAge()
1886 if ($this->_birthdate
== null) {
1890 $d = \DateTime
::createFromFormat('Y-m-d', $this->_birthdate
);
1893 'Invalid birthdate: ' . $this->_birthdate
,
1901 $d->diff(new \
DateTime())->y
,
1902 _T(' (%age years old)')
1907 * Get parent inherited fields
1911 public function getParentFields()
1913 return $this->parent_fields
;
1917 * Handle files (photo and dynamics files)
1919 * @param array $files Files sent
1921 * @return array|true
1923 public function handleFiles($files)
1927 if (isset($files['photo'])) {
1928 if ($files['photo']['error'] === UPLOAD_ERR_OK
) {
1929 if ($files['photo']['tmp_name'] != '') {
1930 if (is_uploaded_file($files['photo']['tmp_name'])) {
1931 $res = $this->picture
->store($files['photo']);
1934 = $this->picture
->getErrorMessage($res);
1938 } elseif ($files['photo']['error'] !== UPLOAD_ERR_NO_FILE
) {
1940 $this->picture
->getPhpErrorMessage($files['photo']['error']),
1943 $this->errors
[] = $this->picture
->getPhpErrorMessage(
1944 $files['photo']['error']
1948 $this->dynamicsFiles($files);
1950 if (count($this->errors
) > 0) {
1952 'Some errors has been throwed attempting to edit/store a member files' . "\n" .
1953 print_r($this->errors
, true),
1956 return $this->errors
;
1963 * Set member as duplicate
1967 public function setDuplicate()
1969 //mark as duplicated
1970 $this->_duplicate
= true;
1971 $infos = $this->_others_infos_admin
;
1972 $this->_others_infos_admin
= str_replace(
1974 [$this->sname
, $this->_id
],
1975 _T('Duplicated from %name (%id)')
1977 if (!empty($infos)) {
1978 $this->_others_infos_admin
.= "\n" . $infos;
1982 //drop email, must be unique
1983 $this->_email
= null;
1984 //drop creation date
1985 $this->_creation_date
= date("Y-m-d");
1987 $this->_login
= null;
1989 $this->_picture
= new Picture();
1991 $this->_birthdate
= null;
1993 $this->_surname
= null;
1995 $this->_admin
= false;
1997 $this->_due_free
= false;
2001 * Get current errors
2005 public function getErrors()
2007 return $this->errors
;
2015 public function getGroups()
2017 return $this->_groups
;
2021 * Get user managed groups
2025 public function getManagedGroups()
2027 return $this->_managed_groups
;
2031 * Can current logged in user edit member
2033 * @param Login $login Login instance
2037 public function canEdit($login)
2039 if ($this->id
&& $login->id
== $this->id ||
$login->isAdmin() ||
$login->isStaff()) {
2043 //check if requested member is part of managed groups
2044 if ($login->isGroupManager()) {
2045 foreach ($this->getGroups() as $g) {
2046 if ($login->isGroupManager($g->getId())) {
2056 * Are we currently duplicated a member?
2060 public function isDuplicate()
2062 return $this->_duplicate
;
2066 * Flag creation mail sending
2068 * @param boolean $send True (default) to send creation email
2072 public function setSendmail($send = true)
2074 $this->sendmail
= $send;
2079 * Should we send administrative emails to member?
2083 public function sendEMail()
2085 return $this->sendmail
;