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