From 9f4e1f43b4f9f61e3e09b257b63035e501b1acb5 Mon Sep 17 00:00:00 2001 From: Eugene Venter Date: Tue, 27 Mar 2018 15:30:50 +1300 Subject: [PATCH] #173 Fix race condition on certificate issues in scheduled task --- classes/task/email_certificate_task.php | 23 ++++++++++++++--------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/classes/task/email_certificate_task.php b/classes/task/email_certificate_task.php index 80b6f52..3a305a8 100644 --- a/classes/task/email_certificate_task.php +++ b/classes/task/email_certificate_task.php @@ -125,16 +125,21 @@ class email_certificate_task extends \core\task\scheduled_task { } } - // Ok, issue them the certificate. - $customcertissue = new \stdClass(); - $customcertissue->customcertid = $customcert->id; - $customcertissue->userid = $enroluser->id; - $customcertissue->code = \mod_customcert\certificate::generate_code(); - $customcertissue->emailed = 0; - $customcertissue->timecreated = time(); + // Ensure the cert hasn't already been issued, e.g via the UI (view.php) - a race condition. + $issueid = $DB->get_field('customcert_issues', 'id', + array('userid' => $enroluser->id, 'customcertid' => $customcert->id)); + if (empty($issueid)) { + // Ok, issue them the certificate. + $customcertissue = new \stdClass(); + $customcertissue->customcertid = $customcert->id; + $customcertissue->userid = $enroluser->id; + $customcertissue->code = \mod_customcert\certificate::generate_code(); + $customcertissue->emailed = 0; + $customcertissue->timecreated = time(); - // Insert the record into the database. - $issueid = $DB->insert_record('customcert_issues', $customcertissue); + // Insert the record into the database. + $issueid = $DB->insert_record('customcert_issues', $customcertissue); + } // Add them to the array so we email them. $enroluser->issueid = $issueid;