3 /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
10 * Copyright © 2012-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/>.
30 * @author Johan Cwiklinski <johan@x-tnd.be>
31 * @copyright 2012-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 - 2012-01-17
37 namespace Galette\Entity
;
40 use Galette\Repository\Groups
;
42 use Galette\Core\Login
;
44 use Laminas\Db\Sql\Expression
;
52 * @author Johan Cwiklinski <johan@x-tnd.be>
53 * @copyright 2012-2023 The Galette Team
54 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL License 3.0 or (at your option) any later version
55 * @link http://galette.tuxfamily.org
56 * @since Available since 0.7dev - 2012-01-17
60 public const TABLE
= 'groups';
61 public const PK
= 'id_group';
63 public const GROUPSUSERS_TABLE
= 'groups_members';
64 public const GROUPSMANAGERS_TABLE
= 'groups_managers';
66 public const MEMBER_TYPE
= 0;
67 public const MANAGER_TYPE
= 1;
71 private $parent_group;
75 private $creation_date;
76 private $count_members;
83 * @param null|int|ArrayObject $args Either a ResultSet row or its id for to load
84 * a specific group, or null to just
87 public function __construct($args = null)
89 if ($args === null ||
is_int($args)) {
90 if (is_int($args) && $args > 0) {
93 } elseif (is_object($args)) {
94 $this->loadFromRS($args);
99 * Loads a group from its id
101 * @param int $id the identifiant for the group to load
103 * @return bool true if query succeed, false otherwise
105 public function load($id)
110 $select = $zdb->select(self
::TABLE
);
111 $select->where(array(self
::PK
=> $id));
113 $results = $zdb->execute($select);
115 if ($results->count() > 0) {
116 $this->loadFromRS($results->current());
121 } catch (Throwable
$e) {
123 'Cannot load group form id `' . $id . '` | ' . $e->getMessage(),
131 * Populate object from a resultset row
133 * @param ArrayObject $r the resultset row
137 private function loadFromRS(ArrayObject
$r)
139 $this->id
= (int)$r->id_group
;
140 $this->group_name
= $r->group_name
;
141 $this->creation_date
= $r->creation_date
;
142 if ($r->parent_group
) {
143 $this->parent_group
= new Group((int)$r->parent_group
);
145 if (isset($r->members
)) {
146 //we're from a list, we just want members count
147 $this->count_members
= $r->members
;
152 * Loads members for the current group
154 * @param int $type Either self::MEMBER_TYPE or self::MANAGER_TYPE
158 private function loadPersons($type)
166 case self
::MEMBER_TYPE
:
167 $join = PREFIX_DB
. self
::GROUPSUSERS_TABLE
;
169 case self
::MANAGER_TYPE
:
170 $join = PREFIX_DB
. self
::GROUPSMANAGERS_TABLE
;
174 $select = $zdb->select(Adherent
::TABLE
, 'a');
176 array('status' => PREFIX_DB
. Status
::TABLE
),
177 'a.' . Status
::PK
. '=status.' . Status
::PK
,
178 array('priorite_statut')
182 'g.' . Adherent
::PK
. '=a.' . Adherent
::PK
,
185 'g.' . self
::PK
=> $this->id
191 $results = $zdb->execute($select);
200 foreach ($results as $m) {
201 $members[] = new Adherent($zdb, $m, $deps);
204 if ($type === self
::MEMBER_TYPE
) {
205 $this->members
= $members;
207 $this->managers
= $members;
209 } catch (Throwable
$e) {
211 'Cannot get group persons | ' . $e->getMessage(),
224 private function loadSubGroups()
228 if (!isset($this->login
) ||
!$this->login
->isLogged()) {
234 $select = $zdb->select(self
::TABLE
, 'a');
236 if (!$this->login
->isAdmin() && !$this->login
->isStaff()) {
238 array('b' => PREFIX_DB
. self
::GROUPSMANAGERS_TABLE
),
239 'a.' . self
::PK
. '=b.' . self
::PK
,
241 )->where(['b.' . Adherent
::PK
=> $this->login
->id
]);
244 $select->where(['parent_group' => $this->id
])
245 ->order('group_name ASC');
247 $results = $zdb->execute($select);
250 foreach ($results as $m) {
251 $group = new Group((int)$m->$grppk);
252 $group->setLogin($this->login
);
255 $this->groups
= $groups;
256 } catch (Throwable
$e) {
258 'Cannot get subgroup for group ' . $this->group_name
.
259 ' (' . $this->id
. ')| ' . $e->getMessage(),
267 * Remove specified group
269 * @param boolean $cascade Also remove members and managers
273 public function remove($cascade = false)
276 $transaction = false;
279 if (!$zdb->connection
->inTransaction()) {
280 $zdb->connection
->beginTransaction();
284 if ($cascade === true) {
285 $subgroups = $this->getGroups();
286 if (count($subgroups) > 0) {
288 'Cascading remove ' . $this->group_name
.
289 '. Subgroups, their members and managers will be detached.',
292 foreach ($subgroups as $subgroup) {
293 $subgroup->remove(true);
298 'Cascading remove ' . $this->group_name
.
299 '. Members and managers will be detached.',
304 $delete = $zdb->delete(self
::GROUPSUSERS_TABLE
);
305 $delete->where([self
::PK
=> $this->id
]);
306 $zdb->execute($delete);
309 $delete = $zdb->delete(self
::GROUPSMANAGERS_TABLE
);
310 $delete->where([self
::PK
=> $this->id
]);
311 $zdb->execute($delete);
314 //delete group itself
315 $delete = $zdb->delete(self
::TABLE
);
316 $delete->where([self
::PK
=> $this->id
]);
317 $zdb->execute($delete);
321 $zdb->connection
->commit();
325 } catch (Throwable
$e) {
327 $zdb->connection
->rollBack();
329 if ($zdb->isForeignKeyException($e)) {
334 'Group "%group" still have members!'
338 $this->isempty
= false;
341 'Unable to delete group ' . $this->group_name
.
342 ' (' . $this->id
. ') |' . $e->getMessage(),
352 * Is group empty? (after first deletion try)
356 public function isEmpty()
358 return $this->isempty
;
362 * Detach a group from its parent
366 public function detach()
371 $update = $zdb->update(self
::TABLE
);
373 array('parent_group' => new Expression('NULL'))
375 [self
::PK
=> $this->id
]
378 $edit = $zdb->execute($update);
380 //edit == 0 does not mean there were an error, but that there
381 //were nothing to change
382 if ($edit->count() > 0) {
383 $this->parent_group
= null;
385 _T("Group has been detached from its parent"),
391 } catch (Throwable
$e) {
393 'Something went wrong detaching group `' . $this->group_name
.
394 '` (' . $this->id
. ') from its parent:\'( | ' .
395 $e->getMessage() . "\n" .
396 $e->getTraceAsString(),
408 public function store()
412 $parent_group = null;
413 if ($this->parent_group
) {
414 $parent_group = $this->parent_group
->getId();
416 if (!Groups
::isUnique($zdb, $this->getName(), $parent_group, $this->getId())) {
418 'Group name is not unique at requested level',
421 throw new \
RuntimeException(
422 _T("The group name you have requested already exists in the database.")
428 self
::PK
=> $this->id
,
429 'group_name' => $this->group_name
432 if ($this->parent_group
) {
433 $values['parent_group'] = $parent_group;
436 if (!isset($this->id
) ||
$this->id
== '') {
437 //we're inserting a new group
438 unset($values[self
::PK
]);
439 $this->creation_date
= date("Y-m-d H:i:s");
440 $values['creation_date'] = $this->creation_date
;
442 $insert = $zdb->insert(self
::TABLE
);
443 $insert->values($values);
444 $add = $zdb->execute($insert);
445 if ($add->count() > 0) {
446 $this->id
= $zdb->getLastGeneratedValue($this);
455 $hist->add(_T("Fail to add new group."));
456 throw new \
Exception(
457 'An error occurred inserting new group!'
461 //we're editing an existing group
462 $update = $zdb->update(self
::TABLE
);
465 ->where([self
::PK
=> $this->id
]);
467 $edit = $zdb->execute($update);
469 //edit == 0 does not mean there were an error, but that there
470 //were nothing to change
471 if ($edit->count() > 0) {
479 /** FIXME: also store members and managers? */
480 } catch (Throwable
$e) {
482 'Something went wrong :\'( | ' . $e->getMessage() . "\n" .
483 $e->getTraceAsString(),
491 * Is current logged-in user manager of the group?
493 * @param Login $login Login instance
497 public function isManager(Login
$login)
499 if ($login->isAdmin() ||
$login->isStaff()) {
500 //admins as well as staff members are managers for all groups!
503 //let's check if current logged-in user is part of group managers
504 if (!is_array($this->managers
)) {
505 $this->loadPersons(self
::MANAGER_TYPE
);
508 foreach ($this->managers
as $manager) {
509 if ($login->login
== $manager->login
) {
522 public function getId()
528 * Get Level of the group
532 public function getLevel()
534 if ($this->parent_group
) {
535 return $this->parent_group
->getLevel() +
1;
541 * Get the full name of the group "foo / bar"
545 public function getFullName()
547 if ($this->parent_group
) {
548 return $this->parent_group
->getFullName() . ' / ' . $this->group_name
;
550 return $this->group_name
;
554 * Get the indented short name of the group " >> bar"
558 public function getIndentName()
560 if (($level = $this->getLevel())) {
561 return str_repeat(" ", 3 * $level) . '» ' . $this->group_name
;
563 return $this->group_name
;
571 public function getName()
573 return $this->group_name
;
581 public function getMembers()
583 if (!is_array($this->members
)) {
584 $this->loadPersons(self
::MEMBER_TYPE
);
586 return $this->members
;
590 * Get groups managers
594 public function getManagers()
596 if (!is_array($this->managers
)) {
597 $this->loadPersons(self
::MANAGER_TYPE
);
599 return $this->managers
;
607 public function getGroups()
609 if (!is_array($this->groups
)) {
610 $this->loadSubGroups();
612 return $this->groups
;
620 public function getParentGroup()
622 return $this->parent_group
;
626 * Get group creation date
628 * @param boolean $formatted Return date formatted, raw if false
632 public function getCreationDate($formatted = true)
634 if ($formatted === true) {
635 $date = new \
DateTime($this->creation_date
);
636 return $date->format(__("Y-m-d"));
638 return $this->creation_date
;
645 * @param boolean $force Force members load, defaults to false
649 public function getMemberCount($force = false)
651 if (isset($this->members
) && is_array($this->members
)) {
652 return count($this->members
);
653 } elseif (isset($this->count_members
)) {
654 return $this->count_members
;
656 if ($force === true) {
657 return count($this->getMembers());
667 * @param string $name Group name
671 public function setName($name)
673 $this->group_name
= $name;
678 * check if can Set parent group
680 * @param Group $group Parent group
684 public function canSetParentGroup(Group
$group)
687 if ($group->getId() == $this->getId()) {
690 } while ($group = $group->getParentGroup());
692 //@phpstan-ignore-next-line
699 * @param int $id Parent group identifier
703 public function setParentGroup($id)
705 $group = new Group((int)$id);
707 if (!$this->canSetParentGroup($group)) {
708 //does not seem to work :/
709 throw new \
Exception(
711 _T('Group `%1$s` cannot be set as parent!'),
717 $this->parent_group
= $group;
724 * @param Adherent[] $members Members list
729 public function setMembers(array $members = []): bool
734 $zdb->connection
->beginTransaction();
736 //first, remove current groups members
737 $delete = $zdb->delete(self
::GROUPSUSERS_TABLE
);
738 $delete->where([self
::PK
=> $this->id
]);
739 $zdb->execute($delete);
742 'Group members has been removed for `' . $this->group_name
.
743 '`, we can now store new ones.',
747 $insert = $zdb->insert(self
::GROUPSUSERS_TABLE
);
750 self
::PK
=> ':group',
751 Adherent
::PK
=> ':adh'
755 $stmt = $zdb->sql
->prepareStatementForSqlObject($insert);
757 foreach ($members as $m) {
758 $result = $stmt->execute(
760 'group' => $this->id
,
767 'Member `' . $m->sname
. '` attached to group `' .
768 $this->group_name
. '`.',
773 'An error occurred trying to attach member `' .
774 $m->sname
. '` to group `' . $this->group_name
.
775 '` (' . $this->id
. ').',
778 throw new \
Exception(
779 'Unable to attach `' . $m->sname
. '` ' .
780 'to ' . $this->group_name
. '(' . $this->id
. ')'
786 $zdb->connection
->commit();
789 'Group members updated successfully.',
794 } catch (Throwable
$e) {
796 $zdb->connection
->rollBack();
799 $messages[] = $e->getMessage();
800 } while ($e = $e->getPrevious());
802 'Unable to attach members to group `' . $this->group_name
.
803 '` (' . $this->id
. ')|' . implode("\n", $messages),
813 * @param Adherent[] $members Managers list
818 public function setManagers(array $members = []): bool
823 $zdb->connection
->beginTransaction();
825 //first, remove current groups managers
826 $delete = $zdb->delete(self
::GROUPSMANAGERS_TABLE
);
827 $delete->where([self
::PK
=> $this->id
]);
828 $zdb->execute($delete);
831 'Group managers has been removed for `' . $this->group_name
.
832 '`, we can now store new ones.',
836 $insert = $zdb->insert(self
::GROUPSMANAGERS_TABLE
);
839 self
::PK
=> ':group',
840 Adherent
::PK
=> ':adh'
844 $stmt = $zdb->sql
->prepareStatementForSqlObject($insert);
846 foreach ($members as $m) {
847 $result = $stmt->execute(
849 'group' => $this->id
,
856 'Manager `' . $m->sname
. '` attached to group `' .
857 $this->group_name
. '`.',
862 'An error occurred trying to attach manager `' .
863 $m->sname
. '` to group `' . $this->group_name
.
864 '` (' . $this->id
. ').',
867 throw new \
Exception(
868 'Unable to attach `' . $m->sname
. '` ' .
869 'to ' . $this->group_name
. '(' . $this->id
. ')'
875 $zdb->connection
->commit();
878 'Groups managers updated successfully.',
883 } catch (Throwable
$e) {
885 $zdb->connection
->rollBack();
888 $messages[] = $e->getMessage();
889 } while ($e = $e->getPrevious());
891 'Unable to attach managers to group `' . $this->group_name
.
892 '` (' . $this->id
. ')|' . implode("\n", $messages),
902 * @param Login $login Login instance
906 public function setLogin(Login
$login)
908 $this->login
= $login;
913 * Can current logged-in user edit group
915 * @param Login $login Login instance
919 public function canEdit(Login
$login): bool
923 //admin and staff users can edit
924 if ($login->isAdmin() ||
$login->isStaff()) {
928 //group managers can edit groups they manage when pref is on
929 if ($preferences->pref_bool_groupsmanagers_edit_groups
&& $this->isManager($login)) {