From d31b110946769bafc32dd5f1ce7e0022f5e08159 Mon Sep 17 00:00:00 2001
From: Yannick Cordel <cordel5@univ-lorraine.fr>
Date: Thu, 27 Jun 2024 15:35:59 +0200
Subject: [PATCH] Gestion groupes Moodle<>Mahara

---
 archive.php                            |  80 ++++++++
 block_mahara_iena.php                  |  21 +-
 classes/table/archive.php              | 101 ++++++++++
 classes/table/groups.php               | 133 ++++++++++++
 entity/block_mahara_iena_connexion.php |  30 ++-
 lang/en/block_mahara_iena.php          |   6 +-
 lang/fr/block_mahara_iena.php          |  10 +-
 mahara_iena_archive.php                |  85 ++++++++
 mahara_iena_groups.php                 |  44 ++--
 mahara_iena_manage.php                 | 269 ++++++++++++-------------
 renderer.php                           |   3 +
 templates/groups_action_menu.mustache  |  31 +++
 12 files changed, 636 insertions(+), 177 deletions(-)
 create mode 100644 archive.php
 create mode 100644 classes/table/archive.php
 create mode 100644 classes/table/groups.php
 create mode 100644 mahara_iena_archive.php
 create mode 100644 templates/groups_action_menu.mustache

diff --git a/archive.php b/archive.php
new file mode 100644
index 0000000..8f8ced3
--- /dev/null
+++ b/archive.php
@@ -0,0 +1,80 @@
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * Wrapper script redirecting user operations to correct destination.
+ *
+ * @copyright 1999 Martin Dougiamas  http://dougiamas.com
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ * @package core_user
+ */
+
+//require_once("../config.php");
+//require_once($CFG->dirroot . '/course/lib.php');
+
+require_once("../../config.php");
+require_once ('entity/block_mahara_iena_connexion.php');
+
+global $DB;
+
+if (!confirm_sesskey()) {
+    throw new \moodle_exception('confirmsesskeybad');
+}
+
+$returnurl = $_POST['returnto'];
+$manage = $_POST['manage'];
+$connexion = new block_mahara_iena_connexion($CFG->wstoken, $CFG->base_mahara);
+$moodle_course = get_course($_POST['courseid']);
+
+$groupsids = [];
+foreach ($_POST as $k => $v) {
+    if (preg_match('/^groups(\d+)$/', $k, $m)) {
+        $groupids[] = $m[1];
+    }
+}
+
+[$insql, $inparams] = $DB->get_in_or_equal($groupids);
+$sql = "SELECT *
+        FROM {block_mahara_iena}
+        WHERE id $insql";
+$rs = $DB->get_recordset_sql($sql, $inparams);
+foreach ($rs as $group) {
+    //active = 0
+    $group->active = 0;
+    $DB->update_record('block_mahara_iena', $group);
+    
+    if ($manage == 0) {
+        //mahara group rename
+        $groupname = $moodle_course->fullname . "_archive_" . date("Ymd_His");
+        $connexion->archiveMaharaGroup($group->mahara_group_id, $groupname);
+        $returnurl .= '&manage=0';
+    } else if ($manage == 1) {
+        //moodle group rename
+        $moodle_group = $DB->get_record('groups', array('id' => $group->moodle_group_id));
+        $moodle_group->name = $moodle_group->name . "_archive_" . date("Ymd_His");
+        $moodle_group->idnumber = $moodle_group->idnumber . "_archive_" . date("Ymd_His");
+        $DB->update_record('groups', $moodle_group);
+        cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($_POST['courseid']));
+        
+        //mahara group rename
+        $connexion->archiveMaharaGroup($group->mahara_group_id, $moodle_course->fullname . " - " . $moodle_group->name);
+        $returnurl .= '&manage=1';
+    }
+
+}
+$rs->close();
+
+redirect($returnurl, get_string("archived_groups", "block_mahara_iena"));
\ No newline at end of file
diff --git a/block_mahara_iena.php b/block_mahara_iena.php
index 40ddfb4..3604a06 100644
--- a/block_mahara_iena.php
+++ b/block_mahara_iena.php
@@ -52,16 +52,13 @@ class block_mahara_iena extends block_base
 		require_once ('entity/block_mahara_iena_connexion.php');
 		$connexion = new block_mahara_iena_connexion($CFG->wstoken,$CFG->base_mahara);
 		$is_mahara_user = $connexion->ensure_user_exists_in_mahara($USER);
