From ae984cfb8b30f80e7969bc447f746091fefc1d94 Mon Sep 17 00:00:00 2001
From: Elke Kreim <elke.kreim@hs-hannover.de>
Date: Wed, 29 Jan 2025 11:05:19 +0100
Subject: [PATCH] Refactoring code

---
 classes/local/exporter.php           | 195 +++++++++++++++++++++++++++
 classes/local/helpers/download.php   | 113 ----------------
 classes/local/helpers/user_query.php |  77 -----------
 download.php                         |  54 --------
 export.php                           |  28 +---
 5 files changed, 198 insertions(+), 269 deletions(-)
 create mode 100644 classes/local/exporter.php
 delete mode 100644 classes/local/helpers/download.php
 delete mode 100644 classes/local/helpers/user_query.php
 delete mode 100644 download.php

diff --git a/classes/local/exporter.php b/classes/local/exporter.php
new file mode 100644
index 0000000..3f7d44d
--- /dev/null
+++ b/classes/local/exporter.php
@@ -0,0 +1,195 @@
+<?php
+// This file is part of Moodle - https://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 <https://www.gnu.org/licenses/>.
+
+namespace local_hshexport\local;
+
+use core\context;
+
+/**
+ * Plugin version and other meta-data are defined here.
+ *
+ * @package     local_hshexport
+ * @copyright   2024 Elke Kreim elke.kreim@hs-hannover.de
+ * @license     https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+class exporter {
+
+    const ENROLEMENT_STATUS = 0;
+    const USER_DELETED = 0;
+    const USER_SUSPENDED = 0;
+    private int $courseid;
+    private string $course_code;
+    private array $roles;
+    private string $filename;
+    private string $content;
+
+
+        public function __construct($data) {
+        $this->courseid = $this->set_courseid($data);
+        $this->course_code = $this->set_course_code($data);
+        $this->roles = $this->set_roles($data);
+        $this->filename = $this->set_filename();
+        $this->content = $this->set_content();
+    }
+
+    private function set_courseid($data) {
+        if (property_exists($data, 'courseid')) {
+            return $data->courseid;
+        } else {
+            throw new \moodle_exception('Error: no course id given.');
+        }
+    }
+
+    private function set_course_code($data) {
+        if (property_exists($data, 'course_code')) {
+            return $data->course_code;
+        } else {
+            return null;
+        }
+    }
+
+    private function set_roles($data): array
+    {
+        if (property_exists($data, 'roles')) {
+            $roleids = array_filter(array_values($data->roles));
+            $roles = array_map('intval', $roleids);
+            return $roles;
+        } else {
+            return [];
+        }
+    }
+
+    private function set_content(): ?string
+    {
+        global $CFG;
+        require_once($CFG->libdir . '/csvlib.class.php');
+
+        $rows = $this->get_rows();
+        $delimiter = $this->get_delimiter();
+
+        return \csv_export_writer::print_array($rows, $delimiter, '"', true);
+    }
+
+    private function set_filename(): string 
+    {
+
+        // use course shortname if no course_code is given
+        $filename = $this->course_code;
+        if (!$filename) {
+            global $DB;
+            $course = $DB->get_record('course', ['id' => $this->courseid], '*', MUST_EXIST);
+            $context = context\course::instance($course->id, MUST_EXIST);
+
+            if ($context->contextlevel != CONTEXT_COURSE) {
+                throw new \moodle_exception('Error: this is not an appropriate course context.');
+            }
+            $filename = str_replace(',', '-', $course->shortname);
+        }
+
+        // extend filename with prefix and date
+        $filename = $this->add_prefix($filename);
+        $filename = $this->add_timestamp($filename);
+        $filename = $this->add_extension($filename);
+        return clean_filename($filename);
+    }
+
+    private function add_prefix($name): string
+    {
+        return 'TN_'.$name;
+    }
+
+    private function add_timestamp($name): string
+    {
+        return $name.'_'.gmdate("Ymd_Hi");
+    }
+
+    private function add_extension($name): string
+    {
+        return $name.'.csv';
+    }
+
+    private function get_delimiter(): string
+    {
+        return 'semicolon';
+    }
+
+    private function get_mimetype(): string
+    {
+        return 'application/download';
+    }
+
+    private function get_rows(): array
+    {
+        $users = $this->get_users_by_role();
+
+        $rows = [];
+
+        foreach ($users as $user) {
+            if ($this->course_code) {
+                $row['course_code'] = $this->course_code;
+            }
+            $row['email'] = $user->email;
+            $rows[] = $row;
+        }
+        return $rows;
+    }
+
+    private function get_users_by_role():array
+    {
+        global $DB;
+
+        $context = context\course::instance($this->courseid, MUST_EXIST);
+
+        if ($context->contextlevel != CONTEXT_COURSE) {
+            throw new \moodle_exception('invalidcontext');
+        }
+
+        [$inrolesql, $params] = $DB->get_in_or_equal($this->roles, SQL_PARAMS_NAMED);
+
+        $sql = "SELECT DISTINCT u.email 
+              FROM {user} u 
+              JOIN {role_assignments} ra ON u.id=ra.userid 
+              JOIN mdl_user_enrolments e ON e.userid=u.id 
+              JOIN mdl_role r ON ra.roleid=r.id 
+              JOIN mdl_context c ON ra.contextid=c.id 
+             WHERE c.contextlevel= :contextlevel
+                   AND e.status = :enrolment_status
+                   AND u.deleted = :user_deleted
+                   AND u.suspended = :user_suspended
+                   AND instanceid = :courseid 
+                   AND r.id {$inrolesql}";
+
+        $params['contextlevel'] = CONTEXT_COURSE;
+        $params['enrolment_status'] = self::ENROLEMENT_STATUS;
+        $params['user_deleted'] = self::USER_DELETED;
+        $params['user_suspended'] = self::USER_SUSPENDED;
+        $params['courseid'] = $this->courseid;
+
+        $users = $DB->get_records_sql($sql, $params);
+
+        return $users;
+    }
+
+    public function send_file(): void
+    {
+        global $CFG;
+        require_once($CFG->libdir.'/filelib.php');
+
+        send_file($this->content, $this->filename, null, 0, true, true,
+            $this->get_mimetype());
+    }
+}
\ No newline at end of file
diff --git a/classes/local/helpers/download.php b/classes/local/helpers/download.php
deleted file mode 100644
index 21860a2..0000000
--- a/classes/local/helpers/download.php
+++ /dev/null
@@ -1,113 +0,0 @@
-<?php
-// This file is part of Moodle - https://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 <https://www.gnu.org/licenses/>.
-
-namespace local_hshexport\local\helpers;
-
-use core\context;
-use local_hshexport\local\helpers\user_query;
-
-/**
- * Plugin version and other meta-data are defined here.
- *
- * @package     local_hshexport
- * @copyright   2024 Elke Kreim elke.kreim@hs-hannover.de
- * @license     https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
- */
-
-class download {
-    public static function get_evaluation_filename($data): string
-    {
-        global $DB;
-
-        define('FILENAME_PREFIX', 'TN_');
-
-        $courseid = $data->courseid;
-        $course = $DB->get_record('course', ['id' => $courseid], '*', MUST_EXIST);
-        $context = context\course::instance($course->id, MUST_EXIST);
-
-        if ($context->contextlevel != CONTEXT_COURSE) {
-            throw new \moodle_exception('invalidcontext');
-        }
-
-        $timestamp = download::get_file_timestamp();
-
-        // use course shortname if no course_code is given
-        $course_code = $data->course_code;
-        if ($course_code == null) {
-            $filename = str_replace(',', '-', $course->shortname);
-        } else {
-            $filename = $course_code;
-        }
-
-        // extend filename with prefix and date
-        $filename = FILENAME_PREFIX . $filename . '_' . $timestamp;
-
-        return $filename;
-    }
-
-    public static function get_file_timestamp(): string
-    {
-        $now = date_create('now');
-        $timestamp = ($now->format('Ymd'));
-
-        return $timestamp;
-    }
-
-    public static function get_rows($users, $course_code = null): array
-    {
-        if ($course_code === null) {
-            return $users;
-        }
-
-        $rows = [];
-
-        foreach ($users as $user) {
-            $row = [
-                'course_code' => $course_code,
-                'email' => $user->email
-            ];
-            array_push($rows, $row);
-        }
-        return $rows;
-    }
-
-    public static function download_csv($rows, $filename, $delimiter="comma", $enclosure='"'): void
-    {
-        global $CFG;
-        require_once($CFG->libdir.'/csvlib.class.php');
-
-        \csv_export_writer::download_array($filename, $rows, $delimiter, $enclosure);
-    }
-
-    public static function csv_file($data): void
-    {
-        global $CFG;
-        require_once($CFG->libdir.'/csvlib.class.php');
-
-        $course_code = $data->course_code;
-        if (!$course_code) {
-            $course = get_course($data->courseid);
-            $course_code = $course->shortname;
-        }
-
-        $filename = self::get_evaluation_filename($data);
-        $roles = array_filter(array_values($data->roles));
-        $roleids = array_map('intval', $roles);
-        $users = user_query::get_users_by_role($data->courseid, $data->coursecontext, $roleids);
-        $rows = self::get_rows($users, $course_code);
-        \csv_export_writer::download_array($filename, $rows, $delimiter='semicolon');
-    }
-}
\ No newline at end of file
diff --git a/classes/local/helpers/user_query.php b/classes/local/helpers/user_query.php
deleted file mode 100644
index b869165..0000000
--- a/classes/local/helpers/user_query.php
+++ /dev/null
@@ -1,77 +0,0 @@
-<?php
-// This file is part of Moodle - https://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 <https://www.gnu.org/licenses/>.
-
-/**
- * Plugin version and other meta-data are defined here.
- *
- * @package     local_hshexport
- * @copyright   2024 Elke Kreim elke.kreim@hs-hannover.de
- * @license     https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
- */
-
-namespace local_hshexport\local\helpers;
-
-use core\context;
-
-class user_query {
-
-    const ENROLEMENT_STATUS = 0;
-    const USER_DELETED = 0;
-    const USER_SUSPENDED = 0;
-
-    public static function get_users_by_role(int $courseid = 0, int $contextid = 0, array $roles = null): array
-    {
-        global $DB;
-
-        $users = [];
-
-        if ($contextid) {
-            $context = context::instance_by_id($contextid, MUST_EXIST);
-            if ($context->contextlevel != CONTEXT_COURSE) {
-                throw new \moodle_exception('invalidcontext');
-            }
-            $course = $DB->get_record('course', array('id' => $context->instanceid), '*', MUST_EXIST);
-        } else {
-            $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
-            $context = context\course::instance($course->id, MUST_EXIST);
-        }
-
-        [$inrolesql, $params] = $DB->get_in_or_equal($roles, SQL_PARAMS_NAMED);
-
-        $sql = "SELECT DISTINCT u.email 
-              FROM {user} u 
-              JOIN {role_assignments} ra ON u.id=ra.userid 
-              JOIN mdl_user_enrolments e ON e.userid=u.id 
-              JOIN mdl_role r ON ra.roleid=r.id 
-              JOIN mdl_context c ON ra.contextid=c.id 
-             WHERE c.contextlevel= :contextlevel
-                   AND e.status = :enrolment_status
-                   AND u.deleted = :user_deleted
-                   AND u.suspended = :user_suspended
-                   AND instanceid = :courseid 
-                   AND r.id {$inrolesql}";
-
-        $params['contextlevel'] = CONTEXT_COURSE;
-        $params['enrolment_status'] = self::ENROLEMENT_STATUS;
-        $params['user_deleted'] = self::USER_DELETED;
-        $params['user_suspended'] = self::USER_SUSPENDED;
-        $params['courseid'] = $courseid;
-
-        $users = $DB->get_records_sql($sql, $params);
-
-        return $users;
-    }
-}
diff --git a/download.php b/download.php
deleted file mode 100644
index c544235..0000000
--- a/download.php
+++ /dev/null
@@ -1,54 +0,0 @@
-<?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 local_hshexport
- */
-
-use local_hshexport\local\helpers\download;
-
-require(__DIR__ . '/../../config.php');
-require_once($CFG->libdir.'/csvlib.class.php');
-
-$PAGE->set_url('/local/hshexport/download.php');
-
-$course_code = optional_param('code', null, PARAM_TEXT);
-$courseid = required_param('id', PARAM_INT);
-$coursecontextid = required_param('context', PARAM_INT);
-$roles = required_param('roles', PARAM_TEXT);
-
-$coursecontext = context_course::instance($courseid);
-$PAGE->set_context($coursecontext);
-require_capability('local/hshexport:canexport', $coursecontext);
-
-$roles = json_decode(urldecode($roles));
-$roleids = array_map('intval', $roles);
-
-$filename = download::get_evaluation_filename($courseid, $course_code);
-$users = local_hshexport\local\helpers\user_query::get_users_by_role($courseid, $coursecontextid, $roles);
-
-if (!$course_code) {
-    $course = get_course($courseid);
-    $course_code = $course->shortname;
-}
-
-$rows = local_hshexport\local\helpers\download::get_rows($users, $course_code);
-
-\csv_export_writer::download_array($filename, $rows, $delimiter='semicolon');
diff --git a/export.php b/export.php
index 0e4da85..43bf12f 100644
--- a/export.php
+++ b/export.php
@@ -23,10 +23,9 @@
  */
 
 use local_hshexport\form\evaluserexportform;
