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 if ($this->isDueFree()) {
769 $ret = _T("Freed of dues");
770 } elseif ($this->_due_date
== '') {
771 $patterns = array('/%days/', '/%date/');
772 $cdate = new \
DateTime($this->_creation_date
);
775 $cdate->format(__("Y-m-d"))
777 if ($this->_active
) {
781 _T("Never contributed: Registered %days days ago (since %date)")
784 $ret = _T("Never contributed");
786 } elseif ($this->_days_remaining
== 0) {
787 $ret = _T("Last day!");
788 } elseif ($this->_days_remaining
< 0) {
789 $patterns = array('/%days/', '/%date/');
790 $ddate = new \
DateTime($this->_due_date
);
792 $this->_days_remaining
* -1,
793 $ddate->format(__("Y-m-d"))
795 if ($this->_active
) {
799 _T("Late of %days days (since %date)")
802 $ret = _T("No longer member");
805 $patterns = array('/%days/', '/%date/');
806 $ddate = new \
DateTime($this->_due_date
);
808 $this->_days_remaining
,
809 $ddate->format(__("Y-m-d"))
814 _T("%days days remaining (ending on %date)")
821 * Retrieve Full name and surname for the specified member id
823 * @param Db $zdb Database instance
824 * @param integer $id Member id
825 * @param boolean $wid Add member id
826 * @param boolean $wnick Add member nickname
828 * @return string formatted Name and Surname
830 public static function getSName($zdb, $id, $wid = false, $wnick = false)
833 $select = $zdb->select(self
::TABLE
);
834 $select->where(self
::PK
. ' = ' . $id);
836 $results = $zdb->execute($select);
837 $row = $results->current();
838 return self
::getNameWithCase(
842 ($wid === true ?
$row->id_adh
: false),
843 ($wnick === true ?
$row->pseudo_adh
: false)
845 } catch (Throwable
$e) {
847 'Cannot get formatted name for member form id `' . $id . '` | ' .
856 * Get member name with correct case
858 * @param string $name Member name
859 * @param string $surname Mmeber surname
860 * @param false|Title $title Member title to show or false
861 * @param false|integer $id Member id to display or false
862 * @param false|string $nick Member nickname to display or false
866 public static function getNameWithCase($name, $surname, $title = false, $id = false, $nick = false)
870 if ($title !== false && $title instanceof Title
) {
871 $str .= $title->tshort
. ' ';
874 $str .= mb_strtoupper($name, 'UTF-8') . ' ' .
875 ucwords(mb_strtolower($surname, 'UTF-8'), " \t\r\n\f\v-_|");
877 if ($id !== false ||
$nick !== false) {
880 if ($nick !== false) {
884 if ($nick !== false && !empty($nick)) {
889 if ($id !== false ||
$nick !== false) {
892 return strip_tags($str);
896 * Change password for a given user
898 * @param Db $zdb Database instance
899 * @param string $id_adh Member identifier
900 * @param string $pass New password
904 public static function updatePassword(Db
$zdb, $id_adh, $pass)
907 $cpass = password_hash($pass, PASSWORD_BCRYPT
);
909 $update = $zdb->update(self
::TABLE
);
911 array('mdp_adh' => $cpass)
912 )->where(self
::PK
. ' = ' . $id_adh);
913 $zdb->execute($update);
915 'Password for `' . $id_adh . '` has been updated.',
919 } catch (Throwable
$e) {
921 'An error occurred while updating password for `' . $id_adh .
922 '` | ' . $e->getMessage(),
932 * @param string $field Field name
936 private function getFieldLabel($field)
938 $label = $this->fields
[$field]['label'];
939 //remove trailing ':' and then nbsp (for french at least)
940 $label = trim(trim($label, ':'), ' ');
945 * Retrieve fields from database
947 * @param Db $zdb Database instance
951 public static function getDbFields(Db
$zdb)
953 $columns = $zdb->getColumns(self
::TABLE
);
955 foreach ($columns as $col) {
956 $fields[] = $col->getName();
962 * Mark as self membership
966 public function setSelfMembership()
968 $this->_self_adh
= true;
972 * Is member up to date?
976 public function isUp2Date()
978 if ($this->_deps
['dues']) {
979 if ($this->isDueFree()) {
980 //member is due free, he's up to date.
983 //let's check from end date, if present
984 if ($this->_due_date
== null) {
987 $ech = new \
DateTime($this->_due_date
);
988 $now = new \
DateTime();
989 $now->setTime(0, 0, 0);
994 throw new \
RuntimeException(
995 'Cannot check if member is up to date, dues deps is disabled!'
1003 * @param Preferences $preferences Preferences instance
1004 * @param array $fields Members fields configuration
1005 * @param History $history History instance
1009 public function setDependencies(
1010 Preferences
$preferences,
1014 $this->preferences
= $preferences;
1015 $this->fields
= $fields;
1016 $this->history
= $history;
1020 * Check posted values validity
1022 * @param array $values All values to check, basically the $_POST array
1023 * after sending the form
1024 * @param array $required Array of required fields
1025 * @param array $disabled Array of disabled fields
1027 * @return true|array
1029 public function check($values, $required, $disabled)
1031 $this->errors
= array();
1034 foreach ($values as &$rawvalue) {
1035 if (is_string($rawvalue)) {
1036 $rawvalue = strip_tags($rawvalue);
1040 $fields = self
::getDbFields($this->zdb
);
1042 //reset company name if needeed
1043 if (!isset($values['is_company'])) {
1044 unset($values['is_company']);
1045 $values['societe_adh'] = '';
1048 //no parent if checkbox was unchecked
1050 !isset($values['attach'])
1051 && empty($this->_id
)
1052 && isset($values['parent_id'])
1054 unset($values['parent_id']);
1057 if (isset($values['duplicate'])) {
1058 //if we're duplicating, keep a trace (if an error occurs)
1059 $this->_duplicate
= true;
1062 foreach ($fields as $key) {
1063 //first of all, let's sanitize values
1064 $key = strtolower($key);
1065 $prop = '_' . $this->fields
[$key]['propname'];
1067 if (isset($values[$key])) {
1068 $value = $values[$key];
1069 if ($value !== true && $value !== false) {
1070 $value = trim($value);
1072 } elseif ($this->_id
== '' ||
$this->_id
== null) {
1074 case 'bool_admin_adh':
1075 case 'bool_exempt_adh':
1076 case 'bool_display_info':
1079 case 'activite_adh':
1080 //values that are setted at object instanciation
1083 case 'date_crea_adh':
1089 //values that are setted at object instanciation
1090 $value = $this->$prop;
1097 //keep stored value on update
1098 if ($prop != '_password' ||
isset($values['mdp_adh']) && isset($values['mdp_adh2'])) {
1099 $value = $this->$prop;
1105 // if the field is enabled, check it
1106 if (!isset($disabled[$key])) {
1107 // fill up the adherent structure
1108 if ($value !== null && $value !== true && $value !== false && !is_object($value)) {
1109 $value = stripslashes($value);
1111 $this->$prop = $value;
1113 // now, check validity
1114 if ($value !== null && $value != '') {
1115 $this->validate($key, $value, $values);
1116 } elseif (!isset($this->_id
)) {
1117 //ensure login and password are not empty
1118 if (($key == 'login_adh' ||
$key == 'mdp_adh') && !isset($required[$key])) {
1119 $p = new Password($this->zdb
);
1120 $generated_value = $p->makeRandomPassword(15);
1121 if ($key == 'login_adh') {
1122 //'@' is not permitted in logins
1123 $this->$prop = str_replace('@', 'a', $generated_value);
1125 $this->$prop = $generated_value;
1132 // missing required fields?
1133 foreach ($required as $key => $val) {
1134 $prop = '_' . $this->fields
[$key]['propname'];
1136 if (!isset($disabled[$key])) {
1137 $mandatory_missing = false;
1138 if (!isset($this->$prop) ||
$this->$prop == '') {
1139 $mandatory_missing = true;
1140 } elseif ($key === 'titre_adh' && $this->$prop == '-1') {
1141 $mandatory_missing = true;
1144 if ($mandatory_missing === true) {
1145 $this->errors
[] = str_replace(
1147 '<a href="#' . $key . '">' . $this->getFieldLabel($key) . '</a>',
1148 _T("- Mandatory field %field empty.")
1154 //attach to/detach from parent
1155 if (isset($values['detach_parent'])) {
1156 $this->_parent
= null;
1159 $this->dynamicsCheck($values, $required, $disabled);
1161 if (count($this->errors
) > 0) {
1163 'Some errors has been throwed attempting to edit/store a member' . "\n" .
1164 print_r($this->errors
, true),
1167 return $this->errors
;
1172 'Member checked successfully.',
1180 * Validate data for given key
1181 * Set valid data in current object, also resets errors list
1183 * @param string $field Field name
1184 * @param mixed $value Value we want to set
1185 * @param array $values All values, for some references
1189 public function validate($field, $value, $values)
1191 global $preferences;
1193 $prop = '_' . $this->fields
[$field]['propname'];
1195 if ($value === null ||
(is_string($value) && trim($value) == '')) {
1196 //empty values are OK
1197 $this->$prop = $value;
1203 case 'date_crea_adh':
1204 case 'date_modif_adh_':
1206 case 'date_echeance':
1208 $d = \DateTime
::createFromFormat(__("Y-m-d"), $value);
1210 //try with non localized date
1211 $d = \DateTime
::createFromFormat("Y-m-d", $value);
1213 throw new \
Exception('Incorrect format');
1217 if ($field === 'ddn_adh') {
1218 $now = new \
DateTime();
1219 $now->setTime(0, 0, 0);
1220 $d->setTime(0, 0, 0);
1222 $diff = $now->diff($d);
1223 $days = (int)$diff->format('%R%a');
1225 $this->errors
[] = _T('- Birthdate must be set in the past!');
1228 $years = (int)$diff->format('%R%Y');
1229 if ($years <= -200) {
1230 $this->errors
[] = str_replace(
1233 _T('- Members must be less than 200 years old (currently %years)!')
1237 $this->$prop = $d->format('Y-m-d');
1238 } catch (Throwable
$e) {
1240 'Wrong date format. field: ' . $field .
1241 ', value: ' . $value . ', expected fmt: ' .
1242 __("Y-m-d") . ' | ' . $e->getMessage(),
1245 $this->errors
[] = str_replace(
1252 $this->getFieldLabel($field)
1254 _T("- Wrong date format (%date_format) for %field!")
1259 if ($value !== null && $value !== '') {
1260 if ($value == '-1') {
1261 $this->$prop = null;
1262 } elseif (!$value instanceof Title
) {
1263 $this->$prop = new Title((int)$value);
1266 $this->$prop = null;
1271 if (!GaletteMail
::isValidEmail($value)) {
1272 $this->errors
[] = _T("- Non-valid E-Mail address!") .
1273 ' (' . $this->getFieldLabel($field) . ')';
1275 if ($field == 'email_adh') {
1277 $select = $this->zdb
->select(self
::TABLE
);
1280 )->where(array('email_adh' => $value));
1281 if ($this->_id
!= '' && $this->_id
!= null) {
1283 self
::PK
. ' != ' . $this->_id
1287 $results = $this->zdb
->execute($select);
1288 if ($results->count() !== 0) {
1289 $this->errors
[] = _T("- This E-Mail address is already used by another member!");
1291 } catch (Throwable
$e) {
1293 'An error occurred checking member email unicity.',
1296 $this->errors
[] = _T("An error has occurred while looking if login already exists.");
1301 if ($value == 'http://') {
1303 } elseif (!isValidWebUrl($value)) {
1304 $this->errors
[] = _T("- Non-valid Website address! Maybe you've skipped the http://?");
1308 /** FIXME: add a preference for login lenght */
1309 if (strlen($value) < 2) {
1310 $this->errors
[] = str_replace(
1313 _T("- The username must be composed of at least %i characters!")
1316 //check if login does not contain the @ character
1317 if (strpos($value, '@') != false) {
1318 $this->errors
[] = _T("- The username cannot contain the @ character");
1320 //check if login is already taken
1322 $select = $this->zdb
->select(self
::TABLE
);
1325 )->where(array('login_adh' => $value));
1326 if ($this->_id
!= '' && $this->_id
!= null) {
1328 self
::PK
. ' != ' . $this->_id
1332 $results = $this->zdb
->execute($select);
1334 $results->count() !== 0
1335 ||
$value == $preferences->pref_admin_login
1337 $this->errors
[] = _T("- This username is already in use, please choose another one!");
1339 } catch (Throwable
$e) {
1341 'An error occurred checking member login unicity.',
1344 $this->errors
[] = _T("An error has occurred while looking if login already exists.");
1351 $this->_self_adh
!== true
1352 && (!isset($values['mdp_adh2'])
1353 ||
$values['mdp_adh2'] != $value)
1355 $this->errors
[] = _T("- The passwords don't match!");
1357 $this->_self_adh
=== true
1358 && !crypt($value, $values['mdp_crypt']) == $values['mdp_crypt']
1360 $this->errors
[] = _T("Password misrepeated: ");
1362 $pinfos = password_get_info($value);
1363 //check if value is already a hash
1364 if ($pinfos['algo'] == 0) {
1365 $this->$prop = password_hash(
1370 $pwcheck = new \Galette\Util\
Password($preferences);
1371 $pwcheck->setAdherent($this);
1372 if (!$pwcheck->isValid($value)) {
1373 $this->errors
= array_merge(
1375 $pwcheck->getErrors()
1383 $this->$prop = (int)$value;
1384 //check if status exists
1385 $select = $this->zdb
->select(Status
::TABLE
);
1386 $select->where(Status
::PK
. '= ' . $value);
1388 $results = $this->zdb
->execute($select);
1389 $result = $results->current();
1391 $this->errors
[] = str_replace(
1394 _T("Status #%id does not exists in database.")
1398 } catch (Throwable
$e) {
1400 'An error occurred checking status existance: ' . $e->getMessage(),
1403 $this->errors
[] = _T("An error has occurred while looking if status does exists.");
1407 if (in_array($value, [self
::NC
, self
::MAN
, self
::WOMAN
])) {
1408 $this->$prop = (int)$value;
1410 $this->errors
[] = _T("Gender %gender does not exists!");
1414 $this->$prop = ($value instanceof Adherent
) ?
(int)$value->id
: (int)$value;
1415 $this->loadParent();
1425 public function store()
1427 global $hist, $emitter;
1432 $fields = self
::getDbFields($this->zdb
);
1434 foreach ($fields as $field) {
1436 $field !== 'date_modif_adh'
1437 ||
!isset($this->_id
)
1440 $prop = '_' . $this->fields
[$field]['propname'];
1442 ($field === 'bool_admin_adh'
1443 ||
$field === 'bool_exempt_adh'
1444 ||
$field === 'bool_display_info'
1445 ||
$field === 'activite_adh')
1446 && $this->$prop === false
1448 //Handle booleans for postgres ; bugs #18899 and #19354
1449 $values[$field] = $this->zdb
->isPostgres() ?
'false' : 0;
1450 } elseif ($field === 'parent_id') {
1452 if ($this->_parent
=== null) {
1453 $values['parent_id'] = new Expression('NULL');
1454 } elseif ($this->parent
instanceof Adherent
) {
1455 $values['parent_id'] = $this->_parent
->id
;
1457 $values['parent_id'] = $this->_parent
;
1460 $values[$field] = $this->$prop;
1465 //an empty value will cause date to be set to 1901-01-01, a null
1466 //will result in 0000-00-00. We want a database NULL value here.
1467 if (!$this->_birthdate
) {
1468 $values['ddn_adh'] = new Expression('NULL');
1470 if (!$this->_due_date
) {
1471 $values['date_echeance'] = new Expression('NULL');
1474 if ($this->_title
instanceof Title
) {
1475 $values['titre_adh'] = $this->_title
->id
;
1477 $values['titre_adh'] = new Expression('NULL');
1480 if (!$this->_parent
) {
1481 $values['parent_id'] = new Expression('NULL');
1484 //fields that cannot be null
1486 '_surname' => 'prenom_adh',
1487 '_nickname' => 'pseudo_adh',
1488 '_address' => 'adresse_adh',
1489 '_zipcode' => 'cp_adh',
1490 '_town' => 'ville_adh'
1492 foreach ($notnull as $prop => $field) {
1493 if ($this->$prop === null) {
1494 $values[$field] = '';
1499 if (!isset($this->_id
) ||
$this->_id
== '') {
1500 //we're inserting a new member
1501 unset($values[self
::PK
]);
1502 //set modification date
1503 $this->_modification_date
= date('Y-m-d');
1504 $values['date_modif_adh'] = $this->_modification_date
;
1506 $insert = $this->zdb
->insert(self
::TABLE
);
1507 $insert->values($values);
1508 $add = $this->zdb
->execute($insert);
1509 if ($add->count() > 0) {
1510 $this->_id
= $this->zdb
->getLastGeneratedValue($this);
1511 $this->_picture
= new Picture($this->_id
);
1513 if ($this->_self_adh
) {
1515 _T("Self_subscription as a member: ") .
1516 $this->getNameWithCase($this->_name
, $this->_surname
),
1521 _T("Member card added"),
1527 $event = 'member.add';
1529 $hist->add(_T("Fail to add new member."));
1530 throw new \
Exception(
1531 'An error occurred inserting new member!'
1535 //we're editing an existing member
1536 if (!$this->isDueFree()) {
1538 $due_date = Contribution
::getDueDate($this->zdb
, $this->_id
);
1540 $values['date_echeance'] = $due_date;
1544 if (!$this->_password
) {
1545 unset($values['mdp_adh']);
1548 $update = $this->zdb
->update(self
::TABLE
);
1549 $update->set($values);
1551 self
::PK
. '=' . $this->_id
1554 $edit = $this->zdb
->execute($update);
1556 //edit == 0 does not mean there were an error, but that there
1557 //were nothing to change
1558 if ($edit->count() > 0) {
1559 $this->updateModificationDate();
1561 _T("Member card updated"),
1567 $event = 'member.edit';
1572 $success = $this->dynamicsStore();
1575 //send event at the end of process, once all has been stored
1576 if ($event !== null) {
1577 $emitter->emit($event, $this);
1580 } catch (Throwable
$e) {
1582 'Something went wrong :\'( | ' . $e->getMessage() . "\n" .
1583 $e->getTraceAsString(),
1591 * Update member modification date
1595 private function updateModificationDate()
1598 $modif_date = date('Y-m-d');
1599 $update = $this->zdb
->update(self
::TABLE
);
1601 array('date_modif_adh' => $modif_date)
1602 )->where(self
::PK
. '=' . $this->_id
);
1604 $edit = $this->zdb
->execute($update);
1605 $this->_modification_date
= $modif_date;
1606 } catch (Throwable
$e) {
1608 'Something went wrong updating modif date :\'( | ' .
1609 $e->getMessage() . "\n" . $e->getTraceAsString(),
1616 * Global getter method
1618 * @param string $name name of the property we want to retrive
1620 * @return false|object the called property
1622 public function __get($name)
1625 'admin', 'staff', 'due_free', 'appears_in_list', 'active',
1626 'row_classes', 'oldness', 'duplicate'
1628 if (!defined('GALETTE_TESTS')) {
1629 $forbidden[] = 'password'; //keep that for tests only
1633 'sadmin', 'sstaff', 'sdue_free', 'sappears_in_list', 'sactive',
1634 'stitle', 'sstatus', 'sfullname', 'sname', 'saddress',
1635 'rbirthdate', 'sgender', 'contribstatus'
1638 if (in_array($name, $forbidden)) {
1641 return $this->isAdmin();
1643 return $this->isStaff();
1645 return $this->isDueFree();
1646 case 'appears_in_list':
1647 return $this->appearsInMembersList();
1649 return $this->isActive();
1651 return $this->isDuplicate();
1653 throw new \
RuntimeException("Call to __get for '$name' is forbidden!");
1656 if (in_array($name, $virtuals)) {
1657 if (substr($name, 0, 1) !== '_') {
1658 $real = '_' . substr($name, 1);
1665 case 'sappears_in_list':
1667 return (($this->$real) ?
_T("Yes") : _T("No"));
1670 return (($this->$real) ?
_T("Active") : _T("Inactive"));
1673 if (isset($this->_title
) && $this->_title
instanceof Title
) {
1674 return $this->_title
->tshort
;
1680 $status = new Status($this->zdb
);
1681 return $status->getLabel($this->_status
);
1684 return $this->getNameWithCase(
1687 (isset($this->_title
) ?
$this->title
: false)
1691 $address = $this->_address
;
1692 if ($this->_address_continuation
!== '' && $this->_address_continuation
!== null) {
1693 $address .= "\n" . $this->_address_continuation
;
1695 return htmlspecialchars($address, ENT_QUOTES
);
1698 return $this->getNameWithCase($this->_name
, $this->_surname
);
1701 return $this->_birthdate
;
1704 switch ($this->gender
) {
1710 return _T('Unspecified');
1713 case 'contribstatus':
1714 return $this->getDues();
1718 if (substr($name, 0, 1) !== '_') {
1719 $rname = '_' . $name;
1727 if ($this->$rname !== null) {
1728 return (int)$this->$rname;
1734 case 'creation_date':
1735 case 'modification_date':
1737 if ($this->$rname != '') {
1739 $d = new \
DateTime($this->$rname);
1740 return $d->format(__("Y-m-d"));
1741 } catch (Throwable
$e) {
1742 //oops, we've got a bad date :/
1744 'Bad date (' . $this->$rname . ') | ' .
1748 return $this->$rname;
1753 if (!property_exists($this, $rname)) {
1755 "Unknown property '$rname'",
1760 return $this->$rname;
1770 * If member does not have an email address, but is attached to
1771 * another member, we'll take information from its parent.
1775 public function getEmail()
1777 $email = $this->_email
;
1778 if (empty($email)) {
1779 $this->loadParent();
1780 $email = $this->parent
->email
;
1787 * Get member address.
1788 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1792 public function getAddress()
1794 $address = $this->_address
;
1795 if (empty($address) && $this->hasParent()) {
1796 $this->loadParent();
1797 $address = $this->parent
->address
;
1804 * Get member address continuation.
1805 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1809 public function getAddressContinuation()
1811 $address = $this->_address
;
1812 $address_continuation = $this->_address_continuation
;
1813 if (empty($address) && $this->hasParent()) {
1814 $this->loadParent();
1815 $address_continuation = $this->parent
->address_continuation
;
1818 return $address_continuation;
1822 * Get member zipcode.
1823 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1827 public function getZipcode()
1829 $address = $this->_address
;
1830 $zip = $this->_zipcode
;
1831 if (empty($address) && $this->hasParent()) {
1832 $this->loadParent();
1833 $zip = $this->parent
->zipcode
;
1841 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1845 public function getTown()
1847 $address = $this->_address
;
1848 $town = $this->_town
;
1849 if (empty($address) && $this->hasParent()) {
1850 $this->loadParent();
1851 $town = $this->parent
->town
;
1858 * Get member country.
1859 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1863 public function getCountry()
1865 $address = $this->_address
;
1866 $country = $this->_country
;
1867 if (empty($address) && $this->hasParent()) {
1868 $this->loadParent();
1869 $country = $this->parent
->country
;
1880 public function getAge()
1882 if ($this->_birthdate
== null) {
1886 $d = \DateTime
::createFromFormat('Y-m-d', $this->_birthdate
);
1889 'Invalid birthdate: ' . $this->_birthdate
,
1897 $d->diff(new \
DateTime())->y
,
1898 _T(' (%age years old)')
1903 * Get parent inherited fields
1907 public function getParentFields()
1909 return $this->parent_fields
;
1913 * Handle files (photo and dynamics files)
1915 * @param array $files Files sent
1917 * @return array|true
1919 public function handleFiles($files)
1923 if (isset($files['photo'])) {
1924 if ($files['photo']['error'] === UPLOAD_ERR_OK
) {
1925 if ($files['photo']['tmp_name'] != '') {
1926 if (is_uploaded_file($files['photo']['tmp_name'])) {
1927 $res = $this->picture
->store($files['photo']);
1930 = $this->picture
->getErrorMessage($res);
1934 } elseif ($files['photo']['error'] !== UPLOAD_ERR_NO_FILE
) {
1936 $this->picture
->getPhpErrorMessage($files['photo']['error']),
1939 $this->errors
[] = $this->picture
->getPhpErrorMessage(
1940 $files['photo']['error']
1944 $this->dynamicsFiles($files);
1946 if (count($this->errors
) > 0) {
1948 'Some errors has been throwed attempting to edit/store a member files' . "\n" .
1949 print_r($this->errors
, true),
1952 return $this->errors
;
1959 * Set member as duplicate
1963 public function setDuplicate()
1965 //mark as duplicated
1966 $this->_duplicate
= true;
1967 $infos = $this->_others_infos_admin
;
1968 $this->_others_infos_admin
= str_replace(
1970 [$this->sname
, $this->_id
],
1971 _T('Duplicated from %name (%id)')
1973 if (!empty($infos)) {
1974 $this->_others_infos_admin
.= "\n" . $infos;
1978 //drop email, must be unique
1979 $this->_email
= null;
1980 //drop creation date
1981 $this->_creation_date
= date("Y-m-d");
1983 $this->_login
= null;
1985 $this->_picture
= new Picture();
1987 $this->_birthdate
= null;
1989 $this->_surname
= null;
1991 $this->_admin
= false;
1993 $this->_due_free
= false;
1997 * Get current errors
2001 public function getErrors()
2003 return $this->errors
;
2011 public function getGroups()
2013 return $this->_groups
;
2017 * Get user managed groups
2021 public function getManagedGroups()
2023 return $this->_managed_groups
;
2027 * Can current logged in user edit member
2029 * @param Login $login Login instance
2033 public function canEdit($login)
2035 if ($this->id
&& $login->id
== $this->id ||
$login->isAdmin() ||
$login->isStaff()) {
2039 //check if requested member is part of managed groups
2040 if ($login->isGroupManager()) {
2041 foreach ($this->getGroups() as $g) {
2042 if ($login->isGroupManager($g->getId())) {
2052 * Are we currently duplicated a member?
2056 public function isDuplicate()
2058 return $this->_duplicate
;
2062 * Flag creation mail sending
2064 * @param boolean $send True (default) to send creation email
2068 public function setSendmail($send = true)
2070 $this->sendmail
= $send;
2075 * Should we send administrative emails to member?
2079 public function sendEMail()
2081 return $this->sendmail
;