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