Example #1
0
 /**
  * Register courses
  * @return array ids of created courses
  */
 public static function register_courses($courses)
 {
     global $DB;
     // Ensure the current user is allowed to run this function
     $context = context_system::instance();
     self::validate_context($context);
     require_capability('local/hub:registercourse', $context);
     $params = self::validate_parameters(self::register_courses_parameters(), array('courses' => $courses));
     $hub = new local_hub();
     //retieve site url
     $token = optional_param('wstoken', '', PARAM_ALPHANUM);
     $siteurl = $hub->get_communication(WSSERVER, REGISTEREDSITE, null, $token)->remoteurl;
     $site = $hub->get_site_by_url($siteurl);
     //check that the number of allowed publication is not reached
     if (isset($site->publicationmax)) {
         //site setting (overwrite the hub setting value)
         $maxpublication = $site->publicationmax;
     } else {
         //hub setting
         $maxpublication = get_config('local_hub', 'maxcoursesperday');
     }
     if ($maxpublication !== false) {
         //retrieve the number of publication for the last 24hours
         $options = array();
         $options['lastpublished'] = strtotime("-1 day");
         $options['siteid'] = $site->id;
         $options['enrollable'] = true;
         $options['downloadable'] = true;
         $lastpublishedcourses = $hub->get_courses($options);
         if (!empty($lastpublishedcourses)) {
             if (count($lastpublishedcourses) >= $maxpublication) {
                 if ($maxpublication > 0) {
                     //get the oldest publication
                     $nextpublicationtime = get_string('never', 'local_hub');
                     $oldestpublicationtime = time();
                     foreach ($lastpublishedcourses as $lastpublishedcourse) {
                         if ($lastpublishedcourse->timepublished < $oldestpublicationtime) {
                             $oldestpublicationtime = $lastpublishedcourse->timepublished;
                         }
                     }
                     $errorinfo = new stdClass();
                     //calculate the time when the site can publish again
                     $errorinfo->time = format_time(24 * 60 * 60 - (time() - $oldestpublicationtime));
                     $errorinfo->maxpublication = $maxpublication;
                     throw new moodle_exception('errormaxpublication', 'local_hub', '', $errorinfo);
                 } else {
                     throw new moodle_exception('errornopublication', 'local_hub');
                 }
             }
         }
     }
     $transaction = $DB->start_delegated_transaction();
     $courseids = array();
     foreach ($params['courses'] as $course) {
         $courseids[] = $hub->register_course($course, $siteurl);
         //'true' indicates registration update mode
     }
     $transaction->allow_commit();
     return $courseids;
 }