-use local_hshexport\local\helpers\download;
+use local_hshexport\local\exporter;
 
 require(__DIR__ . '/../../config.php');
-require_once($CFG->libdir.'/csvlib.class.php');
 
 $courseid = required_param('id',PARAM_INT);
 
@@ -43,8 +42,6 @@ $coursecontext = context_course::instance($course->id);
 $PAGE->set_context($coursecontext);
 require_capability('local/hshexport:canexport', $coursecontext);
 
-
-
 $customdata = [
     'courseid' => $courseid,
     'coursecontext' => $coursecontext,
@@ -58,31 +55,12 @@ if ($mform->is_cancelled()) {
     $returnurl = new moodle_url('/user/index.php', ['id' => $course->id]);
     redirect($returnurl);
 } elseif ($formdata) {
-    download::csv_file($formdata);
+    $exporter = new exporter($formdata);
+    $exporter->csv_download();
 } else {
     $mform->set_data($formdata);
 }
 
-
-
-//
-//    // removes not selected roles from array
-//    $roleids = array_values(array_filter($formdata->roles));
-//    $roles_param = urlencode(json_encode($roleids));
-//
-//    $params = [
-//        'id' => $formdata->courseid,
-//        'context' => $formdata->coursecontextid,
-//        'roles' => $roles_param,
-//        'code' => $formdata->course_code
-//    ];
-//
-////    redirect(new moodle_url('/local/hshexport/download.php', $params));
-//
-//} else {
-//    $mform->set_data($formdata);
-//}
-
 echo $OUTPUT->header();
 echo $OUTPUT->heading($title);
 
-- 
GitLab