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