Skip to content

Commit

Permalink
fix: clean up and some optimisations
Browse files Browse the repository at this point in the history
- add missing phpdocs,
- optimise coursecontext get by caching the call to the class,
- convert moodle_url to abs path
- remove double blank lines
- remove dead code
- fix file upload handling
  • Loading branch information
keevan committed May 3, 2024
1 parent e1bb6c1 commit 25c1397
Show file tree
Hide file tree
Showing 13 changed files with 132 additions and 46 deletions.
3 changes: 0 additions & 3 deletions attendees.php
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,6 @@
// Load cancellations.
$cancellations = facetoface_get_cancellations($session->id);


/*
* Capability checks to see if the current user can view this page
*
Expand Down Expand Up @@ -341,7 +340,6 @@
}
echo html_writer::link($url, get_string('goback', 'facetoface')) . html_writer::end_tag('p');


/*
* Print unapproved requests (if user able to view)
*/
Expand All @@ -358,7 +356,6 @@
echo html_writer::tag('p', get_string('cannotapproveatcapacity', 'facetoface'));
}


$action = new moodle_url('attendees.php', ['s' => $s]);
echo html_writer::start_tag('form', ['action' => $action->out(), 'method' => 'post']);
echo html_writer::empty_tag('input', ['type' => 'hidden', 'name' => 'sesskey', 'value' => $USER->sesskey]);
Expand Down
36 changes: 28 additions & 8 deletions classes/booking_manager.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,10 @@
namespace mod_facetoface;

use context_course;
use moodle_exception;
use context_user;
use file_storage;
use lang_string;
use moodle_exception;

