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;
132 private $_self_adh = false;
133 private $_deps = array(
143 private $preferences;
147 private $parent_fields = [
155 private $errors = [];
157 private $sendmail = false;
160 * Default constructor
162 * @param Db $zdb Database instance
163 * @param mixed $args Either a ResultSet row, its id or its
164 * login or its email for to load s specific
165 * member, or null to just instanciate object
166 * @param false|array $deps Dependencies configuration, see Adherent::$_deps
168 public function __construct(Db
$zdb, $args = null, $deps = null)
174 if ($deps !== null) {
175 if (is_array($deps)) {
176 $this->_deps
= array_merge(
180 } elseif ($deps === false) {
182 $this->_deps
= array_fill_keys(
183 array_keys($this->_deps
),
188 '$deps shoud be an array, ' . gettype($deps) . ' given!',
194 if ($args == null ||
is_int($args)) {
195 if (is_int($args) && $args > 0) {
198 $this->_active
= true;
199 $this->_language
= $i18n->getID();
200 $this->_creation_date
= date("Y-m-d");
201 $this->_status
= $this->getDefaultStatus();
202 $this->_title
= null;
203 $this->_gender
= self
::NC
;
204 $gp = new Password($this->zdb
);
205 $this->_password
= $gp->makeRandomPassword();
206 $this->_picture
= new Picture();
207 $this->_admin
= false;
208 $this->_staff
= false;
209 $this->_due_free
= false;
210 $this->_appears_in_list
= false;
211 $this->_parent
= null;
213 if ($this->_deps
['dynamics'] === true) {
214 $this->loadDynamicFields();
217 } elseif (is_object($args)) {
218 $this->loadFromRS($args);
219 } elseif (is_string($args)) {
220 $this->loadFromLoginOrMail($args);
225 * Loads a member from its id
227 * @param int $id the identifiant for the member to load
229 * @return bool true if query succeed, false otherwise
231 public function load($id)
234 $select = $this->zdb
->select(self
::TABLE
, 'a');
237 array('b' => PREFIX_DB
. Status
::TABLE
),
238 'a.' . Status
::PK
. '=b.' . Status
::PK
,
239 array('priorite_statut')
240 )->where(array(self
::PK
=> $id));
242 $results = $this->zdb
->execute($select);
244 if ($results->count() === 0) {
248 $this->loadFromRS($results->current());
250 } catch (\Exception
$e) {
252 'Cannot load member form id `' . $id . '` | ' . $e->getMessage(),
260 * Loads a member from its login
262 * @param string $login login for the member to load
264 * @return bool true if query succeed, false otherwise
266 public function loadFromLoginOrMail($login)
269 $select = $this->zdb
->select(self
::TABLE
);
270 if (GaletteMail
::isValidEmail($login)) {
271 //we got a valid email address, use it
272 $select->where(array('email_adh' => $login));
274 ///we did not get an email address, consider using login
275 $select->where(array('login_adh' => $login));
278 $results = $this->zdb
->execute($select);
279 $result = $results->current();
281 $this->loadFromRS($result);
283 } catch (\Exception
$e) {
285 'Cannot load member form login `' . $login . '` | ' .
294 * Populate object from a resultset row
296 * @param ResultSet $r the resultset row
300 private function loadFromRS($r)
302 $this->_self_adh
= false;
303 $this->_id
= $r->id_adh
;
305 if ($r->titre_adh
!== null) {
306 $this->_title
= new Title((int)$r->titre_adh
);
308 $this->_company_name
= $r->societe_adh
;
309 $this->_name
= $r->nom_adh
;
310 $this->_surname
= $r->prenom_adh
;
311 $this->_nickname
= $r->pseudo_adh
;
312 if ($r->ddn_adh
!= '1901-01-01') {
313 $this->_birthdate
= $r->ddn_adh
;
315 $this->_birth_place
= $r->lieu_naissance
;
316 $this->_gender
= (int)$r->sexe_adh
;
317 $this->_job
= $r->prof_adh
;
318 $this->_language
= $r->pref_lang
;
319 $this->_active
= ($r->activite_adh
== 1) ?
true : false;
320 $this->_status
= (int)$r->id_statut
;
321 //Contact information
322 $this->_address
= $r->adresse_adh
;
323 /** TODO: remove and merge with address */
324 $this->_address_continuation
= $r->adresse2_adh
;
325 $this->_zipcode
= $r->cp_adh
;
326 $this->_town
= $r->ville_adh
;
327 $this->_country
= $r->pays_adh
;
328 $this->_phone
= $r->tel_adh
;
329 $this->_gsm
= $r->gsm_adh
;
330 $this->_email
= $r->email_adh
;
331 $this->_website
= $r->url_adh
;
333 $this->_msn
= $r->msn_adh
;
335 $this->_icq
= $r->icq_adh
;
337 $this->_jabber
= $r->jabber_adh
;
339 $this->_gnupgid
= $r->gpgid
;
341 $this->_fingerprint
= $r->fingerprint
;
342 //Galette relative information
343 $this->_appears_in_list
= ($r->bool_display_info
== 1) ?
true : false;
344 $this->_admin
= ($r->bool_admin_adh
== 1) ?
true : false;
346 isset($r->priorite_statut
)
347 && $r->priorite_statut
< Members
::NON_STAFF_MEMBERS
349 $this->_staff
= true;
351 $this->_due_free
= ($r->bool_exempt_adh
== 1) ?
true : false;
352 $this->_login
= $r->login_adh
;
353 $this->_password
= $r->mdp_adh
;
354 $this->_creation_date
= $r->date_crea_adh
;
355 if ($r->date_modif_adh
!= '1901-01-01') {
356 $this->_modification_date
= $r->date_modif_adh
;
358 $this->_modification_date
= $this->_creation_date
;
360 $this->_due_date
= $r->date_echeance
;
361 $this->_others_infos
= $r->info_public_adh
;
362 $this->_others_infos_admin
= $r->info_adh
;
364 if ($r->parent_id
!== null) {
365 $this->_parent
= (int)$r->parent_id
;
366 if ($this->_deps
['parent'] === true) {
367 $this->loadParent($r->parent_id
);
371 if ($this->_deps
['children'] === true) {
372 $this->loadChildren();
375 if ($this->_deps
['picture'] === true) {
376 $this->_picture
= new Picture($this->_id
);
379 if ($this->_deps
['groups'] === true) {
383 if ($this->_deps
['dues'] === true) {
387 if ($this->_deps
['dynamics'] === true) {
388 $this->loadDynamicFields();
397 private function loadParent()
399 if (!$this->_parent
instanceof Adherent
) {
400 $deps = array_fill_keys(array_keys($this->_deps
), false);
401 $this->_parent
= new Adherent($this->zdb
, (int)$this->_parent
, $deps);
406 * Load member children
410 private function loadChildren()
412 $this->_children
= array();
415 $select = $this->zdb
->select(self
::TABLE
);
419 'parent_id = ' . $this->_id
422 $results = $this->zdb
->execute($select);
424 if ($results->count() > 0) {
425 foreach ($results as $row) {
426 $deps = $this->_deps
;
427 $deps['children'] = false;
428 $deps['parent'] = false;
429 $this->_children
[] = new Adherent($this->zdb
, (int)$row->$id, $deps);
432 } catch (\Exception
$e) {
434 'Cannot load children for member #' . $this->_id
. ' | ' .
447 public function loadGroups()
449 $this->_groups
= Groups
::loadGroups($this->_id
);
450 $this->_managed_groups
= Groups
::loadManagedGroups($this->_id
);
454 * Retrieve status from preferences
456 * @return pref_statut
459 private function getDefaultStatus()
462 if ($preferences->pref_statut
!= '') {
463 return $preferences->pref_statut
;
466 'Unable to get pref_statut; is it defined in preferences?',
469 return Status
::DEFAULT_STATUS
;
474 * Check for dues status
478 private function checkDues()
480 //how many days since our beloved member has been created
481 $date_now = new \
DateTime();
482 $this->_oldness
= $date_now->diff(
483 new \
DateTime($this->_creation_date
)
486 if ($this->isDueFree()) {
487 //no fee required, we don't care about dates
488 $this->_row_classes
.= ' cotis-exempt';
490 //ok, fee is required. Let's check the dates
491 if ($this->_due_date
== '') {
492 $this->_row_classes
.= ' cotis-never';
494 $date_end = new \
DateTime($this->_due_date
);
495 $date_diff = $date_now->diff($date_end);
496 $this->_days_remaining
= ($date_diff->invert
== 1)
497 ?
$date_diff->days
* -1
500 if ($this->_days_remaining
== 0) {
501 $this->_row_classes
.= ' cotis-lastday';
502 } elseif ($this->_days_remaining
< 0) {
503 //check if member is still active
504 $this->_row_classes
.= $this->isActive() ?
' cotis-late' : ' cotis-old';
505 } elseif ($this->_days_remaining
< 30) {
506 $this->_row_classes
.= ' cotis-soon';
508 $this->_row_classes
.= ' cotis-ok';
519 public function isAdmin()
521 return $this->_admin
;
525 * Is user member of staff?
529 public function isStaff()
531 return $this->_staff
;
535 * Is member freed of dues?
539 public function isDueFree()
541 return $this->_due_free
;
545 * Is member in specified group?
547 * @param string $group_name Group name
551 public function isGroupMember($group_name)
553 if (is_array($this->_groups
)) {
554 foreach ($this->_groups
as $g) {
555 if ($g->getName() == $group_name) {
562 'Calling ' . __METHOD__
. ' without groups loaded!',
570 * Is member manager of specified group?
572 * @param string $group_name Group name
576 public function isGroupManager($group_name)
578 if (is_array($this->_managed_groups
)) {
579 foreach ($this->_managed_groups
as $mg) {
580 if ($mg->getName() == $group_name) {
587 'Calling ' . __METHOD__
. ' without groups loaded!',
595 * Does current member represents a company?
599 public function isCompany()
601 return trim($this->_company_name
) != '';
605 * Is current member a man?
609 public function isMan()
611 return (int)$this->_gender
=== self
::MAN
;
615 * Is current member a woman?
619 public function isWoman()
621 return (int)$this->_gender
=== self
::WOMAN
;
626 * Can member appears in public members list?
630 public function appearsInMembersList()
632 return $this->_appears_in_list
;
640 public function isActive()
642 return $this->_active
;
646 * Does member have uploaded a picture?
650 public function hasPicture()
652 return $this->_picture
->hasPicture();
656 * Does member have a parent?
660 public function hasParent()
662 return !empty($this->_parent
);
666 * Does member have children?
670 public function hasChildren()
672 if ($this->_children
=== null) {
675 'Children has not been loaded!',
681 return count($this->_children
) > 0;
686 * Get row class related to current fee status
688 * @param boolean $public we want the class for public pages
690 * @return string the class to apply
692 public function getRowClass($public = false)
694 $strclass = ($this->isActive()) ?
'active' : 'inactive';
695 if ($public === false) {
696 $strclass .= $this->_row_classes
;
702 * Get current member due status
704 * @return string i18n string representing state of due
706 public function getDues()
709 if ($this->isDueFree()) {
710 $ret = _T("Freed of dues");
711 } elseif ($this->_due_date
== '') {
712 $patterns = array('/%days/', '/%date/');
713 $cdate = new \
DateTime($this->_creation_date
);
716 $cdate->format(__("Y-m-d"))
718 if ($this->_active
) {
722 _T("Never contributed: Registered %days days ago (since %date)")
725 $ret = _T("Never contributed");
727 } elseif ($this->_days_remaining
== 0) {
728 $ret = _T("Last day!");
729 } elseif ($this->_days_remaining
< 0) {
730 $patterns = array('/%days/', '/%date/');
731 $ddate = new \
DateTime($this->_due_date
);
733 $this->_days_remaining
* -1,
734 $ddate->format(__("Y-m-d"))
736 if ($this->_active
) {
740 _T("Late of %days days (since %date)")
743 $ret = _T("No longer member");
746 $patterns = array('/%days/', '/%date/');
747 $ddate = new \
DateTime($this->_due_date
);
749 $this->_days_remaining
,
750 $ddate->format(__("Y-m-d"))
755 _T("%days days remaining (ending on %date)")
762 * Retrieve Full name and surname for the specified member id
764 * @param Db $zdb Database instance
765 * @param integer $id Member id
766 * @param boolean $wid Add member id
767 * @param boolean $wnick Add member nickname
769 * @return string formatted Name and Surname
771 public static function getSName($zdb, $id, $wid = false, $wnick = false)
774 $select = $zdb->select(self
::TABLE
);
775 $select->where(self
::PK
. ' = ' . $id);
777 $results = $zdb->execute($select);
778 $row = $results->current();
779 return self
::getNameWithCase(
783 ($wid === true ?
$row->id_adh
: false),
784 ($wnick === true ?
$row->pseudo_adh
: false)
786 } catch (\Exception
$e) {
788 'Cannot get formatted name for member form id `' . $id . '` | ' .
797 * Get member name with correct case
799 * @param string $name Member name
800 * @param string $surname Mmeber surname
801 * @param false|Title $title Member title to show or false
802 * @param false|integer $id Member id to display or false
803 * @param false|string $nick Member nickname to display or false
807 public static function getNameWithCase($name, $surname, $title = false, $id = false, $nick = false)
811 if ($title !== false && $title instanceof Title
) {
812 $str .= $title->tshort
. ' ';
815 $str .= mb_strtoupper($name, 'UTF-8') . ' ' .
816 ucwords(mb_strtolower($surname, 'UTF-8'), " \t\r\n\f\v-_|");
818 if ($id !== false ||
$nick !== false) {
821 if ($nick !== false) {
825 if ($nick !== false && !empty($nick)) {
830 if ($id !== false ||
$nick !== false) {
837 * Change password for a given user
839 * @param Db $zdb Database instance
840 * @param string $id_adh Member identifier
841 * @param string $pass New password
845 public static function updatePassword(Db
$zdb, $id_adh, $pass)
848 $cpass = password_hash($pass, PASSWORD_BCRYPT
);
850 $update = $zdb->update(self
::TABLE
);
852 array('mdp_adh' => $cpass)
853 )->where(self
::PK
. ' = ' . $id_adh);
854 $zdb->execute($update);
856 'Password for `' . $id_adh . '` has been updated.',
860 } catch (\Exception
$e) {
862 'An error occurred while updating password for `' . $id_adh .
863 '` | ' . $e->getMessage(),
873 * @param string $field Field name
877 private function getFieldLabel($field)
879 $label = $this->fields
[$field]['label'];
880 //remove trailing ':' and then nbsp (for french at least)
881 $label = trim(trim($label, ':'), ' ');
886 * Retrieve fields from database
888 * @param Db $zdb Database instance
892 public static function getDbFields(Db
$zdb)
894 $columns = $zdb->getColumns(self
::TABLE
);
896 foreach ($columns as $col) {
897 $fields[] = $col->getName();
903 * Mark as self membership
907 public function setSelfMembership()
909 $this->_self_adh
= true;
913 * Is member up to date?
917 public function isUp2Date()
919 if ($this->_deps
['dues']) {
920 if ($this->isDueFree()) {
921 //member is due free, he's up to date.
924 //let's check from end date, if present
925 if ($this->_due_date
== null) {
928 $ech = new \
DateTime($this->_due_date
);
929 $now = new \
DateTime();
930 $now->setTime(0, 0, 0);
935 throw new \
RuntimeException(
936 'Cannot check if member is up to date, dues deps is disabled!'
944 * @param Preferences $preferences Preferences instance
945 * @param array $fields Members fields configuration
946 * @param History $history History instance
950 public function setDependencies(
951 Preferences
$preferences,
955 $this->preferences
= $preferences;
956 $this->fields
= $fields;
957 $this->history
= $history;
961 * Check posted values validity
963 * @param array $values All values to check, basically the $_POST array
964 * after sending the form
965 * @param array $required Array of required fields
966 * @param array $disabled Array of disabled fields
970 public function check($values, $required, $disabled)
972 $this->errors
= array();
974 $fields = self
::getDbFields($this->zdb
);
976 //reset company name if needeed
977 if (!isset($values['is_company'])) {
978 unset($values['is_company']);
979 $values['societe_adh'] = '';
982 //no parent if checkbox was unchecked
984 !isset($values['attach'])
986 && isset($values['parent_id'])
988 unset($values['parent_id']);
991 if (isset($values['duplicate'])) {
992 //if we're duplicating, keep a trace (if an error occurs)
993 $this->_duplicate
= true;
996 foreach ($fields as $key) {
997 //first of all, let's sanitize values
998 $key = strtolower($key);
999 $prop = '_' . $this->fields
[$key]['propname'];
1001 if (isset($values[$key])) {
1002 $value = $values[$key];
1003 if ($value !== true && $value !== false) {
1004 $value = trim($value);
1006 } elseif ($this->_id
== '' ||
$this->_id
== null) {
1008 case 'bool_admin_adh':
1009 case 'bool_exempt_adh':
1010 case 'bool_display_info':
1013 case 'activite_adh':
1014 //values that are setted at object instanciation
1017 case 'date_crea_adh':
1023 //values that are setted at object instanciation
1024 $value = $this->$prop;
1030 //keep stored value on update
1031 if ($prop != '_password' ||
isset($values['mdp_adh']) && isset($values['mdp_adh2'])) {
1032 $value = $this->$prop;
1038 // if the field is enabled, check it
1039 if (!isset($disabled[$key])) {
1040 // fill up the adherent structure
1041 if ($value !== null && $value !== true && $value !== false && !is_object($value)) {
1042 $value = stripslashes($value);
1044 $this->$prop = $value;
1046 // now, check validity
1047 if ($value !== null && $value != '') {
1048 $this->validate($key, $value, $values);
1050 ($key == 'login_adh' && !isset($required['login_adh']))
1051 ||
($key == 'mdp_adh' && !isset($required['mdp_adh']))
1052 && !isset($this->_id
)
1054 $p = new Password($this->zdb
);
1055 $this->$prop = $p->makeRandomPassword(15);
1060 // missing required fields?
1061 foreach ($required as $key => $val) {
1062 $prop = '_' . $this->fields
[$key]['propname'];
1064 if (!isset($disabled[$key])) {
1065 $mandatory_missing = false;
1066 if (!isset($this->$prop) ||
$this->$prop == '') {
1067 $mandatory_missing = true;
1068 } elseif ($key === 'titre_adh' && $this->$prop == '-1') {
1069 $mandatory_missing = true;
1072 if ($mandatory_missing === true) {
1073 $this->errors
[] = str_replace(
1075 '<a href="#' . $key . '">' . $this->getFieldLabel($key) . '</a>',
1076 _T("- Mandatory field %field empty.")
1082 //attach to/detach from parent
1083 if (isset($values['detach_parent'])) {
1084 $this->_parent
= null;
1087 $this->dynamicsCheck($values, $required, $disabled);
1089 if (count($this->errors
) > 0) {
1091 'Some errors has been throwed attempting to edit/store a member' . "\n" .
1092 print_r($this->errors
, true),
1095 return $this->errors
;
1100 'Member checked successfully.',
1108 * Validate data for given key
1109 * Set valid data in current object, also resets errors list
1111 * @param string $field Field name
1112 * @param mixed $value Value we want to set
1113 * @param array $values All values, for some references
1117 public function validate($field, $value, $values)
1119 global $preferences;
1121 $prop = '_' . $this->fields
[$field]['propname'];
1123 if ($value === null ||
(is_string($value) && trim($value) == '')) {
1124 //empty values are OK
1125 $this->$prop = $value;
1131 case 'date_crea_adh':
1132 case 'date_modif_adh_':
1134 case 'date_echeance':
1136 $d = \DateTime
::createFromFormat(__("Y-m-d"), $value);
1138 //try with non localized date
1139 $d = \DateTime
::createFromFormat("Y-m-d", $value);
1141 throw new \
Exception('Incorrect format');
1145 if ($field === 'ddn_adh') {
1146 $now = new \
DateTime();
1147 $now->setTime(0, 0, 0);
1148 $d->setTime(0, 0, 0);
1150 $diff = $now->diff($d);
1151 $days = (int)$diff->format('%R%a');
1153 $this->errors
[] = _T('- Birthdate must be set in the past!');
1156 $years = (int)$diff->format('%R%Y');
1157 if ($years <= -200) {
1158 $this->errors
[] = str_replace(
1161 _T('- Members must be less than 200 years old (currently %years)!')
1165 $this->$prop = $d->format('Y-m-d');
1166 } catch (\Exception
$e) {
1168 'Wrong date format. field: ' . $field .
1169 ', value: ' . $value . ', expected fmt: ' .
1170 __("Y-m-d") . ' | ' . $e->getMessage(),
1173 $this->errors
[] = str_replace(
1180 $this->getFieldLabel($field)
1182 _T("- Wrong date format (%date_format) for %field!")
1187 if ($value !== null && $value !== '') {
1188 if ($value == '-1') {
1189 $this->$prop = null;
1190 } elseif (!$value instanceof Title
) {
1191 $this->$prop = new Title((int)$value);
1194 $this->$prop = null;
1199 if (!GaletteMail
::isValidEmail($value)) {
1200 $this->errors
[] = _T("- Non-valid E-Mail address!") .
1201 ' (' . $this->getFieldLabel($field) . ')';
1203 if ($field == 'email_adh') {
1205 $select = $this->zdb
->select(self
::TABLE
);
1208 )->where(array('email_adh' => $value));
1209 if ($this->_id
!= '' && $this->_id
!= null) {
1211 self
::PK
. ' != ' . $this->_id
1215 $results = $this->zdb
->execute($select);
1216 if ($results->count() !== 0) {
1217 $this->errors
[] = _T("- This E-Mail address is already used by another member!");
1219 } catch (\Exception
$e) {
1221 'An error occurred checking member email unicity.',
1224 $this->errors
[] = _T("An error has occurred while looking if login already exists.");
1229 if ($value == 'http://') {
1231 } elseif (!isValidWebUrl($value)) {
1232 $this->errors
[] = _T("- Non-valid Website address! Maybe you've skipped the http://?");
1236 /** FIXME: add a preference for login lenght */
1237 if (strlen($value) < 2) {
1238 $this->errors
[] = str_replace(
1241 _T("- The username must be composed of at least %i characters!")
1244 //check if login does not contain the @ character
1245 if (strpos($value, '@') != false) {
1246 $this->errors
[] = _T("- The username cannot contain the @ character");
1248 //check if login is already taken
1250 $select = $this->zdb
->select(self
::TABLE
);
1253 )->where(array('login_adh' => $value));
1254 if ($this->_id
!= '' && $this->_id
!= null) {
1256 self
::PK
. ' != ' . $this->_id
1260 $results = $this->zdb
->execute($select);
1262 $results->count() !== 0
1263 ||
$value == $preferences->pref_admin_login
1265 $this->errors
[] = _T("- This username is already in use, please choose another one!");
1267 } catch (\Exception
$e) {
1269 'An error occurred checking member login unicity.',
1272 $this->errors
[] = _T("An error has occurred while looking if login already exists.");
1279 $this->_self_adh
!== true
1280 && (!isset($values['mdp_adh2'])
1281 ||
$values['mdp_adh2'] != $value)
1283 $this->errors
[] = _T("- The passwords don't match!");
1285 $this->_self_adh
=== true
1286 && !crypt($value, $values['mdp_crypt']) == $values['mdp_crypt']
1288 $this->errors
[] = _T("Password misrepeated: ");
1290 $pinfos = password_get_info($value);
1291 //check if value is already a hash
1292 if ($pinfos['algo'] == 0) {
1293 $this->$prop = password_hash(
1298 $pwcheck = new \Galette\Util\
Password($preferences);
1299 $pwcheck->setAdherent($this);
1300 if (!$pwcheck->isValid($value)) {
1301 $this->errors
= array_merge(
1303 $pwcheck->getErrors()
1311 $this->$prop = (int)$value;
1312 //check if status exists
1313 $select = $this->zdb
->select(Status
::TABLE
);
1314 $select->where(Status
::PK
. '= ' . $value);
1316 $results = $this->zdb
->execute($select);
1317 $result = $results->current();
1319 $this->errors
[] = str_replace(
1322 _T("Status #%id does not exists in database.")
1326 } catch (\Exception
$e) {
1328 'An error occurred checking status existance: ' . $e->getMessage(),
1331 $this->errors
[] = _T("An error has occurred while looking if status does exists.");
1335 if (in_array($value, [self
::NC
, self
::MAN
, self
::WOMAN
])) {
1336 $this->$prop = (int)$value;
1338 $this->errors
[] = _T("Gender %gender does not exists!");
1342 $this->$prop = ($value instanceof Adherent
) ?
(int)$value->id
: (int)$value;
1343 $this->loadParent();
1353 public function store()
1355 global $hist, $emitter;
1359 $fields = self
::getDbFields($this->zdb
);
1361 foreach ($fields as $field) {
1363 $field !== 'date_modif_adh'
1364 ||
!isset($this->_id
)
1367 $prop = '_' . $this->fields
[$field]['propname'];
1369 ($field === 'bool_admin_adh'
1370 ||
$field === 'bool_exempt_adh'
1371 ||
$field === 'bool_display_info'
1372 ||
$field === 'activite_adh')
1373 && $this->$prop === false
1375 //Handle booleans for postgres ; bugs #18899 and #19354
1376 $values[$field] = $this->zdb
->isPostgres() ?
'false' : 0;
1377 } elseif ($field === 'parent_id') {
1379 if ($this->_parent
=== null) {
1380 $values['parent_id'] = new Expression('NULL');
1381 } elseif ($this->parent
instanceof Adherent
) {
1382 $values['parent_id'] = $this->_parent
->id
;
1384 $values['parent_id'] = $this->_parent
;
1387 $values[$field] = $this->$prop;
1392 //an empty value will cause date to be set to 1901-01-01, a null
1393 //will result in 0000-00-00. We want a database NULL value here.
1394 if (!$this->_birthdate
) {
1395 $values['ddn_adh'] = new Expression('NULL');
1397 if (!$this->_due_date
) {
1398 $values['date_echeance'] = new Expression('NULL');
1401 if ($this->_title
instanceof Title
) {
1402 $values['titre_adh'] = $this->_title
->id
;
1404 $values['titre_adh'] = new Expression('NULL');
1407 if (!$this->_parent
) {
1408 $values['parent_id'] = new Expression('NULL');
1411 //fields that cannot be null
1413 '_surname' => 'prenom_adh',
1414 '_nickname' => 'pseudo_adh',
1415 '_address' => 'adresse_adh',
1416 '_zipcode' => 'cp_adh',
1417 '_town' => 'ville_adh'
1419 foreach ($notnull as $prop => $field) {
1420 if ($this->$prop === null) {
1421 $values[$field] = '';
1426 if (!isset($this->_id
) ||
$this->_id
== '') {
1427 //we're inserting a new member
1428 unset($values[self
::PK
]);
1429 //set modification date
1430 $this->_modification_date
= date('Y-m-d');
1431 $values['date_modif_adh'] = $this->_modification_date
;
1433 $insert = $this->zdb
->insert(self
::TABLE
);
1434 $insert->values($values);
1435 $add = $this->zdb
->execute($insert);
1436 if ($add->count() > 0) {
1437 if ($this->zdb
->isPostgres()) {
1438 $this->_id
= $this->zdb
->driver
->getLastGeneratedValue(
1439 PREFIX_DB
. 'adherents_id_seq'
1442 $this->_id
= $this->zdb
->driver
->getLastGeneratedValue();
1444 $this->_picture
= new Picture($this->_id
);
1446 if ($this->_self_adh
) {
1448 _T("Self_subscription as a member: ") .
1449 $this->getNameWithCase($this->_name
, $this->_surname
),
1454 _T("Member card added"),
1460 $emitter->emit('member.add', $this);
1462 $hist->add(_T("Fail to add new member."));
1463 throw new \
Exception(
1464 'An error occurred inserting new member!'
1468 //we're editing an existing member
1469 if (!$this->isDueFree()) {
1471 $due_date = Contribution
::getDueDate($this->zdb
, $this->_id
);
1473 $values['date_echeance'] = $due_date;
1477 if (!$this->_password
) {
1478 unset($values['mdp_adh']);
1481 $update = $this->zdb
->update(self
::TABLE
);
1482 $update->set($values);
1484 self
::PK
. '=' . $this->_id
1487 $edit = $this->zdb
->execute($update);
1489 //edit == 0 does not mean there were an error, but that there
1490 //were nothing to change
1491 if ($edit->count() > 0) {
1492 $this->updateModificationDate();
1494 _T("Member card updated"),
1500 $emitter->emit('member.edit', $this);
1505 $success = $this->dynamicsStore();
1509 } catch (\Exception
$e) {
1511 'Something went wrong :\'( | ' . $e->getMessage() . "\n" .
1512 $e->getTraceAsString(),
1520 * Update member modification date
1524 private function updateModificationDate()
1527 $modif_date = date('Y-m-d');
1528 $update = $this->zdb
->update(self
::TABLE
);
1530 array('date_modif_adh' => $modif_date)
1531 )->where(self
::PK
. '=' . $this->_id
);
1533 $edit = $this->zdb
->execute($update);
1534 $this->_modification_date
= $modif_date;
1535 } catch (\Exception
$e) {
1537 'Something went wrong updating modif date :\'( | ' .
1538 $e->getMessage() . "\n" . $e->getTraceAsString(),
1545 * Global getter method
1547 * @param string $name name of the property we want to retrive
1549 * @return false|object the called property
1551 public function __get($name)
1554 'admin', 'staff', 'due_free', 'appears_in_list', 'active',
1559 'sadmin', 'sstaff', 'sdue_free', 'sappears_in_list', 'sactive',
1560 'stitle', 'sstatus', 'sfullname', 'sname', 'rowclass', 'saddress',
1561 'rbirthdate', 'sgender', 'contribstatus'
1564 if (in_array($name, $forbidden)) {
1567 return $this->isAdmin();
1570 return $this->isStaff();
1573 return $this->isDueFree();
1575 case 'appears_in_list':
1576 return $this->appearsInMembersList();
1579 return $this->isActive();
1582 throw new \
RuntimeException("Call to __get for '$name' is forbidden!");
1585 if (in_array($name, $virtuals)) {
1586 if (substr($name, 0, 1) !== '_') {
1587 $real = '_' . substr($name, 1);
1594 case 'sappears_in_list':
1596 return (($this->$real) ?
_T("Yes") : _T("No"));
1599 return (($this->$real) ?
_T("Active") : _T("Inactive"));
1602 if (isset($this->_title
)) {
1603 return $this->_title
->tshort
;
1609 $status = new Status($this->zdb
);
1610 return $status->getLabel($this->_status
);
1613 return $this->getNameWithCase(
1616 (isset($this->_title
) ?
$this->title
: false)
1620 $address = $this->_address
;
1621 if ($this->_address_continuation
!== '' && $this->_address_continuation
!== null) {
1622 $address .= "\n" . $this->_address_continuation
;
1627 return $this->getNameWithCase($this->_name
, $this->_surname
);
1630 return $this->_birthdate
;
1633 switch ($this->gender
) {
1639 return __('Unspecified');
1642 case 'contribstatus':
1643 return $this->getDues();
1647 if (substr($name, 0, 1) !== '_') {
1648 $rname = '_' . $name;
1656 if ($this->$rname !== null) {
1657 return (int)$this->$rname;
1663 case 'creation_date':
1664 case 'modification_date':
1666 if ($this->$rname != '') {
1668 $d = new \
DateTime($this->$rname);
1669 return $d->format(__("Y-m-d"));
1670 } catch (\Exception
$e) {
1671 //oops, we've got a bad date :/
1673 'Bad date (' . $this->$rname . ') | ' .
1677 return $this->$rname;
1682 if (!property_exists($this, $rname)) {
1684 "Unknown property '$rname'",
1689 return $this->$rname;
1699 * If member does not have an email address, but is attached to
1700 * another member, we'll take information from its parent.
1704 public function getEmail()
1706 $email = $this->_email
;
1707 if (empty($email)) {
1708 $this->loadParent();
1709 $email = $this->parent
->email
;
1716 * Get member address.
1717 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1721 public function getAddress()
1723 $address = $this->_address
;
1724 if (empty($address) && $this->hasParent()) {
1725 $this->loadParent();
1726 $address = $this->parent
->address
;
1733 * Get member address continuation.
1734 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1738 public function getAddressContinuation()
1740 $address = $this->_address
;
1741 $address_continuation = $this->_address_continuation
;
1742 if (empty($address) && $this->hasParent()) {
1743 $this->loadParent();
1744 $address_continuation = $this->parent
->address_continuation
;
1747 return $address_continuation;
1751 * Get member zipcode.
1752 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1756 public function getZipcode()
1758 $address = $this->_address
;
1759 $zip = $this->_zipcode
;
1760 if (empty($address) && $this->hasParent()) {
1761 $this->loadParent();
1762 $zip = $this->parent
->zipcode
;
1770 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1774 public function getTown()
1776 $address = $this->_address
;
1777 $town = $this->_town
;
1778 if (empty($address) && $this->hasParent()) {
1779 $this->loadParent();
1780 $town = $this->parent
->town
;
1787 * Get member country.
1788 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1792 public function getCountry()
1794 $address = $this->_address
;
1795 $country = $this->_country
;
1796 if (empty($address) && $this->hasParent()) {
1797 $this->loadParent();
1798 $country = $this->parent
->country
;
1809 public function getAge()
1811 if ($this->_birthdate
== null) {
1815 $d = \DateTime
::createFromFormat('Y-m-d', $this->_birthdate
);
1818 'Invalid birthdate: ' . $this->_birthdate
,
1826 $d->diff(new \
DateTime())->y
,
1827 _T(' (%age years old)')
1832 * Get parent inherited fields
1836 public function getParentFields()
1838 return $this->parent_fields
;
1842 * Handle files (photo and dynamics files
1844 * @param array $files Files sent
1846 * @return array|true
1848 public function handleFiles($files)
1852 if (isset($files['photo'])) {
1853 if ($files['photo']['error'] === UPLOAD_ERR_OK
) {
1854 if ($files['photo']['tmp_name'] != '') {
1855 if (is_uploaded_file($files['photo']['tmp_name'])) {
1856 $res = $this->picture
->store($files['photo']);
1859 = $this->picture
->getErrorMessage($res);
1863 } elseif ($files['photo']['error'] !== UPLOAD_ERR_NO_FILE
) {
1865 $this->picture
->getPhpErrorMessage($files['photo']['error']),
1868 $this->errors
[] = $this->picture
->getPhpErrorMessage(
1869 $files['photo']['error']
1873 $this->dynamicsFiles($_FILES);
1875 if (count($this->errors
) > 0) {
1877 'Some errors has been throwed attempting to edit/store a member files' . "\n" .
1878 print_r($this->errors
, true),
1881 return $this->errors
;
1888 * Set member as duplicate
1892 public function setDuplicate()
1894 //mark as duplicated
1895 $this->_duplicate
= true;
1896 $infos = $this->_others_infos_admin
;
1897 $this->_others_infos_admin
= str_replace(
1899 [$this->sname
, $this->_id
],
1900 _T('Duplicated from %name (%id)')
1902 if (!empty($infos)) {
1903 $this->_others_infos_admin
.= "\n" . $infos;
1907 //drop email, must be unique
1908 $this->_email
= null;
1909 //drop creation date
1910 $this->_creation_date
= date("Y-m-d");
1912 $this->_login
= null;
1914 $this->_picture
= new Picture();
1916 $this->_birthdate
= null;
1918 $this->_surname
= null;
1920 $this->_admin
= false;
1922 $this->_due_free
= false;
1926 * Get current errors
1930 public function getErrors()
1932 return $this->errors
;
1940 public function getGroups()
1942 return $this->_groups
;
1946 * Get user managed groups
1950 public function getManagedGroups()
1952 return $this->_managed_groups
;
1956 * Can current logged in user edit member
1958 * @param Login $login Login instance
1962 public function canEdit($login)
1964 if ($this->id
&& $login->id
== $this->id ||
$login->isAdmin() ||
$login->isStaff()) {
1968 //check if requested member is part of managed groups
1969 if ($login->isGroupManager()) {
1970 foreach ($this->getGroups() as $g) {
1971 if ($login->isGroupManager($g->getId())) {
1981 * Are we currently duplicated a member?
1985 public function isDuplicate()
1987 return $this->_duplicate
;
1991 * Flag creation mail sending
1993 * @param boolean $send True (default) to send creation email
1997 public function setSendmail($send = true)
1999 $this->sendmail
= $send;
2004 * Shoudl we send administrative emails to member?
2008 public function sendEMail()
2010 return $this->sendmail
;