]> git.agnieray.net Git - galette.git/blob - galette/lib/Galette/Entity/Adherent.php
Fix password storage
[galette.git] / galette / lib / Galette / Entity / Adherent.php
1 <?php
2
3 /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
4
5 /**
6 * Member class for galette
7 *
8 * PHP version 5
9 *
10 * Copyright © 2009-2021 The Galette Team
11 *
12 * This file is part of Galette (http://galette.tuxfamily.org).
13 *
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.
18 *
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.
23 *
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/>.
26 *
27 * @category Entity
28 * @package Galette
29 *
30 * @author Johan Cwiklinski <johan@x-tnd.be>
31 * @copyright 2009-2021 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
35 */
36
37 namespace Galette\Entity;
38
39 use Throwable;
40 use Analog\Analog;
41 use Laminas\Db\Sql\Expression;
42 use Galette\Core\Db;
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;
50
51 /**
52 * Member class for galette
53 *
54 * @category Entity
55 * @name Adherent
56 * @package Galette
57 * @author Johan Cwiklinski <johan@x-tnd.be>
58 * @copyright 2009-2021 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
62 *
63 * @property integer $id
64 * @property integer|Title $title Either a title id or an instance of Title
65 * @property string $stitle Title label
66 * @property string company_name
67 * @property string $name
68 * @property string $surname
69 * @property string $nickname
70 * @property string $birthdate Localized birth date
71 * @property string $rbirthdate Raw birth date
72 * @property string $birth_place
73 * @property integer $gender
74 * @property string $sgender Gender label
75 * @property string $job
76 * @property string $language
77 * @property integer $status
78 * @property string $sstatus Status label
79 * @property string $address
80 * @property string $address_continuation
81 * @property string $zipcode
82 * @property string $town
83 * @property string $country
84 * @property string $phone
85 * @property string $gsm
86 * @property string $email
87 * @property string $website
88 * @property string $msn
89 * @property string $icq
90 * @property string $jabber
91 * @property string $gnupgid
92 * @property string $fingerprint
93 * @property string $login
94 * @property string $creation_date Localized creation date
95 * @property string $modification_date Localized modification date
96 * @property string $due_date Localized due date
97 * @property string $others_infos
98 * @property string $others_infos_admin
99 * @property Picture $picture
100 * @property array $groups
101 * @property array $managed_groups
102 * @property integer|Adherent $parent Parent id if parent dep is not loaded, Adherent instance otherwise
103 * @property array $children
104 * @property boolean $admin better to rely on isAdmin()
105 * @property boolean $staff better to rely on isStaff()
106 * @property boolean $due_free better to rely on isDueFree()
107 * @property boolean $appears_in_list better to rely on appearsInMembersList()
108 * @property boolean $active better to rely on isActive()
109 * @property boolean $duplicate better to rely on isDuplicate()
110 * @property string $sadmin yes/no
111 * @property string $sstaff yes/no
112 * @property string $sdue_free yes/no
113 * @property string $sappears_in_list yes/no
114 * @property string $sactive yes/no
115 * @property string $sfullname
116 * @property string $sname
117 * @property string $saddress Concatened address and continuation
118 * @property string $contribstatus State of member contributions
119 * @property string $days_remaining
120 */
121 class Adherent
122 {
123 use DynamicsTrait;
124
125 public const TABLE = 'adherents';
126 public const PK = 'id_adh';
127
128 public const NC = 0;
129 public const MAN = 1;
130 public const WOMAN = 2;
131
132 public const AFTER_ADD_DEFAULT = 0;
133 public const AFTER_ADD_TRANS = 1;
134 public const AFTER_ADD_NEW = 2;
135 public const AFTER_ADD_SHOW = 3;
136 public const AFTER_ADD_LIST = 4;
137 public const AFTER_ADD_HOME = 5;
138
139 private $_id;
140 //Identity
141 private $_title;
142 private $_company_name;
143 private $_name;
144 private $_surname;
145 private $_nickname;
146 private $_birthdate;
147 private $_birth_place;
148 private $_gender;
149 private $_job;
150 private $_language;
151 private $_active;
152 private $_status;
153 //Contact information
154 private $_address;
155 private $_address_continuation; /** TODO: remove */
156 private $_zipcode;
157 private $_town;
158 private $_country;
159 private $_phone;
160 private $_gsm;
161 private $_email;
162 private $_website;
163 private $_msn; /** TODO: remove */
164 private $_icq; /** TODO: remove */
165 private $_jabber; /** TODO: remove */
166 private $_gnupgid; /** TODO: remove */
167 private $_fingerprint; /** TODO: remove */
168 //Galette relative information
169 private $_appears_in_list;
170 private $_admin;
171 private $_staff;
172 private $_due_free;
173 private $_login;
174 private $_password;
175 private $_creation_date;
176 private $_modification_date;
177 private $_due_date;
178 private $_others_infos;
179 private $_others_infos_admin;
180 private $_picture;
181 private $_oldness;
182 private $_days_remaining;
183 private $_groups;
184 private $_managed_groups;
185 private $_parent;
186 private $_children;
187 private $_duplicate = false;
188
189 private $_row_classes;
190
191 private $_self_adh = false;
192 private $_deps = array(
193 'picture' => true,
194 'groups' => true,
195 'dues' => true,
196 'parent' => false,
197 'children' => false,
198 'dynamics' => false
199 );
200
201 private $zdb;
202 private $preferences;
203 private $fields;
204 private $history;
205
206 private $parent_fields = [
207 'adresse_adh',
208 'adresse2_adh',
209 'cp_adh',
210 'ville_adh',
211 'email_adh'
212 ];
213
214 private $errors = [];
215
216 private $sendmail = false;
217
218 /**
219 * Default constructor
220 *
221 * @param Db $zdb Database instance
222 * @param mixed $args Either a ResultSet row, its id or its
223 * login or its email for to load s specific
224 * member, or null to just instanciate object
225 * @param false|array $deps Dependencies configuration, see Adherent::$_deps
226 */
227 public function __construct(Db $zdb, $args = null, $deps = null)
228 {
229 global $i18n;
230
231 $this->zdb = $zdb;
232
233 if ($deps !== null) {
234 if (is_array($deps)) {
235 $this->_deps = array_merge(
236 $this->_deps,
237 $deps
238 );
239 } elseif ($deps === false) {
240 //no dependencies
241 $this->_deps = array_fill_keys(
242 array_keys($this->_deps),
243 false
244 );
245 } else {
246 Analog::log(
247 '$deps shoud be an array, ' . gettype($deps) . ' given!',
248 Analog::WARNING
249 );
250 }
251 }
252
253 if ($args == null || is_int($args)) {
254 if (is_int($args) && $args > 0) {
255 $this->load($args);
256 } else {
257 $this->_active = true;
258 $this->_language = $i18n->getID();
259 $this->_creation_date = date("Y-m-d");
260 $this->_status = $this->getDefaultStatus();
261 $this->_title = null;
262 $this->_gender = self::NC;
263 $gp = new Password($this->zdb);
264 $this->_password = $gp->makeRandomPassword();
265 $this->_picture = new Picture();
266 $this->_admin = false;
267 $this->_staff = false;
268 $this->_due_free = false;
269 $this->_appears_in_list = false;
270 $this->_parent = null;
271
272 if ($this->_deps['dynamics'] === true) {
273 $this->loadDynamicFields();
274 }
275 }
276 } elseif (is_object($args)) {
277 $this->loadFromRS($args);
278 } elseif (is_string($args)) {
279 $this->loadFromLoginOrMail($args);
280 }
281 }
282
283 /**
284 * Loads a member from its id
285 *
286 * @param int $id the identifiant for the member to load
287 *
288 * @return bool true if query succeed, false otherwise
289 */
290 public function load($id)
291 {
292 try {
293 $select = $this->zdb->select(self::TABLE, 'a');
294
295 $select->join(
296 array('b' => PREFIX_DB . Status::TABLE),
297 'a.' . Status::PK . '=b.' . Status::PK,
298 array('priorite_statut')
299 )->where(array(self::PK => $id));
300
301 $results = $this->zdb->execute($select);
302
303 if ($results->count() === 0) {
304 return false;
305 }
306
307 $this->loadFromRS($results->current());
308 return true;
309 } catch (Throwable $e) {
310 Analog::log(
311 'Cannot load member form id `' . $id . '` | ' . $e->getMessage(),
312 Analog::WARNING
313 );
314 return false;
315 }
316 }
317
318 /**
319 * Loads a member from its login
320 *
321 * @param string $login login for the member to load
322 *
323 * @return bool true if query succeed, false otherwise
324 */
325 public function loadFromLoginOrMail($login)
326 {
327 try {
328 $select = $this->zdb->select(self::TABLE);
329 if (GaletteMail::isValidEmail($login)) {
330 //we got a valid email address, use it
331 $select->where(array('email_adh' => $login));
332 } else {
333 ///we did not get an email address, consider using login
334 $select->where(array('login_adh' => $login));
335 }
336
337 $results = $this->zdb->execute($select);
338 $result = $results->current();
339 if ($result) {
340 $this->loadFromRS($result);
341 }
342 } catch (Throwable $e) {
343 Analog::log(
344 'Cannot load member form login `' . $login . '` | ' .
345 $e->getMessage(),
346 Analog::WARNING
347 );
348 return false;
349 }
350 }
351
352 /**
353 * Populate object from a resultset row
354 *
355 * @param ResultSet $r the resultset row
356 *
357 * @return void
358 */
359 private function loadFromRS($r)
360 {
361 $this->_self_adh = false;
362 $this->_id = $r->id_adh;
363 //Identity
364 if ($r->titre_adh !== null) {
365 $this->_title = new Title((int)$r->titre_adh);
366 }
367 $this->_company_name = $r->societe_adh;
368 $this->_name = $r->nom_adh;
369 $this->_surname = $r->prenom_adh;
370 $this->_nickname = $r->pseudo_adh;
371 if ($r->ddn_adh != '1901-01-01') {
372 $this->_birthdate = $r->ddn_adh;
373 }
374 $this->_birth_place = $r->lieu_naissance;
375 $this->_gender = (int)$r->sexe_adh;
376 $this->_job = $r->prof_adh;
377 $this->_language = $r->pref_lang;
378 $this->_active = ($r->activite_adh == 1) ? true : false;
379 $this->_status = (int)$r->id_statut;
380 //Contact information
381 $this->_address = $r->adresse_adh;
382 /** TODO: remove and merge with address */
383 $this->_address_continuation = $r->adresse2_adh;
384 $this->_zipcode = $r->cp_adh;
385 $this->_town = $r->ville_adh;
386 $this->_country = $r->pays_adh;
387 $this->_phone = $r->tel_adh;
388 $this->_gsm = $r->gsm_adh;
389 $this->_email = $r->email_adh;
390 $this->_website = $r->url_adh;
391 /** TODO: remove */
392 $this->_msn = $r->msn_adh;
393 /** TODO: remove */
394 $this->_icq = $r->icq_adh;
395 /** TODO: remove */
396 $this->_jabber = $r->jabber_adh;
397 /** TODO: remove */
398 $this->_gnupgid = $r->gpgid;
399 /** TODO: remove */
400 $this->_fingerprint = $r->fingerprint;
401 //Galette relative information
402 $this->_appears_in_list = ($r->bool_display_info == 1) ? true : false;
403 $this->_admin = ($r->bool_admin_adh == 1) ? true : false;
404 if (
405 isset($r->priorite_statut)
406 && $r->priorite_statut < Members::NON_STAFF_MEMBERS
407 ) {
408 $this->_staff = true;
409 }
410 $this->_due_free = ($r->bool_exempt_adh == 1) ? true : false;
411 $this->_login = $r->login_adh;
412 $this->_password = $r->mdp_adh;
413 $this->_creation_date = $r->date_crea_adh;
414 if ($r->date_modif_adh != '1901-01-01') {
415 $this->_modification_date = $r->date_modif_adh;
416 } else {
417 $this->_modification_date = $this->_creation_date;
418 }
419 $this->_due_date = $r->date_echeance;
420 $this->_others_infos = $r->info_public_adh;
421 $this->_others_infos_admin = $r->info_adh;
422
423 if ($r->parent_id !== null) {
424 $this->_parent = (int)$r->parent_id;
425 if ($this->_deps['parent'] === true) {
426 $this->loadParent($r->parent_id);
427 }
428 }
429
430 if ($this->_deps['children'] === true) {
431 $this->loadChildren();
432 }
433
434 if ($this->_deps['picture'] === true) {
435 $this->_picture = new Picture($this->_id);
436 }
437
438 if ($this->_deps['groups'] === true) {
439 $this->loadGroups();
440 }
441
442 if ($this->_deps['dues'] === true) {
443 $this->checkDues();
444 }
445
446 if ($this->_deps['dynamics'] === true) {
447 $this->loadDynamicFields();
448 }
449 }
450
451 /**
452 * Load member parent
453 *
454 * @return void
455 */
456 private function loadParent()
457 {
458 if (!$this->_parent instanceof Adherent) {
459 $deps = array_fill_keys(array_keys($this->_deps), false);
460 $this->_parent = new Adherent($this->zdb, (int)$this->_parent, $deps);
461 }
462 }
463
464 /**
465 * Load member children
466 *
467 * @return void
468 */
469 private function loadChildren()
470 {
471 $this->_children = array();
472 try {
473 $id = self::PK;
474 $select = $this->zdb->select(self::TABLE);
475 $select->columns(
476 array($id)
477 )->where(
478 'parent_id = ' . $this->_id
479 );
480
481 $results = $this->zdb->execute($select);
482
483 if ($results->count() > 0) {
484 foreach ($results as $row) {
485 $deps = $this->_deps;
486 $deps['children'] = false;
487 $deps['parent'] = false;
488 $this->_children[] = new Adherent($this->zdb, (int)$row->$id, $deps);
489 }
490 }
491 } catch (Throwable $e) {
492 Analog::log(
493 'Cannot load children for member #' . $this->_id . ' | ' .
494 $e->getMessage(),
495 Analog::WARNING
496 );
497 return false;
498 }
499 }
500
501 /**
502 * Load member groups
503 *
504 * @return void
505 */
506 public function loadGroups()
507 {
508 $this->_groups = Groups::loadGroups($this->_id);
509 $this->_managed_groups = Groups::loadManagedGroups($this->_id);
510 }
511
512 /**
513 * Retrieve status from preferences
514 *
515 * @return pref_statut
516 *
517 */
518 private function getDefaultStatus()
519 {
520 global $preferences;
521 if ($preferences->pref_statut != '') {
522 return $preferences->pref_statut;
523 } else {
524 Analog::log(
525 'Unable to get pref_statut; is it defined in preferences?',
526 Analog::ERROR
527 );
528 return Status::DEFAULT_STATUS;
529 }
530 }
531
532 /**
533 * Check for dues status
534 *
535 * @return void
536 */
537 private function checkDues()
538 {
539 //how many days since our beloved member has been created
540 $date_now = new \DateTime();
541 $this->_oldness = $date_now->diff(
542 new \DateTime($this->_creation_date)
543 )->days;
544
545 if ($this->isDueFree()) {
546 //no fee required, we don't care about dates
547 $this->_row_classes .= ' cotis-exempt';
548 } else {
549 //ok, fee is required. Let's check the dates
550 if ($this->_due_date == '') {
551 $this->_row_classes .= ' cotis-never';
552 } else {
553 $date_end = new \DateTime($this->_due_date);
554 $date_diff = $date_now->diff($date_end);
555 $this->_days_remaining = ($date_diff->invert == 1)
556 ? $date_diff->days * -1
557 : $date_diff->days;
558
559 if ($this->_days_remaining == 0) {
560 $this->_row_classes .= ' cotis-lastday';
561 } elseif ($this->_days_remaining < 0) {
562 //check if member is still active
563 $this->_row_classes .= $this->isActive() ? ' cotis-late' : ' cotis-old';
564 } elseif ($this->_days_remaining < 30) {
565 $this->_row_classes .= ' cotis-soon';
566 } else {
567 $this->_row_classes .= ' cotis-ok';
568 }
569 }
570 }
571 }
572
573 /**
574 * Is member admin?
575 *
576 * @return bool
577 */
578 public function isAdmin()
579 {
580 return $this->_admin;
581 }
582
583 /**
584 * Is user member of staff?
585 *
586 * @return bool
587 */
588 public function isStaff()
589 {
590 return $this->_staff;
591 }
592
593 /**
594 * Is member freed of dues?
595 *
596 * @return bool
597 */
598 public function isDueFree()
599 {
600 return $this->_due_free;
601 }
602
603 /**
604 * Is member in specified group?
605 *
606 * @param string $group_name Group name
607 *
608 * @return boolean
609 */
610 public function isGroupMember($group_name)
611 {
612 if (is_array($this->_groups)) {
613 foreach ($this->_groups as $g) {
614 if ($g->getName() == $group_name) {
615 return true;
616 break;
617 }
618 }
619 } else {
620 Analog::log(
621 'Calling ' . __METHOD__ . ' without groups loaded!',
622 Analog::ERROR
623 );
624 return false;
625 }
626 }
627
628 /**
629 * Is member manager of specified group?
630 *
631 * @param string $group_name Group name
632 *
633 * @return boolean
634 */
635 public function isGroupManager($group_name)
636 {
637 if (is_array($this->_managed_groups)) {
638 foreach ($this->_managed_groups as $mg) {
639 if ($mg->getName() == $group_name) {
640 return true;
641 break;
642 }
643 }
644 } else {
645 Analog::log(
646 'Calling ' . __METHOD__ . ' without groups loaded!',
647 Analog::ERROR
648 );
649 return false;
650 }
651 }
652
653 /**
654 * Does current member represents a company?
655 *
656 * @return boolean
657 */
658 public function isCompany()
659 {
660 return trim($this->_company_name) != '';
661 }
662
663 /**
664 * Is current member a man?
665 *
666 * @return boolean
667 */
668 public function isMan()
669 {
670 return (int)$this->_gender === self::MAN;
671 }
672
673 /**
674 * Is current member a woman?
675 *
676 * @return boolean
677 */
678 public function isWoman()
679 {
680 return (int)$this->_gender === self::WOMAN;
681 }
682
683
684 /**
685 * Can member appears in public members list?
686 *
687 * @return bool
688 */
689 public function appearsInMembersList()
690 {
691 return $this->_appears_in_list;
692 }
693
694 /**
695 * Is member active?
696 *
697 * @return bool
698 */
699 public function isActive()
700 {
701 return $this->_active;
702 }
703
704 /**
705 * Does member have uploaded a picture?
706 *
707 * @return bool
708 */
709 public function hasPicture()
710 {
711 return $this->_picture->hasPicture();
712 }
713
714 /**
715 * Does member have a parent?
716 *
717 * @return bool
718 */
719 public function hasParent()
720 {
721 return !empty($this->_parent);
722 }
723
724 /**
725 * Does member have children?
726 *
727 * @return bool
728 */
729 public function hasChildren()
730 {
731 if ($this->_children === null) {
732 if ($this->id) {
733 Analog::log(
734 'Children has not been loaded!',
735 Analog::WARNING
736 );
737 }
738 return false;
739 } else {
740 return count($this->_children) > 0;
741 }
742 }
743
744 /**
745 * Get row class related to current fee status
746 *
747 * @param boolean $public we want the class for public pages
748 *
749 * @return string the class to apply
750 */
751 public function getRowClass($public = false)
752 {
753 $strclass = ($this->isActive()) ? 'active' : 'inactive';
754 if ($public === false) {
755 $strclass .= $this->_row_classes;
756 }
757 return $strclass;
758 }
759
760 /**
761 * Get current member due status
762 *
763 * @return string i18n string representing state of due
764 */
765 public function getDues()
766 {
767 $ret = '';
768 if ($this->isDueFree()) {
769 $ret = _T("Freed of dues");
770 } elseif ($this->_due_date == '') {
771 $patterns = array('/%days/', '/%date/');
772 $cdate = new \DateTime($this->_creation_date);
773 $replace = array(
774 $this->_oldness,
775 $cdate->format(__("Y-m-d"))
776 );
777 if ($this->_active) {
778 $ret = preg_replace(
779 $patterns,
780 $replace,
781 _T("Never contributed: Registered %days days ago (since %date)")
782 );
783 } else {
784 $ret = _T("Never contributed");
785 }
786 } elseif ($this->_days_remaining == 0) {
787 $ret = _T("Last day!");
788 } elseif ($this->_days_remaining < 0) {
789 $patterns = array('/%days/', '/%date/');
790 $ddate = new \DateTime($this->_due_date);
791 $replace = array(
792 $this->_days_remaining * -1,
793 $ddate->format(__("Y-m-d"))
794 );
795 if ($this->_active) {
796 $ret = preg_replace(
797 $patterns,
798 $replace,
799 _T("Late of %days days (since %date)")
800 );
801 } else {
802 $ret = _T("No longer member");
803 }
804 } else {
805 $patterns = array('/%days/', '/%date/');
806 $ddate = new \DateTime($this->_due_date);
807 $replace = array(
808 $this->_days_remaining,
809 $ddate->format(__("Y-m-d"))
810 );
811 $ret = preg_replace(
812 $patterns,
813 $replace,
814 _T("%days days remaining (ending on %date)")
815 );
816 }
817 return $ret;
818 }
819
820 /**
821 * Retrieve Full name and surname for the specified member id
822 *
823 * @param Db $zdb Database instance
824 * @param integer $id Member id
825 * @param boolean $wid Add member id
826 * @param boolean $wnick Add member nickname
827 *
828 * @return string formatted Name and Surname
829 */
830 public static function getSName($zdb, $id, $wid = false, $wnick = false)
831 {
832 try {
833 $select = $zdb->select(self::TABLE);
834 $select->where(self::PK . ' = ' . $id);
835
836 $results = $zdb->execute($select);
837 $row = $results->current();
838 return self::getNameWithCase(
839 $row->nom_adh,
840 $row->prenom_adh,
841 false,
842 ($wid === true ? $row->id_adh : false),
843 ($wnick === true ? $row->pseudo_adh : false)
844 );
845 } catch (Throwable $e) {
846 Analog::log(
847 'Cannot get formatted name for member form id `' . $id . '` | ' .
848 $e->getMessage(),
849 Analog::WARNING
850 );
851 return false;
852 }
853 }
854
855 /**
856 * Get member name with correct case
857 *
858 * @param string $name Member name
859 * @param string $surname Mmeber surname
860 * @param false|Title $title Member title to show or false
861 * @param false|integer $id Member id to display or false
862 * @param false|string $nick Member nickname to display or false
863 *
864 * @return string
865 */
866 public static function getNameWithCase($name, $surname, $title = false, $id = false, $nick = false)
867 {
868 $str = '';
869
870 if ($title !== false && $title instanceof Title) {
871 $str .= $title->tshort . ' ';
872 }
873
874 $str .= mb_strtoupper($name, 'UTF-8') . ' ' .
875 ucwords(mb_strtolower($surname, 'UTF-8'), " \t\r\n\f\v-_|");
876
877 if ($id !== false || $nick !== false) {
878 $str .= ' (';
879 }
880 if ($nick !== false) {
881 $str .= $nick;
882 }
883 if ($id !== false) {
884 if ($nick !== false && !empty($nick)) {
885 $str .= ', ';
886 }
887 $str .= $id;
888 }
889 if ($id !== false || $nick !== false) {
890 $str .= ')';
891 }
892 return strip_tags($str);
893 }
894
895 /**
896 * Change password for a given user
897 *
898 * @param Db $zdb Database instance
899 * @param string $id_adh Member identifier
900 * @param string $pass New password
901 *
902 * @return boolean
903 */
904 public static function updatePassword(Db $zdb, $id_adh, $pass)
905 {
906 try {
907 $cpass = password_hash($pass, PASSWORD_BCRYPT);
908
909 $update = $zdb->update(self::TABLE);
910 $update->set(
911 array('mdp_adh' => $cpass)
912 )->where(self::PK . ' = ' . $id_adh);
913 $zdb->execute($update);
914 Analog::log(
915 'Password for `' . $id_adh . '` has been updated.',
916 Analog::DEBUG
917 );
918 return true;
919 } catch (Throwable $e) {
920 Analog::log(
921 'An error occurred while updating password for `' . $id_adh .
922 '` | ' . $e->getMessage(),
923 Analog::ERROR
924 );
925 return false;
926 }
927 }
928
929 /**
930 * Get field label
931 *
932 * @param string $field Field name
933 *
934 * @return string
935 */
936 private function getFieldLabel($field)
937 {
938 $label = $this->fields[$field]['label'];
939 //remove trailing ':' and then nbsp (for french at least)
940 $label = trim(trim($label, ':'), '&nbsp;');
941 return $label;
942 }
943
944 /**
945 * Retrieve fields from database
946 *
947 * @param Db $zdb Database instance
948 *
949 * @return array
950 */
951 public static function getDbFields(Db $zdb)
952 {
953 $columns = $zdb->getColumns(self::TABLE);
954 $fields = array();
955 foreach ($columns as $col) {
956 $fields[] = $col->getName();
957 }
958 return $fields;
959 }
960
961 /**
962 * Mark as self membership
963 *
964 * @return void
965 */
966 public function setSelfMembership()
967 {
968 $this->_self_adh = true;
969 }
970
971 /**
972 * Is member up to date?
973 *
974 * @return boolean
975 */
976 public function isUp2Date()
977 {
978 if ($this->_deps['dues']) {
979 if ($this->isDueFree()) {
980 //member is due free, he's up to date.
981 return true;
982 } else {
983 //let's check from end date, if present
984 if ($this->_due_date == null) {
985 return false;
986 } else {
987 $ech = new \DateTime($this->_due_date);
988 $now = new \DateTime();
989 $now->setTime(0, 0, 0);
990 return $ech >= $now;
991 }
992 }
993 } else {
994 throw new \RuntimeException(
995 'Cannot check if member is up to date, dues deps is disabled!'
996 );
997 }
998 }
999
1000 /**
1001 * Set dependencies
1002 *
1003 * @param Preferences $preferences Preferences instance
1004 * @param array $fields Members fields configuration
1005 * @param History $history History instance
1006 *
1007 * @return void
1008 */
1009 public function setDependencies(
1010 Preferences $preferences,
1011 array $fields,
1012 History $history
1013 ) {
1014 $this->preferences = $preferences;
1015 $this->fields = $fields;
1016 $this->history = $history;
1017 }
1018
1019 /**
1020 * Check posted values validity
1021 *
1022 * @param array $values All values to check, basically the $_POST array
1023 * after sending the form
1024 * @param array $required Array of required fields
1025 * @param array $disabled Array of disabled fields
1026 *
1027 * @return true|array
1028 */
1029 public function check($values, $required, $disabled)
1030 {
1031 $this->errors = array();
1032
1033 //Sanitize
1034 foreach ($values as &$rawvalue) {
1035 if (is_string($rawvalue)) {
1036 $rawvalue = strip_tags($rawvalue);
1037 }
1038 }
1039
1040 $fields = self::getDbFields($this->zdb);
1041
1042 //reset company name if needeed
1043 if (!isset($values['is_company'])) {
1044 unset($values['is_company']);
1045 $values['societe_adh'] = '';
1046 }
1047
1048 //no parent if checkbox was unchecked
1049 if (
1050 !isset($values['attach'])
1051 && empty($this->_id)
1052 && isset($values['parent_id'])
1053 ) {
1054 unset($values['parent_id']);
1055 }
1056
1057 if (isset($values['duplicate'])) {
1058 //if we're duplicating, keep a trace (if an error occurs)
1059 $this->_duplicate = true;
1060 }
1061
1062 foreach ($fields as $key) {
1063 //first of all, let's sanitize values
1064 $key = strtolower($key);
1065 $prop = '_' . $this->fields[$key]['propname'];
1066
1067 if (isset($values[$key])) {
1068 $value = $values[$key];
1069 if ($value !== true && $value !== false) {
1070 $value = trim($value);
1071 }
1072 } elseif ($this->_id == '' || $this->_id == null) {
1073 switch ($key) {
1074 case 'bool_admin_adh':
1075 case 'bool_exempt_adh':
1076 case 'bool_display_info':
1077 $value = 0;
1078 break;
1079 case 'activite_adh':
1080 //values that are setted at object instanciation
1081 $value = true;
1082 break;
1083 case 'date_crea_adh':
1084 case 'sexe_adh':
1085 case 'titre_adh':
1086 case 'id_statut':
1087 case 'pref_lang':
1088 case 'parent_id':
1089 //values that are setted at object instanciation
1090 $value = $this->$prop;
1091 break;
1092 default:
1093 $value = '';
1094 break;
1095 }
1096 } else {
1097 //keep stored value on update
1098 if ($prop != '_password' || isset($values['mdp_adh']) && isset($values['mdp_adh2'])) {
1099 $value = $this->$prop;
1100 } else {
1101 $value = null;
1102 }
1103 }
1104
1105 // if the field is enabled, check it
1106 if (!isset($disabled[$key])) {
1107 // fill up the adherent structure
1108 if ($value !== null && $value !== true && $value !== false && !is_object($value)) {
1109 $value = stripslashes($value);
1110 }
1111 $this->$prop = $value;
1112
1113 // now, check validity
1114 if ($value !== null && $value != '') {
1115 $this->validate($key, $value, $values);
1116 } elseif (!isset($this->_id)) {
1117 //ensure login and password are not empty
1118 if (($key == 'login_adh' || $key == 'mdp_adh') && !isset($required[$key])) {
1119 $p = new Password($this->zdb);
1120 $generated_value = $p->makeRandomPassword(15);
1121 if ($key == 'login_adh') {
1122 //'@' is not permitted in logins
1123 $this->$prop = str_replace('@', 'a', $generated_value);
1124 } else {
1125 $this->$prop = $generated_value;
1126 }
1127 }
1128 }
1129 }
1130 }
1131
1132 // missing required fields?
1133 foreach ($required as $key => $val) {
1134 $prop = '_' . $this->fields[$key]['propname'];
1135
1136 if (!isset($disabled[$key])) {
1137 $mandatory_missing = false;
1138 if (!isset($this->$prop) || $this->$prop == '') {
1139 $mandatory_missing = true;
1140 } elseif ($key === 'titre_adh' && $this->$prop == '-1') {
1141 $mandatory_missing = true;
1142 }
1143
1144 if ($mandatory_missing === true) {
1145 $this->errors[] = str_replace(
1146 '%field',
1147 '<a href="#' . $key . '">' . $this->getFieldLabel($key) . '</a>',
1148 _T("- Mandatory field %field empty.")
1149 );
1150 }
1151 }
1152 }
1153
1154 //attach to/detach from parent
1155 if (isset($values['detach_parent'])) {
1156 $this->_parent = null;
1157 }
1158
1159 $this->dynamicsCheck($values, $required, $disabled);
1160
1161 if (count($this->errors) > 0) {
1162 Analog::log(
1163 'Some errors has been throwed attempting to edit/store a member' . "\n" .
1164 print_r($this->errors, true),
1165 Analog::ERROR
1166 );
1167 return $this->errors;
1168 } else {
1169 $this->checkDues();
1170
1171 Analog::log(
1172 'Member checked successfully.',
1173 Analog::DEBUG
1174 );
1175 return true;
1176 }
1177 }
1178
1179 /**
1180 * Validate data for given key
1181 * Set valid data in current object, also resets errors list
1182 *
1183 * @param string $field Field name
1184 * @param mixed $value Value we want to set
1185 * @param array $values All values, for some references
1186 *
1187 * @return void
1188 */
1189 public function validate($field, $value, $values)
1190 {
1191 global $preferences;
1192
1193 $prop = '_' . $this->fields[$field]['propname'];
1194
1195 if ($value === null || (is_string($value) && trim($value) == '')) {
1196 //empty values are OK
1197 $this->$prop = $value;
1198 return;
1199 }
1200
1201 switch ($field) {
1202 // dates
1203 case 'date_crea_adh':
1204 case 'date_modif_adh_':
1205 case 'ddn_adh':
1206 case 'date_echeance':
1207 try {
1208 $d = \DateTime::createFromFormat(__("Y-m-d"), $value);
1209 if ($d === false) {
1210 //try with non localized date
1211 $d = \DateTime::createFromFormat("Y-m-d", $value);
1212 if ($d === false) {
1213 throw new \Exception('Incorrect format');
1214 }
1215 }
1216
1217 if ($field === 'ddn_adh') {
1218 $now = new \DateTime();
1219 $now->setTime(0, 0, 0);
1220 $d->setTime(0, 0, 0);
1221
1222 $diff = $now->diff($d);
1223 $days = (int)$diff->format('%R%a');
1224 if ($days >= 0) {
1225 $this->errors[] = _T('- Birthdate must be set in the past!');
1226 }
1227
1228 $years = (int)$diff->format('%R%Y');
1229 if ($years <= -200) {
1230 $this->errors[] = str_replace(
1231 '%years',
1232 $years * -1,
1233 _T('- Members must be less than 200 years old (currently %years)!')
1234 );
1235 }
1236 }
1237 $this->$prop = $d->format('Y-m-d');
1238 } catch (Throwable $e) {
1239 Analog::log(
1240 'Wrong date format. field: ' . $field .
1241 ', value: ' . $value . ', expected fmt: ' .
1242 __("Y-m-d") . ' | ' . $e->getMessage(),
1243 Analog::INFO
1244 );
1245 $this->errors[] = str_replace(
1246 array(
1247 '%date_format',
1248 '%field'
1249 ),
1250 array(
1251 __("Y-m-d"),
1252 $this->getFieldLabel($field)
1253 ),
1254 _T("- Wrong date format (%date_format) for %field!")
1255 );
1256 }
1257 break;
1258 case 'titre_adh':
1259 if ($value !== null && $value !== '') {
1260 if ($value == '-1') {
1261 $this->$prop = null;
1262 } elseif (!$value instanceof Title) {
1263 $this->$prop = new Title((int)$value);
1264 }
1265 } else {
1266 $this->$prop = null;
1267 }
1268 break;
1269 case 'email_adh':
1270 case 'msn_adh':
1271 if (!GaletteMail::isValidEmail($value)) {
1272 $this->errors[] = _T("- Non-valid E-Mail address!") .
1273 ' (' . $this->getFieldLabel($field) . ')';
1274 }
1275 if ($field == 'email_adh') {
1276 try {
1277 $select = $this->zdb->select(self::TABLE);
1278 $select->columns(
1279 array(self::PK)
1280 )->where(array('email_adh' => $value));
1281 if ($this->_id != '' && $this->_id != null) {
1282 $select->where(
1283 self::PK . ' != ' . $this->_id
1284 );
1285 }
1286
1287 $results = $this->zdb->execute($select);
1288 if ($results->count() !== 0) {
1289 $this->errors[] = _T("- This E-Mail address is already used by another member!");
1290 }
1291 } catch (Throwable $e) {
1292 Analog::log(
1293 'An error occurred checking member email unicity.',
1294 Analog::ERROR
1295 );
1296 $this->errors[] = _T("An error has occurred while looking if login already exists.");
1297 }
1298 }
1299 break;
1300 case 'url_adh':
1301 if ($value == 'http://') {
1302 $this->$prop = '';
1303 } elseif (!isValidWebUrl($value)) {
1304 $this->errors[] = _T("- Non-valid Website address! Maybe you've skipped the http://?");
1305 }
1306 break;
1307 case 'login_adh':
1308 /** FIXME: add a preference for login lenght */
1309 if (strlen($value) < 2) {
1310 $this->errors[] = str_replace(
1311 '%i',
1312 2,
1313 _T("- The username must be composed of at least %i characters!")
1314 );
1315 } else {
1316 //check if login does not contain the @ character
1317 if (strpos($value, '@') != false) {
1318 $this->errors[] = _T("- The username cannot contain the @ character");
1319 } else {
1320 //check if login is already taken
1321 try {
1322 $select = $this->zdb->select(self::TABLE);
1323 $select->columns(
1324 array(self::PK)
1325 )->where(array('login_adh' => $value));
1326 if ($this->_id != '' && $this->_id != null) {
1327 $select->where(
1328 self::PK . ' != ' . $this->_id
1329 );
1330 }
1331
1332 $results = $this->zdb->execute($select);
1333 if (
1334 $results->count() !== 0
1335 || $value == $preferences->pref_admin_login
1336 ) {
1337 $this->errors[] = _T("- This username is already in use, please choose another one!");
1338 }
1339 } catch (Throwable $e) {
1340 Analog::log(
1341 'An error occurred checking member login unicity.',
1342 Analog::ERROR
1343 );
1344 $this->errors[] = _T("An error has occurred while looking if login already exists.");
1345 }
1346 }
1347 }
1348 break;
1349 case 'mdp_adh':
1350 if (
1351 $this->_self_adh !== true
1352 && (!isset($values['mdp_adh2'])
1353 || $values['mdp_adh2'] != $value)
1354 ) {
1355 $this->errors[] = _T("- The passwords don't match!");
1356 } elseif (
1357 $this->_self_adh === true
1358 && !crypt($value, $values['mdp_crypt']) == $values['mdp_crypt']
1359 ) {
1360 $this->errors[] = _T("Password misrepeated: ");
1361 } else {
1362 $pinfos = password_get_info($value);
1363 //check if value is already a hash
1364 if ($pinfos['algo'] == 0) {
1365 $this->$prop = password_hash(
1366 $value,
1367 PASSWORD_BCRYPT
1368 );
1369
1370 $pwcheck = new \Galette\Util\Password($preferences);
1371 $pwcheck->setAdherent($this);
1372 if (!$pwcheck->isValid($value)) {
1373 $this->errors = array_merge(
1374 $this->errors,
1375 $pwcheck->getErrors()
1376 );
1377 }
1378 }
1379 }
1380 break;
1381 case 'id_statut':
1382 try {
1383 $this->$prop = (int)$value;
1384 //check if status exists
1385 $select = $this->zdb->select(Status::TABLE);
1386 $select->where(Status::PK . '= ' . $value);
1387
1388 $results = $this->zdb->execute($select);
1389 $result = $results->current();
1390 if (!$result) {
1391 $this->errors[] = str_replace(
1392 '%id',
1393 $value,
1394 _T("Status #%id does not exists in database.")
1395 );
1396 break;
1397 }
1398 } catch (Throwable $e) {
1399 Analog::log(
1400 'An error occurred checking status existance: ' . $e->getMessage(),
1401 Analog::ERROR
1402 );
1403 $this->errors[] = _T("An error has occurred while looking if status does exists.");
1404 }
1405 break;
1406 case 'sexe_adh':
1407 if (in_array($value, [self::NC, self::MAN, self::WOMAN])) {
1408 $this->$prop = (int)$value;
1409 } else {
1410 $this->errors[] = _T("Gender %gender does not exists!");
1411 }
1412 break;
1413 case 'parent_id':
1414 $this->$prop = ($value instanceof Adherent) ? (int)$value->id : (int)$value;
1415 $this->loadParent();
1416 break;
1417 }
1418 }
1419
1420 /**
1421 * Store the member
1422 *
1423 * @return boolean
1424 */
1425 public function store()
1426 {
1427 global $hist, $emitter;
1428 $event = null;
1429
1430 try {
1431 $values = array();
1432 $fields = self::getDbFields($this->zdb);
1433
1434 foreach ($fields as $field) {
1435 if (
1436 $field !== 'date_modif_adh'
1437 || !isset($this->_id)
1438 || $this->_id == ''
1439 ) {
1440 $prop = '_' . $this->fields[$field]['propname'];
1441 if (
1442 ($field === 'bool_admin_adh'
1443 || $field === 'bool_exempt_adh'
1444 || $field === 'bool_display_info'
1445 || $field === 'activite_adh')
1446 && $this->$prop === false
1447 ) {
1448 //Handle booleans for postgres ; bugs #18899 and #19354
1449 $values[$field] = $this->zdb->isPostgres() ? 'false' : 0;
1450 } elseif ($field === 'parent_id') {
1451 //handle parents
1452 if ($this->_parent === null) {
1453 $values['parent_id'] = new Expression('NULL');
1454 } elseif ($this->parent instanceof Adherent) {
1455 $values['parent_id'] = $this->_parent->id;
1456 } else {
1457 $values['parent_id'] = $this->_parent;
1458 }
1459 } else {
1460 $values[$field] = $this->$prop;
1461 }
1462 }
1463 }
1464
1465 //an empty value will cause date to be set to 1901-01-01, a null
1466 //will result in 0000-00-00. We want a database NULL value here.
1467 if (!$this->_birthdate) {
1468 $values['ddn_adh'] = new Expression('NULL');
1469 }
1470 if (!$this->_due_date) {
1471 $values['date_echeance'] = new Expression('NULL');
1472 }
1473
1474 if ($this->_title instanceof Title) {
1475 $values['titre_adh'] = $this->_title->id;
1476 } else {
1477 $values['titre_adh'] = new Expression('NULL');
1478 }
1479
1480 if (!$this->_parent) {
1481 $values['parent_id'] = new Expression('NULL');
1482 }
1483
1484 //fields that cannot be null
1485 $notnull = [
1486 '_surname' => 'prenom_adh',
1487 '_nickname' => 'pseudo_adh',
1488 '_address' => 'adresse_adh',
1489 '_zipcode' => 'cp_adh',
1490 '_town' => 'ville_adh'
1491 ];
1492 foreach ($notnull as $prop => $field) {
1493 if ($this->$prop === null) {
1494 $values[$field] = '';
1495 }
1496 }
1497
1498 $success = false;
1499 if (!isset($this->_id) || $this->_id == '') {
1500 //we're inserting a new member
1501 unset($values[self::PK]);
1502 //set modification date
1503 $this->_modification_date = date('Y-m-d');
1504 $values['date_modif_adh'] = $this->_modification_date;
1505
1506 $insert = $this->zdb->insert(self::TABLE);
1507 $insert->values($values);
1508 $add = $this->zdb->execute($insert);
1509 if ($add->count() > 0) {
1510 $this->_id = $this->zdb->getLastGeneratedValue($this);
1511 $this->_picture = new Picture($this->_id);
1512 // logging
1513 if ($this->_self_adh) {
1514 $hist->add(
1515 _T("Self_subscription as a member: ") .
1516 $this->getNameWithCase($this->_name, $this->_surname),
1517 $this->sname
1518 );
1519 } else {
1520 $hist->add(
1521 _T("Member card added"),
1522 $this->sname
1523 );
1524 }
1525 $success = true;
1526
1527 $event = 'member.add';
1528 } else {
1529 $hist->add(_T("Fail to add new member."));
1530 throw new \Exception(
1531 'An error occurred inserting new member!'
1532 );
1533 }
1534 } else {
1535 //we're editing an existing member
1536 if (!$this->isDueFree()) {
1537 // deadline
1538 $due_date = Contribution::getDueDate($this->zdb, $this->_id);
1539 if ($due_date) {
1540 $values['date_echeance'] = $due_date;
1541 }
1542 }
1543
1544 if (!$this->_password) {
1545 unset($values['mdp_adh']);
1546 }
1547
1548 $update = $this->zdb->update(self::TABLE);
1549 $update->set($values);
1550 $update->where(
1551 self::PK . '=' . $this->_id
1552 );
1553
1554 $edit = $this->zdb->execute($update);
1555
1556 //edit == 0 does not mean there were an error, but that there
1557 //were nothing to change
1558 if ($edit->count() > 0) {
1559 $this->updateModificationDate();
1560 $hist->add(
1561 _T("Member card updated"),
1562 $this->sname
1563 );
1564 }
1565 $success = true;
1566
1567 $event = 'member.edit';
1568 }
1569
1570 //dynamic fields
1571 if ($success) {
1572 $success = $this->dynamicsStore();
1573 }
1574
1575 //send event at the end of process, once all has been stored
1576 if ($event !== null) {
1577 $emitter->emit($event, $this);
1578 }
1579 return $success;
1580 } catch (Throwable $e) {
1581 Analog::log(
1582 'Something went wrong :\'( | ' . $e->getMessage() . "\n" .
1583 $e->getTraceAsString(),
1584 Analog::ERROR
1585 );
1586 return false;
1587 }
1588 }
1589
1590 /**
1591 * Update member modification date
1592 *
1593 * @return void
1594 */
1595 private function updateModificationDate()
1596 {
1597 try {
1598 $modif_date = date('Y-m-d');
1599 $update = $this->zdb->update(self::TABLE);
1600 $update->set(
1601 array('date_modif_adh' => $modif_date)
1602 )->where(self::PK . '=' . $this->_id);
1603
1604 $edit = $this->zdb->execute($update);
1605 $this->_modification_date = $modif_date;
1606 } catch (Throwable $e) {
1607 Analog::log(
1608 'Something went wrong updating modif date :\'( | ' .
1609 $e->getMessage() . "\n" . $e->getTraceAsString(),
1610 Analog::ERROR
1611 );
1612 }
1613 }
1614
1615 /**
1616 * Global getter method
1617 *
1618 * @param string $name name of the property we want to retrive
1619 *
1620 * @return false|object the called property
1621 */
1622 public function __get($name)
1623 {
1624 $forbidden = array(
1625 'admin', 'staff', 'due_free', 'appears_in_list', 'active',
1626 'row_classes', 'oldness', 'duplicate'
1627 );
1628 if (!defined('GALETTE_TESTS')) {
1629 $forbidden[] = 'password'; //keep that for tests only
1630 }
1631
1632 $virtuals = array(
1633 'sadmin', 'sstaff', 'sdue_free', 'sappears_in_list', 'sactive',
1634 'stitle', 'sstatus', 'sfullname', 'sname', 'saddress',
1635 'rbirthdate', 'sgender', 'contribstatus'
1636 );
1637
1638 if (in_array($name, $forbidden)) {
1639 switch ($name) {
1640 case 'admin':
1641 return $this->isAdmin();
1642 case 'staff':
1643 return $this->isStaff();
1644 case 'due_free':
1645 return $this->isDueFree();
1646 case 'appears_in_list':
1647 return $this->appearsInMembersList();
1648 case 'active':
1649 return $this->isActive();
1650 case 'duplicate':
1651 return $this->isDuplicate();
1652 default:
1653 throw new \RuntimeException("Call to __get for '$name' is forbidden!");
1654 }
1655 } else {
1656 if (in_array($name, $virtuals)) {
1657 if (substr($name, 0, 1) !== '_') {
1658 $real = '_' . substr($name, 1);
1659 } else {
1660 $real = $name;
1661 }
1662 switch ($name) {
1663 case 'sadmin':
1664 case 'sdue_free':
1665 case 'sappears_in_list':
1666 case 'sstaff':
1667 return (($this->$real) ? _T("Yes") : _T("No"));
1668 break;
1669 case 'sactive':
1670 return (($this->$real) ? _T("Active") : _T("Inactive"));
1671 break;
1672 case 'stitle':
1673 if (isset($this->_title) && $this->_title instanceof Title) {
1674 return $this->_title->tshort;
1675 } else {
1676 return null;
1677 }
1678 break;
1679 case 'sstatus':
1680 $status = new Status($this->zdb);
1681 return $status->getLabel($this->_status);
1682 break;
1683 case 'sfullname':
1684 return $this->getNameWithCase(
1685 $this->_name,
1686 $this->_surname,
1687 (isset($this->_title) ? $this->title : false)
1688 );
1689 break;
1690 case 'saddress':
1691 $address = $this->_address;
1692 if ($this->_address_continuation !== '' && $this->_address_continuation !== null) {
1693 $address .= "\n" . $this->_address_continuation;
1694 }
1695 return htmlspecialchars($address, ENT_QUOTES);
1696 break;
1697 case 'sname':
1698 return $this->getNameWithCase($this->_name, $this->_surname);
1699 break;
1700 case 'rbirthdate':
1701 return $this->_birthdate;
1702 break;
1703 case 'sgender':
1704 switch ($this->gender) {
1705 case self::MAN:
1706 return _T('Man');
1707 case self::WOMAN:
1708 return _T('Woman');
1709 default:
1710 return _T('Unspecified');
1711 }
1712 break;
1713 case 'contribstatus':
1714 return $this->getDues();
1715 break;
1716 }
1717 } else {
1718 if (substr($name, 0, 1) !== '_') {
1719 $rname = '_' . $name;
1720 } else {
1721 $rname = $name;
1722 }
1723
1724 switch ($name) {
1725 case 'id':
1726 case 'id_statut':
1727 if ($this->$rname !== null) {
1728 return (int)$this->$rname;
1729 } else {
1730 return null;
1731 }
1732 break;
1733 case 'birthdate':
1734 case 'creation_date':
1735 case 'modification_date':
1736 case 'due_date':
1737 if ($this->$rname != '') {
1738 try {
1739 $d = new \DateTime($this->$rname);
1740 return $d->format(__("Y-m-d"));
1741 } catch (Throwable $e) {
1742 //oops, we've got a bad date :/
1743 Analog::log(
1744 'Bad date (' . $this->$rname . ') | ' .
1745 $e->getMessage(),
1746 Analog::INFO
1747 );
1748 return $this->$rname;
1749 }
1750 }
1751 break;
1752 default:
1753 if (!property_exists($this, $rname)) {
1754 Analog::log(
1755 "Unknown property '$rname'",
1756 Analog::WARNING
1757 );
1758 return null;
1759 } else {
1760 return $this->$rname;
1761 }
1762 break;
1763 }
1764 }
1765 }
1766 }
1767
1768 /**
1769 * Get member email
1770 * If member does not have an email address, but is attached to
1771 * another member, we'll take information from its parent.
1772 *
1773 * @return string
1774 */
1775 public function getEmail()
1776 {
1777 $email = $this->_email;
1778 if (empty($email)) {
1779 $this->loadParent();
1780 $email = $this->parent->email;
1781 }
1782
1783 return $email;
1784 }
1785
1786 /**
1787 * Get member address.
1788 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1789 *
1790 * @return string
1791 */
1792 public function getAddress()
1793 {
1794 $address = $this->_address;
1795 if (empty($address) && $this->hasParent()) {
1796 $this->loadParent();
1797 $address = $this->parent->address;
1798 }
1799
1800 return $address;
1801 }
1802
1803 /**
1804 * Get member address continuation.
1805 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1806 *
1807 * @return string
1808 */
1809 public function getAddressContinuation()
1810 {
1811 $address = $this->_address;
1812 $address_continuation = $this->_address_continuation;
1813 if (empty($address) && $this->hasParent()) {
1814 $this->loadParent();
1815 $address_continuation = $this->parent->address_continuation;
1816 }
1817
1818 return $address_continuation;
1819 }
1820
1821 /**
1822 * Get member zipcode.
1823 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1824 *
1825 * @return string
1826 */
1827 public function getZipcode()
1828 {
1829 $address = $this->_address;
1830 $zip = $this->_zipcode;
1831 if (empty($address) && $this->hasParent()) {
1832 $this->loadParent();
1833 $zip = $this->parent->zipcode;
1834 }
1835
1836 return $zip;
1837 }
1838
1839 /**
1840 * Get member town.
1841 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1842 *
1843 * @return string
1844 */
1845 public function getTown()
1846 {
1847 $address = $this->_address;
1848 $town = $this->_town;
1849 if (empty($address) && $this->hasParent()) {
1850 $this->loadParent();
1851 $town = $this->parent->town;
1852 }
1853
1854 return $town;
1855 }
1856
1857 /**
1858 * Get member country.
1859 * If member does not have an address, but is attached to another member, we'll take information from its parent.
1860 *
1861 * @return string
1862 */
1863 public function getCountry()
1864 {
1865 $address = $this->_address;
1866 $country = $this->_country;
1867 if (empty($address) && $this->hasParent()) {
1868 $this->loadParent();
1869 $country = $this->parent->country;
1870 }
1871
1872 return $country;
1873 }
1874
1875 /**
1876 * Get member age
1877 *
1878 * @return string
1879 */
1880 public function getAge()
1881 {
1882 if ($this->_birthdate == null) {
1883 return '';
1884 }
1885
1886 $d = \DateTime::createFromFormat('Y-m-d', $this->_birthdate);
1887 if ($d === false) {
1888 Analog::log(
1889 'Invalid birthdate: ' . $this->_birthdate,
1890 Analog::ERROR
1891 );
1892 return;
1893 }
1894
1895 return str_replace(
1896 '%age',
1897 $d->diff(new \DateTime())->y,
1898 _T(' (%age years old)')
1899 );
1900 }
1901
1902 /**
1903 * Get parent inherited fields
1904 *
1905 * @return array
1906 */
1907 public function getParentFields()
1908 {
1909 return $this->parent_fields;
1910 }
1911
1912 /**
1913 * Handle files (photo and dynamics files)
1914 *
1915 * @param array $files Files sent
1916 *
1917 * @return array|true
1918 */
1919 public function handleFiles($files)
1920 {
1921 $this->errors = [];
1922 // picture upload
1923 if (isset($files['photo'])) {
1924 if ($files['photo']['error'] === UPLOAD_ERR_OK) {
1925 if ($files['photo']['tmp_name'] != '') {
1926 if (is_uploaded_file($files['photo']['tmp_name'])) {
1927 $res = $this->picture->store($files['photo']);
1928 if ($res < 0) {
1929 $this->errors[]
1930 = $this->picture->getErrorMessage($res);
1931 }
1932 }
1933 }
1934 } elseif ($files['photo']['error'] !== UPLOAD_ERR_NO_FILE) {
1935 Analog::log(
1936 $this->picture->getPhpErrorMessage($files['photo']['error']),
1937 Analog::WARNING
1938 );
1939 $this->errors[] = $this->picture->getPhpErrorMessage(
1940 $files['photo']['error']
1941 );
1942 }
1943 }
1944 $this->dynamicsFiles($files);
1945
1946 if (count($this->errors) > 0) {
1947 Analog::log(
1948 'Some errors has been throwed attempting to edit/store a member files' . "\n" .
1949 print_r($this->errors, true),
1950 Analog::ERROR
1951 );
1952 return $this->errors;
1953 } else {
1954 return true;
1955 }
1956 }
1957
1958 /**
1959 * Set member as duplicate
1960 *
1961 * @return void
1962 */
1963 public function setDuplicate()
1964 {
1965 //mark as duplicated
1966 $this->_duplicate = true;
1967 $infos = $this->_others_infos_admin;
1968 $this->_others_infos_admin = str_replace(
1969 ['%name', '%id'],
1970 [$this->sname, $this->_id],
1971 _T('Duplicated from %name (%id)')
1972 );
1973 if (!empty($infos)) {
1974 $this->_others_infos_admin .= "\n" . $infos;
1975 }
1976 //drop id_adh
1977 $this->_id = null;
1978 //drop email, must be unique
1979 $this->_email = null;
1980 //drop creation date
1981 $this->_creation_date = date("Y-m-d");
1982 //drop login
1983 $this->_login = null;
1984 //reset picture
1985 $this->_picture = new Picture();
1986 //remove birthdate
1987 $this->_birthdate = null;
1988 //remove surname
1989 $this->_surname = null;
1990 //not admin
1991 $this->_admin = false;
1992 //not due free
1993 $this->_due_free = false;
1994 }
1995
1996 /**
1997 * Get current errors
1998 *
1999 * @return array
2000 */
2001 public function getErrors()
2002 {
2003 return $this->errors;
2004 }
2005
2006 /**
2007 * Get user groups
2008 *
2009 * @return array
2010 */
2011 public function getGroups()
2012 {
2013 return $this->_groups;
2014 }
2015
2016 /**
2017 * Get user managed groups
2018 *
2019 * @return array
2020 */
2021 public function getManagedGroups()
2022 {
2023 return $this->_managed_groups;
2024 }
2025
2026 /**
2027 * Can current logged in user edit member
2028 *
2029 * @param Login $login Login instance
2030 *
2031 * @return boolean
2032 */
2033 public function canEdit($login)
2034 {
2035 if ($this->id && $login->id == $this->id || $login->isAdmin() || $login->isStaff()) {
2036 return true;
2037 }
2038
2039 //check if requested member is part of managed groups
2040 if ($login->isGroupManager()) {
2041 foreach ($this->getGroups() as $g) {
2042 if ($login->isGroupManager($g->getId())) {
2043 return true;
2044 }
2045 }
2046 }
2047
2048 return false;
2049 }
2050
2051 /**
2052 * Are we currently duplicated a member?
2053 *
2054 * @return boolean
2055 */
2056 public function isDuplicate()
2057 {
2058 return $this->_duplicate;
2059 }
2060
2061 /**
2062 * Flag creation mail sending
2063 *
2064 * @param boolean $send True (default) to send creation email
2065 *
2066 * @return Adherent
2067 */
2068 public function setSendmail($send = true)
2069 {
2070 $this->sendmail = $send;
2071 return $this;
2072 }
2073
2074 /**
2075 * Should we send administrative emails to member?
2076 *
2077 * @return boolean
2078 */
2079 public function sendEMail()
2080 {
2081 return $this->sendmail;
2082 }
2083 }