class booking_manager {

Expand All @@ -31,6 +33,9 @@ class booking_manager {
/** @var int The course id. */
private $course;

/** @var context_course The course context. */
private $coursecontext;

/** @var int The course id. */
private $facetoface;

Expand Down Expand Up @@ -58,13 +63,13 @@ public function __construct($f, $records = []) {
$this->f = $f;
$this->facetoface = $facetoface;
$this->course = $course;
$this->coursecontext = context_course::instance($course->id);
$this->records = $records;
}

/**
* Returns file from file system. File must exist.
* @param int $fileitemid Item id of file stored in the current $USER's draft file area
* @return stored_file
*/
public function load_from_file(int $fileitemid) {
global $USER;
Expand All @@ -77,7 +82,7 @@ public function load_from_file(int $fileitemid) {
throw new moodle_exception('error:cannotloadfile', 'mod_facetoface');
}

return current($files);
$this->file = current($files);
}

/**
Expand All @@ -91,6 +96,10 @@ public function load_from_array(array $records) {
return $this;
}

/**
* Get the headers for the records.
* @return array
*/
public static function get_headers(): array {
return [
'email',
Expand All @@ -101,7 +110,11 @@ public static function get_headers(): array {
];
}

private function get_iterator() {
/**
* Get an iterator for the records.
* @return Generator
*/
private function get_iterator(): \Generator {
if (!$this->usefile) {
foreach ($this->records as $record) {
yield $record;
Expand Down Expand Up @@ -131,12 +144,20 @@ private function get_iterator() {
}
}

public function validate() {
/**
* Validate the records provided to ensure they can be processed without errors.
*
* As there are multiple dependant data points (users, sessions, capacity)
* that are checked. They are all in this method.
*
* @return array An array of errors.
*/
public function validate(): array {
global $DB;
$errors = [];
$sessioncapacitycache = [];

// Break into rows.
// Break into rows and validate the multiple interdependant fields together.
foreach ($this->get_iterator() as $index => $entry) {
$row = $index + 1;

Expand Down Expand Up @@ -200,8 +221,7 @@ public function validate() {
}

// Check user enrolment into the course.
$coursecontext = context_course::instance($this->course->id);
if (isset($userid) && !is_enrolled($coursecontext, $userid)) {
if (isset($userid) && !is_enrolled($this->coursecontext, $userid)) {
$errors[] = [$row, new lang_string('error:userisnotenrolledintocourse', 'mod_facetoface', $entry->email)];
}

Expand Down
1 change: 0 additions & 1 deletion classes/event/course_viewed.php
Original file line number Diff line number Diff line change
Expand Up @@ -75,5 +75,4 @@ public static function get_name() {
public function get_url() {
return new \moodle_url('/mod/facetoface/index.php', ['id' => $this->courseid]);
}

}
81 changes: 81 additions & 0 deletions classes/event/csv_processed.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
<?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/>.

namespace mod_facetoface\event;

/**
* The mod_facetoface CSV processed event.
*
* @package mod_facetoface
* @author Kevin Pham <kevinpham@catalyst-au.net>
* @copyright Catalyst IT, 2024
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class csv_processed extends \core\event\base {

/**
* Init method.
*
* @return void
*/
protected function init() {
$this->data['crud'] = 'r';
$this->data['edulevel'] = self::LEVEL_PARTICIPATING;
$this->data['objecttable'] = 'facetoface';
}

/**
* Returns description of what happened.
*
* @return string
*/
public function get_description() {
return "The user with id '$this->userid' has processed an uploaded CSV file for session bookings " .
"in the facetoface instance with the course module id '$this->contextinstanceid'.";
}

/**
* Return localised event name.
*
* @return string
*/
public static function get_name() {
return get_string('eventcsvprocessed', 'mod_facetoface');
}

/**
* Get URL related to the action
*
* @return \moodle_url
*/
public function get_url() {
return new \moodle_url('/mod/facetoface/upload.php', ['f' => $this->objectid]);
}

/**
* Custom validation.
*
* @throws \coding_exception
* @return void
*/
protected function validate_data() {
parent::validate_data();

if ($this->contextlevel != CONTEXT_MODULE) {
throw new \coding_exception('Context level must be CONTEXT_MODULE.');
}
}
}
2 changes: 1 addition & 1 deletion classes/form/confirm_bookings_form.php
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ public function definition() {

$backurl = new moodle_url('/mod/facetoface/upload.php', ['f' => $f]);
$htmlbuttons = $OUTPUT->render((new single_button(
new moodle_url('upload.php', ['f' => $f, 'fileid' => $fileid, 'process' => 1]),
new moodle_url('/mod/facetoface/upload.php', ['f' => $f, 'fileid' => $fileid, 'process' => 1]),
get_string('facetoface:confirmandprocess', 'mod_facetoface'),
'post',
true
Expand Down
4 changes: 2 additions & 2 deletions classes/form/upload_bookings_form.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
class upload_bookings_form extends \moodleform {

/**
* Build form for importing woekflows.
* Build form for importing bookings.
*
* {@inheritDoc}
* @see \moodleform::definition()
Expand All @@ -42,7 +42,7 @@ public function definition() {

$mform->addElement('header', 'settingsheader', get_string('upload'));

$url = new moodle_url('example.csv');
$url = new moodle_url('/mod/facetoface/example.csv');
$link = html_writer::link($url, 'example.csv');
$mform->addElement('static', 'examplecsv', get_string('facetoface:examplecsv', 'mod_facetoface'), $link);

Expand Down
4 changes: 2 additions & 2 deletions classes/privacy/provider.php
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ class provider implements
* @param collection $items a reference to the collection to use to store the metadata.
* @return collection the updated collection of metadata items.
*/
public static function get_metadata(collection $collection) : collection {
public static function get_metadata(collection $collection): collection {
$collection->add_database_table(
'facetoface_signups',
[
Expand Down Expand Up @@ -98,7 +98,7 @@ public static function get_metadata(collection $collection) : collection {
* @param int $userid the userid.
* @return contextlist the list of contexts containing user info for the user.
*/
public static function get_contexts_for_userid(int $userid) : contextlist {
public static function get_contexts_for_userid(int $userid): contextlist {
// Fetch all facetoface contexts with userdata.
$sql = "SELECT c.id
FROM {context} c
Expand Down
1 change: 0 additions & 1 deletion db/upgrade.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@
*/

/**
*
* Sends message to administrator listing all updated
* duplicate custom fields
* @param array $data
Expand Down
1 change: 1 addition & 0 deletions lang/en/facetoface.php
Original file line number Diff line number Diff line change
Expand Up @@ -810,6 +810,7 @@

/* Face-to-face events and logging */
$string['eventaddsession'] = 'Session added';
$string['eventcsvprocessed'] = 'CSV processed';
$string['eventaddsessionfailed'] = 'Session add (FAILED)';
$string['eventapproverequests'] = 'Session approve requests';
$string['eventattendeesviewed'] = 'Session attendees viewed';
Expand Down
22 changes: 5 additions & 17 deletions lib.php
Original file line number Diff line number Diff line change
Expand Up @@ -1162,7 +1162,7 @@ function facetoface_get_attendees($sessionid) {
global $CFG, $DB;

$usernamefields = facetoface_get_all_user_name_fields(true, 'u');
$records = $DB->get_records_sql("
return $DB->get_records_sql("
SELECT u.id, {$usernamefields},
u.email,
su.id AS submissionid,
Expand Down Expand Up @@ -1213,8 +1213,6 @@ function facetoface_get_attendees($sessionid) {
sign.timecreated ASC,
ss.timecreated ASC
", [$sessionid, MDL_F2F_STATUS_BOOKED, MDL_F2F_STATUS_WAITLISTED, $sessionid, MDL_F2F_STATUS_APPROVED]);

return $records;
}

/**
Expand Down Expand Up @@ -1954,7 +1952,6 @@ function facetoface_user_signup($session, $facetoface, $course, $discountcode,

if (!$success) {
throw new moodle_exception('error:couldnotupdatef2frecord', 'facetoface');
return false;
}

// Work out which status to use.
Expand Down Expand Up @@ -1985,7 +1982,6 @@ function facetoface_user_signup($session, $facetoface, $course, $discountcode,
// Update status.
if (!facetoface_update_signup_status($usersignup->id, $newstatus, $userid)) {
throw new moodle_exception('error:f2ffailedupdatestatus', 'facetoface');
return false;
}

// Add to user calendar -- if facetoface usercalentry is set to true.
Expand Down Expand Up @@ -2124,7 +2120,6 @@ function facetoface_send_request_notice($facetoface, $session, $userid) {
* @param bool $usetransaction Set to true if database transactions are to be used
*
* @returns integer ID of newly created signup status, or false
*
*/
function facetoface_update_signup_status($signupid, $statuscode, $createdby, $note='', $grade=null) {
global $DB;
Expand Down Expand Up @@ -2904,7 +2899,7 @@ function facetoface_cm_info_view(cm_info $coursemodule) {
$moreinfolink = html_writer::link(
$signupurl,
get_string($signupstr, 'facetoface'),
['class' => 'f2fsessionlinks f2fsessioninfolink'],
['class' => 'f2fsessionlinks f2fsessioninfolink']
);
$span = html_writer::tag('span', get_string('options', 'facetoface').':', ['class' => 'f2fsessionnotice']);
}
Expand Down Expand Up @@ -2963,13 +2958,13 @@ function facetoface_cm_info_view(cm_info $coursemodule) {
$output .= html_writer::tag(
'span',
get_string('signupforsession', 'facetoface'),
['class' => 'f2fsessionnotice'],
['class' => 'f2fsessionnotice']
);
} else {
$output .= html_writer::tag(
'span',
get_string('upcomingsessions', 'facetoface'),
['class' => 'f2fsessionnotice'],
['class' => 'f2fsessionnotice']
);

if (!empty($futuresessions)) {
Expand Down Expand Up @@ -3860,9 +3855,7 @@ function facetoface_get_customfielddata($sessionid) {
JOIN {facetoface_session_data} d ON f.id = d.fieldid
WHERE d.sessionid = ?";

$records = $DB->get_records_sql($sql, [$sessionid]);

return $records;
return $DB->get_records_sql($sql, [$sessionid]);
}

/**
Expand Down Expand Up @@ -3937,9 +3930,6 @@ function facetoface_update_trainers($sessionid, $form) {

if (!$DB->insert_record('facetoface_session_roles', $newtrainer)) {
throw new moodle_exception('error:couldnotaddtrainer', 'facetoface');
$transaction->force_transaction_rollback();

return false;
}
} else {
unset($oldtrainers[$roleid][$trainer]);
Expand All @@ -3963,8 +3953,6 @@ function facetoface_update_trainers($sessionid, $form) {
'userid' => $trainer->id,
])) {
throw new moodle_exception('error:couldnotdeletetrainer', 'facetoface');
$transaction->force_transaction_rollback();
return false;
}
}
}
Expand Down
2 changes: 0 additions & 2 deletions sessions.php
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,6 @@
'context' => $modulecontext,
];


// Handle deletions.
if ($d && $confirm) {
if (!confirm_sesskey()) {
Expand Down Expand Up @@ -361,7 +360,6 @@

$pagetitle = format_string($facetoface->name);


$PAGE->set_title($pagetitle);
$PAGE->set_heading($course->fullname);

Expand Down
2 changes: 0 additions & 2 deletions sitenotice.php
Original file line number Diff line number Diff line change
Expand Up @@ -97,8 +97,6 @@
throw new moodle_exception('error:unknownbuttonclicked', 'facetoface', $returnurl);
}



$todb = new stdClass();
$todb->name = trim($fromform->name);
$todb->text = trim($fromform->text['text']);
Expand Down
Loading

0 comments on commit 25c1397

Please sign in to comment.