MDL-37781 Allocate workshop submissions without waiting for cron
[moodle.git] / mod / workshop / allocation / scheduled / lib.php
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 // GNU General Public License for more details.
14 //
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
18 /**
19  * Scheduled allocator that internally executes the random allocation later
20  *
21  * @package     workshopallocation_scheduled
22  * @subpackage  mod_workshop
23  * @copyright   2012 David Mudrak <david@moodle.com>
24  * @license     http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25  */
27 defined('MOODLE_INTERNAL') || die();
29 require_once(dirname(dirname(__FILE__)) . '/lib.php');                  // interface definition
30 require_once(dirname(dirname(dirname(__FILE__))) . '/locallib.php');    // workshop internal API
31 require_once(dirname(dirname(__FILE__)) . '/random/lib.php');           // random allocator
32 require_once(dirname(__FILE__) . '/settings_form.php');                 // our settings form
34 /**
35  * Allocates the submissions randomly in a cronjob task
36  */
37 class workshop_scheduled_allocator implements workshop_allocator {
39     /** workshop instance */
40     protected $workshop;
42     /** workshop_scheduled_allocator_form with settings for the random allocator */
43     protected $mform;
45     /**
46      * @param workshop $workshop Workshop API object
47      */
48     public function __construct(workshop $workshop) {
49         $this->workshop = $workshop;
50     }
52     /**
53      * Save the settings for the random allocator to execute it later
54      */
55     public function init() {
56         global $PAGE, $DB;
58         $result = new workshop_allocation_result($this);
60         $customdata = array();
61         $customdata['workshop'] = $this->workshop;
63         $current = $DB->get_record('workshopallocation_scheduled',
64             array('workshopid' => $this->workshop->id), '*', IGNORE_MISSING);
66         $customdata['current'] = $current;
68         $this->mform = new workshop_scheduled_allocator_form($PAGE->url, $customdata);
70         if ($this->mform->is_cancelled()) {
71             redirect($this->workshop->view_url());
72         } else if ($settings = $this->mform->get_data()) {
73             if (empty($settings->enablescheduled)) {
74                 $enabled = false;
75             } else {
76                 $enabled = true;
77             }
78             if (empty($settings->reenablescheduled)) {
79                 $reset = false;
80             } else {
81                 $reset = true;
82             }
83             $settings = workshop_random_allocator_setting::instance_from_object($settings);
84             $this->store_settings($enabled, $reset, $settings, $result);
85             if ($enabled) {
86                 $msg = get_string('resultenabled', 'workshopallocation_scheduled');
87             } else {
88                 $msg = get_string('resultdisabled', 'workshopallocation_scheduled');
89             }
90             $result->set_status(workshop_allocation_result::STATUS_CONFIGURED, $msg);
91             return $result;
92         } else {
93             // this branch is executed if the form is submitted but the data
94             // doesn't validate and the form should be redisplayed
95             // or on the first display of the form.
97             if ($current !== false) {
98                 $data = workshop_random_allocator_setting::instance_from_text($current->settings);
99                 $data->enablescheduled = $current->enabled;
100                 $this->mform->set_data($data);
101             }
103             $result->set_status(workshop_allocation_result::STATUS_VOID);
104             return $result;
105         }
106     }
108     /**
109      * Returns the HTML code to print the user interface
110      */
111     public function ui() {
112         global $PAGE;
114         $output = $PAGE->get_renderer('mod_workshop');
116         $out = $output->container_start('scheduled-allocator');
117         // the nasty hack follows to bypass the sad fact that moodle quickforms do not allow to actually
118         // return the HTML content, just to display it
119         ob_start();
120         $this->mform->display();
121         $out .= ob_get_contents();
122         ob_end_clean();
123         $out .= $output->container_end();
125         return $out;
126     }
128     /**
129      * Executes the allocation
130      *
131      * @return workshop_allocation_result
132      */
133     public function execute() {
134         global $DB;
136         $result = new workshop_allocation_result($this);
138         // make sure the workshop itself is at the expected state
140         if ($this->workshop->phase != workshop::PHASE_SUBMISSION) {
141             $result->set_status(workshop_allocation_result::STATUS_FAILED,
142                 get_string('resultfailedphase', 'workshopallocation_scheduled'));
143             return $result;
144         }
146         if (empty($this->workshop->submissionend)) {
147             $result->set_status(workshop_allocation_result::STATUS_FAILED,
148                 get_string('resultfaileddeadline', 'workshopallocation_scheduled'));
149             return $result;
150         }
152         if ($this->workshop->submissionend > time()) {
153             $result->set_status(workshop_allocation_result::STATUS_VOID,
154                 get_string('resultvoiddeadline', 'workshopallocation_scheduled'));
155             return $result;
156         }
158         $current = $DB->get_record('workshopallocation_scheduled',
159             array('workshopid' => $this->workshop->id, 'enabled' => 1), '*', IGNORE_MISSING);
161         if ($current === false) {
162             $result->set_status(workshop_allocation_result::STATUS_FAILED,
163                 get_string('resultfailedconfig', 'workshopallocation_scheduled'));
164             return $result;
165         }
167         if (!$current->enabled) {
168             $result->set_status(workshop_allocation_result::STATUS_VOID,
169                 get_string('resultdisabled', 'workshopallocation_scheduled'));
170             return $result;
171         }
173         if (!is_null($current->timeallocated) and $current->timeallocated >= $this->workshop->submissionend) {
174             $result->set_status(workshop_allocation_result::STATUS_VOID,
175                 get_string('resultvoidexecuted', 'workshopallocation_scheduled'));
176             return $result;
177         }
179         // so now we know that we are after the submissions deadline and either the scheduled allocation was not
180         // executed yet or it was but the submissions deadline has been prolonged (and hence we should repeat the
181         // allocations)
183         $settings = workshop_random_allocator_setting::instance_from_text($current->settings);
184         $randomallocator = $this->workshop->allocator_instance('random');
185         $randomallocator->execute($settings, $result);
187         // store the result in the instance's table
188         $update = new stdClass();
189         $update->id = $current->id;
190         $update->timeallocated = $result->get_timeend();
191         $update->resultstatus = $result->get_status();
192         $update->resultmessage = $result->get_message();
193         $update->resultlog = json_encode($result->get_logs());
195         $DB->update_record('workshopallocation_scheduled', $update);
197         return $result;
198     }
200     /**
201      * Delete all data related to a given workshop module instance
202      *
203      * @see workshop_delete_instance()
204      * @param int $workshopid id of the workshop module instance being deleted
205      * @return void
206      */
207     public static function delete_instance($workshopid) {
208         // TODO
209         return;
210     }
212     /**
213      * Stores the pre-defined random allocation settings for later usage
214      *
215      * @param bool $enabled is the scheduled allocation enabled
216      * @param bool $reset reset the recent execution info
217      * @param workshop_random_allocator_setting $settings settings form data
218      * @param workshop_allocation_result $result logger
219      */
220     protected function store_settings($enabled, $reset, workshop_random_allocator_setting $settings, workshop_allocation_result $result) {
221         global $DB;
224         $data = new stdClass();
225         $data->workshopid = $this->workshop->id;
226         $data->enabled = $enabled;
227         $data->submissionend = $this->workshop->submissionend;
228         $data->settings = $settings->export_text();
230         if ($reset) {
231             $data->timeallocated = null;
232             $data->resultstatus = null;
233             $data->resultmessage = null;
234             $data->resultlog = null;
235         }
237         $result->log($data->settings, 'debug');
239         $current = $DB->get_record('workshopallocation_scheduled', array('workshopid' => $data->workshopid), '*', IGNORE_MISSING);
241         if ($current === false) {
242             $DB->insert_record('workshopallocation_scheduled', $data);
244         } else {
245             $data->id = $current->id;
246             $DB->update_record('workshopallocation_scheduled', $data);
247         }
248     }
251 /**
252  * Regular jobs to execute via cron
253  */
254 function workshopallocation_scheduled_cron() {
255     global $CFG, $DB;
257     $sql = "SELECT w.*
258               FROM {workshopallocation_scheduled} a
259               JOIN {workshop} w ON a.workshopid = w.id
260              WHERE a.enabled = 1
261                    AND w.phase = 20
262                    AND w.submissionend > 0
263                    AND w.submissionend < ?
264                    AND (a.timeallocated IS NULL OR a.timeallocated < w.submissionend)";
266     $workshops = $DB->get_records_sql($sql, array(time()));
268     if (empty($workshops)) {
269         mtrace('... no workshops awaiting scheduled allocation. ', '');
270         return;
271     }
273     mtrace('... executing scheduled allocation in '.count($workshops).' workshop(s) ... ', '');
275     // let's have some fun!
276     require_once($CFG->dirroot.'/mod/workshop/locallib.php');
278     foreach ($workshops as $workshop) {
279         $cm = get_coursemodule_from_instance('workshop', $workshop->id, $workshop->course, false, MUST_EXIST);
280         $course = $DB->get_record('course', array('id' => $cm->course), '*', MUST_EXIST);
281         $workshop = new workshop($workshop, $cm, $course);
282         $allocator = $workshop->allocator_instance('scheduled');
283         $result = $allocator->execute();
285         // todo inform the teachers about the results
286     }
289 ////////////////////////////////////////////////////////////////////////////////
290 // Events API
291 ////////////////////////////////////////////////////////////////////////////////
293 /**
294  * Handler for the 'workshop_viewed' event
295  *
296  * This does the same job as {@link workshopallocation_scheduled_cron()} but for the
297  * single workshop. The idea is that we do not need to wait forcron to execute.
298  * Displaying the workshop main view.php can trigger the scheduled allocation, too.
299  *
300  * @param stdClass $event event data
301  * @return bool
302  */
303 function workshopallocation_scheduled_workshop_viewed($event) {
304     global $DB;
306     $workshop = $event->workshop;
307     $now = time();
309     // Non-expensive check to see if the scheduled allocation can even happen.
310     if ($workshop->phase == workshop::PHASE_SUBMISSION and $workshop->submissionend > 0 and $workshop->submissionend < $now) {
312         // Make sure the scheduled allocation has been configured for this workshop, that it has not
313         // been executed yet and that the passed workshop record is still valid.
314         $sql = "SELECT a.id
315                   FROM {workshopallocation_scheduled} a
316                   JOIN {workshop} w ON a.workshopid = w.id
317                  WHERE w.id = :workshopid
318                        AND a.enabled = 1
319                        AND w.phase = :phase
320                        AND w.submissionend > 0
321                        AND w.submissionend < :now
322                        AND (a.timeallocated IS NULL OR a.timeallocated < w.submissionend)";
323         $params = array('workshopid' => $workshop->id, 'phase' => workshop::PHASE_SUBMISSION, 'now' => $now);
325         if ($DB->record_exists_sql($sql, $params)) {
326             // Allocate submissions for assessments.
327             $allocator = $workshop->allocator_instance('scheduled');
328             $result = $allocator->execute();
329             // todo inform the teachers about the results
330         }
331     }
333     return true;