3 /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
10 * Copyright © 2012-2021 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-2021 The Galette Team
32 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL License 3.0 or (at your option) any later version
33 * @link http://galette.tuxfamily.org
34 * @since Available since 0.7dev - 2012-01-17
37 namespace Galette\Entity
;
40 use Galette\Core\Login
;
42 use Laminas\Db\Sql\Expression
;
50 * @author Johan Cwiklinski <johan@x-tnd.be>
51 * @copyright 2012-2021 The Galette Team
52 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL License 3.0 or (at your option) any later version
53 * @link http://galette.tuxfamily.org
54 * @since Available since 0.7dev - 2012-01-17
58 public const TABLE
= 'groups';
59 public const PK
= 'id_group';
61 public const GROUPSUSERS_TABLE
= 'groups_members';
62 public const GROUPSMANAGERS_TABLE
= 'groups_managers';
64 public const MEMBER_TYPE
= 0;
65 public const MANAGER_TYPE
= 1;
69 private $parent_group;
73 private $creation_date;
74 private $count_members;
80 * @param null|int|ResultSet $args Either a ResultSet row or its id for to load
81 * a specific group, or null to just
84 public function __construct($args = null)
86 if ($args == null ||
is_int($args)) {
87 if (is_int($args) && $args > 0) {
90 } elseif (is_object($args)) {
91 $this->loadFromRS($args);
96 * Loads a group from its id
98 * @param int $id the identifiant for the group to load
100 * @return bool true if query succeed, false otherwise
102 public function load($id)
107 $select = $zdb->select(self
::TABLE
);
108 $select->where(array(self
::PK
=> $id));
110 $results = $zdb->execute($select);
112 if ($results->count() > 0) {
113 $this->loadFromRS($results->current());
118 } catch (Throwable
$e) {
120 'Cannot load group form id `' . $id . '` | ' . $e->getMessage(),
128 * Populate object from a resultset row
130 * @param ResultSet $r the resultset row
134 private function loadFromRS($r)
136 $this->id
= $r->id_group
;
137 $this->group_name
= $r->group_name
;
138 $this->creation_date
= $r->creation_date
;
139 if ($r->parent_group
) {
140 $this->parent_group
= new Group((int)$r->parent_group
);
142 $adhpk = Adherent
::PK
;
143 if (isset($r->members
)) {
144 //we're from a list, we just want members count
145 $this->count_members
= $r->members
;
147 //we're probably from a single group, let's load sub entities
148 //$this->loadPersons(self::MEMBER_TYPE);
149 //$this->loadPersons(self::MANAGER_TYPE);
150 //$this->loadSubGroups();
155 * Loads members for the current group
157 * @param int $type Either self::MEMBER_TYPE or self::MANAGER_TYPE
161 private function loadPersons($type)
169 case self
::MEMBER_TYPE
:
170 $join = PREFIX_DB
. self
::GROUPSUSERS_TABLE
;
172 case self
::MANAGER_TYPE
:
173 $join = PREFIX_DB
. self
::GROUPSMANAGERS_TABLE
;
177 $select = $zdb->select(Adherent
::TABLE
, 'a');
180 'g.' . Adherent
::PK
. '=a.' . Adherent
::PK
,
183 'g.' . self
::PK
=> $this->id
189 $results = $zdb->execute($select);
198 foreach ($results as $m) {
199 $members[] = new Adherent($zdb, $m, $deps);
202 if ($type === self
::MEMBER_TYPE
) {
203 $this->members
= $members;
205 $this->managers
= $members;
207 } catch (Throwable
$e) {
209 'Cannot get group persons | ' . $e->getMessage(),
222 private function loadSubGroups()
226 if (!isset($this->login
) ||
!$this->login
->isLogged()) {
232 $select = $zdb->select(self
::TABLE
, 'a');
234 if (!$this->login
->isAdmin() && !$this->login
->isStaff()) {
236 array('b' => PREFIX_DB
. self
::GROUPSMANAGERS_TABLE
),
237 'a.' . self
::PK
. '=b.' . self
::PK
,
239 )->where(['b.' . Adherent
::PK
=> $this->login
->id
]);
242 $select->where(['parent_group' => $this->id
])
243 ->order('group_name ASC');
245 $results = $zdb->execute($select);
248 foreach ($results as $m) {
249 $group = new Group((int)$m->$grppk);
250 $group->setLogin($this->login
);
253 $this->groups
= $groups;
254 } catch (Throwable
$e) {
256 'Cannot get subgroup for group ' . $this->group_name
.
257 ' (' . $this->id
. ')| ' . $e->getMessage(),
265 * Remove specified group
267 * @param boolean $cascade Also remove members and managers
271 public function remove($cascade = false)
274 $transaction = false;
277 if (!$zdb->connection
->inTransaction()) {
278 $zdb->connection
->beginTransaction();
282 if ($cascade === true) {
283 $subgroups = $this->getGroups();
284 if (count($subgroups) > 0) {
286 'Cascading remove ' . $this->group_name
.
287 '. Subgroups, their members and managers will be detached.',
290 foreach ($subgroups as $subgroup) {
291 $subgroup->remove(true);
296 'Cascading remove ' . $this->group_name
.
297 '. Members and managers will be detached.',
302 $delete = $zdb->delete(self
::GROUPSUSERS_TABLE
);
303 $delete->where([self
::PK
=> $this->id
]);
304 $zdb->execute($delete);
307 $delete = $zdb->delete(self
::GROUPSMANAGERS_TABLE
);
308 $delete->where([self
::PK
=> $this->id
]);
309 $zdb->execute($delete);
312 //delete group itself
313 $delete = $zdb->delete(self
::TABLE
);
314 $delete->where([self
::PK
=> $this->id
]);
315 $zdb->execute($delete);
319 $zdb->connection
->commit();
323 } catch (Throwable
$e) {
325 $zdb->connection
->rollBack();
327 if (!$zdb->isPostgres() && $e->getCode() == 23000 ||
$zdb->isPostgres() && $e->getCode() == 23503) {
332 'Group "%group" still have members!'
336 $this->isempty
= false;
339 'Unable to delete group ' . $this->group_name
.
340 ' (' . $this->id
. ') |' . $e->getMessage(),
350 * Is group empty? (after first deletion try)
354 public function isEmpty()
356 return $this->isempty
;
360 * Detach a group from its parent
364 public function detach()
369 $update = $zdb->update(self
::TABLE
);
371 array('parent_group' => new Expression('NULL'))
373 [self
::PK
=> $this->id
]
376 $edit = $zdb->execute($update);
378 //edit == 0 does not mean there were an error, but that there
379 //were nothing to change
380 if ($edit->count() > 0) {
381 $this->parent_group
= null;
383 _T("Group has been detached from its parent"),
389 } catch (Throwable
$e) {
391 'Something went wrong detaching group `' . $this->group_name
.
392 '` (' . $this->id
. ') from its parent:\'( | ' .
393 $e->getMessage() . "\n" .
394 $e->getTraceAsString(),
406 public function store()
412 self
::PK
=> $this->id
,
413 'group_name' => $this->group_name
416 if ($this->parent_group
) {
417 $values['parent_group'] = $this->parent_group
->getId();
420 if (!isset($this->id
) ||
$this->id
== '') {
421 //we're inserting a new group
422 unset($values[self
::PK
]);
423 $this->creation_date
= date("Y-m-d H:i:s");
424 $values['creation_date'] = $this->creation_date
;
426 $insert = $zdb->insert(self
::TABLE
);
427 $insert->values($values);
428 $add = $zdb->execute($insert);
429 if ($add->count() > 0) {
430 $this->id
= $zdb->getLastGeneratedValue($this);
439 $hist->add(_T("Fail to add new group."));
440 throw new \
Exception(
441 'An error occurred inserting new group!'
445 //we're editing an existing group
446 $update = $zdb->update(self
::TABLE
);
449 ->where([self
::PK
=> $this->id
]);
451 $edit = $zdb->execute($update);
453 //edit == 0 does not mean there were an error, but that there
454 //were nothing to change
455 if ($edit->count() > 0) {
463 /** FIXME: also store members and managers? */
464 } catch (Throwable
$e) {
466 'Something went wrong :\'( | ' . $e->getMessage() . "\n" .
467 $e->getTraceAsString(),
475 * Is current logged-in user manager of the group?
477 * @param Login $login Login instance
481 public function isManager(Login
$login)
483 if ($login->isAdmin() ||
$login->isStaff()) {
484 //admins as well as staff members are managers for all groups!
487 //let's check if current logged-in user is part of group managers
488 foreach ($this->managers
as $manager) {
489 if ($login->login
== $manager->login
) {
503 public function getId()
509 * Get Level of the group
513 public function getLevel()
515 if ($this->parent_group
) {
516 return $this->parent_group
->getLevel() +
1;
522 * Get the full name of the group "foo / bar"
526 public function getFullName()
528 if ($this->parent_group
) {
529 return $this->parent_group
->getFullName() . ' / ' . $this->group_name
;
531 return $this->group_name
;
535 * Get the indented short name of the group " >> bar"
539 public function getIndentName()
541 if (($level = $this->getLevel())) {
542 return str_repeat(" ", 3 * $level) . '» ' . $this->group_name
;
544 return $this->group_name
;
552 public function getName()
554 return $this->group_name
;
562 public function getMembers()
564 if (!is_array($this->members
)) {
565 $this->loadPersons(self
::MEMBER_TYPE
);
567 return $this->members
;
571 * Get groups managers
575 public function getManagers()
577 if (!is_array($this->managers
)) {
578 $this->loadPersons(self
::MANAGER_TYPE
);
580 return $this->managers
;
588 public function getGroups()
590 if (!is_array($this->groups
)) {
591 $this->loadSubGroups();
593 return $this->groups
;
601 public function getParentGroup()
603 return $this->parent_group
;
607 * Get group creation date
609 * @param boolean $formatted Return date formatted, raw if false
613 public function getCreationDate($formatted = true)
615 if ($formatted === true) {
616 $date = new \
DateTime($this->creation_date
);
617 return $date->format(__("Y-m-d"));
619 return $this->creation_date
;
626 * @param boolean $force Force members load, defaults to false
630 public function getMemberCount($force = false)
632 if (isset($this->members
) && is_array($this->members
)) {
633 return count($this->members
);
634 } elseif (isset($this->count_members
)) {
635 return $this->count_members
;
637 if ($force === true) {
638 return count($this->getMembers());
648 * @param string $name Group name
652 public function setName($name)
654 $this->group_name
= $name;
661 * @param array $groups Groups id
665 public function setSubgroups($groups)
667 $this->groups
= $groups;
672 * check if can Set parent group
674 * @param Group $group Parent group
678 public function canSetParentGroup(Group
$group)
681 if ($group->getId() == $this->getId()) {
684 } while ($group = $group->getParentGroup());
692 * @param int $id Parent group identifier
696 public function setParentGroup($id)
698 $group = new Group((int)$id);
700 if (!$this->canSetParentGroup($group)) {
701 //does not seem to work :/
702 throw new \
Exception(
704 _T('Group `%1$s` cannot be set as parent!'),
710 $this->parent_group
= $group;
717 * @param Adherent[] $members Members list
721 public function setMembers($members)
726 $zdb->connection
->beginTransaction();
728 //first, remove current groups members
729 $delete = $zdb->delete(self
::GROUPSUSERS_TABLE
);
730 $delete->where([self
::PK
=> $this->id
]);
731 $zdb->execute($delete);
734 'Group members has been removed for `' . $this->group_name
.
735 '`, we can now store new ones.',
739 $insert = $zdb->insert(self
::GROUPSUSERS_TABLE
);
742 self
::PK
=> ':group',
743 Adherent
::PK
=> ':adh'
747 $stmt = $zdb->sql
->prepareStatementForSqlObject($insert);
749 if (is_array($members)) {
750 foreach ($members as $m) {
751 $result = $stmt->execute(
753 'group' => $this->id
,
760 'Member `' . $m->sname
. '` attached to group `' .
761 $this->group_name
. '`.',
766 'An error occurred trying to attach member `' .
767 $m->sname
. '` to group `' . $this->group_name
.
768 '` (' . $this->id
. ').',
771 throw new \
Exception(
772 'Unable to attach `' . $m->sname
. '` ' .
773 'to ' . $this->group_name
. '(' . $this->id
. ')'
779 $zdb->connection
->commit();
782 'Group members updated successfully.',
787 } catch (Throwable
$e) {
788 $zdb->connection
->rollBack();
791 $messages[] = $e->getMessage();
792 } while ($e = $e->getPrevious());
794 'Unable to attach members to group `' . $this->group_name
.
795 '` (' . $this->id
. ')|' . implode("\n", $messages),
805 * @param Adherent[] $members Managers list
809 public function setManagers($members)
814 $zdb->connection
->beginTransaction();
816 //first, remove current groups managers
817 $delete = $zdb->delete(self
::GROUPSMANAGERS_TABLE
);
818 $delete->where([self
::PK
=> $this->id
]);
819 $zdb->execute($delete);
822 'Group managers has been removed for `' . $this->group_name
.
823 '`, we can now store new ones.',
827 $insert = $zdb->insert(self
::GROUPSMANAGERS_TABLE
);
830 self
::PK
=> ':group',
831 Adherent
::PK
=> ':adh'
835 $stmt = $zdb->sql
->prepareStatementForSqlObject($insert);
837 if (is_array($members)) {
838 foreach ($members as $m) {
839 $result = $stmt->execute(
841 'group' => $this->id
,
848 'Manager `' . $m->sname
. '` attached to group `' .
849 $this->group_name
. '`.',
854 'An error occurred trying to attach manager `' .
855 $m->sname
. '` to group `' . $this->group_name
.
856 '` (' . $this->id
. ').',
859 throw new \
Exception(
860 'Unable to attach `' . $m->sname
. '` ' .
861 'to ' . $this->group_name
. '(' . $this->id
. ')'
867 $zdb->connection
->commit();
870 'Groups managers updated successfully.',
875 } catch (Throwable
$e) {
876 $zdb->connection
->rollBack();
879 $messages[] = $e->getMessage();
880 } while ($e = $e->getPrevious());
882 'Unable to attach managers to group `' . $this->group_name
.
883 '` (' . $this->id
. ')|' . implode("\n", $messages),
893 * @param Login $login Login instance
897 public function setLogin(Login
$login)
899 $this->login
= $login;