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