3 /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
6 * Member class for galette
10 * Copyright © 2009-2014 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-2014 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
34 * @link http://galette.tuxfamily.org
35 * @since Available since 0.7dev - 2009-06-02
38 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-2014 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
67 const TABLE
= 'adherents';
74 const AFTER_ADD_DEFAULT
= 0;
75 const AFTER_ADD_TRANS
= 1;
76 const AFTER_ADD_NEW
= 2;
77 const AFTER_ADD_SHOW
= 3;
78 const AFTER_ADD_LIST
= 4;
79 const AFTER_ADD_HOME
= 5;
84 private $_company_name;
89 private $_birth_place;
97 private $_address_continuation; /** TODO: remove */
105 private $_msn; /** TODO: remove */
106 private $_icq; /** TODO: remove */
107 private $_jabber; /** TODO: remove */
108 private $_gnupgid; /** TODO: remove */
109 private $_fingerprint; /** TODO: remove */
110 //Galette relative information
111 private $_appears_in_list;
117 private $_creation_date;
118 private $_modification_date;
120 private $_others_infos;
121 private $_others_infos_admin;
124 private $_days_remaining;
126 private $_managed_groups;
129 private $_duplicate = false;
131 private $_row_classes;
132 //fields list and their translation
133 private $_self_adh = false;
134 private $_deps = array(
144 private $preferences;
148 private $parent_fields = [
156 private $errors = [];
159 * Default constructor
161 * @param Db $zdb Database instance
162 * @param mixed $args Either a ResultSet row, its id or its
163 * login or its email for to load s specific
164 * member, or null to just instanciate object
165 * @param boolean $deps Dependencies configuration, see Adherent::$_deps
167 public function __construct(Db
$zdb, $args = null, $deps = null)
173 if ($deps !== null) {
174 if (is_array($deps)) {
175 $this->_deps
= array_merge(
179 } elseif ($deps === false) {
181 $this->deps
= array_fill_keys(
182 array_keys($this->deps
),
187 '$deps shoud be an array, ' . gettype($deps) . ' given!',
193 if ($args == null ||
is_int($args)) {
194 if (is_int($args) && $args > 0) {
197 $this->_active
= true;
198 $this->_language
= $i18n->getID();
199 $this->_creation_date
= date("Y-m-d");
200 $this->_status
= $this->getDefaultStatus();
201 $this->_title
= null;
202 $this->_gender
= self
::NC
;
203 $gp = new Password($this->zdb
);
204 $this->_password
= $gp->makeRandomPassword();
205 $this->_picture
= new Picture();
206 $this->_admin
= false;
207 $this->_staff
= false;
208 $this->_due_free
= false;
209 $this->_appears_in_list
= false;
210 $this->_parent
= null;
212 if ($this->_deps
['dynamics'] === true) {
213 $this->loadDynamicFields();
216 } elseif (is_object($args)) {
217 $this->loadFromRS($args);
218 } elseif (is_string($args)) {
219 $this->loadFromLoginOrMail($args);
224 * Loads a member from its id
226 * @param int $id the identifiant for the member to load
228 * @return bool true if query succeed, false otherwise
230 public function load($id)
233 $select = $this->zdb
->select(self
::TABLE
, 'a');
236 array('b' => PREFIX_DB
. Status
::TABLE
),
237 'a.' . Status
::PK
. '=b.' . Status
::PK
,
238 array('priorite_statut')
239 )->where(array(self
::PK
=> $id));
241 $results = $this->zdb
->execute($select);
243 if ($results->count() === 0) {
247 $this->loadFromRS($results->current());
249 } catch (\Exception
$e) {
251 'Cannot load member form id `' . $id . '` | ' . $e->getMessage(),
259 * Loads a member from its login
261 * @param string $login login for the member to load
263 * @return bool true if query succeed, false otherwise
265 public function loadFromLoginOrMail($login)
268 $select = $this->zdb
->select(self
::TABLE
);
269 if (GaletteMail
::isValidEmail($login)) {
270 //we got a valid email address, use it
271 $select->where(array('email_adh' => $login));
273 ///we did not get an email address, consider using login
274 $select->where(array('login_adh' => $login));
277 $results = $this->zdb
->execute($select);
278 $result = $results->current();
280 $this->loadFromRS($result);
282 } catch (\Exception
$e) {
284 'Cannot load member form login `' . $login . '` | ' .
293 * Populate object from a resultset row
295 * @param ResultSet $r the resultset row
299 private function loadFromRS($r)
301 $this->_self_adh
= false;
302 $this->_id
= $r->id_adh
;
304 if ($r->titre_adh
!== null) {
305 $this->_title
= new Title((int)$r->titre_adh
);
307 $this->_company_name
= $r->societe_adh
;
308 $this->_name
= $r->nom_adh
;
309 $this->_surname
= $r->prenom_adh
;
310 $this->_nickname
= $r->pseudo_adh
;
311 if ($r->ddn_adh
!= '1901-01-01') {
312 $this->_birthdate
= $r->ddn_adh
;
314 $this->_birth_place
= $r->lieu_naissance
;
315 $this->_gender
= (int)$r->sexe_adh
;
316 $this->_job
= $r->prof_adh
;
317 $this->_language
= $r->pref_lang
;
318 $this->_active
= ($r->activite_adh
== 1) ?
true : false;
319 $this->_status
= (int)$r->id_statut
;
320 //Contact information
321 $this->_address
= $r->adresse_adh
;
322 /** TODO: remove and merge with address */
323 $this->_address_continuation
= $r->adresse2_adh
;
324 $this->_zipcode
= $r->cp_adh
;
325 $this->_town
= $r->ville_adh
;
326 $this->_country
= $r->pays_adh
;
327 $this->_phone
= $r->tel_adh
;
328 $this->_gsm
= $r->gsm_adh
;
329 $this->_email
= $r->email_adh
;
330 $this->_website
= $r->url_adh
;
332 $this->_msn
= $r->msn_adh
;
334 $this->_icq
= $r->icq_adh
;
336 $this->_jabber
= $r->jabber_adh
;
338 $this->_gnupgid
= $r->gpgid
;
340 $this->_fingerprint
= $r->fingerprint
;
341 //Galette relative information
342 $this->_appears_in_list
= ($r->bool_display_info
== 1) ?
true : false;
343 $this->_admin
= ($r->bool_admin_adh
== 1) ?
true : false;
344 if (isset($r->priorite_statut
)
345 && $r->priorite_statut
< Members
::NON_STAFF_MEMBERS
347 $this->_staff
= true;
349 $this->_due_free
= ($r->bool_exempt_adh
== 1) ?
true : false;
350 $this->_login
= $r->login_adh
;
351 $this->_password
= $r->mdp_adh
;
352 $this->_creation_date
= $r->date_crea_adh
;
353 if ($r->date_modif_adh
!= '1901-01-01') {
354 $this->_modification_date
= $r->date_modif_adh
;
356 $this->_modification_date
= $this->_creation_date
;
358 $this->_due_date
= $r->date_echeance
;
359 $this->_others_infos
= $r->info_public_adh
;
360 $this->_others_infos_admin
= $r->info_adh
;
362 if ($r->parent_id
!== null) {
363 $this->_parent
= (int)$r->parent_id
;
364 if ($this->_deps
['parent'] === true) {
365 $this->loadParent($r->parent_id
);
369 if ($this->_deps
['children'] === true) {
370 $this->loadChildren();
373 if ($this->_deps
['picture'] === true) {
374 $this->_picture
= new Picture($this->_id
);
377 if ($this->_deps
['groups'] === true) {
381 if ($this->_deps
['dues'] === true) {
385 if ($this->_deps
['dynamics'] === true) {
386 $this->loadDynamicFields();
395 private function loadParent()
397 if (!$this->_parent
instanceof Adherent
) {
398 $deps = array_fill_keys(array_keys($this->_deps
), false);
399 $this->_parent
= new Adherent($this->zdb
, (int)$this->_parent
, $deps);
404 * Load member children
408 private function loadChildren()
410 $this->_children
= array();
413 $select = $this->zdb
->select(self
::TABLE
);
417 'parent_id = ' . $this->_id
420 $results = $this->zdb
->execute($select);
422 if ($results->count() > 0) {
423 foreach ($results as $row) {
424 $deps = $this->_deps
;
425 $deps['children'] = false;
426 $deps['parent'] = false;
427 $this->_children
[] = new Adherent($this->zdb
, (int)$row->$id, $deps);
430 } catch (\Exception
$e) {
432 'Cannot load children for member #' . $this->_id
. ' | ' .
445 public function loadGroups()
447 $this->_groups
= Groups
::loadGroups($this->_id
);
448 $this->_managed_groups
= Groups
::loadManagedGroups($this->_id
);
452 * Retrieve status from preferences
454 * @return pref_statut
457 private function getDefaultStatus()
460 if ($preferences->pref_statut
!= '') {
461 return $preferences->pref_statut
;
464 'Unable to get pref_statut; is it defined in preferences?',
467 return Status
::DEFAULT_STATUS
;
472 * Check for dues status
476 private function checkDues()
478 //how many days since our beloved member has been created
479 $date_now = new \
DateTime();
480 $this->_oldness
= $date_now->diff(
481 new \
DateTime($this->_creation_date
)
484 if ($this->isDueFree()) {
485 //no fee required, we don't care about dates
486 $this->_row_classes
.= ' cotis-exempt';
488 //ok, fee is required. Let's check the dates
489 if ($this->_due_date
== '') {
490 $this->_row_classes
.= ' cotis-never';
492 $date_end = new \
DateTime($this->_due_date
);
493 $date_diff = $date_now->diff($date_end);
494 $this->_days_remaining
= ( $date_diff->invert
== 1 )
495 ?
$date_diff->days
* -1
498 if ($this->_days_remaining
== 0) {
499 $this->_row_classes
.= ' cotis-lastday';
500 } elseif ($this->_days_remaining
< 0) {
501 $this->_row_classes
.= ' cotis-late';
502 } elseif ($this->_days_remaining
< 30) {
503 $this->_row_classes
.= ' cotis-soon';
505 $this->_row_classes
.= ' cotis-ok';
516 public function isAdmin()
518 return $this->_admin
;
522 * Is user member of staff?
526 public function isStaff()
528 return $this->_staff
;
532 * Is member freed of dues?
536 public function isDueFree()
538 return $this->_due_free
;
542 * Is member in specified group?
544 * @param string $group_name Group name
548 public function isGroupMember($group_name)
550 if (is_array($this->_groups
)) {
551 foreach ($this->_groups
as $g) {
552 if ($g->getName() == $group_name) {
559 'Calling ' . __METHOD__
. ' without groups loaded!',
567 * Is member manager of specified group?
569 * @param string $group_name Group name
573 public function isGroupManager($group_name)
575 if (is_array($this->_managed_groups
)) {
576 foreach ($this->_managed_groups
as $mg) {
577 if ($mg->getName() == $group_name) {
584 'Calling ' . __METHOD__
. ' without groups loaded!',
592 * Does current member represents a company?
596 public function isCompany()
598 return trim($this->_company_name
) != '';
602 * Is current member a man?
606 public function isMan()
608 return (int)$this->_gender
=== self
::MAN
;
612 * Is current member a woman?
616 public function isWoman()
618 return (int)$this->_gender
=== self
::WOMAN
;
623 * Can member appears in public members list?
627 public function appearsInMembersList()
629 return $this->_appears_in_list
;
637 public function isActive()
639 return $this->_active
;
643 * Does member have uploaded a picture?
647 public function hasPicture()
649 return $this->_picture
->hasPicture();
653 * Does member have a parent?
657 public function hasParent()
659 return !empty($this->_parent
);
663 * Does member have children?
667 public function hasChildren()
669 if ($this->_children
=== null) {
672 'Children has not been loaded!',
678 return count($this->_children
) > 0;
683 * Get row class related to current fee status
685 * @param boolean $public we want the class for public pages
687 * @return string the class to apply
689 public function getRowClass($public = false)
691 $strclass = ($this->isActive()) ?
'active' : 'inactive';
692 if ($public === false) {
693 $strclass .= $this->_row_classes
;
699 * Get current member due status
701 * @return string i18n string representing state of due
703 public function getDues()
706 if ($this->isDueFree()) {
707 $ret = _T("Freed of dues");
708 } elseif ($this->_due_date
== '') {
709 $patterns = array('/%days/', '/%date/');
710 $cdate = new \
DateTime($this->_creation_date
);
713 $cdate->format(__("Y-m-d"))
715 if ($this->_active
) {
719 _T("Never contributed: Registered %days days ago (since %date)")
722 $ret = _T("Never contributed");
724 } elseif ($this->_days_remaining
== 0) {
725 $ret = _T("Last day!");
726 } elseif ($this->_days_remaining
< 0) {
727 $patterns = array('/%days/', '/%date/');
728 $ddate = new \
DateTime($this->_due_date
);
730 $this->_days_remaining
*-1,
731 $ddate->format(__("Y-m-d"))
733 if ($this->_active
) {
737 _T("Late of %days days (since %date)")
743 $patterns = array('/%days/', '/%date/');
744 $ddate = new \
DateTime($this->_due_date
);
746 $this->_days_remaining
,
747 $ddate->format(__("Y-m-d"))
752 _T("%days days remaining (ending on %date)")
759 * Retrieve Full name and surname for the specified member id
761 * @param Db $zdb Database instance
762 * @param integer $id Member id
763 * @param boolean $wid Add member id
764 * @param boolean $wnick Add member nickname
766 * @return string formatted Name and Surname
768 public static function getSName($zdb, $id, $wid = false, $wnick = false)
771 $select = $zdb->select(self
::TABLE
);
772 $select->where(self
::PK
. ' = ' . $id);
774 $results = $zdb->execute($select);
775 $row = $results->current();
776 return self
::getNameWithCase(
780 ($wid === true ?
$row->id_adh
: false),
781 ($wnick === true ?
$row->pseudo_adh
: false)
783 } catch (\Exception
$e) {
785 'Cannot get formatted name for member form id `' . $id . '` | ' .
794 * Get member name with correct case
796 * @param string $name Member name
797 * @param string $surname Mmeber surname
798 * @param false|Title $title Member title to show or false
799 * @param false|integer $id Member id to display or false
800 * @param false|string $nick Member nickname to display or false
804 public static function getNameWithCase($name, $surname, $title = false, $id = false, $nick = false)
808 if ($title !== false && $title instanceof Title
) {
809 $str .= $title->tshort
. ' ';
812 $str .= mb_strtoupper($name, 'UTF-8') . ' ' .
813 ucwords(mb_strtolower($surname, 'UTF-8'), " \t\r\n\f\v-_|");
815 if ($id !== false ||
$nick !== false) {
818 if ($nick !== false) {
822 if ($nick !== false && !empty($nick)) {
827 if ($id !== false ||
$nick !== false) {
834 * Change password for a given user
836 * @param Db $zdb Database instance
837 * @param string $id_adh Member identifier
838 * @param string $pass New password
842 public static function updatePassword(Db
$zdb, $id_adh, $pass)
845 $cpass = password_hash($pass, PASSWORD_BCRYPT
);
847 $update = $zdb->update(self
::TABLE
);
849 array('mdp_adh' => $cpass)
850 )->where(self
::PK
. ' = ' . $id_adh);
851 $zdb->execute($update);
853 'Password for `' . $id_adh . '` has been updated.',
857 } catch (\Exception
$e) {
859 'An error occurred while updating password for `' . $id_adh .
860 '` | ' . $e->getMessage(),
870 * @param string $field Field name
874 private function getFieldLabel($field)
876 $label = $this->fields
[$field]['label'];
877 //remove trailing ':' and then nbsp (for french at least)
878 $label = trim(trim($label, ':'), ' ');
883 * Retrieve fields from database
885 * @param Db $zdb Database instance
889 public static function getDbFields(Db
$zdb)
891 $columns = $zdb->getColumns(self
::TABLE
);
893 foreach ($columns as $col) {
894 $fields[] = $col->getName();
900 * Mark as self membership
904 public function setSelfMembership()
906 $this->_self_adh
= true;
910 * Is member up to date?
914 public function isUp2Date()
916 if ($this->_deps
['dues']) {
917 if ($this->isDueFree()) {
918 //member is due free, he's up to date.
921 //let's check from end date, if present
922 if ($this->_due_date
== null) {
925 $ech = new \
DateTime($this->_due_date
);
926 $now = new \
DateTime();
927 $now->setTime(0, 0, 0);
932 throw new \
RuntimeException(
933 'Cannot check if member is up to date, dues deps is disabled!'
941 * @param Preferences $preferences Preferences instance
942 * @param array $fields Members fields configuration
943 * @param History $history History instance
947 public function setDependencies(
948 Preferences
$preferences,
952 $this->preferences
= $preferences;
953 $this->fields
= $fields;
954 $this->history
= $history;
958 * Check posted values validity
960 * @param array $values All values to check, basically the $_POST array
961 * after sending the form
962 * @param array $required Array of required fields
963 * @param array $disabled Array of disabled fields
967 public function check($values, $required, $disabled)
969 $this->errors
= array();
971 $fields = self
::getDbFields($this->zdb
);
973 //reset company name if needeed
974 if (!isset($values['is_company'])) {
975 unset($values['is_company']);
976 $values['societe_adh'] = '';
979 //no parent if checkbox was unchecked
980 if (!isset($values['attach'])
982 && isset($values['parent_id'])
984 unset($values['parent_id']);
987 if (isset($values['duplicate'])) {
988 //if we're duplicating, keep a trace (if an error occurs)
989 $this->_duplicate
= true;
992 foreach ($fields as $key) {
993 //first of all, let's sanitize values
994 $key = strtolower($key);
995 $prop = '_' . $this->fields
[$key]['propname'];
997 if (isset($values[$key])) {
998 $value = $values[$key];
999 if ($value !== true && $value !== false) {
1000 $value = trim($value);
1002 } elseif ($this->_id
== '' ||
$this->_id
== null) {
1004 case 'bool_admin_adh':
1005 case 'bool_exempt_adh':
1006 case 'bool_display_info':
1009 case 'activite_adh':
1010 //values that are setted at object instanciation
1013 case 'date_crea_adh':
1019 //values that are setted at object instanciation
1020 $value = $this->$prop;
1026 //keep stored value on update
1027 if ($prop != '_password' ||
isset($values['mdp_adh']) && isset($values['mdp_adh2'])) {
1028 $value = $this->$prop;
1034 // if the field is enabled, check it
1035 if (!isset($disabled[$key])) {
1036 // fill up the adherent structure
1037 if ($value !== null && $value !== true && $value !== false && !is_object($value)) {
1038 $value = stripslashes($value);
1040 $this->$prop = $value;
1042 // now, check validity
1043 if ($value !== null && $value != '') {
1044 $this->validate($key, $value, $values);
1045 } elseif (($key == 'login_adh' && !isset($required['login_adh']))
1046 ||
($key == 'mdp_adh' && !isset($required['mdp_adh']))
1047 && !isset($this->_id
)
1049 $p = new Password($this->zdb
);
1050 $this->$prop = $p->makeRandomPassword(15);
1055 // missing required fields?
1056 foreach ($required as $key => $val) {
1057 $prop = '_' . $this->fields
[$key]['propname'];
1059 if (!isset($disabled[$key])) {
1060 $mandatory_missing = false;
1061 if (!isset($this->$prop) ||
$this->$prop == '') {
1062 $mandatory_missing = true;
1063 } elseif ($key === 'titre_adh' && $this->$prop == '-1') {
1064 $mandatory_missing = true;
1067 if ($mandatory_missing === true) {
1068 $this->errors
[] = str_replace(
1070 '<a href="#' . $key . '">' . $this->getFieldLabel($key) .'</a>',
1071 _T("- Mandatory field %field empty.")
1077 //attach to/detach from parent
1078 if (isset($values['detach_parent'])) {
1079 $this->_parent
= null;
1082 $this->dynamicsCheck($values);
1084 if (count($this->errors
) > 0) {
1086 'Some errors has been throwed attempting to edit/store a member' . "\n" .
1087 print_r($this->errors
, true),
1090 return $this->errors
;
1095 'Member checked successfully.',
1103 * Validate data for given key
1104 * Set valid data in current object, also resets errors list
1106 * @param string $field Field name
1107 * @param mixed $value Value we want to set
1108 * @param array $values All values, for some references
1112 public function validate($field, $value, $values)
1114 global $preferences;
1116 $prop = '_' . $this->fields
[$field]['propname'];
1118 if ($value === null ||
(is_string($value) && trim($value) == '')) {
1119 //empty values are OK
1120 $this->$prop = $value;
1126 case 'date_crea_adh':
1127 case 'date_modif_adh_':
1129 case 'date_echeance':
1131 $d = \DateTime
::createFromFormat(__("Y-m-d"), $value);
1133 //try with non localized date
1134 $d = \DateTime
::createFromFormat("Y-m-d", $value);
1136 throw new \
Exception('Incorrect format');
1140 if ($field === 'ddn_adh') {
1141 $now = new \
DateTime();
1142 $now->setTime(0, 0, 0);
1143 $d->setTime(0, 0, 0);
1145 $diff = $now->diff($d);
1146 $days = (integer)$diff->format('%R%a');
1148 $this->errors
[] =_T('- Birthdate must be set in the past!');
1151 $years = (integer)$diff->format('%R%Y');
1152 if ($years <= -200) {
1153 $this->errors
[] = str_replace(
1156 _T('- Members must be less than 200 years old (currently %years)!')
1160 $this->$prop = $d->format('Y-m-d');
1161 } catch (\Exception
$e) {
1163 'Wrong date format. field: ' . $field .
1164 ', value: ' . $value . ', expected fmt: ' .
1165 __("Y-m-d") . ' | ' . $e->getMessage(),
1168 $this->errors
[] = str_replace(
1175 $this->getFieldLabel($field)
1177 _T("- Wrong date format (%date_format) for %field!")
1182 if ($value !== null && $value !== '') {
1183 if ($value == '-1') {
1184 $this->$prop = null;
1185 } elseif (!$value instanceof Title
) {
1186 $this->$prop = new Title((int)$value);
1189 $this->$prop = null;
1194 if (!GaletteMail
::isValidEmail($value)) {
1195 $this->errors
[] = _T("- Non-valid E-Mail address!") .
1196 ' (' . $this->getFieldLabel($field) . ')';
1198 if ($field == 'email_adh') {
1200 $select = $this->zdb
->select(self
::TABLE
);
1203 )->where(array('email_adh' => $value));
1204 if ($this->_id
!= '' && $this->_id
!= null) {
1206 self
::PK
. ' != ' . $this->_id
1210 $results = $this->zdb
->execute($select);
1211 if ($results->count() !== 0) {
1212 $this->errors
[] = _T("- This E-Mail address is already used by another member!");
1214 } catch (\Exception
$e) {
1216 'An error occurred checking member email unicity.',
1219 $this->errors
[] = _T("An error has occurred while looking if login already exists.");
1224 if ($value == 'http://') {
1226 } elseif (!isValidWebUrl($value)) {
1227 $this->errors
[] = _T("- Non-valid Website address! Maybe you've skipped the http://?");
1231 /** FIXME: add a preference for login lenght */
1232 if (strlen($value) < 2) {
1233 $this->errors
[] = str_replace(
1236 _T("- The username must be composed of at least %i characters!")
1239 //check if login does not contain the @ character
1240 if (strpos($value, '@') != false) {
1241 $this->errors
[] = _T("- The username cannot contain the @ character");
1243 //check if login is already taken
1245 $select = $this->zdb
->select(self
::TABLE
);
1248 )->where(array('login_adh' => $value));
1249 if ($this->_id
!= '' && $this->_id
!= null) {
1251 self
::PK
. ' != ' . $this->_id
1255 $results = $this->zdb
->execute($select);
1256 if ($results->count() !== 0
1257 ||
$value == $preferences->pref_admin_login
1259 $this->errors
[] = _T("- This username is already in use, please choose another one!");
1261 } catch (\Exception
$e) {
1263 'An error occurred checking member login unicity.',
1266 $this->errors
[] = _T("An error has occurred while looking if login already exists.");
1272 if ($this->_self_adh
!== true
1273 && (!isset($values['mdp_adh2'])
1274 ||
$values['mdp_adh2'] != $value)
1276 $this->errors
[] = _T("- The passwords don't match!");
1277 } elseif ($this->_self_adh
=== true
1278 && !crypt($value, $values['mdp_crypt'])==$values['mdp_crypt']
1280 $this->errors
[] = _T("Password misrepeated: ");
1282 $pinfos = password_get_info($value);
1283 //check if value is already a hash
1284 if ($pinfos['algo'] == 0) {
1285 $this->$prop = password_hash(
1290 $pwcheck = new \Galette\Util\
Password($preferences);
1291 $pwcheck->setAdherent($this);
1292 if (!$pwcheck->isValid($value)) {
1293 $this->errors
= array_merge(
1295 $pwcheck->getErrors()
1303 $this->$prop = (int)$value;
1304 //check if status exists
1305 $select = $this->zdb
->select(Status
::TABLE
);
1306 $select->where(Status
::PK
. '= ' . $value);
1308 $results = $this->zdb
->execute($select);
1309 $result = $results->current();
1311 $this->errors
[] = str_replace(
1314 _T("Status #%id does not exists in database.")
1318 } catch (\Exception
$e) {
1320 'An error occurred checking status existance: ' . $e->getMessage(),
1323 $this->errors
[] = _T("An error has occurred while looking if status does exists.");
1327 if (in_array($value, [self
::NC
, self
::MAN
, self
::WOMAN
])) {
1328 $this->$prop = (int)$value;
1330 $this->errors
[] = _T("Gender %gender does not exists!");
1334 $this->$prop = (int)$value;
1335 $this->loadParent();
1345 public function store()
1347 global $hist, $emitter;
1351 $fields = self
::getDbFields($this->zdb
);
1353 foreach ($fields as $field) {
1354 if ($field !== 'date_modif_adh'
1355 ||
!isset($this->_id
)
1358 $prop = '_' . $this->fields
[$field]['propname'];
1359 if (($field === 'bool_admin_adh'
1360 ||
$field === 'bool_exempt_adh'
1361 ||
$field === 'bool_display_info'
1362 ||
$field === 'activite_adh')
1363 && $this->$prop === false
1365 //Handle booleans for postgres ; bugs #18899 and #19354
1366 $values[$field] = $this->zdb
->isPostgres() ?
'false' : 0;
1367 } elseif ($field === 'parent_id') {
1369 if ($this->_parent
=== null) {
1370 $values['parent_id'] = new Expression('NULL');
1371 } elseif ($this->parent
instanceof Adherent
) {
1372 $values['parent_id'] = $this->_parent
->id
;
1374 $values['parent_id'] = $this->_parent
;
1377 $values[$field] = $this->$prop;
1382 //an empty value will cause date to be set to 1901-01-01, a null
1383 //will result in 0000-00-00. We want a database NULL value here.
1384 if (!$this->_birthdate
) {
1385 $values['ddn_adh'] = new Expression('NULL');
1387 if (!$this->_due_date
) {
1388 $values['date_echeance'] = new Expression('NULL');
1391 if ($this->_title
instanceof Title
) {
1392 $values['titre_adh'] = $this->_title
->id
;
1394 $values['titre_adh'] = new Expression('NULL');
1397 if (!$this->_parent
) {
1398 $values['parent_id'] = new Expression('NULL');
1401 //fields that cannot be null
1403 '_surname' => 'prenom_adh',
1404 '_nickname' => 'pseudo_adh',
1405 '_address' => 'adresse_adh',
1406 '_zipcode' => 'cp_adh',
1407 '_town' => 'ville_adh'
1409 foreach ($notnull as $prop => $field) {
1410 if ($this->$prop === null) {
1411 $values[$field] = '';
1416 if (!isset($this->_id
) ||
$this->_id
== '') {
1417 //we're inserting a new member
1418 unset($values[self
::PK
]);
1419 //set modification date
1420 $this->_modification_date
= date('Y-m-d');
1421 $values['date_modif_adh'] = $this->_modification_date
;
1423 $insert = $this->zdb
->insert(self
::TABLE
);
1424 $insert->values($values);
1425 $add = $this->zdb
->execute($insert);
1426 if ($add->count() > 0) {
1427 if ($this->zdb
->isPostgres()) {
1428 $this->_id
= $this->zdb
->driver
->getLastGeneratedValue(
1429 PREFIX_DB
. 'adherents_id_seq'
1432 $this->_id
= $this->zdb
->driver
->getLastGeneratedValue();
1434 $this->_picture
= new Picture($this->_id
);
1436 if ($this->_self_adh
) {
1438 _T("Self_subscription as a member: ") .
1439 $this->getNameWithCase($this->_name
, $this->_surname
),
1444 _T("Member card added"),
1450 $emitter->emit('member.add', $this);
1452 $hist->add(_T("Fail to add new member."));
1453 throw new \
Exception(
1454 'An error occurred inserting new member!'
1458 //we're editing an existing member
1459 if (!$this->isDueFree()) {
1461 $due_date = Contribution
::getDueDate($this->zdb
, $this->_id
);
1463 $values['date_echeance'] = $due_date;
1467 if (!$this->_password
) {
1468 unset($values['mdp_adh']);
1471 $update = $this->zdb
->update(self
::TABLE
);
1472 $update->set($values);
1474 self
::PK
. '=' . $this->_id
1477 $edit = $this->zdb
->execute($update);
1479 //edit == 0 does not mean there were an error, but that there
1480 //were nothing to change
1481 if ($edit->count() > 0) {
1482 $this->updateModificationDate();
1484 _T("Member card updated"),
1490 $emitter->emit('member.edit', $this);
1495 $success = $this->dynamicsStore();
1499 } catch (\Exception
$e) {
1501 'Something went wrong :\'( | ' . $e->getMessage() . "\n" .
1502 $e->getTraceAsString(),
1510 * Update member modification date
1514 private function updateModificationDate()
1517 $modif_date = date('Y-m-d');
1518 $update = $this->zdb
->update(self
::TABLE
);
1520 array('date_modif_adh' => $modif_date)
1521 )->where(self
::PK
. '=' . $this->_id
);
1523 $edit = $this->zdb
->execute($update);
1524 $this->_modification_date
= $modif_date;
1525 } catch (\Exception
$e) {
1527 'Something went wrong updating modif date :\'( | ' .
1528 $e->getMessage() . "\n" . $e->getTraceAsString(),
1535 * Global getter method
1537 * @param string $name name of the property we want to retrive
1539 * @return false|object the called property
1541 public function __get($name)
1544 'admin', 'staff', 'due_free', 'appears_in_list', 'active',
1549 'sadmin', 'sstaff', 'sdue_free', 'sappears_in_list', 'sactive',
1550 'stitle', 'sstatus', 'sfullname', 'sname', 'rowclass', 'saddress',
1551 'rbirthdate', 'sgender', 'contribstatus'
1554 if (in_array($name, $forbidden)) {
1557 return $this->isAdmin();
1560 return $this->isStaff();
1563 return $this->isDueFree();
1565 case 'appears_in_list':
1566 return $this->appearsInMembersList();
1569 return $this->isActive();
1572 throw new \
RuntimeException("Call to __get for '$name' is forbidden!");
1575 if (in_array($name, $virtuals)) {
1576 if (substr($name, 0, 1) !== '_') {
1577 $real = '_' . substr($name, 1);
1584 case 'sappears_in_list':
1586 return (($this->$real) ?
_T("Yes") : _T("No"));
1589 return (($this->$real) ?
_T("Active") : _T("Inactive"));
1592 if (isset($this->_title
)) {
1593 return $this->_title
->tshort
;
1599 $status = new Status($this->zdb
);
1600 return $status->getLabel($this->_status
);
1603 return $this->getNameWithCase(
1606 (isset($this->_title
) ?
$this->title
: false)
1610 $address = $this->_address
;
1611 if ($this->_address_continuation
!== '' && $this->_address_continuation
!== null) {
1612 $address .= "\n" . $this->_address_continuation
;
1617 return $this->getNameWithCase($this->_name
, $this->_surname
);
1620 return $this->_birthdate
;
1623 switch ($this->gender
) {
1629 return __('Unspecified');
1632 case 'contribstatus':
1633 return $this->getDues();
1637 if (substr($name, 0, 1) !== '_') {
1638 $rname = '_' . $name;
1646 if ($this->$rname !== null) {
1647 return (int)$this->$rname;
1653 case 'creation_date':
1654 case 'modification_date':
1656 if ($this->$rname != '') {
1658 $d = new \
DateTime($this->$rname);
1659 return $d->format(__("Y-m-d"));
1660 } catch (\Exception
$e) {
1661 //oops, we've got a bad date :/
1663 'Bad date (' . $this->$rname . ') | ' .
1667 return $this->$rname;
1672 if (!property_exists($this, $rname)) {
1674 "Unknown property '$rname'",
1679 return $this->$rname;
1689 * If member does not have an email address, but is attached to
1690 * another member, we'll take information from its parent.
1694 public function getEmail()
1696 $email = $this->_email
;
1697 if (empty($email)) {
1698 $this->loadParent();
1699 $email = $this->parent
->email
;
1706 * Get member address.
1707 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1711 public function getAddress()
1713 $address = $this->_address
;
1714 if (empty($address) && $this->hasParent()) {
1715 $this->loadParent();
1716 $address = $this->parent
->address
;
1723 * Get member address continuation.
1724 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1728 public function getAddressContinuation()
1730 $address = $this->_address
;
1731 $address_continuation = $this->_address_continuation
;
1732 if (empty($address) && $this->hasParent()) {
1733 $this->loadParent();
1734 $address_continuation = $this->parent
->address_continuation
;
1737 return $address_continuation;
1741 * Get member zipcode.
1742 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1746 public function getZipcode()
1748 $address = $this->_address
;
1749 $zip = $this->_zipcode
;
1750 if (empty($address) && $this->hasParent()) {
1751 $this->loadParent();
1752 $zip = $this->parent
->zipcode
;
1760 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1764 public function getTown()
1766 $address = $this->_address
;
1767 $town = $this->_town
;
1768 if (empty($address) && $this->hasParent()) {
1769 $this->loadParent();
1770 $town = $this->parent
->town
;
1777 * Get member country.
1778 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1782 public function getCountry()
1784 $address = $this->_address
;
1785 $country = $this->_country
;
1786 if (empty($address) && $this->hasParent()) {
1787 $this->loadParent();
1788 $country = $this->parent
->country
;
1799 public function getAge()
1801 if ($this->_birthdate
== null) {
1805 $d = \DateTime
::createFromFormat('Y-m-d', $this->_birthdate
);
1808 'Invalid birthdate: ' . $this->_birthdate
,
1816 $d->diff(new \
DateTime())->y
,
1817 _T(' (%age years old)')
1822 * Get parent inherited fields
1826 public function getParentFields()
1828 return $this->parent_fields
;
1832 * Handle files (photo and dynamics files
1834 * @param array $files Files sent
1836 * @return array|true
1838 public function handleFiles($files)
1842 if (isset($files['photo'])) {
1843 if ($files['photo']['error'] === UPLOAD_ERR_OK
) {
1844 if ($files['photo']['tmp_name'] !='') {
1845 if (is_uploaded_file($files['photo']['tmp_name'])) {
1846 $res = $this->picture
->store($files['photo']);
1849 = $this->picture
->getErrorMessage($res);
1853 } elseif ($files['photo']['error'] !== UPLOAD_ERR_NO_FILE
) {
1855 $this->picture
->getPhpErrorMessage($files['photo']['error']),
1858 $this->errors
[] = $this->picture
->getPhpErrorMessage(
1859 $files['photo']['error']
1863 $this->dynamicsFiles($_FILES);
1865 if (count($this->errors
) > 0) {
1867 'Some errors has been throwed attempting to edit/store a member files' . "\n" .
1868 print_r($this->errors
, true),
1871 return $this->errors
;
1878 * Set member as duplicate
1882 public function setDuplicate()
1884 //mark as duplicated
1885 $this->_duplicate
= true;
1886 $infos = $this->_others_infos_admin
;
1887 $this->_others_infos_admin
= str_replace(
1889 [$this->sname
, $this->_id
],
1890 _T('Duplicated from %name (%id)')
1892 if (!empty($infos)) {
1893 $this->_others_infos_admin
.= "\n" . $infos;
1897 //drop email, must be unique
1898 $this->_email
= null;
1899 //drop creation date
1900 $this->_creation_date
= date("Y-m-d");
1902 $this->_login
= null;
1904 $this->_picture
= new Picture();
1906 $this->_birthdate
= null;
1908 $this->_surname
= null;
1910 $this->_admin
= false;
1912 $this->_due_free
= false;
1916 * Get current errors
1920 public function getErrors()
1922 return $this->errors
;
1930 public function getGroups()
1932 return $this->_groups
;
1936 * Get user managed groups
1940 public function getManagedGroups()
1942 return $this->_managed_groups
;
1946 * Can current logged in user edit member
1948 * @param Login $login Login instance
1952 public function canEdit($login)
1954 if ($this->id
&& $login->id
== $this->id ||
$login->isAdmin() ||
$login->isStaff()) {
1958 //check if requested member is part of managed groups
1959 if ($login->isGroupManager()) {
1960 foreach ($this->getGroups() as $g) {
1961 if ($login->isGroupManager($g->getId())) {
1971 * Are we currently duplicated a member?
1975 public function isDuplicate()
1977 return $this->_duplicate
;