3 /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
6 * Member class for galette
10 * Copyright © 2009-2014 The Galette Team
12 * This file is part of Galette (http://galette.tuxfamily.org).
14 * Galette is free software: you can redistribute it and/or modify
15 * it under the terms of the GNU General Public License as published by
16 * the Free Software Foundation, either version 3 of the License, or
17 * (at your option) any later version.
19 * Galette is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 * GNU General Public License for more details.
24 * You should have received a copy of the GNU General Public License
25 * along with Galette. If not, see <http://www.gnu.org/licenses/>.
30 * @author Johan Cwiklinski <johan@x-tnd.be>
31 * @copyright 2009-2014 The Galette Team
32 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL License 3.0 or (at your option) any later version
34 * @link http://galette.tuxfamily.org
35 * @since Available since 0.7dev - 2009-06-02
38 namespace Galette\Entity
;
41 use Laminas\Db\Sql\Expression
;
43 use Galette\Core\Picture
;
44 use Galette\Core\GaletteMail
;
45 use Galette\Core\Password
;
46 use Galette\Core\Preferences
;
47 use Galette\Core\History
;
48 use Galette\Repository\Groups
;
49 use Galette\Repository\Members
;
52 * Member class for galette
57 * @author Johan Cwiklinski <johan@x-tnd.be>
58 * @copyright 2009-2014 The Galette Team
59 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL License 3.0 or (at your option) any later version
60 * @link http://galette.tuxfamily.org
61 * @since Available since 0.7dev - 02-06-2009
67 const TABLE
= 'adherents';
74 const AFTER_ADD_DEFAULT
= 0;
75 const AFTER_ADD_TRANS
= 1;
76 const AFTER_ADD_NEW
= 2;
77 const AFTER_ADD_SHOW
= 3;
78 const AFTER_ADD_LIST
= 4;
79 const AFTER_ADD_HOME
= 5;
84 private $_company_name;
89 private $_birth_place;
97 private $_address_continuation; /** TODO: remove */
105 private $_msn; /** TODO: remove */
106 private $_icq; /** TODO: remove */
107 private $_jabber; /** TODO: remove */
108 private $_gnupgid; /** TODO: remove */
109 private $_fingerprint; /** TODO: remove */
110 //Galette relative information
111 private $_appears_in_list;
117 private $_creation_date;
118 private $_modification_date;
120 private $_others_infos;
121 private $_others_infos_admin;
124 private $_days_remaining;
126 private $_managed_groups;
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 boolean $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;
343 if (isset($r->priorite_statut
)
344 && $r->priorite_statut
< Members
::NON_STAFF_MEMBERS
346 $this->_staff
= true;
348 $this->_due_free
= ($r->bool_exempt_adh
== 1) ?
true : false;
349 $this->_login
= $r->login_adh
;
350 $this->_password
= $r->mdp_adh
;
351 $this->_creation_date
= $r->date_crea_adh
;
352 if ($r->date_modif_adh
!= '1901-01-01') {
353 $this->_modification_date
= $r->date_modif_adh
;
355 $this->_modification_date
= $this->_creation_date
;
357 $this->_due_date
= $r->date_echeance
;
358 $this->_others_infos
= $r->info_public_adh
;
359 $this->_others_infos_admin
= $r->info_adh
;
361 if ($r->parent_id
!== null) {
362 $this->_parent
= (int)$r->parent_id
;
363 if ($this->_deps
['parent'] === true) {
364 $this->loadParent($r->parent_id
);
368 if ($this->_deps
['children'] === true) {
369 $this->loadChildren();
372 if ($this->_deps
['picture'] === true) {
373 $this->_picture
= new Picture($this->_id
);
376 if ($this->_deps
['groups'] === true) {
380 if ($this->_deps
['dues'] === true) {
384 if ($this->_deps
['dynamics'] === true) {
385 $this->loadDynamicFields();
394 private function loadParent()
396 if (!$this->_parent
instanceof Adherent
) {
397 $deps = array_fill_keys(array_keys($this->_deps
), false);
398 $this->_parent
= new Adherent($this->zdb
, (int)$this->_parent
, $deps);
403 * Load member children
407 private function loadChildren()
409 $this->_children
= array();
412 $select = $this->zdb
->select(self
::TABLE
);
416 'parent_id = ' . $this->_id
419 $results = $this->zdb
->execute($select);
421 if ($results->count() > 0) {
422 foreach ($results as $row) {
423 $deps = $this->_deps
;
424 $deps['children'] = false;
425 $deps['parent'] = false;
426 $this->_children
[] = new Adherent($this->zdb
, (int)$row->$id, $deps);
429 } catch (\Exception
$e) {
431 'Cannot load children for member #' . $this->_id
. ' | ' .
444 public function loadGroups()
446 $this->_groups
= Groups
::loadGroups($this->_id
);
447 $this->_managed_groups
= Groups
::loadManagedGroups($this->_id
);
451 * Retrieve status from preferences
453 * @return pref_statut
456 private function getDefaultStatus()
459 if ($preferences->pref_statut
!= '') {
460 return $preferences->pref_statut
;
463 'Unable to get pref_statut; is it defined in preferences?',
466 return Status
::DEFAULT_STATUS
;
471 * Check for dues status
475 private function checkDues()
477 //how many days since our beloved member has been created
478 $date_now = new \
DateTime();
479 $this->_oldness
= $date_now->diff(
480 new \
DateTime($this->_creation_date
)
483 if ($this->isDueFree()) {
484 //no fee required, we don't care about dates
485 $this->_row_classes
.= ' cotis-exempt';
487 //ok, fee is required. Let's check the dates
488 if ($this->_due_date
== '') {
489 $this->_row_classes
.= ' cotis-never';
491 $date_end = new \
DateTime($this->_due_date
);
492 $date_diff = $date_now->diff($date_end);
493 $this->_days_remaining
= ( $date_diff->invert
== 1 )
494 ?
$date_diff->days
* -1
497 if ($this->_days_remaining
== 0) {
498 $this->_row_classes
.= ' cotis-lastday';
499 } elseif ($this->_days_remaining
< 0) {
500 $this->_row_classes
.= ' cotis-late';
501 } elseif ($this->_days_remaining
< 30) {
502 $this->_row_classes
.= ' cotis-soon';
504 $this->_row_classes
.= ' cotis-ok';
515 public function isAdmin()
517 return $this->_admin
;
521 * Is user member of staff?
525 public function isStaff()
527 return $this->_staff
;
531 * Is member freed of dues?
535 public function isDueFree()
537 return $this->_due_free
;
541 * Is member in specified group?
543 * @param string $group_name Group name
547 public function isGroupMember($group_name)
549 if (is_array($this->_groups
)) {
550 foreach ($this->_groups
as $g) {
551 if ($g->getName() == $group_name) {
558 'Calling ' . __METHOD__
. ' without groups loaded!',
566 * Is member manager of specified group?
568 * @param string $group_name Group name
572 public function isGroupManager($group_name)
574 if (is_array($this->_managed_groups
)) {
575 foreach ($this->_managed_groups
as $mg) {
576 if ($mg->getName() == $group_name) {
583 'Calling ' . __METHOD__
. ' without groups loaded!',
591 * Does current member represents a company?
595 public function isCompany()
597 return trim($this->_company_name
) != '';
601 * Is current member a man?
605 public function isMan()
607 return (int)$this->_gender
=== self
::MAN
;
611 * Is current member a woman?
615 public function isWoman()
617 return (int)$this->_gender
=== self
::WOMAN
;
622 * Can member appears in public members list?
626 public function appearsInMembersList()
628 return $this->_appears_in_list
;
636 public function isActive()
638 return $this->_active
;
642 * Does member have uploaded a picture?
646 public function hasPicture()
648 return $this->_picture
->hasPicture();
652 * Does member have a parent?
656 public function hasParent()
658 return !empty($this->_parent
);
662 * Does member have children?
666 public function hasChildren()
668 if ($this->_children
=== null) {
670 'Children has not been loaded!',
675 return count($this->_children
) > 0;
680 * Get row class related to current fee status
682 * @param boolean $public we want the class for public pages
684 * @return string the class to apply
686 public function getRowClass($public = false)
688 $strclass = ($this->isActive()) ?
'active' : 'inactive';
689 if ($public === false) {
690 $strclass .= $this->_row_classes
;
696 * Get current member due status
698 * @return string i18n string representing state of due
700 public function getDues()
703 if ($this->isDueFree()) {
704 $ret = _T("Freed of dues");
705 } elseif ($this->_due_date
== '') {
706 $patterns = array('/%days/', '/%date/');
707 $cdate = new \
DateTime($this->_creation_date
);
710 $cdate->format(__("Y-m-d"))
712 if ($this->_active
) {
716 _T("Never contributed: Registered %days days ago (since %date)")
719 $ret = _T("Never contributed");
721 } elseif ($this->_days_remaining
== 0) {
722 $ret = _T("Last day!");
723 } elseif ($this->_days_remaining
< 0) {
724 $patterns = array('/%days/', '/%date/');
725 $ddate = new \
DateTime($this->_due_date
);
727 $this->_days_remaining
*-1,
728 $ddate->format(__("Y-m-d"))
730 if ($this->_active
) {
734 _T("Late of %days days (since %date)")
740 $patterns = array('/%days/', '/%date/');
741 $ddate = new \
DateTime($this->_due_date
);
743 $this->_days_remaining
,
744 $ddate->format(__("Y-m-d"))
749 _T("%days days remaining (ending on %date)")
756 * Retrieve Full name and surname for the specified member id
758 * @param Db $zdb Database instance
759 * @param integer $id Member id
760 * @param boolean $wid Add member id
761 * @param boolean $wnick Add member nickname
763 * @return string formatted Name and Surname
765 public static function getSName($zdb, $id, $wid = false, $wnick = false)
768 $select = $zdb->select(self
::TABLE
);
769 $select->where(self
::PK
. ' = ' . $id);
771 $results = $zdb->execute($select);
772 $row = $results->current();
773 return self
::getNameWithCase(
777 ($wid === true ?
$row->id_adh
: false),
778 ($wnick === true ?
$row->pseudo_adh
: false)
780 } catch (\Exception
$e) {
782 'Cannot get formatted name for member form id `' . $id . '` | ' .
791 * Get member name with correct case
793 * @param string $name Member name
794 * @param string $surname Mmeber surname
795 * @param false|Title $title Member title to show or false
796 * @param false|integer $id Member id to display or false
797 * @param false|string $nick Member nickname to display or false
801 public static function getNameWithCase($name, $surname, $title = false, $id = false, $nick = false)
805 if ($title !== false && $title instanceof Title
) {
806 $str .= $title->tshort
. ' ';
809 $str .= mb_strtoupper($name, 'UTF-8') . ' ' .
810 ucwords(mb_strtolower($surname, 'UTF-8'), " \t\r\n\f\v-_|");
812 if ($id !== false ||
$nick !== false) {
815 if ($nick !== false) {
819 if ($nick !== false && !empty($nick)) {
824 if ($id !== false ||
$nick !== false) {
831 * Change password for a given user
833 * @param Db $zdb Database instance
834 * @param string $id_adh Member identifier
835 * @param string $pass New password
839 public static function updatePassword(Db
$zdb, $id_adh, $pass)
842 $cpass = password_hash($pass, PASSWORD_BCRYPT
);
844 $update = $zdb->update(self
::TABLE
);
846 array('mdp_adh' => $cpass)
847 )->where(self
::PK
. ' = ' . $id_adh);
848 $zdb->execute($update);
850 'Password for `' . $id_adh . '` has been updated.',
854 } catch (\Exception
$e) {
856 'An error occurred while updating password for `' . $id_adh .
857 '` | ' . $e->getMessage(),
867 * @param string $field Field name
871 private function getFieldLabel($field)
873 $label = $this->fields
[$field]['label'];
874 //remove trailing ':' and then nbsp (for french at least)
875 $label = trim(trim($label, ':'), ' ');
880 * Retrieve fields from database
882 * @param Db $zdb Database instance
886 public static function getDbFields(Db
$zdb)
888 $columns = $zdb->getColumns(self
::TABLE
);
890 foreach ($columns as $col) {
891 $fields[] = $col->getName();
897 * Mark as self membership
901 public function setSelfMembership()
903 $this->_self_adh
= true;
907 * Is member up to date?
911 public function isUp2Date()
913 if ($this->_deps
['dues']) {
914 if ($this->isDueFree()) {
915 //member is due free, he's up to date.
918 //let's check from end date, if present
919 if ($this->_due_date
== null) {
922 $ech = new \
DateTime($this->_due_date
);
923 $now = new \
DateTime();
924 $now->setTime(0, 0, 0);
929 throw new \
RuntimeException(
930 'Cannot check if member is up to date, dues deps is disabled!'
938 * @param Preferences $preferences Preferences instance
939 * @param array $fields Members fields configuration
940 * @param History $history History instance
944 public function setDependencies(
945 Preferences
$preferences,
949 $this->preferences
= $preferences;
950 $this->fields
= $fields;
951 $this->history
= $history;
955 * Check posted values validity
957 * @param array $values All values to check, basically the $_POST array
958 * after sending the form
959 * @param array $required Array of required fields
960 * @param array $disabled Array of disabled fields
964 public function check($values, $required, $disabled)
966 $this->errors
= array();
968 $fields = self
::getDbFields($this->zdb
);
970 //reset company name if needeed
971 if (!isset($values['is_company'])) {
972 unset($values['is_company']);
973 $values['societe_adh'] = '';
976 //no parent if checkbox was unchecked
977 if (!isset($values['attach'])
979 && isset($values['parent_id'])
981 unset($values['parent_id']);
984 foreach ($fields as $key) {
985 //first of all, let's sanitize values
986 $key = strtolower($key);
987 $prop = '_' . $this->fields
[$key]['propname'];
989 if (isset($values[$key])) {
990 $value = $values[$key];
991 if ($value !== true && $value !== false) {
992 $value = trim($value);
994 } elseif ($this->_id
== '' ||
$this->_id
== null) {
996 case 'bool_admin_adh':
997 case 'bool_exempt_adh':
998 case 'bool_display_info':
1001 case 'activite_adh':
1002 //values that are setted at object instanciation
1005 case 'date_crea_adh':
1011 //values that are setted at object instanciation
1012 $value = $this->$prop;
1018 //keep stored value on update
1019 if ($prop != '_password' ||
isset($values['mdp_adh']) && isset($values['mdp_adh2'])) {
1020 $value = $this->$prop;
1026 // if the field is enabled, check it
1027 if (!isset($disabled[$key])) {
1028 // fill up the adherent structure
1029 if ($value !== null && $value !== true && $value !== false && !is_object($value)) {
1030 $value = stripslashes($value);
1032 $this->$prop = $value;
1034 // now, check validity
1035 if ($value !== null && $value != '') {
1036 $this->validate($key, $value, $values);
1037 } elseif (($key == 'login_adh' && !isset($required['login_adh']))
1038 ||
($key == 'mdp_adh' && !isset($required['mdp_adh']))
1039 && !isset($this->_id
)
1041 $p = new Password($this->zdb
);
1042 $this->$prop = $p->makeRandomPassword(15);
1047 // missing required fields?
1048 foreach ($required as $key => $val) {
1049 $prop = '_' . $this->fields
[$key]['propname'];
1051 if (!isset($disabled[$key])) {
1052 $mandatory_missing = false;
1053 if (!isset($this->$prop) ||
$this->$prop == '') {
1054 $mandatory_missing = true;
1055 } elseif ($key === 'titre_adh' && $this->$prop == '-1') {
1056 $mandatory_missing = true;
1059 if ($mandatory_missing === true) {
1060 $this->errors
[] = str_replace(
1062 '<a href="#' . $key . '">' . $this->getFieldLabel($key) .'</a>',
1063 _T("- Mandatory field %field empty.")
1069 //attach to/detach from parent
1070 if (isset($values['detach_parent'])) {
1071 $this->_parent
= null;
1074 $this->dynamicsCheck($values);
1076 if (count($this->errors
) > 0) {
1078 'Some errors has been throwed attempting to edit/store a member' . "\n" .
1079 print_r($this->errors
, true),
1082 return $this->errors
;
1087 'Member checked successfully.',
1095 * Validate data for given key
1096 * Set valid data in current object, also resets errors list
1098 * @param string $field Field name
1099 * @param mixed $value Value we want to set
1100 * @param array $values All values, for some references
1104 public function validate($field, $value, $values)
1106 global $preferences;
1108 $prop = '_' . $this->fields
[$field]['propname'];
1110 if ($value === null ||
trim($value) == '') {
1111 //empty values are OK
1112 $this->$prop = $value;
1118 case 'date_crea_adh':
1119 case 'date_modif_adh_':
1121 case 'date_echeance':
1123 $d = \DateTime
::createFromFormat(__("Y-m-d"), $value);
1125 //try with non localized date
1126 $d = \DateTime
::createFromFormat("Y-m-d", $value);
1128 throw new \
Exception('Incorrect format');
1132 if ($field === 'ddn_adh') {
1133 $now = new \
DateTime();
1134 $now->setTime(0, 0, 0);
1135 $d->setTime(0, 0, 0);
1137 $diff = $now->diff($d);
1138 $days = (integer)$diff->format('%R%a');
1140 $this->errors
[] =_T('- Birthdate must be set in the past!');
1143 $years = (integer)$diff->format('%R%Y');
1144 if ($years <= -200) {
1145 $this->errors
[] = str_replace(
1148 _T('- Members must be less than 200 years old (currently %years)!')
1152 $this->$prop = $d->format('Y-m-d');
1153 } catch (\Exception
$e) {
1155 'Wrong date format. field: ' . $field .
1156 ', value: ' . $value . ', expected fmt: ' .
1157 __("Y-m-d") . ' | ' . $e->getMessage(),
1160 $this->errors
[] = str_replace(
1167 $this->getFieldLabel($field)
1169 _T("- Wrong date format (%date_format) for %field!")
1174 if ($value !== null && $value !== '') {
1175 if ($value == '-1') {
1176 $this->$prop = null;
1177 } elseif (!$value instanceof Title
) {
1178 $this->$prop = new Title((int)$value);
1181 $this->$prop = null;
1186 if (!GaletteMail
::isValidEmail($value)) {
1187 $this->errors
[] = _T("- Non-valid E-Mail address!") .
1188 ' (' . $this->getFieldLabel($field) . ')';
1190 if ($field == 'email_adh') {
1192 $select = $this->zdb
->select(self
::TABLE
);
1195 )->where(array('email_adh' => $value));
1196 if ($this->_id
!= '' && $this->_id
!= null) {
1198 self
::PK
. ' != ' . $this->_id
1202 $results = $this->zdb
->execute($select);
1203 if ($results->count() !== 0) {
1204 $this->errors
[] = _T("- This E-Mail address is already used by another member!");
1206 } catch (\Exception
$e) {
1208 'An error occurred checking member email unicity.',
1211 $this->errors
[] = _T("An error has occurred while looking if login already exists.");
1216 if ($value == 'http://') {
1218 } elseif (!isValidWebUrl($value)) {
1219 $this->errors
[] = _T("- Non-valid Website address! Maybe you've skipped the http://?");
1223 /** FIXME: add a preference for login lenght */
1224 if (strlen($value) < 2) {
1225 $this->errors
[] = str_replace(
1228 _T("- The username must be composed of at least %i characters!")
1231 //check if login does not contain the @ character
1232 if (strpos($value, '@') != false) {
1233 $this->errors
[] = _T("- The username cannot contain the @ character");
1235 //check if login is already taken
1237 $select = $this->zdb
->select(self
::TABLE
);
1240 )->where(array('login_adh' => $value));
1241 if ($this->_id
!= '' && $this->_id
!= null) {
1243 self
::PK
. ' != ' . $this->_id
1247 $results = $this->zdb
->execute($select);
1248 if ($results->count() !== 0
1249 ||
$value == $preferences->pref_admin_login
1251 $this->errors
[] = _T("- This username is already in use, please choose another one!");
1253 } catch (\Exception
$e) {
1255 'An error occurred checking member login unicity.',
1258 $this->errors
[] = _T("An error has occurred while looking if login already exists.");
1264 if ($this->_self_adh
!== true
1265 && (!isset($values['mdp_adh2'])
1266 ||
$values['mdp_adh2'] != $value)
1268 $this->errors
[] = _T("- The passwords don't match!");
1269 } elseif ($this->_self_adh
=== true
1270 && !crypt($value, $values['mdp_crypt'])==$values['mdp_crypt']
1272 $this->errors
[] = _T("Password misrepeated: ");
1274 $pinfos = password_get_info($value);
1275 //check if value is already a hash
1276 if ($pinfos['algo'] == 0) {
1277 $this->$prop = password_hash(
1282 $pwcheck = new \Galette\Util\
Password($preferences);
1283 $pwcheck->setAdherent($this);
1284 if (!$pwcheck->isValid($value)) {
1285 $this->errors
= array_merge(
1287 $pwcheck->getErrors()
1295 $this->$prop = (int)$value;
1296 //check if status exists
1297 $select = $this->zdb
->select(Status
::TABLE
);
1298 $select->where(Status
::PK
. '= ' . $value);
1300 $results = $this->zdb
->execute($select);
1301 $result = $results->current();
1303 $this->errors
[] = str_replace(
1306 _T("Status #%id does not exists in database.")
1310 } catch (\Exception
$e) {
1312 'An error occurred checking status existance: ' . $e->getMessage(),
1315 $this->errors
[] = _T("An error has occurred while looking if status does exists.");
1319 if (in_array($value, [self
::NC
, self
::MAN
, self
::WOMAN
])) {
1320 $this->$prop = (int)$value;
1322 $this->errors
[] = _T("Gender %gender does not exists!");
1333 public function store()
1335 global $hist, $emitter;
1339 $fields = self
::getDbFields($this->zdb
);
1341 foreach ($fields as $field) {
1342 if ($field !== 'date_modif_adh'
1343 ||
!isset($this->_id
)
1346 $prop = '_' . $this->fields
[$field]['propname'];
1347 if (($field === 'bool_admin_adh'
1348 ||
$field === 'bool_exempt_adh'
1349 ||
$field === 'bool_display_info'
1350 ||
$field === 'activite_adh')
1351 && $this->$prop === false
1353 //Handle booleans for postgres ; bugs #18899 and #19354
1354 $values[$field] = $this->zdb
->isPostgres() ?
'false' : 0;
1355 } elseif ($field === 'parent_id') {
1357 if ($this->_parent
=== null) {
1358 $values['parent_id'] = new Expression('NULL');
1359 } elseif ($this->parent
instanceof Adherent
) {
1360 $values['parent_id'] = $this->_parent
->id
;
1362 $values['parent_id'] = $this->_parent
;
1365 $values[$field] = $this->$prop;
1370 //an empty value will cause date to be set to 1901-01-01, a null
1371 //will result in 0000-00-00. We want a database NULL value here.
1372 if (!$this->_birthdate
) {
1373 $values['ddn_adh'] = new Expression('NULL');
1375 if (!$this->_due_date
) {
1376 $values['date_echeance'] = new Expression('NULL');
1379 if ($this->_title
instanceof Title
) {
1380 $values['titre_adh'] = $this->_title
->id
;
1382 $values['titre_adh'] = new Expression('NULL');
1385 if (!$this->_parent
) {
1386 $values['parent_id'] = new Expression('NULL');
1389 //fields that cannot be null
1391 '_surname' => 'prenom_adh',
1392 '_nickname' => 'pseudo_adh',
1393 '_address' => 'adresse_adh',
1394 '_zipcode' => 'cp_adh',
1395 '_town' => 'ville_adh'
1397 foreach ($notnull as $prop => $field) {
1398 if ($this->$prop === null) {
1399 $values[$field] = '';
1404 if (!isset($this->_id
) ||
$this->_id
== '') {
1405 //we're inserting a new member
1406 unset($values[self
::PK
]);
1407 //set modification date
1408 $this->_modification_date
= date('Y-m-d');
1409 $values['date_modif_adh'] = $this->_modification_date
;
1411 $insert = $this->zdb
->insert(self
::TABLE
);
1412 $insert->values($values);
1413 $add = $this->zdb
->execute($insert);
1414 if ($add->count() > 0) {
1415 if ($this->zdb
->isPostgres()) {
1416 $this->_id
= $this->zdb
->driver
->getLastGeneratedValue(
1417 PREFIX_DB
. 'adherents_id_seq'
1420 $this->_id
= $this->zdb
->driver
->getLastGeneratedValue();
1422 $this->_picture
= new Picture($this->_id
);
1424 if ($this->_self_adh
) {
1426 _T("Self_subscription as a member: ") .
1427 $this->getNameWithCase($this->_name
, $this->_surname
),
1432 _T("Member card added"),
1438 $emitter->emit('member.add', $this);
1440 $hist->add(_T("Fail to add new member."));
1441 throw new \
Exception(
1442 'An error occurred inserting new member!'
1446 //we're editing an existing member
1447 if (!$this->isDueFree()) {
1449 $due_date = Contribution
::getDueDate($this->zdb
, $this->_id
);
1451 $values['date_echeance'] = $due_date;
1455 if (!$this->_password
) {
1456 unset($values['mdp_adh']);
1459 $update = $this->zdb
->update(self
::TABLE
);
1460 $update->set($values);
1462 self
::PK
. '=' . $this->_id
1465 $edit = $this->zdb
->execute($update);
1467 //edit == 0 does not mean there were an error, but that there
1468 //were nothing to change
1469 if ($edit->count() > 0) {
1470 $this->updateModificationDate();
1472 _T("Member card updated"),
1478 $emitter->emit('member.edit', $this);
1483 $success = $this->dynamicsStore();
1487 } catch (\Exception
$e) {
1489 'Something went wrong :\'( | ' . $e->getMessage() . "\n" .
1490 $e->getTraceAsString(),
1498 * Update member modification date
1502 private function updateModificationDate()
1505 $modif_date = date('Y-m-d');
1506 $update = $this->zdb
->update(self
::TABLE
);
1508 array('date_modif_adh' => $modif_date)
1509 )->where(self
::PK
. '=' . $this->_id
);
1511 $edit = $this->zdb
->execute($update);
1512 $this->_modification_date
= $modif_date;
1513 } catch (\Exception
$e) {
1515 'Something went wrong updating modif date :\'( | ' .
1516 $e->getMessage() . "\n" . $e->getTraceAsString(),
1523 * Global getter method
1525 * @param string $name name of the property we want to retrive
1527 * @return false|object the called property
1529 public function __get($name)
1532 'admin', 'staff', 'due_free', 'appears_in_list', 'active',
1537 'sadmin', 'sstaff', 'sdue_free', 'sappears_in_list', 'sactive',
1538 'stitle', 'sstatus', 'sfullname', 'sname', 'rowclass', 'saddress',
1542 if (in_array($name, $forbidden)) {
1544 "Call to __get for '$name' is forbidden!",
1549 return $this->isAdmin();
1552 return $this->isStaff();
1555 return $this->isDueFree();
1557 case 'appears_in_list':
1558 return $this->appearsInMembersList();
1561 return $this->isActive();
1564 throw new \
RuntimeException("Call to __get for '$name' is forbidden!");
1567 if (in_array($name, $virtuals)) {
1568 if (substr($name, 0, 1) !== '_') {
1569 $real = '_' . substr($name, 1);
1576 case 'sappears_in_list':
1578 return (($this->$real) ?
_T("Yes") : _T("No"));
1581 return (($this->$real) ?
_T("Active") : _T("Inactive"));
1584 if (isset($this->_title
)) {
1585 return $this->_title
->tshort
;
1591 $status = new Status($this->zdb
);
1592 return $status->getLabel($this->_status
);
1595 return $this->getNameWithCase(
1598 (isset($this->_title
) ?
$this->title
: false)
1602 $address = $this->_address
;
1603 if ($this->_address_continuation
!== '' && $this->_address_continuation
!== null) {
1604 $address .= "\n" . $this->_address_continuation
;
1609 return $this->getNameWithCase($this->_name
, $this->_surname
);
1612 return $this->_birthdate
;
1616 if (substr($name, 0, 1) !== '_') {
1617 $rname = '_' . $name;
1625 return (int)$this->$rname;
1628 case 'creation_date':
1629 case 'modification_date':
1631 if ($this->$rname != '') {
1633 $d = new \
DateTime($this->$rname);
1634 return $d->format(__("Y-m-d"));
1635 } catch (\Exception
$e) {
1636 //oops, we've got a bad date :/
1638 'Bad date (' . $this->$rname . ') | ' .
1642 return $this->$rname;
1647 if (!property_exists($this, $rname)) {
1649 "Unknown property '$rname'",
1654 return $this->$rname;
1664 * If member does not have an email address, but is attached to
1665 * another member, we'll take information from its parent.
1669 public function getEmail()
1671 $email = $this->_email
;
1672 if (empty($email)) {
1673 $this->loadParent();
1674 $email = $this->parent
->email
;
1681 * Get member address.
1682 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1686 public function getAddress()
1688 $address = $this->_address
;
1689 if (empty($address) && $this->hasParent()) {
1690 $this->loadParent();
1691 $address = $this->parent
->address
;
1698 * Get member address continuation.
1699 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1703 public function getAddressContinuation()
1705 $address = $this->_address
;
1706 $address_continuation = $this->_address_continuation
;
1707 if (empty($address) && $this->hasParent()) {
1708 $this->loadParent();
1709 $address_continuation = $this->parent
->address_continuation
;
1712 return $address_continuation;
1716 * Get member zipcode.
1717 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1721 public function getZipcode()
1723 $address = $this->_address
;
1724 $zip = $this->_zipcode
;
1725 if (empty($address) && $this->hasParent()) {
1726 $this->loadParent();
1727 $zip = $this->parent
->zipcode
;
1735 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1739 public function getTown()
1741 $address = $this->_address
;
1742 $town = $this->_town
;
1743 if (empty($address) && $this->hasParent()) {
1744 $this->loadParent();
1745 $town = $this->parent
->town
;
1752 * Get member country.
1753 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1757 public function getCountry()
1759 $address = $this->_address
;
1760 $country = $this->_country
;
1761 if (empty($address) && $this->hasParent()) {
1762 $this->loadParent();
1763 $country = $this->parent
->country
;
1774 public function getAge()
1776 if ($this->_birthdate
== null) {
1780 $d = \DateTime
::createFromFormat('Y-m-d', $this->_birthdate
);
1783 'Invalid birthdate: ' . $this->_birthdate
,
1791 $d->diff(new \
DateTime())->y
,
1792 _T(' (%age years old)')
1797 * Get parent inherited fields
1801 public function getParentFields()
1803 return $this->parent_fields
;
1807 * Handle files (phot and dynamics files
1809 * @param array $files Files sent
1811 * @return array|true
1813 public function handleFiles($files)
1817 if (isset($files['photo'])) {
1818 if ($files['photo']['error'] === UPLOAD_ERR_OK
) {
1819 if ($files['photo']['tmp_name'] !='') {
1820 if (is_uploaded_file($files['photo']['tmp_name'])) {
1821 $res = $this->picture
->store($files['photo']);
1824 = $this->picture
->getErrorMessage($res);
1828 } elseif ($files['photo']['error'] !== UPLOAD_ERR_NO_FILE
) {
1830 $this->picture
->getPhpErrorMessage($files['photo']['error']),
1833 $this->errors
[] = $this->picture
->getPhpErrorMessage(
1834 $files['photo']['error']
1838 $this->dynamicsFiles($_FILES);
1840 if (count($this->errors
) > 0) {
1842 'Some errors has been throwed attempting to edit/store a member files' . "\n" .
1843 print_r($this->errors
, true),
1846 return $this->errors
;
1853 * Set member as duplicate
1857 public function setDuplicate()
1859 //mark as duplicated
1860 $infos = $this->_others_infos_admin
;
1861 $this->_others_infos_admin
= str_replace(
1863 [$this->sname
, $this->_id
],
1864 _T('Duplicated from %name (%id)')
1866 if (!empty($infos)) {
1867 $this->_others_infos_admin
.= "\n" . $infos;
1871 //drop email, must be unique
1872 $this->_email
= null;
1876 * Get current errors
1880 public function getErrors()
1882 return $this->errors
;