Script to create courses automatically

Script to create courses automatically

by Richard Crawford -
Number of replies: 2

I'm working on a script that will create courses automatically based on a cron job, pulling data from our local database. The courses are pretty standard, and each has the following elements:

  1. A news forum
  2. An "Introduce Yourself" forum
  3. A class participation forum
  4. An open chat

The script works fine when I'm logged in as a site administrator in one tab of my browser and run the script in another. However, when the script runs on its own, I get the following error message:

Sorry, but you do not currently have permissions to update calendar event

during the chat creation function. Does this mean that the chat_add_instance() function accesses the calendar API at some point?

At any rate, I have two ideas for how to fix this:

  1. Rewrite the chat_add_instance() function so that it does not call the calendar API;
  2. Somehow log the script in as an admin user while it is running. This strikes me as pretty dangerous, though.

Would either of these options work? How would I go about implementing them? 

We are currently using Moodle 2.3.2. This script worked fine in Moodle 1.9.3.

Average of ratings: -
In reply to Richard Crawford

Re: Script to create courses automatically

by Davo Smith -
Picture of Core developers Picture of Particularly helpful Moodlers Picture of Peer reviewers Picture of Plugin developers

You should be able to call 'cron_setup_user()' to make sure that the $USER global points at a site admin (who should have the capabilities to do anything with the calendar).

Alternatively, you could try the following:

$olduser = $USER;
$USER = get_admin();
// call your functions
$USER = $olduser;

As for running a cron script as an admin being dangerous - given that *any* script running on your Moodle site has the ability to call $DB->delete_records('user'), or any other such thing, I don't think that running the cron script as an 'admin' is something to worry about. If you don't trust the code to run safely, then capability checks won't protect you (they are there to stop users from doing bad things, not the code).