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