3 /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
10 * Copyright © 2009-2023 The Galette Team
12 * This file is part of Galette (http://galette.tuxfamily.org).
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.
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.
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/>.
27 * @category Repository
30 * @author Johan Cwiklinski <johan@x-tnd.be>
31 * @copyright 2009-2023 The Galette Team
32 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL License 3.0 or (at your option) any later version
33 * @link http://galette.tuxfamily.org
34 * @since Available since 0.7dev - 2009-02-28
37 namespace Galette\Repository
;
39 use Galette\Core\Login
;
40 use Galette\Entity\Social
;
41 use Galette\Events\GaletteEvent
;
42 use Laminas\Db\ResultSet\ResultSet
;
43 use Laminas\Db\Sql\Predicate\IsNull
;
45 use Galette\DynamicFields\DynamicField
;
46 use Galette\Entity\DynamicFieldsHandle
;
48 use Laminas\Db\Sql\Expression
;
49 use Laminas\Db\Sql\Select
;
50 use Laminas\Db\Sql\Predicate\PredicateSet
;
51 use Laminas\Db\Sql\Predicate\Operator
;
52 use Galette\Entity\Adherent
;
53 use Galette\Entity\Contribution
;
54 use Galette\Entity\Transaction
;
55 use Galette\Entity\Reminder
;
56 use Galette\Filters\MembersList
;
57 use Galette\Filters\AdvancedMembersList
;
58 use Galette\Core\Picture
;
59 use Galette\Entity\Group
;
60 use Galette\Entity\Status
;
64 * Members class for galette
67 * @category Repository
70 * @author Johan Cwiklinski <johan@x-tnd.be>
71 * @copyright 2009-2023 The Galette Team
72 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL License 3.0 or (at your option) any later version
73 * @link http://galette.tuxfamily.org
77 public const TABLE
= Adherent
::TABLE
;
78 public const PK
= Adherent
::PK
;
80 public const ALL_ACCOUNTS
= 0;
81 public const ACTIVE_ACCOUNT
= 1;
82 public const INACTIVE_ACCOUNT
= 2;
84 public const SHOW_LIST
= 0;
85 public const SHOW_PUBLIC_LIST
= 1;
86 public const SHOW_ARRAY_LIST
= 2;
87 public const SHOW_STAFF
= 3;
88 public const SHOW_MANAGED
= 4;
89 public const SHOW_EXPORT
= 5;
91 public const FILTER_NAME
= 0;
92 public const FILTER_ADDRESS
= 1;
93 public const FILTER_MAIL
= 2;
94 public const FILTER_JOB
= 3;
95 public const FILTER_INFOS
= 4;
96 public const FILTER_DC_EMAIL
= 5;
97 public const FILTER_W_EMAIL
= 6;
98 public const FILTER_WO_EMAIL
= 7;
99 public const FILTER_COMPANY_NAME
= 8;
100 public const FILTER_DC_PUBINFOS
= 9;
101 public const FILTER_W_PUBINFOS
= 10;
102 public const FILTER_WO_PUBINFOS
= 11;
103 public const FILTER_ID
= 12;
104 public const FILTER_NUMBER
= 13;
106 public const MEMBERSHIP_ALL
= 0;
107 public const MEMBERSHIP_UP2DATE
= 3;
108 public const MEMBERSHIP_NEARLY
= 1;
109 public const MEMBERSHIP_LATE
= 2;
110 public const MEMBERSHIP_NEVER
= 4;
111 public const MEMBERSHIP_STAFF
= 5;
112 public const MEMBERSHIP_ADMIN
= 6;
113 public const MEMBERSHIP_NONE
= 7;
115 public const ORDERBY_NAME
= 'name';
116 public const ORDERBY_NICKNAME
= 'nickname';
117 public const ORDERBY_STATUS
= 'status';
118 public const ORDERBY_FEE_STATUS
= 'fee_status';
119 public const ORDERBY_MODIFDATE
= 'modif_date';
120 public const ORDERBY_ID
= 'id';
122 public const NON_STAFF_MEMBERS
= 30;
124 private $filters = false;
125 private $count = null;
126 private $errors = array();
129 * Default constructor
131 * @param MembersList $filters Filtering
133 public function __construct($filters = null)
135 if ($filters === null) {
136 $this->filters
= new MembersList();
138 $this->filters
= $filters;
143 * Get staff members list
145 * @param bool $as_members return the results as an array of
147 * @param array $fields field(s) name(s) to get. Should be a string or
148 * an array. If null, all fields will be
150 * @param boolean $count true if we want to count members
151 * @param boolean $limit true to LIMIT query
153 * @return Adherent[]|ResultSet
155 public function getStaffMembersList(
161 return $this->getMembersList(
172 * Get managed members list (for groups managers)
174 * @param bool $as_members return the results as an array of
176 * @param array $fields field(s) name(s) to get. Should be a string or
177 * an array. If null, all fields will be
179 * @param boolean $count true if we want to count members
180 * @param boolean $limit true to LIMIT query
182 * @return Adherent[]|ResultSet
184 public function getManagedMembersList(
190 return $this->getMembersList(
203 * @param bool $as_members return the results as an array of
205 * @param array $fields field(s) name(s) to get. Should be a string or
206 * an array. If null, all fields will be
208 * @param boolean $count true if we want to count members
209 * @param boolean $staff true if we want only staff members
210 * @param boolean $managed true if we want only managed groups
211 * @param boolean $limit true if we want records pagination
212 * @param boolean $export true if we are exporting
214 * @return Adherent[]|ResultSet
216 public function getMembersList(
227 if ($limit === true) {
228 //force count if limit is active
233 $_mode = self
::SHOW_LIST
;
234 if ($staff !== false) {
235 $_mode = self
::SHOW_STAFF
;
237 if ($managed !== false) {
238 $_mode = self
::SHOW_MANAGED
;
240 if ($export !== false) {
241 $_mode = self
::SHOW_EXPORT
;
244 $select = $this->buildSelect(
251 //add limits to retrieve only relavant rows
252 if ($limit === true) {
253 $this->filters
->setLimits($select);
256 $rows = $zdb->execute($select);
257 $this->filters
->query
= $zdb->query_string
;
265 foreach ($rows as $row) {
266 $members[] = new Adherent($zdb, $row, $deps);
272 } catch (Throwable
$e) {
274 'Cannot list members | ' . $e->getMessage(),
282 * Remove specified members
284 * @param integer|array $ids Members identifiers to delete
288 public function removeMembers($ids)
290 global $zdb, $hist, $emitter;
292 $processed = array();
294 if (is_array($ids)) {
296 } elseif (is_numeric($ids)) {
303 $zdb->connection
->beginTransaction();
305 //Retrieve some information
306 $select = $zdb->select(self
::TABLE
);
308 array(self
::PK
, 'nom_adh', 'prenom_adh', 'email_adh')
309 )->where
->in(self
::PK
, $list);
311 $results = $zdb->execute($select);
314 foreach ($results as $member) {
315 $str_adh = $member->id_adh
. ' (' . $member->nom_adh
. ' ' .
316 $member->prenom_adh
. ')';
317 $infos .= $str_adh . "\n";
319 $p = new Picture($member->id_adh
);
320 if ($p->hasPicture()) {
321 if (!$p->delete(false)) {
323 'Unable to delete picture for member ' . $str_adh,
326 throw new \
Exception(
327 'Unable to delete picture for member ' .
332 _T("Member Picture deleted"),
339 'id_adh' => $member->id_adh
,
340 'nom_adh' => $member->nom_adh
,
341 'prenom_adh' => $member->prenom_adh
,
342 'email_adh' => $member->email_adh
346 //delete contributions
347 $del_qry = $zdb->delete(Contribution
::TABLE
);
352 $zdb->execute($del_qry);
355 $select = $zdb->select(Transaction
::TABLE
);
356 $select->where
->in(self
::PK
, $list);
357 $results = $zdb->execute($select);
359 //if members has transactions;
360 //reset link with other contributions
362 if ($results->count() > 0) {
364 foreach ($results as $transaction) {
365 $transactions[] = $transaction[Transaction
::PK
];
368 $update = $zdb->update(Contribution
::TABLE
);
370 Transaction
::PK
=> new Expression('NULL')
375 $zdb->execute($update);
378 //delete transactions
379 $del_qry = $zdb->delete(Transaction
::TABLE
);
380 $del_qry->where
->in(self
::PK
, $list);
381 $zdb->execute($del_qry);
383 //delete groups membership/mamagmentship
384 Groups
::removeMembersFromGroups($list);
387 $del_qry = $zdb->delete(Reminder
::TABLE
);
392 $zdb->execute($del_qry);
394 //delete dynamic fields values
395 $del_qry = $zdb->delete(DynamicFieldsHandle
::TABLE
);
396 $del_qry->where(['field_form' => 'adh']);
397 $del_qry->where
->in('item_id', $list);
398 $zdb->execute($del_qry);
401 $del_qry = $zdb->delete(self
::TABLE
);
406 $zdb->execute($del_qry);
409 $zdb->connection
->commit();
411 foreach ($processed as $p) {
412 $emitter->dispatch(new GaletteEvent('member.remove', $p));
415 //add a history entry
417 _T("Delete members cards, transactions and dues"),
422 } catch (Throwable
$e) {
423 if ($zdb->connection
->inTransaction()) {
424 $zdb->connection
->rollBack();
426 if ($e->getCode() == 23000) {
428 'Member still have existing dependencies in the ' .
429 'database, maybe a mailing or some content from a ' .
430 'plugin. Please remove dependencies before trying ' .
434 $this->errors
[] = _T("Cannot remove a member who still have dependencies (mailings, ...)");
437 'Unable to delete selected member(s) |' .
450 * @param boolean $as_members return the results as an array of
452 * @param array $fields field(s) name(s) to get. Should be a string or
453 * an array. If null, all fields will be
456 * @return Adherent[]|ResultSet
458 public function getList($as_members = false, $fields = null)
460 return $this->getMembersList(
472 * Get members list with public information available
474 * @param boolean $with_photos get only members which have uploaded a
475 * photo (for trombinoscope)
479 public function getPublicList($with_photos)
484 $select = $this->buildSelect(
485 self
::SHOW_PUBLIC_LIST
,
491 $this->filters
->setLimits($select);
493 $results = $zdb->execute($select);
498 'picture' => $with_photos
500 foreach ($results as $row) {
501 $members[] = new Adherent($zdb, $row, $deps);
504 } catch (Throwable
$e) {
506 'Cannot list members with public information (photos: '
507 . $with_photos . ') | ' . $e->getMessage(),
515 * Get list of members that has been selected
517 * @param array $ids an array of members id that has been selected
518 * @param array $orderby SQL order clause (optional)
519 * @param boolean $with_photos Should photos be loaded?
520 * @param boolean $as_members Return Adherent[] or simple ResultSet
521 * @param array $fields Fields to use
522 * @param boolean $export True if we are exporting
523 * @param boolean $dues True if load dues as Adherent dependency
524 * @param boolean $parent True if load parent as Adherent dependency
526 * @return Adherent[]|false
528 public function getArrayList(
531 $with_photos = false,
540 if (!is_array($ids) ||
count($ids) < 1) {
541 Analog
::log('No member selected for labels.', Analog
::INFO
);
546 $damode = self
::SHOW_ARRAY_LIST
;
547 if ($export === true) {
548 $damode = self
::SHOW_EXPORT
;
550 $select = $this->buildSelect(
556 $select->where
->in('a.' . self
::PK
, $ids);
557 if (is_array($orderby) && count($orderby) > 0) {
558 foreach ($orderby as $o) {
563 $results = $zdb->execute($select);
567 'picture' => $with_photos,
572 foreach ($results as $o) {
573 if ($as_members === true) {
574 $members[] = new Adherent($zdb, $o, $deps);
580 } catch (Throwable
$e) {
582 'Cannot load members form ids array | ' . $e->getMessage(),
590 * Builds the SELECT statement
592 * @param int $mode the current mode (see self::SHOW_*)
593 * @param array $fields fields list to retrieve
594 * @param bool $photos true if we want to get only members with photos
595 * Default to false, only relevant for SHOW_PUBLIC_LIST
596 * @param bool $count true if we want to count members, defaults to false
598 * @return Select SELECT statement
600 private function buildSelect($mode, $fields, $photos, $count = false): Select
605 if ($fields != null && is_array($fields) && !in_array('id_adh', $fields)) {
606 $fields[] = 'id_adh';
608 $fieldsList = ($fields != null)
609 ?
((!is_array($fields) ||
count($fields) < 1) ?
(array)'*'
610 : $fields) : (array)'*';
612 $select = $zdb->select(self
::TABLE
, 'a');
614 $select->columns($fieldsList);
616 $select->quantifier('DISTINCT');
619 array('so' => PREFIX_DB
. Social
::TABLE
),
620 'a.' . Adherent
::PK
. '=so.' . Adherent
::PK
,
626 array('parent' => PREFIX_DB
. self
::TABLE
),
627 'a.parent_id=parent.' . self
::PK
,
633 case self
::SHOW_STAFF
:
634 case self
::SHOW_LIST
:
635 case self
::SHOW_ARRAY_LIST
:
636 case self
::SHOW_EXPORT
:
638 array('status' => PREFIX_DB
. Status
::TABLE
),
639 'a.' . Status
::PK
. '=status.' . Status
::PK
,
640 array('priorite_statut')
643 case self
::SHOW_MANAGED
:
645 array('status' => PREFIX_DB
. Status
::TABLE
),
646 'a.' . Status
::PK
. '=status.' . Status
::PK
648 array('gr' => PREFIX_DB
. Group
::GROUPSUSERS_TABLE
),
649 'a.' . Adherent
::PK
. '=gr.' . Adherent
::PK
,
652 array('m' => PREFIX_DB
. Group
::GROUPSMANAGERS_TABLE
),
653 'gr.' . Group
::PK
. '=m.' . Group
::PK
,
655 )->where(['m.' . Adherent
::PK
=> $login->id
]);
657 case self
::SHOW_PUBLIC_LIST
:
660 array('picture' => PREFIX_DB
. Picture
::TABLE
),
661 'a.' . self
::PK
. '= picture.' . self
::PK
,
668 //check for contributions filtering
670 $this->filters
instanceof AdvancedMembersList
671 && $this->filters
->withinContributions()
674 array('ct' => PREFIX_DB
. Contribution
::TABLE
),
675 'ct.' . self
::PK
. '=a.' . self
::PK
,
681 //check if there are dynamic fields in filter
684 if ($this->filters
instanceof AdvancedMembersList
) {
686 (bool)count($this->filters
->free_search
)
687 && !isset($this->filters
->free_search
['empty'])
689 $free_searches = $this->filters
->free_search
;
690 foreach ($free_searches as $fs) {
691 if (strpos($fs['field'], 'dyn_') === 0) {
692 // simple dynamic fields
694 $dfs[] = str_replace('dyn_', '', $fs['field']);
700 //check if there are dynamic fields for contributions in filter
706 $this->filters
instanceof AdvancedMembersList
707 && $this->filters
->withinContributions()
710 count($this->filters
->contrib_dynamic
) > 0
711 && !isset($this->filters
->contrib_dynamic
['empty'])
715 //check if there are dynamic fields in the filter
716 foreach ($this->filters
->contrib_dynamic
as $k => $cd) {
725 if ($hasDfc === true ||
$hasCdfc === true) {
727 array('dfc' => PREFIX_DB
. DynamicFieldsHandle
::TABLE
),
728 'dfc.item_id=ct.' . Contribution
::PK
,
734 // simple dynamic fields
735 if ($hasDf === true) {
736 foreach ($dfs as $df) {
737 $subselect = $zdb->select(DynamicFieldsHandle
::TABLE
, 'df');
740 'item_id' => 'item_id',
744 $subselect->where(['df.field_form' => 'adh']);
745 $subselect->where(['df.field_id' => $df]);
747 array('df' . $df => $subselect),
748 'a.id_adh = df' . $df . '.item_id',
755 // choice dynamic fields
756 if ($hasCdfc === true) {
757 $cdf_field = 'cdf.id';
758 if (TYPE_DB
=== 'pgsql') {
759 $cdf_field .= '::text';
762 $cdf_field = 'cdfc.id';
763 if (TYPE_DB
=== 'pgsql') {
764 $cdf_field .= '::text';
766 foreach ($cdfcs as $cdf) {
767 $rcdf_field = str_replace(
773 array('cdfc' . $cdf => DynamicField
::getFixedValuesTableName($cdf, true)),
774 $rcdf_field . '=dfc.field_val',
781 if ($mode == self
::SHOW_LIST ||
$mode == self
::SHOW_MANAGED
) {
782 if ($this->filters
!== false) {
783 $this->buildWhereClause($select);
785 } elseif ($mode == self
::SHOW_PUBLIC_LIST
) {
798 new Expression('true')
806 'a.bool_display_info',
808 new Expression('true')
813 new Expression('true')
822 if ($mode === self
::SHOW_STAFF
) {
823 $select->where
->lessThan(
824 'status.priorite_statut',
825 self
::NON_STAFF_MEMBERS
830 $this->proceedCount($select);
833 $this->buildOrderClause($select, $fields);
836 } catch (Throwable
$e) {
838 'Cannot build SELECT clause for members | ' . $e->getMessage(),
846 * Count members from the query
848 * @param Select $select Original select
852 private function proceedCount(Select
$select)
857 $countSelect = clone $select;
858 $countSelect->reset($countSelect::COLUMNS
);
859 $countSelect->reset($countSelect::ORDER
);
860 $countSelect->reset($countSelect::HAVING
);
861 $joins = $countSelect->joins
;
862 $countSelect->reset($countSelect::JOINS
);
863 foreach ($joins as $join) {
870 unset($join['columns']);
872 $countSelect->columns(
874 'count' => new Expression('count(DISTINCT a.' . self
::PK
. ')')
878 $have = $select->having
;
879 if ($have->count() > 0) {
880 foreach ($have->getPredicates() as $h) {
881 $countSelect->where($h);
885 $results = $zdb->execute($countSelect);
887 $this->count
= (int)$results->current()->count
;
888 if (isset($this->filters
) && $this->count
> 0) {
889 $this->filters
->setCounter($this->count
);
891 } catch (Throwable
$e) {
893 'Cannot count members | ' . $e->getMessage(),
901 * Builds the order clause
903 * @param Select $select Original select
904 * @param array $fields Fields list to ensure ORDER clause
905 * references selected fields. Optional.
909 private function buildOrderClause(Select
$select, $fields = null): Select
913 switch ($this->filters
->orderby
) {
914 case self
::ORDERBY_NICKNAME
:
915 if ($this->canOrderBy('pseudo_adh', $fields)) {
916 $order[] = 'pseudo_adh ' . $this->filters
->getDirection();
919 case self
::ORDERBY_STATUS
:
920 if ($this->canOrderBy('priorite_statut', $fields)) {
921 $order[] = 'priorite_statut ' . $this->filters
->getDirection();
924 case self
::ORDERBY_MODIFDATE
:
925 if ($this->canOrderBy('date_modif_adh', $fields)) {
926 $order[] = 'date_modif_adh ' . $this->filters
->getDirection();
929 case 'list_adh_contribstatus':
930 case self
::ORDERBY_FEE_STATUS
:
931 if ($this->canOrderBy('bool_exempt_adh', $fields)) {
932 $order[] = 'bool_exempt_adh ' . $this->filters
->getDirection();
935 if ($this->canOrderBy('date_echeance', $fields)) {
936 $order[] = 'date_echeance ' . $this->filters
->getDirection();
939 case self
::ORDERBY_ID
:
940 if ($this->canOrderBy('id_adh', $fields)) {
941 $order[] = 'id_adh ' . $this->filters
->getDirection();
944 case 'list_adh_name':
947 case self
::ORDERBY_NAME
:
951 if ($this->canOrderBy($this->filters
->orderby
, $fields)) {
952 $order[] = 'a.' . $this->filters
->orderby
. ' ' . $this->filters
->getDirection();
957 //anyways, we want to order by firstname, lastname
958 if ($this->canOrderBy('nom_adh', $fields)) {
959 $order[] = 'nom_adh ' . $this->filters
->getDirection();
961 if ($this->canOrderBy('prenom_adh', $fields)) {
962 $order[] = 'prenom_adh ' . $this->filters
->getDirection();
965 $select->order($order);
970 * Is field allowed to order? it should be present in
971 * provided fields list (those that are SELECT'ed).
973 * @param string $field_name Field name to order by
974 * @param array $fields SELECTE'ed fields
978 private function canOrderBy($field_name, $fields)
980 if ($fields === null) {
982 } elseif (!is_array($fields)) {
984 } elseif (in_array($field_name, $fields)) {
988 'Trying to order by ' . $field_name . ' while it is not in ' .
997 * Builds where clause, for filtering on simple list mode
999 * @param Select $select Original select
1003 private function buildWhereClause(Select
$select)
1005 global $zdb, $login;
1008 if ($this->filters
->email_filter
== self
::FILTER_W_EMAIL
) {
1009 $select->where('(a.email_adh != \'\' OR a.parent_id IS NOT NULL AND parent.email_adh != \'\')');
1011 if ($this->filters
->email_filter
== self
::FILTER_WO_EMAIL
) {
1012 $select->where('(a.email_adh = \'\' OR a.email_adh IS NULL) AND (parent.email_adh = \'\' OR parent.email_adh IS NULL)');
1015 if ($this->filters
->filter_str
!= '') {
1016 $token = $zdb->platform
->quoteValue(
1017 '%' . strtolower($this->filters
->filter_str
) . '%'
1019 switch ($this->filters
->field_filter
) {
1020 case self
::FILTER_NAME
:
1021 if (TYPE_DB
=== 'pgsql') {
1022 $sep = " || ' ' || ";
1033 $pre . 'LOWER(a.nom_adh)' . $sep .
1034 'LOWER(a.prenom_adh)' . $sep .
1035 'LOWER(a.pseudo_adh)' . $post . ' LIKE ' .
1038 $pre . 'LOWER(a.prenom_adh)' . $sep .
1039 'LOWER(a.nom_adh)' . $sep .
1040 'LOWER(a.pseudo_adh)' . $post . ' LIKE ' .
1045 case self
::FILTER_COMPANY_NAME
:
1047 'LOWER(a.societe_adh) LIKE ' .
1051 case self
::FILTER_ADDRESS
:
1054 'LOWER(a.adresse_adh) LIKE ' . $token
1056 'a.cp_adh LIKE ' . $token
1058 'LOWER(a.ville_adh) LIKE ' . $token
1060 'LOWER(a.pays_adh) LIKE ' . $token
1064 case self
::FILTER_MAIL
:
1067 'LOWER(a.email_adh) LIKE ' . $token
1069 'LOWER(so.url) LIKE ' . $token
1073 case self
::FILTER_JOB
:
1075 'LOWER(a.prof_adh) LIKE ' . $token
1078 case self
::FILTER_INFOS
:
1080 if ($login->isAdmin() ||
$login->isStaff()) {
1081 $more = ' OR LOWER(a.info_adh) LIKE ' . $token;
1084 '(LOWER(a.info_public_adh) LIKE ' .
1085 $token . $more . ')'
1088 case self
::FILTER_NUMBER
:
1089 $select->where
->equalTo('a.num_adh', $this->filters
->filter_str
);
1091 case self
::FILTER_ID
:
1092 $select->where
->equalTo('a.id_adh', $this->filters
->filter_str
);
1097 if ($this->filters
->membership_filter
) {
1098 switch ($this->filters
->membership_filter
) {
1099 case self
::MEMBERSHIP_NEARLY
:
1100 $now = new \
DateTime();
1101 $due_date = clone $now;
1102 $due_date->modify('+30 days');
1104 ->greaterThanOrEqualTo(
1106 $now->format('Y-m-d')
1107 )->lessThanOrEqualTo(
1109 $due_date->format('Y-m-d')
1110 )->equalTo('a.bool_exempt_adh', new Expression('false'));
1112 case self
::MEMBERSHIP_LATE
:
1116 date('Y-m-d', time())
1117 )->equalTo('a.bool_exempt_adh', new Expression('false'));
1119 case self
::MEMBERSHIP_UP2DATE
:
1121 '(' . 'a.date_echeance >= \'' . date('Y-m-d', time())
1122 . '\' OR a.bool_exempt_adh=true)'
1125 case self
::MEMBERSHIP_NEVER
:
1126 $select->where('a.date_echeance IS NULL')
1127 ->where('a.bool_exempt_adh = false');
1129 case self
::MEMBERSHIP_STAFF
:
1130 $select->where
->lessThan(
1131 'status.priorite_statut',
1132 self
::NON_STAFF_MEMBERS
1135 case self
::MEMBERSHIP_ADMIN
:
1136 $select->where
->equalTo('a.bool_admin_adh', true);
1138 case self
::MEMBERSHIP_NONE
:
1139 $select->where
->equalTo('a.id_statut', Status
::DEFAULT_STATUS
);
1144 if ($this->filters
->filter_account
) {
1145 switch ($this->filters
->filter_account
) {
1146 case self
::ACTIVE_ACCOUNT
:
1147 $select->where('a.activite_adh=true');
1149 case self
::INACTIVE_ACCOUNT
:
1150 $select->where('a.activite_adh=false');
1155 if ($this->filters
->group_filter
) {
1157 array('g' => PREFIX_DB
. Group
::GROUPSUSERS_TABLE
),
1158 'a.' . Adherent
::PK
. '=g.' . Adherent
::PK
,
1162 array('gs' => PREFIX_DB
. Group
::TABLE
),
1163 'gs.' . Group
::PK
. '=g.' . Group
::PK
,
1167 '(g.' . Group
::PK
. ' = ' . $zdb->platform
->quoteValue($this->filters
->group_filter
) .
1168 ' OR gs.parent_group = NULL OR gs.parent_group = ' .
1169 $this->filters
->group_filter
. ')'
1173 if ($this->filters
instanceof AdvancedMembersList
) {
1174 $this->buildAdvancedWhereClause($select);
1176 } catch (Throwable
$e) {
1178 __METHOD__
. ' | ' . $e->getMessage(),
1186 * Builds where clause, for advanced filtering on simple list mode
1188 * @param Select $select Original select
1192 private function buildAdvancedWhereClause(Select
$select)
1196 // Search members who belong to any (OR) or all (AND) listed groups.
1197 // Idea is to build an array of members ID that fits groups selection
1198 // we will use in the final query.
1199 // The OR case is quite simple, AND is a bit more complex; since we must
1200 // check each member do belongs to all listed groups.
1202 count($this->filters
->groups_search
) > 0
1203 && !isset($this->filters
->groups_search
['empty'])
1208 foreach ($this->filters
->groups_search
as $gs) { // then add a row for each group
1209 $wheregroups[] = $gs['group'];
1212 $gselect = $zdb->select(Group
::GROUPSUSERS_TABLE
, 'gu');
1216 array('g' => PREFIX_DB
. Group
::TABLE
),
1217 'gu.id_group=g.' . Group
::PK
,
1222 'g.id_group' => ':group',
1223 'g.parent_group' => ':pgroup'
1227 $gselect->group(['gu.id_adh']);
1229 $stmt = $zdb->sql
->prepareStatementForSqlObject($gselect);
1233 foreach ($this->filters
->groups_search
as $gs) { // then add a row for each ig/searched group pair
1234 $gresults = $stmt->execute(
1236 'group' => $gs['group'],
1237 'pgroup' => $gs['group']
1241 switch ($this->filters
->groups_search_log_op
) {
1242 case AdvancedMembersList
::OP_AND
:
1243 foreach ($gresults as $gresult) {
1244 if (!isset($ids[$gresult['id_adh']])) {
1245 $ids[$gresult['id_adh']] = 0;
1247 $ids[$gresult['id_adh']] +
= 1;
1250 case AdvancedMembersList
::OP_OR
:
1251 foreach ($gresults as $gresult) {
1252 $mids[$gresult['id_adh']] = $gresult['id_adh'];
1259 foreach ($ids as $id_adh => $count) {
1260 if ($count == count($wheregroups)) {
1261 $mids[$id_adh] = $id_adh;
1267 //limit on found members
1268 $select->where
->in('a.id_adh', $mids);
1270 //no match in groups, end of game.
1271 $select->where('false = true');
1275 //FIXME: should be retrieved from members_fields
1277 'a.ddn_adh' => 'birth_date',
1278 'a.date_crea_adh' => 'creation_date',
1279 'a.date_modif_adh' => 'modif_date',
1280 'a.date_echeance' => 'due_date',
1281 'ct.date_enreg' => 'contrib_creation_date',
1282 'ct.date_debut_cotis' => 'contrib_begin_date',
1283 'ct.date_fin_cotis' => 'contrib_end_date'
1286 foreach ($dates as $field => $property) {
1287 $bprop = "r{$property}_begin";
1288 if ($this->filters
->$bprop) {
1289 $d = new \
DateTime($this->filters
->$bprop);
1290 $select->where
->greaterThanOrEqualTo(
1295 $eprop = "r{$property}_end";
1296 if ($this->filters
->$eprop) {
1297 $d = new \
DateTime($this->filters
->$eprop);
1298 $select->where
->lessThanOrEqualTo(
1305 if ($this->filters
->show_public_infos
) {
1306 switch ($this->filters
->show_public_infos
) {
1307 case self
::FILTER_W_PUBINFOS
:
1308 $select->where('a.bool_display_info = true');
1310 case self
::FILTER_WO_PUBINFOS
:
1311 $select->where('a.bool_display_info = false');
1313 case self
::FILTER_DC_PUBINFOS
:
1314 //nothing to do here.
1319 if ($this->filters
->status
) {
1322 $this->filters
->status
1327 $this->filters
->contrib_min_amount
1328 ||
$this->filters
->contrib_max_amount
1330 if ($this->filters
->contrib_min_amount
) {
1331 $select->where
->greaterThanOrEqualTo(
1333 $this->filters
->contrib_min_amount
1336 if ($this->filters
->contrib_max_amount
) {
1337 $select->where
->lessThanOrEqualTo(
1339 $this->filters
->contrib_max_amount
1344 if ($this->filters
->contributions_types
) {
1347 $this->filters
->contributions_types
1351 if ($this->filters
->payments_types
) {
1353 'ct.type_paiement_cotis',
1354 $this->filters
->payments_types
1359 count($this->filters
->contrib_dynamic
) > 0
1360 && !isset($this->filters
->contrib_dynamic
['empty'])
1362 foreach ($this->filters
->contrib_dynamic
as $k => $cd) {
1368 if (is_array($cd)) {
1369 //dynamic choice spotted!
1370 $prefix = 'cdfc' . $k . '.';
1371 $qry = 'dfc.field_form = \'contrib\' AND ' .
1372 'dfc.field_id = ' . $k;
1374 $select->where($qry);
1375 $select->where
->in($prefix . $field, $cd);
1377 //dynamic field spotted!
1379 $qry = 'dfc.field_form = \'contrib\' AND ' .
1380 'dfc.field_id = ' . $k . ' AND ';
1381 $field = 'field_val';
1382 $qry .= 'LOWER(' . $prefix . $field . ') ' .
1384 $select->where($qry . $zdb->platform
->quoteValue('%' . strtolower($cd) . '%'));
1390 count($this->filters
->free_search
) > 0
1391 && !isset($this->filters
->free_search
['empty'])
1393 foreach ($this->filters
->free_search
as $fs) {
1394 $fs['search'] = mb_strtolower($fs['search']);
1396 switch ($fs['qry_op']) {
1397 case AdvancedMembersList
::OP_EQUALS
:
1400 case AdvancedMembersList
::OP_CONTAINS
:
1402 $fs['search'] = '%' . $fs['search'] . '%';
1404 case AdvancedMembersList
::OP_NOT_EQUALS
:
1407 case AdvancedMembersList
::OP_NOT_CONTAINS
:
1409 $fs['search'] = '%' . $fs['search'] . '%';
1411 case AdvancedMembersList
::OP_STARTS_WITH
:
1413 $fs['search'] = $fs['search'] . '%';
1415 case AdvancedMembersList
::OP_ENDS_WITH
:
1417 $fs['search'] = '%' . $fs['search'];
1419 case AdvancedMembersList
::OP_BEFORE
:
1422 case AdvancedMembersList
::OP_AFTER
:
1427 'Unknown query operator: ' . $fs['qry_op'] .
1428 ' (will fallback to equals)',
1438 if (strpos($fs['field'], 'dyn_') === 0) {
1439 // simple dynamic field spotted!
1440 $index = str_replace('dyn_', '', $fs['field']);
1441 $dyn_field = DynamicField
::loadFieldType($zdb, (int)$index);
1442 $prefix = 'df' . $index . '.';
1443 $fs['field'] = 'val';
1446 //handle socials networks
1447 if (strpos($fs['field'], 'socials_') === 0) {
1449 $type = str_replace('socials_', '', $fs['field']);
1451 $fs['field'] = 'url';
1452 $select->where(['so.type' => $type]);
1455 if ($dyn_field && $dyn_field instanceof \Galette\DynamicFields\Boolean
) {
1456 if ($fs['search'] != 0) {
1457 $qry .= $prefix . $fs['field'] . $qop . ' ' .
1460 $qry .= $prefix . $fs['field'] . ' IS NULL';
1462 } elseif (!strncmp($fs['field'], 'bool_', strlen('bool_'))) {
1463 $qry .= $prefix . $fs['field'] . $qop . ' ' .
1466 $fs['qry_op'] === AdvancedMembersList
::OP_BEFORE
1467 ||
$fs['qry_op'] === AdvancedMembersList
::OP_AFTER
1469 if ($prefix === 'a.') {
1470 //dates are OK in the main fields. no cast, just query!
1471 $qry .= $prefix . $fs['field'] . $qop . ' ' .
1472 $zdb->platform
->quoteValue($fs['search']);
1474 //dynamic dates are stored in their localized format :/
1475 //use current lang format to query for now
1476 if ($zdb->isPostgres()) {
1477 $fs['search'] = "to_date('" . $fs['search'] . "', 'YYYY-MM-DD')";
1478 $store_fmt = __("Y-m-d") === 'Y-m-d' ?
'YYYY-MM-DD' : 'DD/MM/YYYY';
1479 $qry .= "to_date('" . $prefix . $fs['field'] . "', '$store_fmt')";
1481 $fs['search'] = "STR_TO_DATE('" . $fs['search'] . "', '%Y-%m-%d')";
1482 $store_fmt = __("Y-m-d") === 'Y-m-d' ?
'%Y-%m-%d' : '%d/%m/%Y';
1483 $qry .= 'STR_TO_DATE(' . $prefix . $fs['field'] . ', \'' . $store_fmt . '\') ';
1486 $qry .= $qop . ' ' . $fs['search'];
1488 } elseif ($fs['field'] == 'status_label') {
1489 $qry_pattern = '%p%field %op %value';
1490 $qry .= str_replace(
1501 $zdb->platform
->quoteValue($fs['search'])
1506 $field = $prefix . $fs['field'];
1507 if ($zdb->isPostgres()) {
1508 $field = 'CAST(' . $field . ' AS TEXT)';
1510 $qry .= 'LOWER(' . $field . ') ' .
1511 $qop . ' ' . $zdb->platform
->quoteValue($fs['search']);
1514 if ($fs['log_op'] === AdvancedMembersList
::OP_AND
) {
1515 $select->where($qry);
1516 } elseif ($fs['log_op'] === AdvancedMembersList
::OP_OR
) {
1517 $select->where($qry, PredicateSet
::OP_OR
);
1524 * Login and password field cannot be empty.
1526 * If those are not required, or if a file has been imported
1527 * (from a CSV file for example), we fill here random values.
1531 public function emptyLogins()
1536 $zdb->connection
->beginTransaction();
1537 $select = $zdb->select(Adherent
::TABLE
);
1539 array('id_adh', 'login_adh', 'mdp_adh')
1548 new IsNull('login_adh'),
1554 new IsNull('mdp_adh'),
1560 $results = $zdb->execute($select);
1563 if ($results->count() > 0) {
1564 $update = $zdb->update(Adherent
::TABLE
);
1567 'login_adh' => ':login',
1568 'mdp_adh' => ':pass'
1570 )->where
->equalTo(Adherent
::PK
, ':id');
1572 $stmt = $zdb->sql
->prepareStatementForSqlObject($update);
1574 $p = new \Galette\Core\
Password($zdb);
1576 foreach ($results as $m) {
1580 ||
!isset($m->login_adh
)
1581 ||
$m->login_adh
== 'NULL'
1583 $m->login_adh
= $p->makeRandomPassword(15);
1589 ||
!isset($m->mdp_adh
)
1590 ||
$m->mdp_adh
== 'NULL'
1592 $randomp = $p->makeRandomPassword(15);
1593 $m->mdp_adh
= password_hash(
1600 if ($dirty === true) {
1603 'login' => $m->login_adh
,
1604 'pass' => $m->mdp_adh
,
1612 $zdb->connection
->commit();
1613 $this->count
= $processed;
1615 } catch (Throwable
$e) {
1616 $zdb->connection
->rollBack();
1618 'An error occurred trying to retrieve members with ' .
1619 'empty logins/passwords (' . $e->getMessage(),
1627 * Get reminders count based on members state of dues
1631 public function getRemindersCount()
1635 $reminders = array();
1637 // Count close to be expired reminders
1638 $select = $zdb->select(Adherent
::TABLE
, 'a');
1641 'cnt' => new Expression('count(a.' . Adherent
::PK
. ')')
1646 array('parent' => PREFIX_DB
. self
::TABLE
),
1647 'a.parent_id=parent.' . self
::PK
,
1653 ->where('a.activite_adh=true')
1654 ->where('a.bool_exempt_adh=false');
1656 $now = new \
DateTime();
1657 $due_date = clone $now;
1658 $due_date->modify('+30 days');
1661 ->greaterThanOrEqualTo('a.date_echeance', $now->format('Y-m-d'))
1662 ->lessThanOrEqualTo('a.date_echeance', $due_date->format('Y-m-d'));
1664 $select_wo_mail = clone $select;
1665 //per default, limit to members who have an email address
1667 '(a.email_adh != \'\' OR a.parent_id IS NOT NULL AND parent.email_adh != \'\')'
1669 $select_wo_mail->where(
1670 '(a.email_adh = \'\' OR a.email_adh IS NULL) AND (parent.email_adh = \'\' OR parent.email_adh IS NULL)'
1673 $results = $zdb->execute($select);
1674 $res = $results->current();
1675 $reminders['impending'] = $res->cnt
;
1677 $results_wo_mail = $zdb->execute($select_wo_mail);
1678 $res_wo_mail = $results_wo_mail->current();
1679 $reminders['nomail']['impending'] = $res_wo_mail->cnt
;
1681 // Count late reminders
1682 $select = $zdb->select(Adherent
::TABLE
, 'a');
1685 'cnt' => new Expression('count(a.' . Adherent
::PK
. ')')
1690 array('parent' => PREFIX_DB
. self
::TABLE
),
1691 'a.parent_id=parent.' . self
::PK
,
1697 ->where('a.activite_adh=true')
1698 ->where('a.bool_exempt_adh=false');
1701 ->lessThan('a.date_echeance', $now->format('Y-m-d'));
1703 $select_wo_mail = clone $select;
1704 //per default, limit to members who have an email address
1706 '(a.email_adh != \'\' OR a.parent_id IS NOT NULL AND parent.email_adh != \'\')'
1708 $select_wo_mail->where(
1709 '(a.email_adh = \'\' OR a.email_adh IS NULL) AND (parent.email_adh = \'\' OR parent.email_adh IS NULL)'
1712 $results = $zdb->execute($select);
1713 $res = $results->current();
1714 $reminders['late'] = $res->cnt
;
1716 $results_wo_mail = $zdb->execute($select_wo_mail);
1717 $res_wo_mail = $results_wo_mail->current();
1718 $reminders['nomail']['late'] = $res_wo_mail->cnt
;
1724 * Get count for current query
1728 public function getCount()
1730 return $this->count
;
1734 * Get registered errors
1738 public function getErrors()
1740 return $this->errors
;
1744 * Get all existing emails
1746 * @param Db $zdb Database instance
1748 * @return array ['email' => 'id_adh']
1750 public static function getEmails(Db
$zdb)
1753 $select = $zdb->select(self
::TABLE
);
1758 $select->where('email_adh != \'\' AND email_adh IS NOT NULL');
1759 $rows = $zdb->execute($select);
1760 foreach ($rows as $row) {
1761 $emails[$row->email_adh
] = $row->{self
::PK
};
1767 * Get current filters
1769 * @return MembersList
1771 public function getFilters()
1773 return $this->filters
;
1777 * Get members list to instanciate dropdowns
1779 * @param Db $zdb Database instance
1780 * @param Login $login Login instance
1781 * @param integer $current Current member
1785 public function getDropdownMembers(Db
$zdb, Login
$login, $current = null)
1788 $required_fields = array(
1796 if ($login->isAdmin() ||
$login->isStaff()) {
1797 $list_members = $this->getList(false, $required_fields);
1798 } elseif ($login->isGroupManager()) {
1799 $list_members = $this->getManagedMembersList(false, $required_fields);
1802 if (count($list_members) > 0) {
1803 foreach ($list_members as $member) {
1806 $members[$member->$pk] = Adherent
::getNameWithCase(
1808 $member->prenom_adh
,
1816 //check if current attached member is part of the list
1817 if ($current !== null && !isset($members[$current])) {
1819 [$current => Adherent
::getSName($zdb, $current, true, true)] +