-		$result = $DB->get_records_sql('SELECT * FROM {block_mahara_iena} WHERE course = ?', array($COURSE->id));
-
-		// var_dump($result);
+		$result = $DB->get_records_sql('SELECT * FROM {block_mahara_iena} WHERE active = 1 AND course = ?', array($COURSE->id));
 
 		// for teachers
 		if (has_capability('moodle/course:update', $context = context_course::instance($COURSE->id), $USER->id)) {
 
 			// if block is not instanciated, propose du create mahara group(s) for this course
 			if (count($result) == 0 && $is_mahara_user) {
-
 				// create one mahara group for the course
 				$this->content->text = '<a href="' . $CFG->wwwroot . '/blocks/mahara_iena/mahara_iena.php?courseid='
 				. $COURSE->id . '" class="btn btn-block btn-primary iena-btn-big">' . get_string('create_group', 'block_mahara_iena', $CFG->mahara_alias) . '</a><p class="text-muted">Créer un groupe dans '.$CFG->mahara_alias.'.</p>';
@@ -134,12 +131,14 @@ class block_mahara_iena extends block_base
 				/* pour chaque groupe moodle de l'utilisateur */
 				foreach ($user_groups[0] as $user_group) {
 					$mo_ma_exists = false;
+
 					/* pour chaque association existante */
 					foreach ($result as $mo_ma) {
 						/* si le groupe moodle est associé à un groupe mahara */
+
 						if ( $mo_ma->moodle_group_id == $user_group ) {
 							/* stocker le nom du groupe moodle et l'id du groupe mahara */
-							$ma_links[] = ["mo_gr_name" => groups_get_group_name($user_group), "mo_gr_id" => $user_group, "ma_group_id" => $mo_ma->mahara_group_id];
+							$ma_links[] = ["mo_gr_name" => groups_get_group_name($user_group), "mo_gr_id" => $user_group, "ma_group_id" => $mo_ma->mahara_group_id, "active" => $mo_ma->active];
 							$mo_ma_exists = true;
 						}
 					}
@@ -147,12 +146,13 @@ class block_mahara_iena extends block_base
 					if ( $mo_ma_exists == false ) {
 						/* stocker le nom du groupe moodle et un id vide du groupe mahara : le linker créera le groupe */
 						$ma_links[] = ["mo_gr_name" => groups_get_group_name($user_group), "mo_gr_id" => $user_group, "ma_group_id" => ""];
-					}
+					}						
+
 				}
 
 				/* afficher la liste des groupes s'il y en a (on est déjà dans une condition où il y en a toujours en théorie) */
 				if ( count($ma_links) != 0 ) {
-					if ( count($ma_links) == 1 ) {
+					if ( count($ma_links) == 1) {
 						/* si il n'y a qu'un groupe, on affiche un bouton */
 						$this->content->text = "<a target='_blank' class='btn btn-block btn-primary iena-btn-big' href='$CFG->wwwroot/blocks/mahara_iena/mahara_iena_link.php?courseid=$COURSE->id&mahara_group=" . $ma_links[0]['ma_group_id'] . "&moodle_group=" . $ma_links[0]['mo_gr_id'] . "'>Aller à mon groupe sur ".$CFG->mahara_alias."</a><p class='alert alert-secondary'>Mon groupe : ".$ma_links[0]['mo_gr_name'].".</p>";
 					} elseif ( count($ma_links) > 1 && count($ma_links) <= 5 ) {
@@ -160,7 +160,9 @@ class block_mahara_iena extends block_base
 						$this->content->text = "<p style='border-left: 2px solid #1177d1;padding-left: 0.5rem;font-weight: 600;margin-bottom: 0.5rem;'>Accéder à mon groupe sur $CFG->mahara_alias&nbsp;: </p>
 						<ul class='iena-dashed p-l-0'>";
 						foreach ($ma_links as $ma_link) {
+							if (isset($ma_link["active"]) && $ma_link["active"] == 1){
 							$this->content->text .= "<li>Groupe : <a target='_blank' href='$CFG->wwwroot/blocks/mahara_iena/mahara_iena_link.php?courseid=$COURSE->id&mahara_group=" . $ma_link['ma_group_id'] . "&moodle_group=" . $ma_link['mo_gr_id'] . "'>" . $ma_link['mo_gr_name'] . "</a></li>";
+							}
 						}
 						$this->content->text .= "</ul>";
 					} elseif ( count($ma_links) > 5 ) {
@@ -184,11 +186,16 @@ class block_mahara_iena extends block_base
 			} else {
 				/* quand un seul groupe mahara pour tout le cours ($hasgroup à false) */
 				$this->content->text = "<a target='_blank' class='btn btn-block btn-primary iena-btn-big' href='$CFG->wwwroot/blocks/mahara_iena/mahara_iena_link.php?courseid=$COURSE->id&mahara_group=" . reset($result)->mahara_group_id . "&moodle_group=nogroups'>Aller au groupe sur ".$CFG->mahara_alias."</a>";
+				if (has_capability('moodle/course:update', $context = context_course::instance($COURSE->id), $USER->id)) {
+					$this->content->text .= "<a class='btn btn-block btn-secondary iena-btn-big' href='$CFG->wwwroot/blocks/mahara_iena/mahara_iena_manage.php?courseid=$COURSE->id&manage=0'>".get_string('manage_groups', 'block_mahara_iena')."</a>";
+				}
 			}
 			/* permet à l'enseignant de créer tous les groupes mahara en fonction des groupes moodle existant à un temps t. Ca n'inscrit pas les utilisateurs à part lui. */
 			if ( $has_groups && has_capability('moodle/course:update', $context = context_course::instance($COURSE->id), $USER->id) ) {
 				$this->content->text .= '<a id="create_all_groups" href="'.$CFG->wwwroot . '/blocks/mahara_iena/mahara_iena_groups_all.php?courseid=' . $COURSE->id . '&create_all_groups=1" class="btn btn-block btn-warning iena-btn-big">Créer tous les groupes</a><p class="text-muted">Créer manuellement tous les groupes sur '.$CFG->mahara_alias.' liés à ce cours et s\'y inscrire en tant qu\'enseignant.</p>';
 				$this->content->text .= "<script>document.getElementById('create_all_groups').onclick = function (e) {e.preventDefault(); var confirm_cr_gr = confirm('ATTENTION ! Voulez-vous vraiment créer manuellement tous les groupes liés à ce cours ET VOUS Y INSCRIRE ? Attention, vous serez inscrit dans tous les groupes. Si vous ne créez pas les groupes, ils seront créé automatiquement la première fois que un des membres de chaque groupe y accèdera. '); if (confirm_cr_gr) { window.location.href = e.target.href; } };</script>";
+				$this->content->text .=  "<p><a class='btn btn-block btn-secondary iena-btn-big' href='$CFG->wwwroot/blocks/mahara_iena/mahara_iena_manage.php?courseid=$COURSE->id&manage=1'>".get_string('manage_groups', 'block_mahara_iena')."</a></p>";
+
 				// $this->content->text .= '<a href="'.$CFG->wwwroot . '/blocks/mahara_iena/mahara_iena_groups_all.php?courseid=' . $COURSE->id . '" class="btn btn-block btn-warning iena-btn-big">S\'inscrire dans tous les groupes</a><p class="text-muted">S\'inscrire en tant qu\'enseignant dans tous les groupes '.$CFG->mahara_alias.' liés à ce cours.</p>';
 
 				/* POUR PLUS TARD : liste les groupes moodle liés à mahara qui n'existent plus dans moodle */
diff --git a/classes/table/archive.php b/classes/table/archive.php
new file mode 100644
index 0000000..2970276
--- /dev/null
+++ b/classes/table/archive.php
@@ -0,0 +1,101 @@
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * Contains the class used for the displaying the participants table.
+ *
+ * @package    block_mahara_iena
+ * @copyright  2024 Université de Lorraine
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+namespace block_mahara_iena\table;
+
+defined('MOODLE_INTERNAL') || die;
+
+require_once($CFG->libdir . '/tablelib.php');
+
+
+/**
+ * Class for the displaying the groups table.
+ *
+ * @package    block_mahara_iena
+ * @copyright  2024 Université de Lorraine
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class archive extends \table_sql {
+
+
+    public function out($pagesize, $useinitialsbar, $downloadhelpbutton='') {
+        global $OUTPUT;
+
+        $headers = [];
+        $columns = [];
+
+        $headers[] = get_string('idnumber');
+        $columns[] = 'id';
+
+        $headers[] = get_string('course');
+        $columns[] = 'course';
+
+        $headers[] = 'mahara grp';
+        $columns[] = 'mahara_group_id';
+
+        $headers[] = 'moodle grp';
+        $columns[] = 'moodle_group_id';
+
+        $headers[] = 'active';
+        $columns[] = 'active';
+
+        $headers[] = get_string('groupname', 'group');
+        $columns[] = 'name';
+
+        
+        $this->define_headers($headers);
+        $this->define_columns($columns);
+
+        //$this->sortable(true, 'name');
+        $this->column_style('id', 'display', 'none');
+        $this->column_style('course', 'display', 'none');
+        $this->column_style('mahara_group_id', 'display', 'none');
+        $this->column_style('moodle_group_id', 'display', 'none');
+        $this->column_style('active', 'display', 'none');
+
+        $this->pagesize = $pagesize;
+        $this->setup();
+        $this->query_db($pagesize, $useinitialsbar);
+
+        $this->build_table();
+        $this->close_recordset();
+        $this->finish_output();  
+
+    }
+    /**
+     * Generate the fullname column.
+     *
+     * @param \stdClass $data
+     * @return string
+     */
+    public function col_name($data) {
+        global $CFG;
+
+        $data->name = '<a href="'. $CFG->base_mahara .'group/view.php?id=' . $data->mahara_group_id . '" target="_blank">' . $data->name . '</a>';
+
+        return $data->name;
+    }
+
+}
+
diff --git a/classes/table/groups.php b/classes/table/groups.php
new file mode 100644
index 0000000..1d738e7
--- /dev/null
+++ b/classes/table/groups.php
@@ -0,0 +1,133 @@
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * Contains the class used for the displaying the participants table.
+ *
+ * @package    block_mahara_iena
+ * @copyright  2024 Université de Lorraine
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+namespace block_mahara_iena\table;
+
+defined('MOODLE_INTERNAL') || die;
+
+require_once($CFG->libdir . '/tablelib.php');
+
+
+/**
+ * Class for the displaying the groups table.
+ *
+ * @package    block_mahara_iena
+ * @copyright  2024 Université de Lorraine
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class groups extends \table_sql {
+
+
+    public function out($pagesize, $useinitialsbar, $downloadhelpbutton='') {
+        global $OUTPUT;
+
+        $headers = [];
+        $columns = [];
+
+        // At the very least, the user viewing this table will be able to use bulk actions, so add 'select' column.
+        $checkbox = new \core\output\checkbox_toggleall('groups-table', true, [
+            'id' => 'select-all-groups',
+            'name' => 'select-all-groups',
+            'label' => get_string('selectall'),
+            'labelclasses' => 'sr-only',
+            'classes' => 'm-1',
+            'checked' => false,
+        ]);
+        $headers[] = $OUTPUT->render($checkbox);
+        $columns[] = 'select';
+
+        $headers[] = get_string('idnumber');
+        $columns[] = 'id';
+
+        $headers[] = get_string('course');
+        $columns[] = 'course';
+
+        $headers[] = 'mahara grp';
+        $columns[] = 'mahara_group_id';
+
+        $headers[] = 'moodle grp';
+        $columns[] = 'moodle_group_id';
+
+        $headers[] = 'active';
+        $columns[] = 'active';
+
+        $headers[] = get_string('groupname', 'group');
+        $columns[] = 'name';
+
+        
+        $this->define_headers($headers);
+        $this->define_columns($columns);
+
+        //$this->sortable(true, 'name');
+        $this->no_sorting('select');        
+        $this->column_class('select', 'col-select');
+        $this->column_style('id', 'display', 'none');
+        $this->column_style('course', 'display', 'none');
+        $this->column_style('mahara_group_id', 'display', 'none');
+        $this->column_style('moodle_group_id', 'display', 'none');
+        $this->column_style('active', 'display', 'none');
+
+        $this->pagesize = $pagesize;
+        $this->setup();
+        $this->query_db($pagesize, $useinitialsbar);
+
+        $this->build_table();
+        $this->close_recordset();
+        $this->finish_output();  
+
+    }
+    /**
+     * Generate the fullname column.
+     *
+     * @param \stdClass $data
+     * @return string
+     */
+    public function col_name($data) {
+        return $data->name;
+    }
+
+
+    /**
+     * Generate the select column.
+     *
+     * @param \stdClass $data
+     * @return string
+     */
+    public function col_select($data) {
+        global $OUTPUT;
+
+        $checkbox = new \core\output\checkbox_toggleall('groups-table', false, [
+            'classes' => 'groupscheckbox m-1',
+            'id' => 'groups' . $data->id,
+            'name' => 'groups' . $data->id,
+            'checked' => false,
+            'label' => get_string('selectitem', 'moodle', fullname($data)),
+            'labelclasses' => 'accesshide',
+        ]);
+
+        return $OUTPUT->render($checkbox);
+    }
+
+}
+
diff --git a/entity/block_mahara_iena_connexion.php b/entity/block_mahara_iena_connexion.php
index 94db262..1018e14 100644
--- a/entity/block_mahara_iena_connexion.php
+++ b/entity/block_mahara_iena_connexion.php
@@ -401,8 +401,31 @@ class block_mahara_iena_connexion
 	 * @param  [type] $courseId      [description]
 	 * @return [type]                [description]
 	 */
-	public function archiveMaharaGroup($maharaGroupId, $courseId){
-		return true;
+	public function archiveMaharaGroup($groupid, $groupname){
+		global $COURSE;
+
+		$course_name=block_mahara_iena_getCourseName($COURSE->shortname);
+
+		$group = new stdClass();
+		$group->id = $groupid;
+		$group->name = $groupname;
+		$group->description = $course_name . " – " . $groupname;
+
+		$params = array (
+			'groups' =>
+			array (
+				0 => $group
+			)
+		);
+		$params = http_build_query($params);
+		$mahara_group_update_groups = "mahara_group_update_groups_details";
+		$url = $this->create_url($mahara_group_update_groups);
+		$res = json_decode($this->httpPost($params, $url), true);
+		if (isset($res->error)) {
+			return false;
+		} else {
+			return true;
+		}
 	}	
 
 	/**
@@ -430,6 +453,7 @@ class block_mahara_iena_connexion
 				'role' => "admin",
 			));
 		}
+
 		$courseName=block_mahara_iena_getCourseName($courseShortName);
 		//All params used for mahara_group_create_groups her we can add/change some lines
 		$params = array (
@@ -468,7 +492,7 @@ class block_mahara_iena_connexion
 		$msg="";
 		// '@' is use because json_decode some time cause fatal error
 		$data=$this->createCourseGroupRequest($maharaUser, $COURSE->shortname, $CFG->instution_mahara);
-		$result = $DB->get_records_sql('SELECT * FROM {block_mahara_iena} WHERE course = ?', array($COURSE->id));
+		$result = $DB->get_records_sql('SELECT * FROM {block_mahara_iena} WHERE active = 1 AND course = ?', array($COURSE->id));
 		// IF json_decode fail we stop all
 		if ($data == null){
 			$msg = 'error';
diff --git a/lang/en/block_mahara_iena.php b/lang/en/block_mahara_iena.php
index 2ba8186..d8581a7 100644
--- a/lang/en/block_mahara_iena.php
+++ b/lang/en/block_mahara_iena.php
@@ -24,5 +24,9 @@
     $string['err_no_stud'] = 'You have to enrol users in this course before to create a {$a} group. ';
     $string['course_group'] = 'Group for course';
     $string['bulk_group_confirmation'] = 'Group creation succeed. ';
-
+    $string['manage_groups'] = 'Manage groups';
+    $string['manage_title'] = 'Managing groups linked to this course on {$a}.';
+    $string['archive_groups'] = 'Archive groups {$a}';
+    $string['archive'] = 'Archived groups';
+    $string['archived_groups'] = 'Group(s) archived';
 ?>
\ No newline at end of file
diff --git a/lang/fr/block_mahara_iena.php b/lang/fr/block_mahara_iena.php
index f9010cb..14eb46e 100644
--- a/lang/fr/block_mahara_iena.php
+++ b/lang/fr/block_mahara_iena.php
@@ -24,9 +24,9 @@
     $string['err_no_stud'] = 'Vous devez inscrire des utilisateurs dans le cours avant de créer un groupe {$a}. ';
     $string['course_group'] = 'Groupe du cours';
     $string['bulk_group_confirmation'] = 'Les groupes ont bien été créés. ';
-
-
-
-
-
+    $string['manage_groups'] = 'Gérer les groupes';
+    $string['manage_title'] = 'Gestion des groupes liés à ce cours sur {$a}.';
+    $string['archive_groups'] = 'Archiver les groupes {$a}';
+    $string['archive'] = 'Groupes archivés';
+    $string['archived_groups'] = 'Groupe(s) archivé(s)';
 ?>
\ No newline at end of file
diff --git a/mahara_iena_archive.php b/mahara_iena_archive.php
new file mode 100644
index 0000000..19fab34
--- /dev/null
+++ b/mahara_iena_archive.php
@@ -0,0 +1,85 @@
+<?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * @package    block_mahara_iena
+ * @copyright  2024 Université de Lorraine
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+use core\output\select_menu;
+use core_completion\manager;
+
+require_once(dirname(__FILE__) . '/../../config.php');
+require_once ($CFG->dirroot . '/blocks/mahara_iena/entity/block_mahara_iena_connexion.php');
+require "$CFG->libdir/tablelib.php";
+
+$courseid = required_param('courseid', PARAM_INT);
+$manage = required_param('manage', PARAM_INT);
+$course = get_course($courseid);
+
+require_course_login($course, false);
+$coursecontext = context_course::instance($course->id);
+$PAGE->set_context($coursecontext);
+$PAGE->set_url(new moodle_url('/blocks/mahara_iena/mahara_iena_manage.php', array('courseid' => $course->id)));
+
+$PAGE->set_pagelayout('base');
+$pagetitle = get_string('manage_title', 'block_mahara_iena', $CFG->mahara_alias);
+$PAGE->set_title($pagetitle);
+$PAGE->set_heading($OUTPUT->heading($COURSE->fullname, 2, 'headingblock header outline'));
+$returnurl = $CFG->wwwroot . '/course/view.php?id=' . $course->id;
+
+$course_groups = groups_get_all_groups($COURSE->id);
+
+$data = array(
+    'course' => $course->id,
+    'groups' => $course_groups
+);
+
+echo $OUTPUT->header();
+
+$selectmenu = new stdClass;
+$activelink = new moodle_url('/blocks/mahara_iena/mahara_iena_archive.php', array('courseid' => $course->id, 'manage' => $manage)) ;
+$link = new moodle_url('/blocks/mahara_iena/mahara_iena_manage.php', array('courseid' => $course->id, 'manage' => $manage));
+$selectmenu->activelink = $activelink->out(false);
+$selectmenu->activelabel = get_string('archive', 'block_mahara_iena');
+$selectmenu->link = $selectmenu->activelink = $link->out(false);
+$selectmenu->label = get_string('groups', 'group');
+
+$renderer = $PAGE->get_renderer('block_mahara_iena');
+$renderer->get_groups_action_menu($selectmenu);
+
+$grouptable = new \block_mahara_iena\table\archive("archivetable-{$course->id}");
+
+$grouptable->define_baseurl($PAGE->url);
+
+if ($manage == 0) {
+  $fields = 'm.id, m.course, m.mahara_group_id, m.moodle_group_id, m.active, c.fullname as name';
+  $from = '{block_mahara_iena} m LEFT JOIN {course} c on c.id = m.course';
+  $where = 'm.active = 0 AND m.course = :courseid';
+  $grouptable->set_sql($fields, $from, $where, array('courseid' => $COURSE->id));
+} else if ($manage == 1) {
+  $fields = 'm.id, m.course, m.mahara_group_id, m.moodle_group_id, m.active, g.name';
+  $from = '{block_mahara_iena} m LEFT JOIN {groups} g on g.id = m.moodle_group_id';
+  $where = 'm.active = 0 AND g.courseid = :courseid';
+  $grouptable->set_sql($fields, $from, $where, array('courseid' => $COURSE->id));
+} else {
+  throw new \moodle_exception('invalidarguments');
+}
+
+$grouptable->out(20, true);
+
+echo $OUTPUT->footer();
\ No newline at end of file
diff --git a/mahara_iena_groups.php b/mahara_iena_groups.php
index 56cef83..1a97fbe 100644
--- a/mahara_iena_groups.php
+++ b/mahara_iena_groups.php
@@ -48,9 +48,14 @@ if (count($students) == 0) {
 	$user_group_ids = groups_get_user_groups($COURSE->id, $USER->id)[0];
 
 	foreach ($groups as $group) {
+		$archive = $DB->get_record('block_mahara_iena', array('moodle_group_id' => $group->id));
+		$archived = false;
+		if ($archive && $archive->active == 0) {
+			$archived = true;
+		}
 
 		// if current group id is not in USER group ids : skip this group
-		if ( !in_array($group->id, $user_group_ids) ) {
+		if ( !in_array($group->id, $user_group_ids)) {
 			continue;
 		}
 
@@ -75,22 +80,25 @@ if (count($students) == 0) {
 			continue;
 		}
 
-		$course_name=block_mahara_iena_getCourseName($COURSE->shortname);
-		array_push($mahara_groups, array(
-			'name' =>$course_name . " – " . $group->name,
-			'description' => get_string('course_group', 'block_mahara_iena') . " " . $course_name . " – " . $group->name,
-			'grouptype' => 'course',
-			'request' => true,
-			'public' => false,
-			'institution' => $CFG->instution_mahara,
-			'members' => $usersTab,
-			'editroles' => 'all'
-		));
-
-		array_push($name_groups, array(
-			"group_id" => $group->id,
-			"group_name" => $course_name . " – " . $group->name,
-		));
+		if (!$archived) {
+			$course_name=block_mahara_iena_getCourseName($COURSE->shortname);
+			array_push($mahara_groups, array(
+				'name' =>$course_name . " – " . $group->name,
+				'description' => get_string('course_group', 'block_mahara_iena') . " " . $course_name . " – " . $group->name,
+				'grouptype' => 'course',
+				'request' => true,
+				'public' => false,
+				'institution' => $CFG->instution_mahara,
+				'members' => $usersTab,
+				'editroles' => 'all'
+			));
+
+			array_push($name_groups, array(
+				"group_id" => $group->id,
+				"group_name" => $course_name . " – " . $group->name,
+				"active" => $archived
+			));
+		}
 	}
 
 	if ( count($mahara_groups) == 0 ) {
@@ -106,7 +114,7 @@ if (count($students) == 0) {
 		$resultPost = $connexion->httpPost($params, $murl);
 	// '@' is use because json_decode some time cause fatal error
 		$data = @json_decode($resultPost);
-		$result = $DB->get_records_sql('SELECT * FROM {block_mahara_iena} WHERE course = ?', array($COURSE->id));
+		$result = $DB->get_records_sql('SELECT * FROM {block_mahara_iena} WHERE active=1 AND course = ?', array($COURSE->id));
 	// IF json_decode fail we stop all
 		if ($data == null){
 			echo 'error';
diff --git a/mahara_iena_manage.php b/mahara_iena_manage.php
index ce5028f..ae068d7 100644
--- a/mahara_iena_manage.php
+++ b/mahara_iena_manage.php
@@ -1,159 +1,142 @@
 <?php
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * @package    block_mahara_iena
+ * @copyright  2024 Université de Lorraine
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+use core\output\select_menu;
+use core_completion\manager;
+
+require_once(dirname(__FILE__) . '/../../config.php');
+require_once ($CFG->dirroot . '/blocks/mahara_iena/entity/block_mahara_iena_connexion.php');
+require "$CFG->libdir/tablelib.php";
 
-require_once('../../config.php');
-require_once ('entity/block_mahara_iena_connexion.php');
-
-global $COURSE, $DB, $USER, $CFG;
 
 $courseid = required_param('courseid', PARAM_INT);
-$url = new moodle_url('/blocks/mahara_iena/mahara_iena_manage.php', array('courseid' => $courseid));
-
-$PAGE->set_pagelayout('course');
-$PAGE->set_url($url);
+$manage = required_param('manage', PARAM_INT);
+$course = get_course($courseid);
 
-$course = $DB->get_record('course', array('id'=>$courseid), '*', MUST_EXIST);
-require_login($course, false, NULL);
+require_course_login($course, false);
+$coursecontext = context_course::instance($course->id);
+$PAGE->set_context($coursecontext);
+$PAGE->set_url(new moodle_url('/blocks/mahara_iena/mahara_iena_manage.php', array('courseid' => $course->id)));
 
-$context = context_course::instance($courseid);
+require_capability('moodle/course:update', $coursecontext);
 
-if (!has_capability('moodle/course:update', $context, $USER->id)) {
-    header("Location: {$_SERVER['HTTP_REFERER']}");
-    exit;
-}
 
-$page_title = "Gestion des groupes liés à ce cours sur " . $CFG->mahara_alias;
-$PAGE->set_title($page_title);
+$PAGE->set_pagelayout('base');
+$pagetitle = get_string('manage_title', 'block_mahara_iena', $CFG->mahara_alias);
+$PAGE->set_title($pagetitle);
 $PAGE->set_heading($OUTPUT->heading($COURSE->fullname, 2, 'headingblock header outline'));
+$returnurl = $CFG->wwwroot . '/course/view.php?id=' . $course->id;
 
-$connexion = new block_mahara_iena_connexion($CFG->wstoken, $CFG->base_mahara);
-
-echo $OUTPUT->header();
-
-
-
-/* Liste des liaisons moodle mahara en base. */
-$mo_ma_groups = $DB->get_records_sql('SELECT * FROM {block_mahara_iena} WHERE course = ?', array($COURSE->id));
-/* Tous les groupes moodle. */
 $course_groups = groups_get_all_groups($COURSE->id);
-/* Table d'affichage des informations. */
-$archived_groups=[];
-$course_group=[];
-$mahara_groups=[];
-
-
-foreach ($mo_ma_groups as $mo_ma_group) {
-    var_dump($mo_ma_group);
-    //Si le moodle_group_id=0 c'est une espace de cours unique
-    if($mo_ma_group->moodle_group_id ==0){
-        //Si le groupe est archivé on l'ajoute au tableau correspondant
-        if($mo_ma_group->active==0){
-            array_push($archived_groups, $mo_ma_group);
-        }
-        else{
-            $course_group=$mo_ma_group;
-        }
-        
-
-    }
-    //Si le moodle_group_id != 0 c'est un groupe associé à un groupe Mahara
-    else if(isset($course_groups[$mo_ma_group->moodle_group_id])) {
-        //Si le groupe est archivé on l'ajoute au tableau correspondant
-        if($mo_ma_group->active==0){
-            array_push($archived_groups, $mo_ma_group);
-        }
-        else{
-            $course_groups[$mo_ma_group->moodle_group_id]->mahara_group_id=$mo_ma_group->mahara_group_id;
-        }
-    }
-}
-//On va répartir les groupes dans leur onglet respectif : groupe unique (moodle_group_id 0), groupes liés (id du groupe moodle) et groupes archivés (active->0)
-/*foreach ($course_groups as $group) {
-    $group->name=groups_get_group_name($group->id);
-    $group->url=$CFG->wwwroot.'/group/group.php?courseid='.$COURSE->id.'&id='.$group->id;
-    $group->url_members=$CFG->wwwroot.'/group/group.php?courseid='.$COURSE->id.'&id='.$group->id;
-    
-    if($group->active==0){
-        array_push($archived_groups, $group);
-    }
-    else{*/
-
-        /* Détermine si le groupe moodle est lié à un groupe mahara. */
-        /*$group->mahara_group_id = false;
-        foreach ($mo_ma_groups as $mo_ma_group) {
-            if($mo_ma_group->moodle_group_id ==0){
-                $course_group=$mo_ma_group->mahara_group_id;
-            }
-            else ( $mo_ma_group->moodle_group_id == $group->id ) {
-                $group->mahara_group_id = $mo_ma_group->mahara_group_id;
-                break;
-            }
-        }
-        /* Si le groupe moodle est lié à un groupe mahara. */
-        /* Récupération sur mahara des infos de groupe. */
-        /*if ( $group->mahara_group_id ) {
-            
-            $params = array (
-                'groups' =>
-                array (
-                    0 =>
-                    array (
-                        'id' => $group->mahara_group_id
-                    )
-                )
-            );
-            $mahara_group = $connexion->getMaharaGroups($params);
-
-            //ON LAISSE CA DE COTE POUR LE MOMENT
-            /* USER membre du groupe mahara ? */
-            /*$group->is_ma_group_member = false;
-            foreach ($mahara_group[0]->members as $ma_group_member) {
-                if ( $ma_group_member->username == $USER->username ) {
-                    $group->is_ma_group_member = true;
-                }
-            }
-
-            /* Inscription ou désinscription du groupe mahara du USER. */
-            /*if ( $group->is_ma_group_member ) {
-                $group->url_link=$CFG->wwwroot."/blocks/mahara_iena/mahara_iena_link.php?courseid=$COURSE->id&connect_direct=true&mahara_group=".$mahara_group[0]->id."'>".$mahara_group[0]->name;
-                $group->mahara_group_name=$mahara_group[0]->name;
-
-            }*/
-/*      }
-    }
-}*/
-
-
-$tab = optional_param('t', 1, PARAM_INT);
-$tabs = [];
-$tab1_title="Espaces Compact par groupes";
-$tab2_title="Espace Compact unique";
-$tab3_title="Groupes archivés";
-$url="http://localhost/moodle/blocks/mahara_iena/mahara_iena_manage.php?courseid=7#tab-content";
-$tabs[] = new tabobject(1, new moodle_url($url, ['t'=>1]), $tab1_title);
-$tabs[] = new tabobject(2, new moodle_url($url, ['t'=>2]), $tab2_title);
-$tabs[] = new tabobject(3, new moodle_url($url, ['t'=>3]), $tab3_title);
-
-
-
-
-$data=array();
-$data['mahara_alias']=$CFG->mahara_alias;
-$data['page_title']=$page_title;
 
+$data = array(
+    'course' => $course->id,
+    'groups' => $course_groups
+);
 
+echo $OUTPUT->header();
+
+$selectmenu = new stdClass;
+$activelink = new moodle_url('/blocks/mahara_iena/mahara_iena_manage.php', array('courseid' => $course->id, 'manage' => $manage));
+$link = new moodle_url('/blocks/mahara_iena/mahara_iena_archive.php', array('courseid' => $course->id, 'manage' => $manage)) ;
+$selectmenu->activelink = $activelink->out(false);
+$selectmenu->activelabel = get_string("groups", "group");
+$selectmenu->link = $selectmenu->activelink = $link->out(false);
+$selectmenu->label = get_string("archive", "block_mahara_iena");
 
 $renderer = $PAGE->get_renderer('block_mahara_iena');
-$renderer->get_header_manage_groups($data);
-echo $OUTPUT->tabtree($tabs, $tab);
-if ($tab == 1) {
-    $data['course_groups']=array_values($course_groups);
-    $renderer->get_manage_groups($data);
-} else if($tab == 2){
-    // Show data for course group
-    $data['course_group']=$course_group;
-    $renderer->get_manage_group($data);
-} else{
-    $data['archived_groups']=$archived_groups;
-    $renderer->get_archived_groups($data);
+$renderer->get_groups_action_menu($selectmenu);
+
+$grouptable = new \block_mahara_iena\table\groups("groupstable-{$course->id}");
+
+$grouptable->define_baseurl($PAGE->url);
+
+if ($manage == 0) {
+  $fields = 'm.id, m.course, m.mahara_group_id, m.moodle_group_id, m.active, c.fullname as name';
+  $from = '{block_mahara_iena} m LEFT JOIN {course} c on c.id = m.course';
+  $where = 'm.active = 1 AND m.course = :courseid';
+  $grouptable->set_sql($fields, $from, $where, array('courseid' => $COURSE->id));
+} else if ($manage == 1) {
+  $fields = 'm.id, m.course, m.mahara_group_id, m.moodle_group_id, m.active, g.name';
+  $from = '{block_mahara_iena} m LEFT JOIN {groups} g on g.id = m.moodle_group_id';
+  $where = 'm.active = 1 AND g.courseid = :courseid';
+  $grouptable->set_sql($fields, $from, $where, array('courseid' => $COURSE->id));
+} else {
+  throw new \moodle_exception('invalidarguments');
 }
-echo $OUTPUT->footer();
+
+echo html_writer::start_tag('form', [
+    'action' => 'archive.php',
+    'method' => 'post',
+    'id' => 'groupsform',
+    'data-course-id' => $course->id,
+    'data-table-unique-id' => $grouptable->uniqueid,
+  ]);
+
+echo html_writer::start_div();
+echo html_writer::tag('input', '',[
+    'type' => 'hidden',
+    'name' => 'sesskey',
+    'value' => sesskey()
+]);
+echo html_writer::tag('input', '',[
+    'type' => 'hidden',
+    'name' => 'manage',
+    'value' => $manage
+]);
+echo html_writer::tag('input', '',[
+    'type' => 'hidden',
+    'name' => 'returnto',
+    'value' => s($PAGE->url->out(false))
+]);
+echo html_writer::tag('input', '',[
+    'type' => 'hidden',
+    'name' => 'courseid',
+    'value' => $course->id
+]);
+
+$grouptable->out(20, true);
+
+$bulkoptions = (object) [
+  'uniqueid' => $grouptable->uniqueid,
+];
+
+echo html_writer::start_div('buttons');
+echo html_writer::start_div('form-inline');
+
+echo html_writer::tag('button', get_string('archive_groups', 'block_mahara_iena', $CFG->mahara_alias), [
+    'id' => 'formactionid',
+    'class' => 'btn btn-primary',
+    'data-action' => 'toggle',
+    'data-togglegroup' => 'groups-table',
+    'data-toggle' => 'action',
+    'disabled' => 'disabled' 
+]);
+
+echo html_writer::end_div();
+echo html_writer::end_div();
+echo html_writer::end_div();
+
+echo html_writer::end_tag('form');
+echo html_writer::end_div();
+
+echo $OUTPUT->footer();
\ No newline at end of file
diff --git a/renderer.php b/renderer.php
index e547890..bbb065a 100644
--- a/renderer.php
+++ b/renderer.php
@@ -17,5 +17,8 @@ class block_mahara_iena_renderer extends plugin_renderer_base {
     function get_archived_groups($data){
         echo $this->render_from_template('block_mahara_iena/manage_archived_groups', $data);
     }
+    function get_groups_action_menu($data){
+        echo $this->render_from_template('block_mahara_iena/groups_action_menu', $data);
+    }
 }
 
diff --git a/templates/groups_action_menu.mustache b/templates/groups_action_menu.mustache
new file mode 100644
index 0000000..841c608
--- /dev/null
+++ b/templates/groups_action_menu.mustache
@@ -0,0 +1,31 @@
+{{!
+    This file is part of Moodle - http://moodle.org/
+
+    Moodle is free software: you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation, either version 3 of the License, or
+    (at your option) any later version.
+
+    Moodle is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+}}
+<div class="tertiary-navigation full-width-bottom-border ml-0" id="tertiary-navigation">
+    <div class="row pb-3">
+        <nav class="tertiary-navigation-selector">
+            <div class="dropdown select-menu">
+            <a class="btn dropdown-toggle" href="{{activelink}}" role="button" id="dropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
+                {{activelabel}}
+            </a>
+
+            <div class="dropdown-menu" aria-labelledby="dropdownMenuLink">
+                <a class="dropdown-item" href="{{link}}">{{label}}</a>
+            </div>
+            </div>
+        </nav>
+    </div>
+</div>
\ No newline at end of file
-- 
GitLab