I realize this is old, but $DB needs to be included for anything that writes to the database. I don't think $COURSE is needed. I can't see anything in the code that uses it.
I'd change the first line to the following:
global $DB;
The code isn't exactly using the Calendar API which may be newer than this post. It would be best to use that to rework this code.