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
33 * @link http://galette.tuxfamily.org
34 * @since Available since 0.7dev - 2009-06-02
37 namespace Galette\Entity
;
40 use Laminas\Db\Sql\Expression
;
42 use Galette\Core\Picture
;
43 use Galette\Core\GaletteMail
;
44 use Galette\Core\Password
;
45 use Galette\Core\Preferences
;
46 use Galette\Core\History
;
47 use Galette\Repository\Groups
;
48 use Galette\Repository\Members
;
51 * Member class for galette
56 * @author Johan Cwiklinski <johan@x-tnd.be>
57 * @copyright 2009-2014 The Galette Team
58 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL License 3.0 or (at your option) any later version
59 * @link http://galette.tuxfamily.org
60 * @since Available since 0.7dev - 02-06-2009
66 const TABLE
= 'adherents';
73 const AFTER_ADD_DEFAULT
= 0;
74 const AFTER_ADD_TRANS
= 1;
75 const AFTER_ADD_NEW
= 2;
76 const AFTER_ADD_SHOW
= 3;
77 const AFTER_ADD_LIST
= 4;
78 const AFTER_ADD_HOME
= 5;
83 private $_company_name;
88 private $_birth_place;
96 private $_address_continuation; /** TODO: remove */
104 private $_msn; /** TODO: remove */
105 private $_icq; /** TODO: remove */
106 private $_jabber; /** TODO: remove */
107 private $_gnupgid; /** TODO: remove */
108 private $_fingerprint; /** TODO: remove */
109 //Galette relative information
110 private $_appears_in_list;
116 private $_creation_date;
117 private $_modification_date;
119 private $_others_infos;
120 private $_others_infos_admin;
123 private $_days_remaining;
125 private $_managed_groups;
128 private $_duplicate = false;
130 private $_row_classes;
131 //fields list and their translation
132 private $_self_adh = false;
133 private $_deps = array(
143 private $preferences;
147 private $parent_fields = [
155 private $errors = [];
158 * Default constructor
160 * @param Db $zdb Database instance
161 * @param mixed $args Either a ResultSet row, its id or its
162 * login or its email for to load s specific
163 * member, or null to just instanciate object
164 * @param false|array $deps Dependencies configuration, see Adherent::$_deps
166 public function __construct(Db
$zdb, $args = null, $deps = null)
172 if ($deps !== null) {
173 if (is_array($deps)) {
174 $this->_deps
= array_merge(
178 } elseif ($deps === false) {
180 $this->_deps
= array_fill_keys(
181 array_keys($this->_deps
),
186 '$deps shoud be an array, ' . gettype($deps) . ' given!',
192 if ($args == null ||
is_int($args)) {
193 if (is_int($args) && $args > 0) {
196 $this->_active
= true;
197 $this->_language
= $i18n->getID();
198 $this->_creation_date
= date("Y-m-d");
199 $this->_status
= $this->getDefaultStatus();
200 $this->_title
= null;
201 $this->_gender
= self
::NC
;
202 $gp = new Password($this->zdb
);
203 $this->_password
= $gp->makeRandomPassword();
204 $this->_picture
= new Picture();
205 $this->_admin
= false;
206 $this->_staff
= false;
207 $this->_due_free
= false;
208 $this->_appears_in_list
= false;
209 $this->_parent
= null;
211 if ($this->_deps
['dynamics'] === true) {
212 $this->loadDynamicFields();
215 } elseif (is_object($args)) {
216 $this->loadFromRS($args);
217 } elseif (is_string($args)) {
218 $this->loadFromLoginOrMail($args);
223 * Loads a member from its id
225 * @param int $id the identifiant for the member to load
227 * @return bool true if query succeed, false otherwise
229 public function load($id)
232 $select = $this->zdb
->select(self
::TABLE
, 'a');
235 array('b' => PREFIX_DB
. Status
::TABLE
),
236 'a.' . Status
::PK
. '=b.' . Status
::PK
,
237 array('priorite_statut')
238 )->where(array(self
::PK
=> $id));
240 $results = $this->zdb
->execute($select);
242 if ($results->count() === 0) {
246 $this->loadFromRS($results->current());
248 } catch (\Exception
$e) {
250 'Cannot load member form id `' . $id . '` | ' . $e->getMessage(),
258 * Loads a member from its login
260 * @param string $login login for the member to load
262 * @return bool true if query succeed, false otherwise
264 public function loadFromLoginOrMail($login)
267 $select = $this->zdb
->select(self
::TABLE
);
268 if (GaletteMail
::isValidEmail($login)) {
269 //we got a valid email address, use it
270 $select->where(array('email_adh' => $login));
272 ///we did not get an email address, consider using login
273 $select->where(array('login_adh' => $login));
276 $results = $this->zdb
->execute($select);
277 $result = $results->current();
279 $this->loadFromRS($result);
281 } catch (\Exception
$e) {
283 'Cannot load member form login `' . $login . '` | ' .
292 * Populate object from a resultset row
294 * @param ResultSet $r the resultset row
298 private function loadFromRS($r)
300 $this->_self_adh
= false;
301 $this->_id
= $r->id_adh
;
303 if ($r->titre_adh
!== null) {
304 $this->_title
= new Title((int)$r->titre_adh
);
306 $this->_company_name
= $r->societe_adh
;
307 $this->_name
= $r->nom_adh
;
308 $this->_surname
= $r->prenom_adh
;
309 $this->_nickname
= $r->pseudo_adh
;
310 if ($r->ddn_adh
!= '1901-01-01') {
311 $this->_birthdate
= $r->ddn_adh
;
313 $this->_birth_place
= $r->lieu_naissance
;
314 $this->_gender
= (int)$r->sexe_adh
;
315 $this->_job
= $r->prof_adh
;
316 $this->_language
= $r->pref_lang
;
317 $this->_active
= ($r->activite_adh
== 1) ?
true : false;
318 $this->_status
= (int)$r->id_statut
;
319 //Contact information
320 $this->_address
= $r->adresse_adh
;
321 /** TODO: remove and merge with address */
322 $this->_address_continuation
= $r->adresse2_adh
;
323 $this->_zipcode
= $r->cp_adh
;
324 $this->_town
= $r->ville_adh
;
325 $this->_country
= $r->pays_adh
;
326 $this->_phone
= $r->tel_adh
;
327 $this->_gsm
= $r->gsm_adh
;
328 $this->_email
= $r->email_adh
;
329 $this->_website
= $r->url_adh
;
331 $this->_msn
= $r->msn_adh
;
333 $this->_icq
= $r->icq_adh
;
335 $this->_jabber
= $r->jabber_adh
;
337 $this->_gnupgid
= $r->gpgid
;
339 $this->_fingerprint
= $r->fingerprint
;
340 //Galette relative information
341 $this->_appears_in_list
= ($r->bool_display_info
== 1) ?
true : false;
342 $this->_admin
= ($r->bool_admin_adh
== 1) ?
true : false;
344 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
981 !isset($values['attach'])
983 && isset($values['parent_id'])
985 unset($values['parent_id']);
988 if (isset($values['duplicate'])) {
989 //if we're duplicating, keep a trace (if an error occurs)
990 $this->_duplicate
= true;
993 foreach ($fields as $key) {
994 //first of all, let's sanitize values
995 $key = strtolower($key);
996 $prop = '_' . $this->fields
[$key]['propname'];
998 if (isset($values[$key])) {
999 $value = $values[$key];
1000 if ($value !== true && $value !== false) {
1001 $value = trim($value);
1003 } elseif ($this->_id
== '' ||
$this->_id
== null) {
1005 case 'bool_admin_adh':
1006 case 'bool_exempt_adh':
1007 case 'bool_display_info':
1010 case 'activite_adh':
1011 //values that are setted at object instanciation
1014 case 'date_crea_adh':
1020 //values that are setted at object instanciation
1021 $value = $this->$prop;
1027 //keep stored value on update
1028 if ($prop != '_password' ||
isset($values['mdp_adh']) && isset($values['mdp_adh2'])) {
1029 $value = $this->$prop;
1035 // if the field is enabled, check it
1036 if (!isset($disabled[$key])) {
1037 // fill up the adherent structure
1038 if ($value !== null && $value !== true && $value !== false && !is_object($value)) {
1039 $value = stripslashes($value);
1041 $this->$prop = $value;
1043 // now, check validity
1044 if ($value !== null && $value != '') {
1045 $this->validate($key, $value, $values);
1047 ($key == 'login_adh' && !isset($required['login_adh']))
1048 ||
($key == 'mdp_adh' && !isset($required['mdp_adh']))
1049 && !isset($this->_id
)
1051 $p = new Password($this->zdb
);
1052 $this->$prop = $p->makeRandomPassword(15);
1057 // missing required fields?
1058 foreach ($required as $key => $val) {
1059 $prop = '_' . $this->fields
[$key]['propname'];
1061 if (!isset($disabled[$key])) {
1062 $mandatory_missing = false;
1063 if (!isset($this->$prop) ||
$this->$prop == '') {
1064 $mandatory_missing = true;
1065 } elseif ($key === 'titre_adh' && $this->$prop == '-1') {
1066 $mandatory_missing = true;
1069 if ($mandatory_missing === true) {
1070 $this->errors
[] = str_replace(
1072 '<a href="#' . $key . '">' . $this->getFieldLabel($key) . '</a>',
1073 _T("- Mandatory field %field empty.")
1079 //attach to/detach from parent
1080 if (isset($values['detach_parent'])) {
1081 $this->_parent
= null;
1084 $this->dynamicsCheck($values);
1086 if (count($this->errors
) > 0) {
1088 'Some errors has been throwed attempting to edit/store a member' . "\n" .
1089 print_r($this->errors
, true),
1092 return $this->errors
;
1097 'Member checked successfully.',
1105 * Validate data for given key
1106 * Set valid data in current object, also resets errors list
1108 * @param string $field Field name
1109 * @param mixed $value Value we want to set
1110 * @param array $values All values, for some references
1114 public function validate($field, $value, $values)
1116 global $preferences;
1118 $prop = '_' . $this->fields
[$field]['propname'];
1120 if ($value === null ||
(is_string($value) && trim($value) == '')) {
1121 //empty values are OK
1122 $this->$prop = $value;
1128 case 'date_crea_adh':
1129 case 'date_modif_adh_':
1131 case 'date_echeance':
1133 $d = \DateTime
::createFromFormat(__("Y-m-d"), $value);
1135 //try with non localized date
1136 $d = \DateTime
::createFromFormat("Y-m-d", $value);
1138 throw new \
Exception('Incorrect format');
1142 if ($field === 'ddn_adh') {
1143 $now = new \
DateTime();
1144 $now->setTime(0, 0, 0);
1145 $d->setTime(0, 0, 0);
1147 $diff = $now->diff($d);
1148 $days = (int)$diff->format('%R%a');
1150 $this->errors
[] = _T('- Birthdate must be set in the past!');
1153 $years = (int)$diff->format('%R%Y');
1154 if ($years <= -200) {
1155 $this->errors
[] = str_replace(
1158 _T('- Members must be less than 200 years old (currently %years)!')
1162 $this->$prop = $d->format('Y-m-d');
1163 } catch (\Exception
$e) {
1165 'Wrong date format. field: ' . $field .
1166 ', value: ' . $value . ', expected fmt: ' .
1167 __("Y-m-d") . ' | ' . $e->getMessage(),
1170 $this->errors
[] = str_replace(
1177 $this->getFieldLabel($field)
1179 _T("- Wrong date format (%date_format) for %field!")
1184 if ($value !== null && $value !== '') {
1185 if ($value == '-1') {
1186 $this->$prop = null;
1187 } elseif (!$value instanceof Title
) {
1188 $this->$prop = new Title((int)$value);
1191 $this->$prop = null;
1196 if (!GaletteMail
::isValidEmail($value)) {
1197 $this->errors
[] = _T("- Non-valid E-Mail address!") .
1198 ' (' . $this->getFieldLabel($field) . ')';
1200 if ($field == 'email_adh') {
1202 $select = $this->zdb
->select(self
::TABLE
);
1205 )->where(array('email_adh' => $value));
1206 if ($this->_id
!= '' && $this->_id
!= null) {
1208 self
::PK
. ' != ' . $this->_id
1212 $results = $this->zdb
->execute($select);
1213 if ($results->count() !== 0) {
1214 $this->errors
[] = _T("- This E-Mail address is already used by another member!");
1216 } catch (\Exception
$e) {
1218 'An error occurred checking member email unicity.',
1221 $this->errors
[] = _T("An error has occurred while looking if login already exists.");
1226 if ($value == 'http://') {
1228 } elseif (!isValidWebUrl($value)) {
1229 $this->errors
[] = _T("- Non-valid Website address! Maybe you've skipped the http://?");
1233 /** FIXME: add a preference for login lenght */
1234 if (strlen($value) < 2) {
1235 $this->errors
[] = str_replace(
1238 _T("- The username must be composed of at least %i characters!")
1241 //check if login does not contain the @ character
1242 if (strpos($value, '@') != false) {
1243 $this->errors
[] = _T("- The username cannot contain the @ character");
1245 //check if login is already taken
1247 $select = $this->zdb
->select(self
::TABLE
);
1250 )->where(array('login_adh' => $value));
1251 if ($this->_id
!= '' && $this->_id
!= null) {
1253 self
::PK
. ' != ' . $this->_id
1257 $results = $this->zdb
->execute($select);
1259 $results->count() !== 0
1260 ||
$value == $preferences->pref_admin_login
1262 $this->errors
[] = _T("- This username is already in use, please choose another one!");
1264 } catch (\Exception
$e) {
1266 'An error occurred checking member login unicity.',
1269 $this->errors
[] = _T("An error has occurred while looking if login already exists.");
1276 $this->_self_adh
!== true
1277 && (!isset($values['mdp_adh2'])
1278 ||
$values['mdp_adh2'] != $value)
1280 $this->errors
[] = _T("- The passwords don't match!");
1282 $this->_self_adh
=== true
1283 && !crypt($value, $values['mdp_crypt']) == $values['mdp_crypt']
1285 $this->errors
[] = _T("Password misrepeated: ");
1287 $pinfos = password_get_info($value);
1288 //check if value is already a hash
1289 if ($pinfos['algo'] == 0) {
1290 $this->$prop = password_hash(
1295 $pwcheck = new \Galette\Util\
Password($preferences);
1296 $pwcheck->setAdherent($this);
1297 if (!$pwcheck->isValid($value)) {
1298 $this->errors
= array_merge(
1300 $pwcheck->getErrors()
1308 $this->$prop = (int)$value;
1309 //check if status exists
1310 $select = $this->zdb
->select(Status
::TABLE
);
1311 $select->where(Status
::PK
. '= ' . $value);
1313 $results = $this->zdb
->execute($select);
1314 $result = $results->current();
1316 $this->errors
[] = str_replace(
1319 _T("Status #%id does not exists in database.")
1323 } catch (\Exception
$e) {
1325 'An error occurred checking status existance: ' . $e->getMessage(),
1328 $this->errors
[] = _T("An error has occurred while looking if status does exists.");
1332 if (in_array($value, [self
::NC
, self
::MAN
, self
::WOMAN
])) {
1333 $this->$prop = (int)$value;
1335 $this->errors
[] = _T("Gender %gender does not exists!");
1339 $this->$prop = ($value instanceof Adherent
) ?
(int)$value->id
: (int)$value;
1340 $this->loadParent();
1350 public function store()
1352 global $hist, $emitter;
1356 $fields = self
::getDbFields($this->zdb
);
1358 foreach ($fields as $field) {
1360 $field !== 'date_modif_adh'
1361 ||
!isset($this->_id
)
1364 $prop = '_' . $this->fields
[$field]['propname'];
1366 ($field === 'bool_admin_adh'
1367 ||
$field === 'bool_exempt_adh'
1368 ||
$field === 'bool_display_info'
1369 ||
$field === 'activite_adh')
1370 && $this->$prop === false
1372 //Handle booleans for postgres ; bugs #18899 and #19354
1373 $values[$field] = $this->zdb
->isPostgres() ?
'false' : 0;
1374 } elseif ($field === 'parent_id') {
1376 if ($this->_parent
=== null) {
1377 $values['parent_id'] = new Expression('NULL');
1378 } elseif ($this->parent
instanceof Adherent
) {
1379 $values['parent_id'] = $this->_parent
->id
;
1381 $values['parent_id'] = $this->_parent
;
1384 $values[$field] = $this->$prop;
1389 //an empty value will cause date to be set to 1901-01-01, a null
1390 //will result in 0000-00-00. We want a database NULL value here.
1391 if (!$this->_birthdate
) {
1392 $values['ddn_adh'] = new Expression('NULL');
1394 if (!$this->_due_date
) {
1395 $values['date_echeance'] = new Expression('NULL');
1398 if ($this->_title
instanceof Title
) {
1399 $values['titre_adh'] = $this->_title
->id
;
1401 $values['titre_adh'] = new Expression('NULL');
1404 if (!$this->_parent
) {
1405 $values['parent_id'] = new Expression('NULL');
1408 //fields that cannot be null
1410 '_surname' => 'prenom_adh',
1411 '_nickname' => 'pseudo_adh',
1412 '_address' => 'adresse_adh',
1413 '_zipcode' => 'cp_adh',
1414 '_town' => 'ville_adh'
1416 foreach ($notnull as $prop => $field) {
1417 if ($this->$prop === null) {
1418 $values[$field] = '';
1423 if (!isset($this->_id
) ||
$this->_id
== '') {
1424 //we're inserting a new member
1425 unset($values[self
::PK
]);
1426 //set modification date
1427 $this->_modification_date
= date('Y-m-d');
1428 $values['date_modif_adh'] = $this->_modification_date
;
1430 $insert = $this->zdb
->insert(self
::TABLE
);
1431 $insert->values($values);
1432 $add = $this->zdb
->execute($insert);
1433 if ($add->count() > 0) {
1434 if ($this->zdb
->isPostgres()) {
1435 $this->_id
= $this->zdb
->driver
->getLastGeneratedValue(
1436 PREFIX_DB
. 'adherents_id_seq'
1439 $this->_id
= $this->zdb
->driver
->getLastGeneratedValue();
1441 $this->_picture
= new Picture($this->_id
);
1443 if ($this->_self_adh
) {
1445 _T("Self_subscription as a member: ") .
1446 $this->getNameWithCase($this->_name
, $this->_surname
),
1451 _T("Member card added"),
1457 $emitter->emit('member.add', $this);
1459 $hist->add(_T("Fail to add new member."));
1460 throw new \
Exception(
1461 'An error occurred inserting new member!'
1465 //we're editing an existing member
1466 if (!$this->isDueFree()) {
1468 $due_date = Contribution
::getDueDate($this->zdb
, $this->_id
);
1470 $values['date_echeance'] = $due_date;
1474 if (!$this->_password
) {
1475 unset($values['mdp_adh']);
1478 $update = $this->zdb
->update(self
::TABLE
);
1479 $update->set($values);
1481 self
::PK
. '=' . $this->_id
1484 $edit = $this->zdb
->execute($update);
1486 //edit == 0 does not mean there were an error, but that there
1487 //were nothing to change
1488 if ($edit->count() > 0) {
1489 $this->updateModificationDate();
1491 _T("Member card updated"),
1497 $emitter->emit('member.edit', $this);
1502 $success = $this->dynamicsStore();
1506 } catch (\Exception
$e) {
1508 'Something went wrong :\'( | ' . $e->getMessage() . "\n" .
1509 $e->getTraceAsString(),
1517 * Update member modification date
1521 private function updateModificationDate()
1524 $modif_date = date('Y-m-d');
1525 $update = $this->zdb
->update(self
::TABLE
);
1527 array('date_modif_adh' => $modif_date)
1528 )->where(self
::PK
. '=' . $this->_id
);
1530 $edit = $this->zdb
->execute($update);
1531 $this->_modification_date
= $modif_date;
1532 } catch (\Exception
$e) {
1534 'Something went wrong updating modif date :\'( | ' .
1535 $e->getMessage() . "\n" . $e->getTraceAsString(),
1542 * Global getter method
1544 * @param string $name name of the property we want to retrive
1546 * @return false|object the called property
1548 public function __get($name)
1551 'admin', 'staff', 'due_free', 'appears_in_list', 'active',
1556 'sadmin', 'sstaff', 'sdue_free', 'sappears_in_list', 'sactive',
1557 'stitle', 'sstatus', 'sfullname', 'sname', 'rowclass', 'saddress',
1558 'rbirthdate', 'sgender', 'contribstatus'
1561 if (in_array($name, $forbidden)) {
1564 return $this->isAdmin();
1567 return $this->isStaff();
1570 return $this->isDueFree();
1572 case 'appears_in_list':
1573 return $this->appearsInMembersList();
1576 return $this->isActive();
1579 throw new \
RuntimeException("Call to __get for '$name' is forbidden!");
1582 if (in_array($name, $virtuals)) {
1583 if (substr($name, 0, 1) !== '_') {
1584 $real = '_' . substr($name, 1);
1591 case 'sappears_in_list':
1593 return (($this->$real) ?
_T("Yes") : _T("No"));
1596 return (($this->$real) ?
_T("Active") : _T("Inactive"));
1599 if (isset($this->_title
)) {
1600 return $this->_title
->tshort
;
1606 $status = new Status($this->zdb
);
1607 return $status->getLabel($this->_status
);
1610 return $this->getNameWithCase(
1613 (isset($this->_title
) ?
$this->title
: false)
1617 $address = $this->_address
;
1618 if ($this->_address_continuation
!== '' && $this->_address_continuation
!== null) {
1619 $address .= "\n" . $this->_address_continuation
;
1624 return $this->getNameWithCase($this->_name
, $this->_surname
);
1627 return $this->_birthdate
;
1630 switch ($this->gender
) {
1636 return __('Unspecified');
1639 case 'contribstatus':
1640 return $this->getDues();
1644 if (substr($name, 0, 1) !== '_') {
1645 $rname = '_' . $name;
1653 if ($this->$rname !== null) {
1654 return (int)$this->$rname;
1660 case 'creation_date':
1661 case 'modification_date':
1663 if ($this->$rname != '') {
1665 $d = new \
DateTime($this->$rname);
1666 return $d->format(__("Y-m-d"));
1667 } catch (\Exception
$e) {
1668 //oops, we've got a bad date :/
1670 'Bad date (' . $this->$rname . ') | ' .
1674 return $this->$rname;
1679 if (!property_exists($this, $rname)) {
1681 "Unknown property '$rname'",
1686 return $this->$rname;
1696 * If member does not have an email address, but is attached to
1697 * another member, we'll take information from its parent.
1701 public function getEmail()
1703 $email = $this->_email
;
1704 if (empty($email)) {
1705 $this->loadParent();
1706 $email = $this->parent
->email
;
1713 * Get member address.
1714 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1718 public function getAddress()
1720 $address = $this->_address
;
1721 if (empty($address) && $this->hasParent()) {
1722 $this->loadParent();
1723 $address = $this->parent
->address
;
1730 * Get member address continuation.
1731 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1735 public function getAddressContinuation()
1737 $address = $this->_address
;
1738 $address_continuation = $this->_address_continuation
;
1739 if (empty($address) && $this->hasParent()) {
1740 $this->loadParent();
1741 $address_continuation = $this->parent
->address_continuation
;
1744 return $address_continuation;
1748 * Get member zipcode.
1749 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1753 public function getZipcode()
1755 $address = $this->_address
;
1756 $zip = $this->_zipcode
;
1757 if (empty($address) && $this->hasParent()) {
1758 $this->loadParent();
1759 $zip = $this->parent
->zipcode
;
1767 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1771 public function getTown()
1773 $address = $this->_address
;
1774 $town = $this->_town
;
1775 if (empty($address) && $this->hasParent()) {
1776 $this->loadParent();
1777 $town = $this->parent
->town
;
1784 * Get member country.
1785 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1789 public function getCountry()
1791 $address = $this->_address
;
1792 $country = $this->_country
;
1793 if (empty($address) && $this->hasParent()) {
1794 $this->loadParent();
1795 $country = $this->parent
->country
;
1806 public function getAge()
1808 if ($this->_birthdate
== null) {
1812 $d = \DateTime
::createFromFormat('Y-m-d', $this->_birthdate
);
1815 'Invalid birthdate: ' . $this->_birthdate
,
1823 $d->diff(new \
DateTime())->y
,
1824 _T(' (%age years old)')
1829 * Get parent inherited fields
1833 public function getParentFields()
1835 return $this->parent_fields
;
1839 * Handle files (photo and dynamics files
1841 * @param array $files Files sent
1843 * @return array|true
1845 public function handleFiles($files)
1849 if (isset($files['photo'])) {
1850 if ($files['photo']['error'] === UPLOAD_ERR_OK
) {
1851 if ($files['photo']['tmp_name'] != '') {
1852 if (is_uploaded_file($files['photo']['tmp_name'])) {
1853 $res = $this->picture
->store($files['photo']);
1856 = $this->picture
->getErrorMessage($res);
1860 } elseif ($files['photo']['error'] !== UPLOAD_ERR_NO_FILE
) {
1862 $this->picture
->getPhpErrorMessage($files['photo']['error']),
1865 $this->errors
[] = $this->picture
->getPhpErrorMessage(
1866 $files['photo']['error']
1870 $this->dynamicsFiles($_FILES);
1872 if (count($this->errors
) > 0) {
1874 'Some errors has been throwed attempting to edit/store a member files' . "\n" .
1875 print_r($this->errors
, true),
1878 return $this->errors
;
1885 * Set member as duplicate
1889 public function setDuplicate()
1891 //mark as duplicated
1892 $this->_duplicate
= true;
1893 $infos = $this->_others_infos_admin
;
1894 $this->_others_infos_admin
= str_replace(
1896 [$this->sname
, $this->_id
],
1897 _T('Duplicated from %name (%id)')
1899 if (!empty($infos)) {
1900 $this->_others_infos_admin
.= "\n" . $infos;
1904 //drop email, must be unique
1905 $this->_email
= null;
1906 //drop creation date
1907 $this->_creation_date
= date("Y-m-d");
1909 $this->_login
= null;
1911 $this->_picture
= new Picture();
1913 $this->_birthdate
= null;
1915 $this->_surname
= null;
1917 $this->_admin
= false;
1919 $this->_due_free
= false;
1923 * Get current errors
1927 public function getErrors()
1929 return $this->errors
;
1937 public function getGroups()
1939 return $this->_groups
;
1943 * Get user managed groups
1947 public function getManagedGroups()
1949 return $this->_managed_groups
;
1953 * Can current logged in user edit member
1955 * @param Login $login Login instance
1959 public function canEdit($login)
1961 if ($this->id
&& $login->id
== $this->id ||
$login->isAdmin() ||
$login->isStaff()) {
1965 //check if requested member is part of managed groups
1966 if ($login->isGroupManager()) {
1967 foreach ($this->getGroups() as $g) {
1968 if ($login->isGroupManager($g->getId())) {
1978 * Are we currently duplicated a member?
1982 public function isDuplicate()
1984 return $this->_duplicate
;