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 public const TABLE
= 'adherents';
67 public const PK
= 'id_adh';
71 public const WOMAN
= 2;
73 public const AFTER_ADD_DEFAULT
= 0;
74 public const AFTER_ADD_TRANS
= 1;
75 public const AFTER_ADD_NEW
= 2;
76 public const AFTER_ADD_SHOW
= 3;
77 public const AFTER_ADD_LIST
= 4;
78 public 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 //check if member is still active
502 $this->_row_classes
.= $this->isActive() ?
' cotis-late' : ' cotis-old';
503 } elseif ($this->_days_remaining
< 30) {
504 $this->_row_classes
.= ' cotis-soon';
506 $this->_row_classes
.= ' cotis-ok';
517 public function isAdmin()
519 return $this->_admin
;
523 * Is user member of staff?
527 public function isStaff()
529 return $this->_staff
;
533 * Is member freed of dues?
537 public function isDueFree()
539 return $this->_due_free
;
543 * Is member in specified group?
545 * @param string $group_name Group name
549 public function isGroupMember($group_name)
551 if (is_array($this->_groups
)) {
552 foreach ($this->_groups
as $g) {
553 if ($g->getName() == $group_name) {
560 'Calling ' . __METHOD__
. ' without groups loaded!',
568 * Is member manager of specified group?
570 * @param string $group_name Group name
574 public function isGroupManager($group_name)
576 if (is_array($this->_managed_groups
)) {
577 foreach ($this->_managed_groups
as $mg) {
578 if ($mg->getName() == $group_name) {
585 'Calling ' . __METHOD__
. ' without groups loaded!',
593 * Does current member represents a company?
597 public function isCompany()
599 return trim($this->_company_name
) != '';
603 * Is current member a man?
607 public function isMan()
609 return (int)$this->_gender
=== self
::MAN
;
613 * Is current member a woman?
617 public function isWoman()
619 return (int)$this->_gender
=== self
::WOMAN
;
624 * Can member appears in public members list?
628 public function appearsInMembersList()
630 return $this->_appears_in_list
;
638 public function isActive()
640 return $this->_active
;
644 * Does member have uploaded a picture?
648 public function hasPicture()
650 return $this->_picture
->hasPicture();
654 * Does member have a parent?
658 public function hasParent()
660 return !empty($this->_parent
);
664 * Does member have children?
668 public function hasChildren()
670 if ($this->_children
=== null) {
673 'Children has not been loaded!',
679 return count($this->_children
) > 0;
684 * Get row class related to current fee status
686 * @param boolean $public we want the class for public pages
688 * @return string the class to apply
690 public function getRowClass($public = false)
692 $strclass = ($this->isActive()) ?
'active' : 'inactive';
693 if ($public === false) {
694 $strclass .= $this->_row_classes
;
700 * Get current member due status
702 * @return string i18n string representing state of due
704 public function getDues()
707 if ($this->isDueFree()) {
708 $ret = _T("Freed of dues");
709 } elseif ($this->_due_date
== '') {
710 $patterns = array('/%days/', '/%date/');
711 $cdate = new \
DateTime($this->_creation_date
);
714 $cdate->format(__("Y-m-d"))
716 if ($this->_active
) {
720 _T("Never contributed: Registered %days days ago (since %date)")
723 $ret = _T("Never contributed");
725 } elseif ($this->_days_remaining
== 0) {
726 $ret = _T("Last day!");
727 } elseif ($this->_days_remaining
< 0) {
728 $patterns = array('/%days/', '/%date/');
729 $ddate = new \
DateTime($this->_due_date
);
731 $this->_days_remaining
* -1,
732 $ddate->format(__("Y-m-d"))
734 if ($this->_active
) {
738 _T("Late of %days days (since %date)")
741 $ret = _T("No longer member");
744 $patterns = array('/%days/', '/%date/');
745 $ddate = new \
DateTime($this->_due_date
);
747 $this->_days_remaining
,
748 $ddate->format(__("Y-m-d"))
753 _T("%days days remaining (ending on %date)")
760 * Retrieve Full name and surname for the specified member id
762 * @param Db $zdb Database instance
763 * @param integer $id Member id
764 * @param boolean $wid Add member id
765 * @param boolean $wnick Add member nickname
767 * @return string formatted Name and Surname
769 public static function getSName($zdb, $id, $wid = false, $wnick = false)
772 $select = $zdb->select(self
::TABLE
);
773 $select->where(self
::PK
. ' = ' . $id);
775 $results = $zdb->execute($select);
776 $row = $results->current();
777 return self
::getNameWithCase(
781 ($wid === true ?
$row->id_adh
: false),
782 ($wnick === true ?
$row->pseudo_adh
: false)
784 } catch (\Exception
$e) {
786 'Cannot get formatted name for member form id `' . $id . '` | ' .
795 * Get member name with correct case
797 * @param string $name Member name
798 * @param string $surname Mmeber surname
799 * @param false|Title $title Member title to show or false
800 * @param false|integer $id Member id to display or false
801 * @param false|string $nick Member nickname to display or false
805 public static function getNameWithCase($name, $surname, $title = false, $id = false, $nick = false)
809 if ($title !== false && $title instanceof Title
) {
810 $str .= $title->tshort
. ' ';
813 $str .= mb_strtoupper($name, 'UTF-8') . ' ' .
814 ucwords(mb_strtolower($surname, 'UTF-8'), " \t\r\n\f\v-_|");
816 if ($id !== false ||
$nick !== false) {
819 if ($nick !== false) {
823 if ($nick !== false && !empty($nick)) {
828 if ($id !== false ||
$nick !== false) {
835 * Change password for a given user
837 * @param Db $zdb Database instance
838 * @param string $id_adh Member identifier
839 * @param string $pass New password
843 public static function updatePassword(Db
$zdb, $id_adh, $pass)
846 $cpass = password_hash($pass, PASSWORD_BCRYPT
);
848 $update = $zdb->update(self
::TABLE
);
850 array('mdp_adh' => $cpass)
851 )->where(self
::PK
. ' = ' . $id_adh);
852 $zdb->execute($update);
854 'Password for `' . $id_adh . '` has been updated.',
858 } catch (\Exception
$e) {
860 'An error occurred while updating password for `' . $id_adh .
861 '` | ' . $e->getMessage(),
871 * @param string $field Field name
875 private function getFieldLabel($field)
877 $label = $this->fields
[$field]['label'];
878 //remove trailing ':' and then nbsp (for french at least)
879 $label = trim(trim($label, ':'), ' ');
884 * Retrieve fields from database
886 * @param Db $zdb Database instance
890 public static function getDbFields(Db
$zdb)
892 $columns = $zdb->getColumns(self
::TABLE
);
894 foreach ($columns as $col) {
895 $fields[] = $col->getName();
901 * Mark as self membership
905 public function setSelfMembership()
907 $this->_self_adh
= true;
911 * Is member up to date?
915 public function isUp2Date()
917 if ($this->_deps
['dues']) {
918 if ($this->isDueFree()) {
919 //member is due free, he's up to date.
922 //let's check from end date, if present
923 if ($this->_due_date
== null) {
926 $ech = new \
DateTime($this->_due_date
);
927 $now = new \
DateTime();
928 $now->setTime(0, 0, 0);
933 throw new \
RuntimeException(
934 'Cannot check if member is up to date, dues deps is disabled!'
942 * @param Preferences $preferences Preferences instance
943 * @param array $fields Members fields configuration
944 * @param History $history History instance
948 public function setDependencies(
949 Preferences
$preferences,
953 $this->preferences
= $preferences;
954 $this->fields
= $fields;
955 $this->history
= $history;
959 * Check posted values validity
961 * @param array $values All values to check, basically the $_POST array
962 * after sending the form
963 * @param array $required Array of required fields
964 * @param array $disabled Array of disabled fields
968 public function check($values, $required, $disabled)
970 $this->errors
= array();
972 $fields = self
::getDbFields($this->zdb
);
974 //reset company name if needeed
975 if (!isset($values['is_company'])) {
976 unset($values['is_company']);
977 $values['societe_adh'] = '';
980 //no parent if checkbox was unchecked
982 !isset($values['attach'])
984 && isset($values['parent_id'])
986 unset($values['parent_id']);
989 if (isset($values['duplicate'])) {
990 //if we're duplicating, keep a trace (if an error occurs)
991 $this->_duplicate
= true;
994 foreach ($fields as $key) {
995 //first of all, let's sanitize values
996 $key = strtolower($key);
997 $prop = '_' . $this->fields
[$key]['propname'];
999 if (isset($values[$key])) {
1000 $value = $values[$key];
1001 if ($value !== true && $value !== false) {
1002 $value = trim($value);
1004 } elseif ($this->_id
== '' ||
$this->_id
== null) {
1006 case 'bool_admin_adh':
1007 case 'bool_exempt_adh':
1008 case 'bool_display_info':
1011 case 'activite_adh':
1012 //values that are setted at object instanciation
1015 case 'date_crea_adh':
1021 //values that are setted at object instanciation
1022 $value = $this->$prop;
1028 //keep stored value on update
1029 if ($prop != '_password' ||
isset($values['mdp_adh']) && isset($values['mdp_adh2'])) {
1030 $value = $this->$prop;
1036 // if the field is enabled, check it
1037 if (!isset($disabled[$key])) {
1038 // fill up the adherent structure
1039 if ($value !== null && $value !== true && $value !== false && !is_object($value)) {
1040 $value = stripslashes($value);
1042 $this->$prop = $value;
1044 // now, check validity
1045 if ($value !== null && $value != '') {
1046 $this->validate($key, $value, $values);
1048 ($key == 'login_adh' && !isset($required['login_adh']))
1049 ||
($key == 'mdp_adh' && !isset($required['mdp_adh']))
1050 && !isset($this->_id
)
1052 $p = new Password($this->zdb
);
1053 $this->$prop = $p->makeRandomPassword(15);
1058 // missing required fields?
1059 foreach ($required as $key => $val) {
1060 $prop = '_' . $this->fields
[$key]['propname'];
1062 if (!isset($disabled[$key])) {
1063 $mandatory_missing = false;
1064 if (!isset($this->$prop) ||
$this->$prop == '') {
1065 $mandatory_missing = true;
1066 } elseif ($key === 'titre_adh' && $this->$prop == '-1') {
1067 $mandatory_missing = true;
1070 if ($mandatory_missing === true) {
1071 $this->errors
[] = str_replace(
1073 '<a href="#' . $key . '">' . $this->getFieldLabel($key) . '</a>',
1074 _T("- Mandatory field %field empty.")
1080 //attach to/detach from parent
1081 if (isset($values['detach_parent'])) {
1082 $this->_parent
= null;
1085 $this->dynamicsCheck($values, $required, $disabled);
1087 if (count($this->errors
) > 0) {
1089 'Some errors has been throwed attempting to edit/store a member' . "\n" .
1090 print_r($this->errors
, true),
1093 return $this->errors
;
1098 'Member checked successfully.',
1106 * Validate data for given key
1107 * Set valid data in current object, also resets errors list
1109 * @param string $field Field name
1110 * @param mixed $value Value we want to set
1111 * @param array $values All values, for some references
1115 public function validate($field, $value, $values)
1117 global $preferences;
1119 $prop = '_' . $this->fields
[$field]['propname'];
1121 if ($value === null ||
(is_string($value) && trim($value) == '')) {
1122 //empty values are OK
1123 $this->$prop = $value;
1129 case 'date_crea_adh':
1130 case 'date_modif_adh_':
1132 case 'date_echeance':
1134 $d = \DateTime
::createFromFormat(__("Y-m-d"), $value);
1136 //try with non localized date
1137 $d = \DateTime
::createFromFormat("Y-m-d", $value);
1139 throw new \
Exception('Incorrect format');
1143 if ($field === 'ddn_adh') {
1144 $now = new \
DateTime();
1145 $now->setTime(0, 0, 0);
1146 $d->setTime(0, 0, 0);
1148 $diff = $now->diff($d);
1149 $days = (int)$diff->format('%R%a');
1151 $this->errors
[] = _T('- Birthdate must be set in the past!');
1154 $years = (int)$diff->format('%R%Y');
1155 if ($years <= -200) {
1156 $this->errors
[] = str_replace(
1159 _T('- Members must be less than 200 years old (currently %years)!')
1163 $this->$prop = $d->format('Y-m-d');
1164 } catch (\Exception
$e) {
1166 'Wrong date format. field: ' . $field .
1167 ', value: ' . $value . ', expected fmt: ' .
1168 __("Y-m-d") . ' | ' . $e->getMessage(),
1171 $this->errors
[] = str_replace(
1178 $this->getFieldLabel($field)
1180 _T("- Wrong date format (%date_format) for %field!")
1185 if ($value !== null && $value !== '') {
1186 if ($value == '-1') {
1187 $this->$prop = null;
1188 } elseif (!$value instanceof Title
) {
1189 $this->$prop = new Title((int)$value);
1192 $this->$prop = null;
1197 if (!GaletteMail
::isValidEmail($value)) {
1198 $this->errors
[] = _T("- Non-valid E-Mail address!") .
1199 ' (' . $this->getFieldLabel($field) . ')';
1201 if ($field == 'email_adh') {
1203 $select = $this->zdb
->select(self
::TABLE
);
1206 )->where(array('email_adh' => $value));
1207 if ($this->_id
!= '' && $this->_id
!= null) {
1209 self
::PK
. ' != ' . $this->_id
1213 $results = $this->zdb
->execute($select);
1214 if ($results->count() !== 0) {
1215 $this->errors
[] = _T("- This E-Mail address is already used by another member!");
1217 } catch (\Exception
$e) {
1219 'An error occurred checking member email unicity.',
1222 $this->errors
[] = _T("An error has occurred while looking if login already exists.");
1227 if ($value == 'http://') {
1229 } elseif (!isValidWebUrl($value)) {
1230 $this->errors
[] = _T("- Non-valid Website address! Maybe you've skipped the http://?");
1234 /** FIXME: add a preference for login lenght */
1235 if (strlen($value) < 2) {
1236 $this->errors
[] = str_replace(
1239 _T("- The username must be composed of at least %i characters!")
1242 //check if login does not contain the @ character
1243 if (strpos($value, '@') != false) {
1244 $this->errors
[] = _T("- The username cannot contain the @ character");
1246 //check if login is already taken
1248 $select = $this->zdb
->select(self
::TABLE
);
1251 )->where(array('login_adh' => $value));
1252 if ($this->_id
!= '' && $this->_id
!= null) {
1254 self
::PK
. ' != ' . $this->_id
1258 $results = $this->zdb
->execute($select);
1260 $results->count() !== 0
1261 ||
$value == $preferences->pref_admin_login
1263 $this->errors
[] = _T("- This username is already in use, please choose another one!");
1265 } catch (\Exception
$e) {
1267 'An error occurred checking member login unicity.',
1270 $this->errors
[] = _T("An error has occurred while looking if login already exists.");
1277 $this->_self_adh
!== true
1278 && (!isset($values['mdp_adh2'])
1279 ||
$values['mdp_adh2'] != $value)
1281 $this->errors
[] = _T("- The passwords don't match!");
1283 $this->_self_adh
=== true
1284 && !crypt($value, $values['mdp_crypt']) == $values['mdp_crypt']
1286 $this->errors
[] = _T("Password misrepeated: ");
1288 $pinfos = password_get_info($value);
1289 //check if value is already a hash
1290 if ($pinfos['algo'] == 0) {
1291 $this->$prop = password_hash(
1296 $pwcheck = new \Galette\Util\
Password($preferences);
1297 $pwcheck->setAdherent($this);
1298 if (!$pwcheck->isValid($value)) {
1299 $this->errors
= array_merge(
1301 $pwcheck->getErrors()
1309 $this->$prop = (int)$value;
1310 //check if status exists
1311 $select = $this->zdb
->select(Status
::TABLE
);
1312 $select->where(Status
::PK
. '= ' . $value);
1314 $results = $this->zdb
->execute($select);
1315 $result = $results->current();
1317 $this->errors
[] = str_replace(
1320 _T("Status #%id does not exists in database.")
1324 } catch (\Exception
$e) {
1326 'An error occurred checking status existance: ' . $e->getMessage(),
1329 $this->errors
[] = _T("An error has occurred while looking if status does exists.");
1333 if (in_array($value, [self
::NC
, self
::MAN
, self
::WOMAN
])) {
1334 $this->$prop = (int)$value;
1336 $this->errors
[] = _T("Gender %gender does not exists!");
1340 $this->$prop = ($value instanceof Adherent
) ?
(int)$value->id
: (int)$value;
1341 $this->loadParent();
1351 public function store()
1353 global $hist, $emitter;
1357 $fields = self
::getDbFields($this->zdb
);
1359 foreach ($fields as $field) {
1361 $field !== 'date_modif_adh'
1362 ||
!isset($this->_id
)
1365 $prop = '_' . $this->fields
[$field]['propname'];
1367 ($field === 'bool_admin_adh'
1368 ||
$field === 'bool_exempt_adh'
1369 ||
$field === 'bool_display_info'
1370 ||
$field === 'activite_adh')
1371 && $this->$prop === false
1373 //Handle booleans for postgres ; bugs #18899 and #19354
1374 $values[$field] = $this->zdb
->isPostgres() ?
'false' : 0;
1375 } elseif ($field === 'parent_id') {
1377 if ($this->_parent
=== null) {
1378 $values['parent_id'] = new Expression('NULL');
1379 } elseif ($this->parent
instanceof Adherent
) {
1380 $values['parent_id'] = $this->_parent
->id
;
1382 $values['parent_id'] = $this->_parent
;
1385 $values[$field] = $this->$prop;
1390 //an empty value will cause date to be set to 1901-01-01, a null
1391 //will result in 0000-00-00. We want a database NULL value here.
1392 if (!$this->_birthdate
) {
1393 $values['ddn_adh'] = new Expression('NULL');
1395 if (!$this->_due_date
) {
1396 $values['date_echeance'] = new Expression('NULL');
1399 if ($this->_title
instanceof Title
) {
1400 $values['titre_adh'] = $this->_title
->id
;
1402 $values['titre_adh'] = new Expression('NULL');
1405 if (!$this->_parent
) {
1406 $values['parent_id'] = new Expression('NULL');
1409 //fields that cannot be null
1411 '_surname' => 'prenom_adh',
1412 '_nickname' => 'pseudo_adh',
1413 '_address' => 'adresse_adh',
1414 '_zipcode' => 'cp_adh',
1415 '_town' => 'ville_adh'
1417 foreach ($notnull as $prop => $field) {
1418 if ($this->$prop === null) {
1419 $values[$field] = '';
1424 if (!isset($this->_id
) ||
$this->_id
== '') {
1425 //we're inserting a new member
1426 unset($values[self
::PK
]);
1427 //set modification date
1428 $this->_modification_date
= date('Y-m-d');
1429 $values['date_modif_adh'] = $this->_modification_date
;
1431 $insert = $this->zdb
->insert(self
::TABLE
);
1432 $insert->values($values);
1433 $add = $this->zdb
->execute($insert);
1434 if ($add->count() > 0) {
1435 if ($this->zdb
->isPostgres()) {
1436 $this->_id
= $this->zdb
->driver
->getLastGeneratedValue(
1437 PREFIX_DB
. 'adherents_id_seq'
1440 $this->_id
= $this->zdb
->driver
->getLastGeneratedValue();
1442 $this->_picture
= new Picture($this->_id
);
1444 if ($this->_self_adh
) {
1446 _T("Self_subscription as a member: ") .
1447 $this->getNameWithCase($this->_name
, $this->_surname
),
1452 _T("Member card added"),
1458 $emitter->emit('member.add', $this);
1460 $hist->add(_T("Fail to add new member."));
1461 throw new \
Exception(
1462 'An error occurred inserting new member!'
1466 //we're editing an existing member
1467 if (!$this->isDueFree()) {
1469 $due_date = Contribution
::getDueDate($this->zdb
, $this->_id
);
1471 $values['date_echeance'] = $due_date;
1475 if (!$this->_password
) {
1476 unset($values['mdp_adh']);
1479 $update = $this->zdb
->update(self
::TABLE
);
1480 $update->set($values);
1482 self
::PK
. '=' . $this->_id
1485 $edit = $this->zdb
->execute($update);
1487 //edit == 0 does not mean there were an error, but that there
1488 //were nothing to change
1489 if ($edit->count() > 0) {
1490 $this->updateModificationDate();
1492 _T("Member card updated"),
1498 $emitter->emit('member.edit', $this);
1503 $success = $this->dynamicsStore();
1507 } catch (\Exception
$e) {
1509 'Something went wrong :\'( | ' . $e->getMessage() . "\n" .
1510 $e->getTraceAsString(),
1518 * Update member modification date
1522 private function updateModificationDate()
1525 $modif_date = date('Y-m-d');
1526 $update = $this->zdb
->update(self
::TABLE
);
1528 array('date_modif_adh' => $modif_date)
1529 )->where(self
::PK
. '=' . $this->_id
);
1531 $edit = $this->zdb
->execute($update);
1532 $this->_modification_date
= $modif_date;
1533 } catch (\Exception
$e) {
1535 'Something went wrong updating modif date :\'( | ' .
1536 $e->getMessage() . "\n" . $e->getTraceAsString(),
1543 * Global getter method
1545 * @param string $name name of the property we want to retrive
1547 * @return false|object the called property
1549 public function __get($name)
1552 'admin', 'staff', 'due_free', 'appears_in_list', 'active',
1557 'sadmin', 'sstaff', 'sdue_free', 'sappears_in_list', 'sactive',
1558 'stitle', 'sstatus', 'sfullname', 'sname', 'rowclass', 'saddress',
1559 'rbirthdate', 'sgender', 'contribstatus'
1562 if (in_array($name, $forbidden)) {
1565 return $this->isAdmin();
1568 return $this->isStaff();
1571 return $this->isDueFree();
1573 case 'appears_in_list':
1574 return $this->appearsInMembersList();
1577 return $this->isActive();
1580 throw new \
RuntimeException("Call to __get for '$name' is forbidden!");
1583 if (in_array($name, $virtuals)) {
1584 if (substr($name, 0, 1) !== '_') {
1585 $real = '_' . substr($name, 1);
1592 case 'sappears_in_list':
1594 return (($this->$real) ?
_T("Yes") : _T("No"));
1597 return (($this->$real) ?
_T("Active") : _T("Inactive"));
1600 if (isset($this->_title
)) {
1601 return $this->_title
->tshort
;
1607 $status = new Status($this->zdb
);
1608 return $status->getLabel($this->_status
);
1611 return $this->getNameWithCase(
1614 (isset($this->_title
) ?
$this->title
: false)
1618 $address = $this->_address
;
1619 if ($this->_address_continuation
!== '' && $this->_address_continuation
!== null) {
1620 $address .= "\n" . $this->_address_continuation
;
1625 return $this->getNameWithCase($this->_name
, $this->_surname
);
1628 return $this->_birthdate
;
1631 switch ($this->gender
) {
1637 return __('Unspecified');
1640 case 'contribstatus':
1641 return $this->getDues();
1645 if (substr($name, 0, 1) !== '_') {
1646 $rname = '_' . $name;
1654 if ($this->$rname !== null) {
1655 return (int)$this->$rname;
1661 case 'creation_date':
1662 case 'modification_date':
1664 if ($this->$rname != '') {
1666 $d = new \
DateTime($this->$rname);
1667 return $d->format(__("Y-m-d"));
1668 } catch (\Exception
$e) {
1669 //oops, we've got a bad date :/
1671 'Bad date (' . $this->$rname . ') | ' .
1675 return $this->$rname;
1680 if (!property_exists($this, $rname)) {
1682 "Unknown property '$rname'",
1687 return $this->$rname;
1697 * If member does not have an email address, but is attached to
1698 * another member, we'll take information from its parent.
1702 public function getEmail()
1704 $email = $this->_email
;
1705 if (empty($email)) {
1706 $this->loadParent();
1707 $email = $this->parent
->email
;
1714 * Get member address.
1715 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1719 public function getAddress()
1721 $address = $this->_address
;
1722 if (empty($address) && $this->hasParent()) {
1723 $this->loadParent();
1724 $address = $this->parent
->address
;
1731 * Get member address continuation.
1732 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1736 public function getAddressContinuation()
1738 $address = $this->_address
;
1739 $address_continuation = $this->_address_continuation
;
1740 if (empty($address) && $this->hasParent()) {
1741 $this->loadParent();
1742 $address_continuation = $this->parent
->address_continuation
;
1745 return $address_continuation;
1749 * Get member zipcode.
1750 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1754 public function getZipcode()
1756 $address = $this->_address
;
1757 $zip = $this->_zipcode
;
1758 if (empty($address) && $this->hasParent()) {
1759 $this->loadParent();
1760 $zip = $this->parent
->zipcode
;
1768 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1772 public function getTown()
1774 $address = $this->_address
;
1775 $town = $this->_town
;
1776 if (empty($address) && $this->hasParent()) {
1777 $this->loadParent();
1778 $town = $this->parent
->town
;
1785 * Get member country.
1786 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1790 public function getCountry()
1792 $address = $this->_address
;
1793 $country = $this->_country
;
1794 if (empty($address) && $this->hasParent()) {
1795 $this->loadParent();
1796 $country = $this->parent
->country
;
1807 public function getAge()
1809 if ($this->_birthdate
== null) {
1813 $d = \DateTime
::createFromFormat('Y-m-d', $this->_birthdate
);
1816 'Invalid birthdate: ' . $this->_birthdate
,
1824 $d->diff(new \
DateTime())->y
,
1825 _T(' (%age years old)')
1830 * Get parent inherited fields
1834 public function getParentFields()
1836 return $this->parent_fields
;
1840 * Handle files (photo and dynamics files
1842 * @param array $files Files sent
1844 * @return array|true
1846 public function handleFiles($files)
1850 if (isset($files['photo'])) {
1851 if ($files['photo']['error'] === UPLOAD_ERR_OK
) {
1852 if ($files['photo']['tmp_name'] != '') {
1853 if (is_uploaded_file($files['photo']['tmp_name'])) {
1854 $res = $this->picture
->store($files['photo']);
1857 = $this->picture
->getErrorMessage($res);
1861 } elseif ($files['photo']['error'] !== UPLOAD_ERR_NO_FILE
) {
1863 $this->picture
->getPhpErrorMessage($files['photo']['error']),
1866 $this->errors
[] = $this->picture
->getPhpErrorMessage(
1867 $files['photo']['error']
1871 $this->dynamicsFiles($_FILES);
1873 if (count($this->errors
) > 0) {
1875 'Some errors has been throwed attempting to edit/store a member files' . "\n" .
1876 print_r($this->errors
, true),
1879 return $this->errors
;
1886 * Set member as duplicate
1890 public function setDuplicate()
1892 //mark as duplicated
1893 $this->_duplicate
= true;
1894 $infos = $this->_others_infos_admin
;
1895 $this->_others_infos_admin
= str_replace(
1897 [$this->sname
, $this->_id
],
1898 _T('Duplicated from %name (%id)')
1900 if (!empty($infos)) {
1901 $this->_others_infos_admin
.= "\n" . $infos;
1905 //drop email, must be unique
1906 $this->_email
= null;
1907 //drop creation date
1908 $this->_creation_date
= date("Y-m-d");
1910 $this->_login
= null;
1912 $this->_picture
= new Picture();
1914 $this->_birthdate
= null;
1916 $this->_surname
= null;
1918 $this->_admin
= false;
1920 $this->_due_free
= false;
1924 * Get current errors
1928 public function getErrors()
1930 return $this->errors
;
1938 public function getGroups()
1940 return $this->_groups
;
1944 * Get user managed groups
1948 public function getManagedGroups()
1950 return $this->_managed_groups
;
1954 * Can current logged in user edit member
1956 * @param Login $login Login instance
1960 public function canEdit($login)
1962 if ($this->id
&& $login->id
== $this->id ||
$login->isAdmin() ||
$login->isStaff()) {
1966 //check if requested member is part of managed groups
1967 if ($login->isGroupManager()) {
1968 foreach ($this->getGroups() as $g) {
1969 if ($login->isGroupManager($g->getId())) {
1979 * Are we currently duplicated a member?
1983 public function isDuplicate()
1985 return $this->_duplicate
;