Exemple #1
0
function create_course_pditt($category,$idnumber,$kodemk,$namamk,$summary,$startdate=0,$visible=0,$format='topics'){
    global $DB, $CFG;
    //$x = $DB->get_record('course', array('idnumber'=>$idnumber, 'shortname'=>$kodemk), '*');
    $x = $DB->get_record('course', array('idnumber'=>$idnumber), '*');
    if (!$x) {
        $data = new stdClass();
        $data->category=$category;
        $data->idnumber = $idnumber;
        $data->fullname=$namamk;
        $data->shortname = $kodemk;
        $data->summary = $summary;
        $data->summaryformat=0;
        $data->format=$format;
        $data->startdate = $startdate;
        $data->showgrades=1;
        $data->visible=$visible;
        $h=create_course($data);
        return $h->id; 
    } else {
        $data = new stdClass();
        $data->fullname=$namamk;
        $data->idnumber = $idnumber;
        $data->shortname = $kodemk;
        $data->summary = $summary;
        $data->id = $x->id;
        update_course($data);
        return $x->id;
    }

}
Exemple #2
0
 public function execute()
 {
     global $CFG;
     require_once $CFG->dirroot . '/course/lib.php';
     foreach ($this->arguments as $argument) {
         $this->expandOptionsManually(array($argument));
         $options = $this->expandedOptions;
         $course = new \stdClass();
         $course->fullname = $options['fullname'];
         $course->shortname = $argument;
         $course->description = $options['description'];
         $format = $options['format'];
         if (!$format) {
             $format = get_config('moodlecourse', 'format');
         }
         $course->format = $format;
         $course->idnumber = $options['idnumber'];
         $visible = strtolower($options['visible']);
         if ($visible == 'n' || $visible == 'no') {
             $visible = 0;
         } else {
             $visible = 1;
         }
         $course->visible = $visible;
         $course->category = $options['category'];
         $course->summary = '';
         $course->summaryformat = FORMAT_HTML;
         $course->startdate = time();
         //either use API create_course
         $newcourse = create_course($course);
         echo $newcourse->id . "\n";
     }
 }
Exemple #3
0
 public function test_create_course()
 {
     global $DB;
     $this->resetAfterTest(true);
     $defaultcategory = $DB->get_field_select('course_categories', "MIN(id)", "parent=0");
     $course = new stdClass();
     $course->fullname = 'Apu loves Unit Təsts';
     $course->shortname = 'Spread the lŭve';
     $course->idnumber = '123';
     $course->summary = 'Awesome!';
     $course->summaryformat = FORMAT_PLAIN;
     $course->format = 'topics';
     $course->newsitems = 0;
     $course->numsections = 5;
     $course->category = $defaultcategory;
     $created = create_course($course);
     $context = context_course::instance($created->id);
     // Compare original and created.
     $original = (array) $course;
     $this->assertEquals($original, array_intersect_key((array) $created, $original));
     // Ensure default section is created.
     $sectioncreated = $DB->record_exists('course_sections', array('course' => $created->id, 'section' => 0));
     $this->assertTrue($sectioncreated);
     // Ensure blocks have been associated to the course.
     $blockcount = $DB->count_records('block_instances', array('parentcontextid' => $context->id));
     $this->assertGreaterThan(0, $blockcount);
 }
Exemple #4
0
/**
 * Create a new course using existing Moodle functionality
 *
 * @author Andrew Zoltay
 * date    2010-05-03
 * @param associative array $newcourse used to create new course
 * @param string $pagecontent contents of page resource
 * @return int id of new course or failure of course creation
 */
function cace_create_newcourse($newcourse, $pagecontent)
{
    global $DB, $USER;
    // Need to force a user so the system can log who is doing the action.
    $USER = $DB->get_record('user', array('username' => 'mdladmin'));
    // Prep the course info.
    $course = cace_prep_newcourse($newcourse);
    // Verify $course was prepared correctly.
    if (!$course) {
        cace_write_to_log("ERROR - Moodle cace_prep_newcourse() failed for {$newcourse->idnumber}");
        return false;
    }
    // Create the new course shell.
    try {
        $createdcourse = create_course($course);
        // If course shell was created, add "Development Notes" resource to new shell
        // First prep the data - default section to the first one in the course (0).
        $data = cace_prep_page_data($createdcourse, 0, $pagecontent);
        if (!cace_add_page_resource($createdcourse, $data)) {
            // Just report the error - don't stop execution.
            cace_write_to_log("ERROR - Failed to add {$data->name} for course {$newcourse->idnumber}");
        }
        // Add default blocks to the right column.
        cace_update_default_course_blocks($createdcourse);
        // Add a record in the grade categories table and also in the grade items table to support letter grade and percentages
        // in the course totals column.
        cace_add_grade_records($createdcourse->id);
        return $createdcourse->id;
    } catch (moodle_exception $e) {
        cace_write_to_log("ERROR - Moodle create_course() failed for {$newcourse->idnumber} " . $e->getMessage());
        return false;
    }
}
 /**
  * Validate that appropriate fields are synched over to Moodle when PM user is enrolled in a class instance during an import.
  */
 public function test_user_sync_on_pm_user_create()
 {
     global $CFG, $DB;
     require_once $CFG->dirroot . '/course/lib.php';
     require_once $CFG->dirroot . '/local/elisprogram/lib/setup.php';
     require_once elispm::lib('data/classmoodlecourse.class.php');
     require_once elispm::lib('data/course.class.php');
     require_once elispm::lib('data/pmclass.class.php');
     require_once elispm::lib('data/user.class.php');
     // Configure the elis enrolment plugin.
     $roleid = $DB->get_field('role', 'id', array(), IGNORE_MULTIPLE);
     set_config('roleid', $roleid, 'enrol_elis');
     $user = new user(array('idnumber' => 'testuseridnumber', 'username' => 'testuserusername', 'firstname' => 'testuserfirstname', 'lastname' => 'testuserlastname', 'email' => '*****@*****.**', 'country' => 'CA'));
     $user->save();
     $course = new course(array('name' => 'testcoursename', 'idnumber' => 'testcourseidnumber', 'syllabus' => ''));
     $course->save();
     $class = new pmclass(array('courseid' => $course->id, 'idnumber' => 'testclassidnumber'));
     $class->save();
     $category = new stdClass();
     $category->name = 'testcategoryname';
     $category->id = $DB->insert_record('course_categories', $category);
     // Create the associated context.
     context_coursecat::instance($category->id);
     $mdlcourse = new stdClass();
     $mdlcourse->category = $category->id;
     $mdlcourse->fullname = 'testcoursefullname';
     $mdlcourse = create_course($mdlcourse);
     // Associate class instance to Moodle course.
     $classmoodlecourse = new classmoodlecourse(array('classid' => $class->id, 'moodlecourseid' => $mdlcourse->id));
     $classmoodlecourse->save();
     // Run the enrolment create action.
     $record = new stdClass();
     $record->context = 'class_testclassidnumber';
     $record->user_username = '******';
     $importplugin = rlip_dataplugin_factory::factory('dhimport_version1elis');
     $importplugin->fslogger = new silent_fslogger(null);
     $importplugin->class_enrolment_create($record, 'bogus', 'testclassidnumber');
     // Validate the enrolment.
     $enrolid = $DB->get_field('enrol', 'id', array('enrol' => 'elis', 'courseid' => $mdlcourse->id));
     $this->assertNotEquals(false, $enrolid);
     $mdluserid = $DB->get_field('user', 'id', array('username' => 'testuserusername'));
     $this->assertNotEquals(false, $mdluserid);
     $this->assertTrue($DB->record_exists('user_enrolments', array('enrolid' => $enrolid, 'userid' => $mdluserid)));
     // Validate the role assignment.
     $mdlcoursecontext = context_course::instance($mdlcourse->id);
     $this->assertTrue($DB->record_exists('role_assignments', array('roleid' => $roleid, 'contextid' => $mdlcoursecontext->id, 'userid' => $mdluserid)));
 }
 public static function create_course($course)
 {
     global $CFG, $DB;
     // Valida os parametros.
     $params = self::validate_parameters(self::create_course_parameters(), array('course' => $course));
     // Inlcui a biblioteca de curso do moodle
     require_once "{$CFG->dirroot}/course/lib.php";
     // Transforma o array em objeto.
     $course = (object) $course;
     // Inicia a transacao, qualquer erro que aconteca o rollback sera executado.
     $transaction = $DB->start_delegated_transaction();
     // Busca o id do curso apartir do trm_id da turma.
     $courseid = self::get_course_by_trm_id($course->trm_id);
     // Dispara uma excessao se essa turma ja estiver mapeado para um curso.
     if ($courseid) {
         throw new Exception("Essa turma ja esta mapeada com o curso de id: " . $courseid);
     }
     // Cria o curso usando a biblioteca do proprio moodle.
     $result = create_course($course);
     // Caso o curso tenha sido criado adiciona a tabela de controle os dados dos curso e da turma.
     if ($result->id) {
         $data['trm_id'] = $course->trm_id;
         $data['courseid'] = $result->id;
         $res = $DB->insert_record('itg_turma_course', $data);
     }
     // Persiste as operacoes em caso de sucesso.
     $transaction->allow_commit();
     // Prepara o array de retorno.
     if ($res) {
         $returndata['id'] = $result->id;
         $returndata['status'] = 'success';
         $returndata['message'] = 'Curso criado com sucesso';
     } else {
         $returndata['id'] = 0;
         $returndata['status'] = 'error';
         $returndata['message'] = 'Erro ao tentar criar o curso';
     }
     return $returndata;
 }
Exemple #7
0
 /**
  * Create the fixture
  *
  * This method must be safe to call multiple times.
  *
  * @return void
  * @throws moodle_exception
  */
 public function build()
 {
     global $CFG, $DB;
     require_once $CFG->libdir . '/coursecatlib.php';
     if (!$this->exists()) {
         $course = (object) $this->get_options();
         // Clean course table - can happen when unit tests fail...
         if (!empty($course->shortname) and $record = $DB->get_record('course', array('shortname' => $course->shortname))) {
             delete_course($record, false);
         }
         if (!empty($course->idnumber) and $record = $DB->get_record('course', array('idnumber' => $course->idnumber))) {
             delete_course($record, false);
         }
         // Try to help folks out...
         if (!property_exists($course, 'category')) {
             $course->category = coursecat::get_default()->id;
         }
         if (!property_exists($course, 'fullname')) {
             $course->fullname = '';
         }
         $course = create_course($course);
         $this->set_results($DB->get_record('course', array('id' => $course->id), '*', MUST_EXIST));
     }
 }
Exemple #8
0
    /**
     * Create  courses
     *
     * @param array $courses
     * @return array courses (id and shortname only)
     * @since Moodle 2.2
     */
    public static function create_courses($courses) {
        global $CFG, $DB;
        require_once($CFG->dirroot . "/course/lib.php");
        require_once($CFG->libdir . '/completionlib.php');

        $params = self::validate_parameters(self::create_courses_parameters(),
                        array('courses' => $courses));

        $availablethemes = core_component::get_plugin_list('theme');
        $availablelangs = get_string_manager()->get_list_of_translations();

        $transaction = $DB->start_delegated_transaction();

        foreach ($params['courses'] as $course) {

            // Ensure the current user is allowed to run this function
            $context = context_coursecat::instance($course['categoryid'], IGNORE_MISSING);
            try {
                self::validate_context($context);
            } catch (Exception $e) {
                $exceptionparam = new stdClass();
                $exceptionparam->message = $e->getMessage();
                $exceptionparam->catid = $course['categoryid'];
                throw new moodle_exception('errorcatcontextnotvalid', 'webservice', '', $exceptionparam);
            }
            require_capability('moodle/course:create', $context);

            // Make sure lang is valid
            if (array_key_exists('lang', $course) and empty($availablelangs[$course['lang']])) {
                throw new moodle_exception('errorinvalidparam', 'webservice', '', 'lang');
            }

            // Make sure theme is valid
            if (array_key_exists('forcetheme', $course)) {
                if (!empty($CFG->allowcoursethemes)) {
                    if (empty($availablethemes[$course['forcetheme']])) {
                        throw new moodle_exception('errorinvalidparam', 'webservice', '', 'forcetheme');
                    } else {
                        $course['theme'] = $course['forcetheme'];
                    }
                }
            }

            //force visibility if ws user doesn't have the permission to set it
            $category = $DB->get_record('course_categories', array('id' => $course['categoryid']));
            if (!has_capability('moodle/course:visibility', $context)) {
                $course['visible'] = $category->visible;
            }

            //set default value for completion
            $courseconfig = get_config('moodlecourse');
            if (completion_info::is_enabled_for_site()) {
                if (!array_key_exists('enablecompletion', $course)) {
                    $course['enablecompletion'] = $courseconfig->enablecompletion;
                }
            } else {
                $course['enablecompletion'] = 0;
            }

            $course['category'] = $course['categoryid'];

            // Summary format.
            $course['summaryformat'] = external_validate_format($course['summaryformat']);

            if (!empty($course['courseformatoptions'])) {
                foreach ($course['courseformatoptions'] as $option) {
                    $course[$option['name']] = $option['value'];
                }
            }

            //Note: create_course() core function check shortname, idnumber, category
            $course['id'] = create_course((object) $course)->id;

            $resultcourses[] = array('id' => $course['id'], 'shortname' => $course['shortname']);
        }

        $transaction->allow_commit();

        return $resultcourses;
    }
Exemple #9
0
 /**
  * Performs a full sync with external database.
  *
  * First it creates new courses if necessary, then
  * enrols and unenrols users.
  *
  * @param bool $verbose
  * @return int 0 means success, 1 db connect failure, 4 db read failure
  */
 public function sync_courses($verbose = false)
 {
     global $CFG, $DB;
     // Make sure we sync either enrolments or courses.
     if (!$this->get_config('dbtype') or !$this->get_config('dbhost') or !$this->get_config('newcoursetable') or !$this->get_config('newcoursefullname') or !$this->get_config('newcourseshortname')) {
         if ($verbose) {
             mtrace('Course synchronisation skipped.');
         }
         return 0;
     }
     if ($verbose) {
         mtrace('Starting course synchronisation...');
     }
     // We may need a lot of memory here.
     @set_time_limit(0);
     raise_memory_limit(MEMORY_HUGE);
     if (!($extdb = $this->db_init())) {
         mtrace('Error while communicating with external enrolment database');
         return 1;
     }
     $table = $this->get_config('newcoursetable');
     $fullname = trim($this->get_config('newcoursefullname'));
     $shortname = trim($this->get_config('newcourseshortname'));
     $idnumber = trim($this->get_config('newcourseidnumber'));
     $category = trim($this->get_config('newcoursecategory'));
     // Lowercased versions - necessary because we normalise the resultset with array_change_key_case().
     $fullname_l = strtolower($fullname);
     $shortname_l = strtolower($shortname);
     $idnumber_l = strtolower($idnumber);
     $category_l = strtolower($category);
     $localcategoryfield = $this->get_config('localcategoryfield', 'id');
     $defaultcategory = $this->get_config('defaultcategory');
     if (!$DB->record_exists('course_categories', array('id' => $defaultcategory))) {
         if ($verbose) {
             mtrace("  default course category does not exist!");
         }
         $categories = $DB->get_records('course_categories', array(), 'sortorder', 'id', 0, 1);
         $first = reset($categories);
         $defaultcategory = $first->id;
     }
     $sqlfields = array($fullname, $shortname);
     if ($category) {
         $sqlfields[] = $category;
     }
     if ($idnumber) {
         $sqlfields[] = $idnumber;
     }
     $sql = $this->db_get_sql($table, array(), $sqlfields, true);
     $createcourses = array();
     if ($rs = $extdb->Execute($sql)) {
         if (!$rs->EOF) {
             while ($fields = $rs->FetchRow()) {
                 $fields = array_change_key_case($fields, CASE_LOWER);
                 $fields = $this->db_decode($fields);
                 if (empty($fields[$shortname_l]) or empty($fields[$fullname_l])) {
                     if ($verbose) {
                         mtrace('  error: invalid external course record, shortname and fullname are mandatory: ' . json_encode($fields));
                         // Hopefully every geek can read JS, right?
                     }
                     continue;
                 }
                 if ($DB->record_exists('course', array('shortname' => $fields[$shortname_l]))) {
                     // Already exists, skip.
                     continue;
                 }
                 // Allow empty idnumber but not duplicates.
                 if ($idnumber and $fields[$idnumber_l] !== '' and $fields[$idnumber_l] !== null and $DB->record_exists('course', array('idnumber' => $fields[$idnumber_l]))) {
                     if ($verbose) {
                         mtrace('  error: duplicate idnumber, can not create course: ' . $fields[$shortname_l] . ' [' . $fields[$idnumber_l] . ']');
                     }
                     continue;
                 }
                 $course = new stdClass();
                 $course->fullname = $fields[$fullname_l];
                 $course->shortname = $fields[$shortname_l];
                 $course->idnumber = $idnumber ? $fields[$idnumber_l] : '';
                 if ($category) {
                     if (empty($fields[$category_l])) {
                         // Empty category means use default.
                         $course->category = $defaultcategory;
                     } else {
                         if ($coursecategory = $DB->get_record('course_categories', array($localcategoryfield => $fields[$category_l]), 'id')) {
                             // Yay, correctly specified category!
                             $course->category = $coursecategory->id;
                             unset($coursecategory);
                         } else {
                             // Bad luck, better not continue because unwanted ppl might get access to course in different category.
                             if ($verbose) {
                                 mtrace('  error: invalid category ' . $localcategoryfield . ', can not create course: ' . $fields[$shortname_l]);
                             }
                             continue;
                         }
                     }
                 } else {
                     $course->category = $defaultcategory;
                 }
                 $createcourses[] = $course;
             }
         }
         $rs->Close();
     } else {
         mtrace('Error reading data from the external course table');
         $extdb->Close();
         return 4;
     }
     if ($createcourses) {
         require_once "{$CFG->dirroot}/course/lib.php";
         $templatecourse = $this->get_config('templatecourse');
         $template = false;
         if ($templatecourse) {
             if ($template = $DB->get_record('course', array('shortname' => $templatecourse))) {
                 $template = fullclone(course_get_format($template)->get_course());
                 unset($template->id);
                 unset($template->fullname);
                 unset($template->shortname);
                 unset($template->idnumber);
             } else {
                 if ($verbose) {
                     mtrace("  can not find template for new course!");
                 }
             }
         }
         if (!$template) {
             $courseconfig = get_config('moodlecourse');
             $template = new stdClass();
             $template->summary = '';
             $template->summaryformat = FORMAT_HTML;
             $template->format = $courseconfig->format;
             $template->newsitems = $courseconfig->newsitems;
             $template->showgrades = $courseconfig->showgrades;
             $template->showreports = $courseconfig->showreports;
             $template->maxbytes = $courseconfig->maxbytes;
             $template->groupmode = $courseconfig->groupmode;
             $template->groupmodeforce = $courseconfig->groupmodeforce;
             $template->visible = $courseconfig->visible;
             $template->lang = $courseconfig->lang;
             $template->groupmodeforce = $courseconfig->groupmodeforce;
         }
         foreach ($createcourses as $fields) {
             $newcourse = clone $template;
             $newcourse->fullname = $fields->fullname;
             $newcourse->shortname = $fields->shortname;
             $newcourse->idnumber = $fields->idnumber;
             $newcourse->category = $fields->category;
             // Detect duplicate data once again, above we can not find duplicates
             // in external data using DB collation rules...
             if ($DB->record_exists('course', array('shortname' => $newcourse->shortname))) {
                 if ($verbose) {
                     mtrace("  can not insert new course, duplicate shortname detected: " . $newcourse->shortname);
                 }
                 continue;
             } else {
                 if (!empty($newcourse->idnumber) and $DB->record_exists('course', array('idnumber' => $newcourse->idnumber))) {
                     if ($verbose) {
                         mtrace("  can not insert new course, duplicate idnumber detected: " . $newcourse->idnumber);
                     }
                     continue;
                 }
             }
             $c = create_course($newcourse);
             if ($verbose) {
                 mtrace("  creating course: {$c->id}, {$c->fullname}, {$c->shortname}, {$c->idnumber}, {$c->category}");
             }
         }
         unset($createcourses);
         unset($template);
     }
     // Close db connection.
     $extdb->Close();
     if ($verbose) {
         mtrace('...course synchronisation finished.');
     }
     return 0;
 }
Exemple #10
0
 /**
  * This function approves the request turning it into a course
  *
  * This function converts the course request into a course, at the same time
  * transferring any files used in the summary to the new course and then removing
  * the course request and the files associated with it.
  *
  * @return int The id of the course that was created from this request
  */
 public function approve()
 {
     global $CFG, $DB, $USER;
     $user = $DB->get_record('user', array('id' => $this->properties->requester, 'deleted' => 0), '*', MUST_EXIST);
     $category = get_course_category($CFG->defaultrequestcategory);
     $courseconfig = get_config('moodlecourse');
     // Transfer appropriate settings
     $data = clone $this->properties;
     unset($data->id);
     unset($data->reason);
     unset($data->requester);
     // Set category
     $data->category = $category->id;
     $data->sortorder = $category->sortorder;
     // place as the first in category
     // Set misc settings
     $data->requested = 1;
     // Apply course default settings
     $data->format = $courseconfig->format;
     $data->numsections = $courseconfig->numsections;
     $data->hiddensections = $courseconfig->hiddensections;
     $data->newsitems = $courseconfig->newsitems;
     $data->showgrades = $courseconfig->showgrades;
     $data->showreports = $courseconfig->showreports;
     $data->maxbytes = $courseconfig->maxbytes;
     $data->groupmode = $courseconfig->groupmode;
     $data->groupmodeforce = $courseconfig->groupmodeforce;
     $data->visible = $courseconfig->visible;
     $data->visibleold = $data->visible;
     $data->lang = $courseconfig->lang;
     $course = create_course($data);
     $context = get_context_instance(CONTEXT_COURSE, $course->id, MUST_EXIST);
     // add enrol instances
     if (!$DB->record_exists('enrol', array('courseid' => $course->id, 'enrol' => 'manual'))) {
         if ($manual = enrol_get_plugin('manual')) {
             $manual->add_default_instance($course);
         }
     }
     // enrol the requester as teacher if necessary
     if (!empty($CFG->creatornewroleid) and !is_viewing($context, $user, 'moodle/role:assign') and !is_enrolled($context, $user, 'moodle/role:assign')) {
         enrol_try_internal_enrol($course->id, $user->id, $CFG->creatornewroleid);
     }
     $this->delete();
     $a = new stdClass();
     $a->name = format_string($course->fullname, true, array('context' => get_context_instance(CONTEXT_COURSE, $course->id)));
     $a->url = $CFG->wwwroot . '/course/view.php?id=' . $course->id;
     $this->notify($user, $USER, 'courserequestapproved', get_string('courseapprovedsubject'), get_string('courseapprovedemail2', 'moodle', $a));
     return $course->id;
 }
Exemple #11
0
    /**
     * Create a test course
     * @param array|stdClass $record
     * @param array $options with keys:
     *      'createsections'=>bool precreate all sections
     * @return stdClass course record
     */
    public function create_course($record=null, array $options=null) {
        global $DB, $CFG;
        require_once("$CFG->dirroot/course/lib.php");

        $this->coursecount++;
        $i = $this->coursecount;

        $record = (array)$record;

        if (!isset($record['fullname'])) {
            $record['fullname'] = 'Test course '.$i;
        }

        if (!isset($record['shortname'])) {
            $record['shortname'] = 'tc_'.$i;
        }

        if (!isset($record['idnumber'])) {
            $record['idnumber'] = '';
        }

        if (!isset($record['format'])) {
            $record['format'] = 'topics';
        }

        if (!isset($record['newsitems'])) {
            $record['newsitems'] = 0;
        }

        if (!isset($record['numsections'])) {
            $record['numsections'] = 5;
        }

        if (!isset($record['summary'])) {
            $record['summary'] = "Test course $i\n$this->loremipsum";
        }

        if (!isset($record['summaryformat'])) {
            $record['summaryformat'] = FORMAT_MOODLE;
        }

        if (!isset($record['category'])) {
            $record['category'] = $DB->get_field_select('course_categories', "MIN(id)", "parent=0");
        }

        $course = create_course((object)$record);
        context_course::instance($course->id);
        if (!empty($options['createsections'])) {
            if (isset($course->numsections)) {
                course_create_sections_if_missing($course, range(0, $course->numsections));
            } else {
                course_create_sections_if_missing($course, 0);
            }
        }

        return $course;
    }
function create_restored_course(&$tool_content, $restoreThis, $course_code, $course_lang, $course_title, $course_desc, $course_vis, $course_prof) {
    global $webDir, $urlServer, $urlAppend, $langEnter, $langBack, $currentCourseCode;
    require_once 'modules/create_course/functions.php';
    require_once 'modules/course_info/restorehelper.class.php';
    require_once 'include/lib/fileManageLib.inc.php';
    $new_course_code = null;
    $new_course_id = null;

    Database::get()->transaction(function() use (&$new_course_code, &$new_course_id, $restoreThis, $course_code, $course_lang, $course_title, $course_desc, $course_vis, $course_prof, $webDir, &$tool_content, $urlServer, $urlAppend) {
        $departments = array();
        if (isset($_POST['department'])) {
            foreach ($_POST['department'] as $did) {
                $departments[] = intval($did);
            }
        } else {
            $minDep = Database::get()->querySingle("SELECT MIN(id) AS min FROM hierarchy");
            if ($minDep) {
                $departments[0] = $minDep->min;
            }
        }

        $r = $restoreThis . '/html';
        list($new_course_code, $new_course_id) = create_course($course_code, $course_lang, $course_title, $course_desc, $departments, $course_vis, $course_prof);
        if (!$new_course_code) {
            $tool_content = "<div class='alert alert-warning'>" . $GLOBALS['langError'] . "</div>";
            draw($tool_content, 3);
            exit;
        }

        if (!file_exists($restoreThis)) {
            redirect_to_home_page('modules/course_info/restore_course.php');
        }
        $config_data = unserialize(file_get_contents($restoreThis . '/config_vars'));
        // If old $urlAppend didn't end in /, add it
        if (substr($config_data['urlAppend'], -1) !== '/') {
            $config_data['urlAppend'] .= '/';
        }
        $eclass_version = (isset($config_data['version'])) ? $config_data['version'] : null;
        $backupData = null;
        if (file_exists($restoreThis . '/backup.php')) {
            $backupData = parse_backup_php($restoreThis . '/backup.php');
            $eclass_version = $backupData['eclass_version'];
        }
        $restoreHelper = new RestoreHelper($eclass_version);

        $course_file = $restoreThis . '/' . $restoreHelper->getFile('course');
        if (file_exists($course_file)) {
            $course_dataArr = unserialize(file_get_contents($course_file));
            $course_data = $course_dataArr[0];
            // update course query
            $upd_course_sql = "UPDATE course SET keywords = ?s, doc_quota = ?f, video_quota = ?f, "
                            . " group_quota = ?f, dropbox_quota = ?f, glossary_expand = ?d ";
            $upd_course_args = array(
                $course_data[$restoreHelper->getField('course', 'keywords')],
                floatval($course_data['doc_quota']),
                floatval($course_data['video_quota']),
                floatval($course_data['group_quota']),
                floatval($course_data['dropbox_quota']),
                intval($course_data[$restoreHelper->getField('course', 'glossary_expand')])
            );
            if (isset($course_data['home_layout']) and isset($course_data['course_image'])) {
                $upd_course_sql .= ', home_layout = ?d, course_image = ?s ';
                $upd_course_args[] = $course_data['home_layout'];
                $upd_course_args[] = $course_data['course_image'];
            }
            // Set keywords to '' if NULL
            if (!isset($upd_course_args[0])) {
                $upd_course_args[0] = '';
            }
            // handle course weekly if exists
            if (isset($course_data['view_type']) && isset($course_data['start_date']) && isset($course_data['finish_date'])) {
                $upd_course_sql .= " , view_type = ?s, start_date = ?t, finish_date = ?t ";
                array_push($upd_course_args,
                    $course_data['view_type'],
                    $course_data['start_date'],
                    $course_data['finish_date']
                );
            }
            $upd_course_sql .= " WHERE id = ?d ";
            array_push($upd_course_args, intval($new_course_id));

            Database::get()->query($upd_course_sql, $upd_course_args);
        }

        $userid_map = array();
        $user_file = $restoreThis . '/user';
        if (file_exists($user_file)) {
            $cours_user = unserialize(file_get_contents($restoreThis . '/' . $restoreHelper->getFile('course_user')));
            $userid_map = restore_users(unserialize(file_get_contents($user_file)), $cours_user, $departments, $restoreHelper);
            register_users($new_course_id, $userid_map, $cours_user, $restoreHelper);
        }
        $userid_map[0] = 0;
        $userid_map[-1] = -1;

        $coursedir = "${webDir}/courses/$new_course_code";
        $videodir = "${webDir}/video/$new_course_code";
        move_dir($r, $coursedir);
        if (is_dir($restoreThis . '/video_files')) {
            move_dir($restoreThis . '/video_files', $videodir);
        }
        course_index($new_course_code);
        $tool_content .= "<div class='alert alert-info'>" . $GLOBALS['langCopyFiles'] . " $coursedir</div>";

        require_once 'upgrade/functions.php';
        load_global_messages();

        $url_prefix_map = array(
            $config_data['urlServer'] . 'modules/ebook/show.php/' . $course_data['code'] =>
            $urlServer . 'modules/ebook/show.php/' . $new_course_code,
            $config_data['urlAppend'] . 'modules/ebook/show.php/' . $course_data['code'] =>
            $urlAppend . 'modules/ebook/show.php/' . $new_course_code,
            $config_data['urlServer'] . 'modules/document/file.php/' . $course_data['code'] =>
            $urlServer . 'modules/document/file.php/' . $new_course_code,
            $config_data['urlAppend'] . 'modules/document/file.php/' . $course_data['code'] =>
            $urlAppend . 'modules/document/file.php/' . $new_course_code,
            $config_data['urlServer'] . 'courses/' . $course_data['code'] =>
            $urlServer . 'courses/' . $new_course_code,
            $config_data['urlAppend'] . 'courses/' . $course_data['code'] =>
            $urlAppend . 'courses/' . $new_course_code,
            $course_data['code'] =>
            $new_course_code);

        if ($restoreHelper->getBackupVersion() === RestoreHelper::STYLE_3X) {
            restore_table($restoreThis, 'course_module', array('set' => array('course_id' => $new_course_id), 'delete' => array('id')), $url_prefix_map, $backupData, $restoreHelper);
        } else if ($restoreHelper->getBackupVersion() === RestoreHelper::STYLE_2X) {
            create_modules($new_course_id);
            foreach (get_tabledata_from_parsed('accueil', $backupData, $restoreHelper) as $accueil) {
                Database::get()->query('UPDATE course_module SET visible = ?d WHERE course_id = ?d AND module_id = ?d',
                    $accueil['visible'], $new_course_id, $accueil['id']);
            }
        }
        restore_table($restoreThis, 'announcement', array('set' => array('course_id' => $new_course_id), 'delete' => array('id', 'preview')), $url_prefix_map, $backupData, $restoreHelper);
        restore_table($restoreThis, 'group_properties', array('set' => array('course_id' => $new_course_id)), $url_prefix_map, $backupData, $restoreHelper);
        $group_map = restore_table($restoreThis, 'group', array('set' => array('course_id' => $new_course_id), 'return_mapping' => 'id'), $url_prefix_map, $backupData, $restoreHelper);
        restore_table($restoreThis, 'group_members', array('map' => array('group_id' => $group_map, 'user_id' => $userid_map)), $url_prefix_map, $backupData, $restoreHelper);

        // Forums Restore
        $forum_category_map = restore_table($restoreThis, 'forum_category', array('set' => array('course_id' => $new_course_id),
            'return_mapping' => 'id'), $url_prefix_map, $backupData, $restoreHelper);
        $forum_category_map[0] = 0;
        $forum_map = restore_table($restoreThis, 'forum', array('set' => array('course_id' => $new_course_id),
            'return_mapping' => 'id', 'map' => array('cat_id' => $forum_category_map)), $url_prefix_map, $backupData, $restoreHelper);
        $forum_map[0] = 0;
        $forum_topic_map = restore_table($restoreThis, 'forum_topic', array('return_mapping' => 'id',
            'map' => array('forum_id' => $forum_map, 'poster_id' => $userid_map)), $url_prefix_map, $backupData, $restoreHelper);
        $forum_topic_map[0] = 0;
        $forum_post_options = array('return_mapping' => 'id',
                                    'map' => array('topic_id' => $forum_topic_map,
                                                   'poster_id' => $userid_map));
        if ($restoreHelper->getBackupVersion() === RestoreHelper::STYLE_2X) {
            $forum_post_options['set'] = array('post_text' => '');
        }
        $forum_post_map = restore_table($restoreThis, 'forum_post', $forum_post_options, $url_prefix_map, $backupData, $restoreHelper);
        $forum_post_map[0] = 0;
        restore_table($restoreThis, 'forum_notify', array('set' => array('course_id' => $new_course_id),
            'map' => array('user_id' => $userid_map, 'cat_id' => $forum_category_map, 'forum_id' => $forum_map, 'topic_id' => $forum_topic_map),
            'delete' => array('id')), $url_prefix_map, $backupData, $restoreHelper);
        restore_table($restoreThis, 'forum_user_stats', array('set' => array('course_id' => $new_course_id),
        'map' => array('user_id' => $userid_map)), $url_prefix_map, $backupData, $restoreHelper);
        if ($restoreHelper->getBackupVersion() === RestoreHelper::STYLE_2X
                && isset($backupData) && is_array($backupData)
                && isset($backupData['query']) && is_array($backupData['query'])) {
            $postsText = get_tabledata_from_parsed('posts_text', $backupData, $restoreHelper);
            foreach ($postsText as $ptData) {
                if (array_key_exists($ptData['post_id'], $forum_post_map)) {
                    Database::get()->query("UPDATE forum_post SET post_text = ?s WHERE id = ?d", $ptData['post_text'], intval($forum_post_map[$ptData['post_id']]));
                }
            }
        }

        $forumLastPosts = Database::get()->queryArray("SELECT DISTINCT last_post_id FROM forum WHERE course_id = ?d ", intval($new_course_id));
        if (is_array($forumLastPosts) && count($forumLastPosts) > 0) {
            foreach ($forumLastPosts as $lastPost) {
                if (isset($forum_post_map[$lastPost->last_post_id])) {
                    Database::get()->query("UPDATE forum SET last_post_id = ?d WHERE course_id = ?d AND last_post_id = ?d", intval($forum_post_map[$lastPost->last_post_id]), intval($new_course_id), intval($lastPost->last_post_id));
                }
            }
        }

        $topicLastPosts = Database::get()->queryArray("SELECT DISTINCT last_post_id FROM forum_topic WHERE forum_id IN (SELECT id FROM forum WHERE course_id = ?d)", intval($new_course_id));
        if (is_array($topicLastPosts) && count($topicLastPosts) > 0) {
            foreach ($topicLastPosts as $lastPost) {
                if (isset($forum_post_map[$lastPost->last_post_id])) {
                    Database::get()->query("UPDATE forum_topic SET last_post_id = ?d WHERE last_post_id = ?d", intval($forum_post_map[$lastPost->last_post_id]), intval($lastPost->last_post_id));
                }
            }
        }

        $parentPosts = Database::get()->queryArray("SELECT DISTINCT parent_post_id FROM forum_post WHERE topic_id IN (SELECT id FROM forum_topic WHERE forum_id IN (SELECT id FROM forum WHERE course_id = ?d))", intval($new_course_id));
        if (is_array($parentPosts) && count($parentPosts) > 0) {
            foreach ($parentPosts as $parentPost) {
                if (isset($forum_post_map[$parentPost->parent_post_id])) {
                    Database::get()->query("UPDATE forum_post SET parent_post_id = ?d WHERE parent_post_id = ?d", intval($forum_post_map[$parentPost->parent_post_id]), intval($parentPost->parent_post_id));
                }
            }
        }
        // Forums Restore End

        // Glossary Restore
        $glossary_category_map = restore_table($restoreThis, 'glossary_category', array('set' => array('course_id' => $new_course_id),
            'return_mapping' => 'id'), $url_prefix_map, $backupData, $restoreHelper);
        $glossary_category_map[0] = 0;
        restore_table($restoreThis, 'glossary', array('set' => array('course_id' => $new_course_id),
            'delete' => array('id'), 'map' => array('category_id' => $glossary_category_map)), $url_prefix_map, $backupData, $restoreHelper);
        // Glossary Restore End

        $link_category_map = restore_table($restoreThis, 'link_category', array('set' => array('course_id' => $new_course_id),
            'return_mapping' => 'id'), $url_prefix_map, $backupData, $restoreHelper);
        $link_category_map[0] = 0;
        $link_category_map[-1] = -1;
        $link_category_map[-2] = -2;
        $link_map = restore_table($restoreThis, 'link', array('set' => array('course_id' => $new_course_id),
            'map' => array('category' => $link_category_map, 'user_id' => $userid_map), 'return_mapping' => 'id'), $url_prefix_map, $backupData, $restoreHelper);
        $ebook_map = restore_table($restoreThis, 'ebook', array('set' => array('course_id' => $new_course_id), 'return_mapping' => 'id'), $url_prefix_map, $backupData, $restoreHelper);
        foreach ($ebook_map as $old_id => $new_id) {
            // new and old id might overlap as the map contains multiple values!
            rename("$coursedir/ebook/$old_id", "$coursedir/ebook/__during_restore__$new_id");
        }
        foreach ($ebook_map as $old_id => $new_id) {
            // better to use an intermediary rename step
            rename("$coursedir/ebook/__during_restore__$new_id", "$coursedir/ebook/$new_id");
        }
        $document_map = restore_table($restoreThis, 'document', array('set' => array('course_id' => $new_course_id),
            'map_function' => 'document_map_function',
            'map_function_data' => array(1 => $group_map, 2 => $ebook_map),
            'return_mapping' => 'id'), $url_prefix_map, $backupData, $restoreHelper);
        $ebook_section_map = restore_table($restoreThis, 'ebook_section', array('map' => array('ebook_id' => $ebook_map),
            'return_mapping' => 'id'), $url_prefix_map, $backupData, $restoreHelper);
        $ebook_subsection_map = restore_table($restoreThis, 'ebook_subsection', array('map' => array('section_id' => $ebook_section_map,
            'file_id' => $document_map), 'delete' => array('file'), 'return_mapping' => 'id'), $url_prefix_map, $backupData, $restoreHelper);

        // Video
        $videocat_map = restore_table($restoreThis, 'video_category', array('set' => array('course_id' => $new_course_id), 'return_mapping' => 'id'), $url_prefix_map, $backupData, $restoreHelper);
        $videocat_map[''] = '';
        $videocat_map[0] = 0;
        $video_map = restore_table($restoreThis, 'video', array(
            'map' => array('category' => $videocat_map),
            'set' => array('course_id' => $new_course_id),
            'return_mapping' => 'id'
        ), $url_prefix_map, $backupData, $restoreHelper);
        $videolink_map = restore_table($restoreThis, 'videolink', array(
            'map' => array('category' => $videocat_map),
            'set' => array('course_id' => $new_course_id),
            'return_mapping' => 'id'
        ), $url_prefix_map, $backupData, $restoreHelper);

        // Dropbox
        $dropbox_map = restore_table($restoreThis, 'dropbox_msg', array('set' => array('course_id' => $new_course_id),
                'map' => array('author_id' => $userid_map), 'return_mapping' => 'id'), $url_prefix_map, $backupData, $restoreHelper);
        restore_table($restoreThis, 'dropbox_attachment', array('map' => array('msg_id' => $dropbox_map), 'return_mapping' => 'id'), $url_prefix_map, $backupData, $restoreHelper);
        restore_table($restoreThis, 'dropbox_index', array('map' => array('msg_id' => $dropbox_map, 'recipient_id' => $userid_map)), $url_prefix_map, $backupData, $restoreHelper);

        // Learning Path
        $lp_learnPath_map = restore_table($restoreThis, 'lp_learnPath', array('set' => array('course_id' => $new_course_id),
            'return_mapping' => 'learnPath_id'), $url_prefix_map, $backupData, $restoreHelper);
        $lp_module_map = restore_table($restoreThis, 'lp_module', array('set' => array('course_id' => $new_course_id),
            'return_mapping' => 'module_id'), $url_prefix_map, $backupData, $restoreHelper);
        $lp_asset_map = restore_table($restoreThis, 'lp_asset', array('map' => array('module_id' => $lp_module_map),
            'return_mapping' => 'asset_id'), $url_prefix_map, $backupData, $restoreHelper);
        // update lp_module startAsset_id with new asset_id from map
        foreach ($lp_asset_map as $key => $value) {
            Database::get()->query("UPDATE lp_module SET `startAsset_id` = ?d "
                    . "WHERE `course_id` = ?d "
                    . "AND `startAsset_id` = ?d", intval($value), intval($new_course_id), intval($key));
        }
        $lp_rel_learnPath_module_map = restore_table($restoreThis, 'lp_rel_learnPath_module', array('map' => array('learnPath_id' => $lp_learnPath_map,
            'module_id' => $lp_module_map), 'return_mapping' => 'learnPath_module_id'), $url_prefix_map, $backupData, $restoreHelper);
        // update parent
        foreach ($lp_rel_learnPath_module_map as $key => $value) {
            Database::get()->query("UPDATE lp_rel_learnPath_module SET `parent` = ?d "
                    . "WHERE `learnPath_id` IN (SELECT learnPath_id FROM lp_learnPath WHERE course_id = ?d) "
                    . "AND `parent` = ?d", intval($value), intval($new_course_id), intval($key));
        }
        restore_table($restoreThis, 'lp_user_module_progress', array('delete' => array('user_module_progress_id'),
            'map' => array('user_id' => $userid_map,
            'learnPath_module_id' => $lp_rel_learnPath_module_map,
            'learnPath_id' => $lp_learnPath_map)), $url_prefix_map, $backupData, $restoreHelper);
        foreach ($lp_learnPath_map as $old_id => $new_id) {
            // new and old id might overlap as the map contains multiple values!
            $old_dir = "$coursedir/scormPackages/path_$old_id";
            if (file_exists($old_dir) && is_dir($old_dir)) {
                rename($old_dir, "$coursedir/scormPackages/__during_restore__$new_id");
            }
        }
        foreach ($lp_learnPath_map as $old_id => $new_id) {
            // better to use an intermediary rename step
            $tempLPDir = "$coursedir/scormPackages/__during_restore__$new_id";
            if (file_exists($tempLPDir) && is_dir($tempLPDir)) {
                rename($tempLPDir, "$coursedir/scormPackages/path_$new_id");
            }
        }

        // Wiki
        $wiki_map = restore_table($restoreThis, 'wiki_properties', array('set' => array('course_id' => $new_course_id),
            'return_mapping' => 'id'), $url_prefix_map, $backupData, $restoreHelper);
        restore_table($restoreThis, 'wiki_acls', array('map' => array('wiki_id' => $wiki_map)), $url_prefix_map, $backupData, $restoreHelper);
        $wiki_pages_map = restore_table($restoreThis, 'wiki_pages', array('map' => array('wiki_id' => $wiki_map,
            'owner_id' => $userid_map), 'return_mapping' => 'id'), $url_prefix_map, $backupData, $restoreHelper);
        restore_table($restoreThis, 'wiki_pages_content', array('delete' => array('id'),
            'map' => array('pid' => $wiki_pages_map, 'editor_id' => $userid_map)), $url_prefix_map, $backupData, $restoreHelper);

        // Blog
        if (file_exists("$restoreThis/blog_post")) {
            $blog_map = restore_table($restoreThis, 'blog_post', array('set' => array('course_id' => $new_course_id),
            'return_mapping' => 'id'), $url_prefix_map, $backupData, $restoreHelper);
        }

        // Comments
        if (file_exists("$restoreThis/comments")) {
            $comment_map = restore_table($restoreThis, 'comments', array('delete' => array('id'),
            'map' => array('user_id' => $userid_map),
            'map_function' => 'comments_map_function',
            'map_function_data' => array($blog_map, $new_course_id),
            'return_mapping' => 'id'), $url_prefix_map, $backupData, $restoreHelper);
        }
        
        //Abuse Report
        if (file_exists("$restoreThis/abuse_report")) {
            restore_table($restoreThis, 'abuse_report', array('delete' => array('id'),
            'set' => array('course_id' => $new_course_id),
            'map' => array('user_id' => $userid_map),
            'map_function' => 'abuse_report_map_function',
            'map_function_data' => array($forum_post_map, 
            $comment_map, $link_map)), $url_prefix_map, $backupData, $restoreHelper);
        }

        // Rating
        if (file_exists("$restoreThis/rating")) {
            restore_table($restoreThis, 'rating', array('delete' => array('rate_id'),
            'map' => array('user_id' => $userid_map),
            'map_function' => 'ratings_map_function',
            'map_function_data' => array($blog_map, $forum_post_map, $link_map,
            $new_course_id)), $url_prefix_map, $backupData, $restoreHelper);
        }
        if (file_exists("$restoreThis/rating_cache")) {
            restore_table($restoreThis, 'rating_cache', array('delete' => array('rate_cache_id'),
            'map_function' => 'ratings_map_function',
            'map_function_data' => array($blog_map, $forum_post_map, $link_map,
            $new_course_id)), $url_prefix_map, $backupData, $restoreHelper);
        }

        
        // Course_settings
        if (file_exists("$restoreThis/course_settings")) {
            restore_table($restoreThis, 'course_settings', array('set' => array('course_id' => $new_course_id)), $url_prefix_map, $backupData, $restoreHelper);
        }

        // Polls
        $poll_map = restore_table($restoreThis, 'poll', array('set' => array('course_id' => $new_course_id),
            'map' => array('creator_id' => $userid_map), 'return_mapping' => 'pid', 'delete' => array('type')),
             $url_prefix_map, $backupData, $restoreHelper);
        $poll_question_map = restore_table($restoreThis, 'poll_question', array('map' => array('pid' => $poll_map),
            'return_mapping' => 'pqid'), $url_prefix_map, $backupData, $restoreHelper);
        $poll_answer_map = restore_table($restoreThis, 'poll_question_answer', array('map' => array('pqid' => $poll_question_map),
            'return_mapping' => 'pqaid'), $url_prefix_map, $backupData, $restoreHelper);
        restore_table($restoreThis, 'poll_answer_record', array('delete' => array('arid'),
            'map' => array('pid' => $poll_map,
            'qid' => $poll_question_map,
            'aid' => $poll_answer_map,
            'user_id' => $userid_map)), $url_prefix_map, $backupData, $restoreHelper);

        // Assignments
        if (!isset($group_map[0])) {
            $group_map[0] = 0;
        }
        $assignments_map = restore_table($restoreThis, 'assignment', array('set' => array('course_id' => $new_course_id),
            'return_mapping' => 'id'), $url_prefix_map, $backupData, $restoreHelper);
        $assignments_map[0] = 0;
        restore_table($restoreThis, 'assignment_submit', array('delete' => array('id'),
            'map' => array('uid' => $userid_map, 'assignment_id' => $assignments_map, 'group_id' => $group_map)), $url_prefix_map, $backupData, $restoreHelper);

        // Agenda
        $agenda_map = restore_table($restoreThis, 'agenda', array(
            'return_mapping' => 'id',
            'set' => array('course_id' => $new_course_id)
        ), $url_prefix_map, $backupData, $restoreHelper);
        $agenda_map[0] = 0;

        // Exercises
        $exercise_map = restore_table($restoreThis, 'exercise', array(
            'set' => array('course_id' => $new_course_id),
            'return_mapping' => 'id'
            ), $url_prefix_map, $backupData, $restoreHelper);
        $exercise_map[0] = 0;
        restore_table($restoreThis, 'exercise_user_record', array(
            'delete' => array('eurid'),
            'map' => array('eid' => $exercise_map, 'uid' => $userid_map)
            ), $url_prefix_map, $backupData, $restoreHelper);
        $question_category_map = restore_table($restoreThis, 'exercise_question_cats', array(
            'set' => array('course_id' => $new_course_id),
            'return_mapping' => 'question_cat_id'
            ), $url_prefix_map, $backupData, $restoreHelper);
        $question_category_map[0] = 0;
        $question_map = restore_table($restoreThis, 'exercise_question', array(
            'set' => array('course_id' => $new_course_id),
            'init' => array('category' => 0),
            'map' => array('category' => $question_category_map),
            'return_mapping' => 'id'
            ), $url_prefix_map, $backupData, $restoreHelper);
        restore_table($restoreThis, 'exercise_answer', array(
            'delete' => array('id'),
            'map' => array('question_id' => $question_map)
            ), $url_prefix_map, $backupData, $restoreHelper);
        restore_table($restoreThis, 'exercise_answer_record', array(
            'delete' => array('answer_record_id'),
            'map' => array('question_id' => $question_map,
                'eurid' => $userid_map)
            ), $url_prefix_map, $backupData, $restoreHelper);
        restore_table($restoreThis, 'exercise_with_questions', array(
            'map' => array('question_id' => $question_map, 'exercise_id' => $exercise_map)
            ), $url_prefix_map, $backupData, $restoreHelper);

        $sql = "SELECT asset.asset_id, asset.path FROM `lp_module` AS module, `lp_asset` AS asset
                        WHERE module.startAsset_id = asset.asset_id
                        AND course_id = ?d AND contentType = 'EXERCISE' AND path <> '' AND path IS NOT NULL";
        $rows = Database::get()->queryArray($sql, intval($new_course_id));

        if (is_array($rows) && count($rows) > 0) {
            foreach ($rows as $row) {
                Database::get()->query("UPDATE `lp_asset` SET path = ?s WHERE asset_id = ?d", $exercise_map[$row->path], intval($row->asset_id));
            }
        }

        // Attendance
        $attendance_map = restore_table($restoreThis, 'attendance', array(
            'set' => array('course_id' => $new_course_id),
            'return_mapping' => 'id'
        ), $url_prefix_map, $backupData, $restoreHelper);
        $attendance_activities_map = restore_table($restoreThis, 'attendance_activities', array(
            'map' => array('attendance_id' => $attendance_map),
            'map_function' => 'attendance_gradebook_activities_map_function',
            'map_function_data' => array($assignments_map, $exercise_map),
            'return_mapping' => 'id'
        ), $url_prefix_map, $backupData, $restoreHelper);
        restore_table($restoreThis, 'attendance_book', array(
            'map' => array(
                'attendance_activity_id' => $attendance_activities_map,
                'uid' => $userid_map
            ),
            'delete' => array('id')
        ), $url_prefix_map, $backupData, $restoreHelper);
        restore_table($restoreThis, 'attendance_users', array(
            'map' => array(
                'attendance_id' => $attendance_map,
                'uid' => $userid_map
            ),
            'delete' => array('id')
        ), $url_prefix_map, $backupData, $restoreHelper);

        // Gradebook
        $gradebook_map = restore_table($restoreThis, 'gradebook', array(
            'set' => array('course_id' => $new_course_id),
            'return_mapping' => 'id'
        ), $url_prefix_map, $backupData, $restoreHelper);
        $gradebook_activities_map = restore_table($restoreThis, 'gradebook_activities', array(
            'map' => array('gradebook_id' => $gradebook_map),
            'map_function' => 'attendance_gradebook_activities_map_function',
            'map_function_data' => array($assignments_map, $exercise_map),
            'return_mapping' => 'id'
        ), $url_prefix_map, $backupData, $restoreHelper);
        restore_table($restoreThis, 'gradebook_book', array(
            'map' => array(
                'gradebook_activity_id' => $gradebook_activities_map,
                'uid' => $userid_map
            ),
            'delete' => array('id')
        ), $url_prefix_map, $backupData, $restoreHelper);
        restore_table($restoreThis, 'gradebook_users', array(
            'map' => array(
                'gradebook_id' => $gradebook_map,
                'uid' => $userid_map
            ),
            'delete' => array('id')
        ), $url_prefix_map, $backupData, $restoreHelper);

        // Notes
        restore_table($restoreThis, 'note', array(
            'set' => array('reference_obj_course' => $new_course_id),
            'map' => array('user_id' => $userid_map),
            'map_function' => 'notes_map_function',
            'map_function_data' => array($new_course_id, $agenda_map, $document_map, $link_map,
                $video_map, $videolink_map, $assignments_map, $exercise_map, $ebook_map,
                $lp_learnPath_map),
            'delete' => array('id')
        ), $url_prefix_map, $backupData, $restoreHelper);

        // Units
        $unit_map = restore_table($restoreThis, 'course_units', array('set' => array('course_id' => $new_course_id), 'return_mapping' => 'id'), $url_prefix_map, $backupData, $restoreHelper);
        restore_table($restoreThis, 'unit_resources', array('delete' => array('id'),
            'map' => array('unit_id' => $unit_map),
            'map_function' => 'unit_map_function',
            'map_function_data' => array($document_map,
                $link_category_map,
                $link_map,
                $ebook_map,
                $ebook_section_map,
                $ebook_subsection_map,
                $video_map,
                $videolink_map,
                $lp_learnPath_map,
                $wiki_map,
                $assignments_map,
                $exercise_map,
                $forum_map,
                $forum_topic_map)
            ), $url_prefix_map, $backupData, $restoreHelper);

        // Weekly
        $weekly_map = restore_table($restoreThis, 'course_weekly_view', array(
            'set' => array('course_id' => $new_course_id),
            'return_mapping' => 'id'
            ), $url_prefix_map, $backupData, $restoreHelper);
        restore_table($restoreThis, 'course_weekly_view_activities', array(
            'delete' => array('id'),
            'map' => array('course_weekly_view_id' => $weekly_map),
            'map_function' => 'unit_map_function',
            'map_function_data' => array($document_map,
                $link_category_map,
                $link_map,
                $ebook_map,
                $ebook_section_map,
                $ebook_subsection_map,
                $video_map,
                $videolink_map,
                $lp_learnPath_map,
                $wiki_map,
                $assignments_map,
                $exercise_map,
                $forum_map,
                $forum_topic_map)
            ), $url_prefix_map, $backupData, $restoreHelper);

        restore_table($restoreThis, 'course_description', array(
            'set' => array('course_id' => $new_course_id),
            'delete' => array('id')
            ), $url_prefix_map, $backupData, $restoreHelper);

        removeDir($restoreThis);

        // index course after restoring
        require_once 'modules/search/indexer.class.php';
        Indexer::queueAsync(Indexer::REQUEST_REMOVEALLBYCOURSE, Indexer::RESOURCE_IDX, $new_course_id);
        Indexer::queueAsync(Indexer::REQUEST_STOREALLBYCOURSE, Indexer::RESOURCE_IDX, $new_course_id);
    });

    // check/cleanup video files after restore transaction
    if ($new_course_code != null && $new_course_id != null) {
        $videodir = $webDir . "/video/" . $new_course_code;
        $videos = scandir($videodir);
        foreach ($videos as $videofile) {
            if (is_dir($videofile)) {
                continue;
            }

            $vlike = '/' . $videofile;

            if (!isWhitelistAllowed($videofile)) {
                unlink($videodir . "/" . $videofile);
                Database::get()->query("DELETE FROM `video` WHERE course_id = ?d AND path LIKE ?s", $new_course_id, $vlike);
                continue;
            }

            $vcnt = Database::get()->querySingle("SELECT count(id) AS count FROM `video` WHERE course_id = ?d AND path LIKE ?s", $new_course_id, $vlike)->count;
            if ($vcnt <= 0) {
                unlink($videodir . "/" . $videofile);
            }
        }
        $backUrl = $urlAppend . (isset($currentCourseCode)? "courses/$currentCourseCode/": 'modules/admin/');
        $tool_content .= action_bar(array(
            array('title' => $langEnter,
                  'url' => $urlAppend . "courses/$new_course_code/",
                  'icon' => 'fa-arrow-right',
                  'level' => 'primary-label',
                  'button-class' => 'btn-success'),
            array('title' => $langBack,
                  'url' => $backUrl,
                  'icon' => 'fa-reply',
                  'level' => 'primary-label')), false);

    }
}
Exemple #13
0
 /**
  * Will create the moodle course from the template
  * course_ext is an array as obtained from ldap -- flattened somewhat
  *
  * @param array $course_ext
  * @param progress_trace $trace
  * @return mixed false on error, id for the newly created course otherwise.
  */
 function create_course($course_ext, progress_trace $trace)
 {
     global $CFG, $DB;
     require_once "{$CFG->dirroot}/course/lib.php";
     // Override defaults with template course
     $template = false;
     if ($this->get_config('template')) {
         if ($template = $DB->get_record('course', array('shortname' => $this->get_config('template')))) {
             $template = fullclone(course_get_format($template)->get_course());
             unset($template->id);
             // So we are clear to reinsert the record
             unset($template->fullname);
             unset($template->shortname);
             unset($template->idnumber);
         }
     }
     if (!$template) {
         $courseconfig = get_config('moodlecourse');
         $template = new stdClass();
         $template->summary = '';
         $template->summaryformat = FORMAT_HTML;
         $template->format = $courseconfig->format;
         $template->newsitems = $courseconfig->newsitems;
         $template->showgrades = $courseconfig->showgrades;
         $template->showreports = $courseconfig->showreports;
         $template->maxbytes = $courseconfig->maxbytes;
         $template->groupmode = $courseconfig->groupmode;
         $template->groupmodeforce = $courseconfig->groupmodeforce;
         $template->visible = $courseconfig->visible;
         $template->lang = $courseconfig->lang;
         $template->enablecompletion = $courseconfig->enablecompletion;
     }
     $course = $template;
     $course->category = $this->get_config('category');
     if (!$DB->record_exists('course_categories', array('id' => $this->get_config('category')))) {
         $categories = $DB->get_records('course_categories', array(), 'sortorder', 'id', 0, 1);
         $first = reset($categories);
         $course->category = $first->id;
     }
     // Override with required ext data
     $course->idnumber = $course_ext[$this->get_config('course_idnumber')][0];
     $course->fullname = $course_ext[$this->get_config('course_fullname')][0];
     $course->shortname = $course_ext[$this->get_config('course_shortname')][0];
     if (empty($course->idnumber) || empty($course->fullname) || empty($course->shortname)) {
         // We are in trouble!
         $trace->output(get_string('cannotcreatecourse', 'enrol_ldap') . ' ' . var_export($course, true));
         return false;
     }
     $summary = $this->get_config('course_summary');
     if (!isset($summary) || empty($course_ext[$summary][0])) {
         $course->summary = '';
     } else {
         $course->summary = $course_ext[$this->get_config('course_summary')][0];
     }
     // Check if the shortname already exists if it does - skip course creation.
     if ($DB->record_exists('course', array('shortname' => $course->shortname))) {
         $trace->output(get_string('duplicateshortname', 'enrol_ldap', $course));
         return false;
     }
     $newcourse = create_course($course);
     return $newcourse->id;
 }
Exemple #14
0
 /**
  * Proceed with the import of the course.
  *
  * @return void
  */
 public function proceed()
 {
     global $CFG, $USER;
     if (!$this->prepared) {
         throw new coding_exception('The course has not been prepared.');
     } else {
         if ($this->has_errors()) {
             throw new moodle_exception('Cannot proceed, errors were detected.');
         } else {
             if ($this->processstarted) {
                 throw new coding_exception('The process has already been started.');
             }
         }
     }
     $this->processstarted = true;
     if ($this->do === self::DO_DELETE) {
         if ($this->delete()) {
             $this->status('coursedeleted', new lang_string('coursedeleted', 'tool_uploadcourse'));
         } else {
             $this->error('errorwhiledeletingcourse', new lang_string('errorwhiledeletingcourse', 'tool_uploadcourse'));
         }
         return true;
     } else {
         if ($this->do === self::DO_CREATE) {
             $course = create_course((object) $this->data);
             $this->id = $course->id;
             $this->status('coursecreated', new lang_string('coursecreated', 'tool_uploadcourse'));
         } else {
             if ($this->do === self::DO_UPDATE) {
                 $course = (object) $this->data;
                 update_course($course);
                 $this->id = $course->id;
                 $this->status('courseupdated', new lang_string('courseupdated', 'tool_uploadcourse'));
             } else {
                 // Strangely the outcome has not been defined, or is unknown!
                 throw new coding_exception('Unknown outcome!');
             }
         }
     }
     // Restore a course.
     if (!empty($this->restoredata)) {
         $rc = new restore_controller($this->restoredata, $course->id, backup::INTERACTIVE_NO, backup::MODE_IMPORT, $USER->id, backup::TARGET_CURRENT_ADDING);
         // Check if the format conversion must happen first.
         if ($rc->get_status() == backup::STATUS_REQUIRE_CONV) {
             $rc->convert();
         }
         if ($rc->execute_precheck()) {
             $rc->execute_plan();
             $this->status('courserestored', new lang_string('courserestored', 'tool_uploadcourse'));
         } else {
             $this->error('errorwhilerestoringcourse', new lang_string('errorwhilerestoringthecourse', 'tool_uploadcourse'));
         }
         $rc->destroy();
     }
     // Proceed with enrolment data.
     $this->process_enrolment_data($course);
     // Reset the course.
     if ($this->importoptions['reset'] || $this->options['reset']) {
         if ($this->do === self::DO_UPDATE && $this->can_reset()) {
             $this->reset($course);
             $this->status('coursereset', new lang_string('coursereset', 'tool_uploadcourse'));
         }
     }
     // Mark context as dirty.
     $context = context_course::instance($course->id);
     $context->mark_dirty();
 }
Exemple #15
0
 raise_memory_limit(MEMORY_EXTRA);
 // Are we creating a new context (that means a new course tool)?
 if ($service == 'create_context') {
     $custom_context_template = $context->info['custom_context_template'];
     if (!($tplcourse = $DB->get_record('course', array('idnumber' => $custom_context_template), '*', IGNORE_MULTIPLE))) {
         print_error('invalidtplcourse', 'local_ltiprovider');
     }
     require_once "{$CFG->dirroot}/course/lib.php";
     $newcourse = new stdClass();
     $newcourse->fullname = local_ltiprovider_get_new_course_info('fullname', $context);
     $newcourse->shortname = local_ltiprovider_get_new_course_info('shortname', $context);
     $newcourse->idnumber = local_ltiprovider_get_new_course_info('idnumber', $context);
     $categories = $DB->get_records('course_categories', null, '', 'id', 0, 1);
     $category = array_shift($categories);
     $newcourse->category = $category->id;
     $course = create_course($newcourse);
     $coursecontext = context_course::instance($course->id);
     // Create the tool that provide the full course.
     $tool = local_ltiprovider_create_tool($course->id, $coursecontext->id, $context);
     $username = local_ltiprovider_create_username($context->info['oauth_consumer_key'], $context->info['user_id']);
     $userrestoringid = $DB->get_field('user', 'id', array('username' => $username));
     // Duplicate course + users.
     $course = local_ltiprovider_duplicate_course($tplcourse->id, $course, 1, $options = array(array('name' => 'users', 'value' => 1)), $userrestoringid, $context);
     echo json_encode($course);
 } else {
     if ($service == 'duplicate_resource') {
         $idnumber = $context->info['custom_resource_link_copy_id'];
         $resource_link_id = $context->info['resource_link_id'];
         if (!$tool) {
             print_error('missingrequiredtool', 'local_ltiprovider');
         }
    redirect($returnurl);
} else {
    if ($data = $mform->get_data()) {
        $data->userid = $USER->id;
        // Merge data with course defaults.
        $company = $DB->get_record('company', array('id' => $companyid));
        if (!empty($company->category)) {
            $data->category = $company->category;
        } else {
            $data->category = $CFG->defaultrequestcategory;
        }
        $courseconfig = get_config('moodlecourse');
        $mergeddata = (object) array_merge((array) $courseconfig, (array) $data);
        // Turn on restricted modules.
        $mergeddata->restrictmodules = 1;
        if (!($course = create_course($mergeddata, $editoroptions))) {
            $this->verbose("Error inserting a new course in the database!");
            if (!$this->get('ignore_errors')) {
                die;
            }
        }
        // If licensed course, turn off all enrolments apart from license enrolment as
        // default  Moving this to a separate page.
        if ($data->selfenrol == 0) {
            if ($instances = $DB->get_records('enrol', array('courseid' => $course->id))) {
                foreach ($instances as $instance) {
                    $updateinstance = (array) $instance;
                    if ($instance->enrol == 'self') {
                        $updateinstance['status'] = 0;
                    } else {
                        if ($instance->enrol == 'license') {
Exemple #17
0
 public function test_update_course()
 {
     global $DB;
     $this->resetAfterTest();
     $defaultcategory = $DB->get_field_select('course_categories', 'MIN(id)', 'parent = 0');
     $course = new stdClass();
     $course->fullname = 'Apu loves Unit Təsts';
     $course->shortname = 'test1';
     $course->idnumber = '1';
     $course->summary = 'Awesome!';
     $course->summaryformat = FORMAT_PLAIN;
     $course->format = 'topics';
     $course->newsitems = 0;
     $course->numsections = 5;
     $course->category = $defaultcategory;
     $created = create_course($course);
     // Ensure the checks only work on idnumber/shortname that are not already ours.
     update_course($created);
     $course->shortname = 'test2';
     $course->idnumber = '2';
     $created2 = create_course($course);
     // Test duplicate idnumber.
     $created2->idnumber = '1';
     try {
         update_course($created2);
         $this->fail('Expected exception when trying to update a course with duplicate idnumber');
     } catch (moodle_exception $e) {
         $this->assertEquals(get_string('courseidnumbertaken', 'error', $created2->idnumber), $e->getMessage());
     }
     // Test duplicate shortname.
     $created2->idnumber = '2';
     $created2->shortname = 'test1';
     try {
         update_course($created2);
         $this->fail('Expected exception when trying to update a course with a duplicate shortname');
     } catch (moodle_exception $e) {
         $this->assertEquals(get_string('shortnametaken', 'error', $created2->shortname), $e->getMessage());
     }
 }
 /**
  * Create  courses
  * @param array $courses
  * @return array courses (id and shortname only)
  */
 public static function create_courses($courses)
 {
     global $CFG, $DB;
     require_once $CFG->dirroot . "/course/lib.php";
     require_once $CFG->libdir . '/completionlib.php';
     $params = self::validate_parameters(self::create_courses_parameters(), array('courses' => $courses));
     $availablethemes = get_plugin_list('theme');
     $availablelangs = get_string_manager()->get_list_of_translations();
     $transaction = $DB->start_delegated_transaction();
     foreach ($params['courses'] as $course) {
         // Ensure the current user is allowed to run this function
         $context = get_context_instance(CONTEXT_COURSECAT, $course['categoryid']);
         try {
             self::validate_context($context);
         } catch (Exception $e) {
             $a = new stdClass();
             $a->message = $e->getMessage();
             $a->catid = $course['categoryid'];
             if (!empty($course['idnumber'])) {
                 $a->idnumber = $course['idnumber'];
             } else {
                 $a->idnumber = get_string('alert_not_reported', 'local_sistemaaulaws');
             }
             throw new moodle_exception('error_cat_context_not_valid', 'local_sistemaaulaws', '', $a);
         }
         require_capability('moodle/course:create', $context);
         // Make sure lang is valid
         if (key_exists('lang', $course) and empty($availablelangs[$course['lang']])) {
             $a = new stdClass();
             $a->lang = $course['lang'];
             $a->idnumber = $course['idnumber'];
             $a->name = $course['fullname'];
             $a->object = get_string('object_name_course', 'local_sistemaaulaws');
             $a->object_text_name = get_string('object_text_name_course', 'local_sistemaaulaws');
             throw new moodle_exception('invalid_language_code', 'local_sistemaaulaws', '', $a);
         }
         // Make sure theme is valid
         if (key_exists('forcetheme', $course)) {
             if (!empty($CFG->allowcoursethemes)) {
                 if (empty($availablethemes[$course['forcetheme']])) {
                     $a = new stdClass();
                     $a->idnumber = $course['idnumber'];
                     $a->name = $course['fullname'];
                     $a->theme = $course['forcetheme'];
                     $a->object = get_string('object_name_course', 'local_sistemaaulaws');
                     $a->object_text_name = get_string('object_text_name_course', 'local_sistemaaulaws');
                     throw new modle_exception('invalid_theme', 'local_sistemaaulaws', '', $a);
                 } else {
                     $course['theme'] = $course['forcetheme'];
                 }
             }
         }
         //force visibility if ws user doesn't have the permission to set it
         $category = $DB->get_record('course_categories', array('id' => $course['categoryid']));
         if (!has_capability('moodle/course:visibility', $context)) {
             $course['visible'] = $category->visible;
         }
         //set default value for completion
         $courseconfig = get_config('moodlecourse');
         if (completion_info::is_enabled_for_site()) {
             if (!key_exists('enablecompletion', $course)) {
                 $course['enablecompletion'] = $courseconfig->enablecompletion;
             }
             if (!key_exists('completionstartonenrol', $course)) {
                 $course['completionstartonenrol'] = $courseconfig->completionstartonenrol;
             }
         } else {
             $course['enablecompletion'] = 0;
             $course['completionstartonenrol'] = 0;
         }
         $course['category'] = $course['categoryid'];
         //Note: create_course() core function check shortname, idnumber, category
         $course['id'] = create_course((object) $course)->id;
         $resultcourses[] = array('id' => $course['id'], 'idnumber' => $course['idnumber'], 'shortname' => $course['shortname']);
     }
     $transaction->allow_commit();
     return $resultcourses;
 }
Exemple #19
0
 /**
  * Performs a full sync with external database.
  *
  * First it creates new courses if necessary, then
  * enrols and unenrols users.
  *
  * @param bool $verbose
  * @return int 0 means success, 1 db connect failure, 4 db read failure
  */
 public function sync_courses($verbose = false)
 {
     global $CFG, $DB;
     // make sure we sync either enrolments or courses
     if (!$this->get_config('dbtype') or !$this->get_config('dbhost') or !$this->get_config('newcoursetable') or !$this->get_config('newcoursefullname') or !$this->get_config('newcourseshortname')) {
         if ($verbose) {
             mtrace('Course synchronisation skipped.');
         }
         return 0;
     }
     if ($verbose) {
         mtrace('Starting course synchronisation...');
     }
     // we may need a lot of memory here
     @set_time_limit(0);
     raise_memory_limit(MEMORY_HUGE);
     if (!($extdb = $this->db_init())) {
         mtrace('Error while communicating with external enrolment database');
         return 1;
     }
     // first create new courses
     $table = $this->get_config('newcoursetable');
     $fullname = strtolower($this->get_config('newcoursefullname'));
     $shortname = strtolower($this->get_config('newcourseshortname'));
     $idnumber = strtolower($this->get_config('newcourseidnumber'));
     $category = strtolower($this->get_config('newcoursecategory'));
     $localcategoryfield = $this->get_config('localcategoryfield', 'id');
     $sqlfields = array($fullname, $shortname);
     if ($category) {
         $sqlfields[] = $category;
     }
     if ($idnumber) {
         $sqlfields[] = $idnumber;
     }
     $sql = $this->db_get_sql($table, array(), $sqlfields);
     $createcourses = array();
     if ($rs = $extdb->Execute($sql)) {
         if (!$rs->EOF) {
             while ($fields = $rs->FetchRow()) {
                 $fields = array_change_key_case($fields, CASE_LOWER);
                 $fields = $this->db_decode($fields);
                 if (empty($fields[$shortname]) or empty($fields[$fullname])) {
                     if ($verbose) {
                         mtrace('  error: invalid external course record, shortname and fullname are mandatory: ' . json_encode($fields));
                         // hopefully every geek can read JS, right?
                     }
                     continue;
                 }
                 if ($DB->record_exists('course', array('shortname' => $fields[$shortname]))) {
                     // already exists
                     continue;
                 }
                 // allow empty idnumber but not duplicates
                 if ($idnumber and $fields[$idnumber] !== '' and $fields[$idnumber] !== null and $DB->record_exists('course', array('idnumber' => $fields[$idnumber]))) {
                     if ($verbose) {
                         mtrace('  error: duplicate idnumber, can not create course: ' . $fields[$shortname] . ' [' . $fields[$idnumber] . ']');
                     }
                     continue;
                 }
                 if ($category and !($coursecategory = $DB->get_record('course_categories', array($localcategoryfield => $fields[$category]), 'id'))) {
                     if ($verbose) {
                         mtrace('  error: invalid category ' . $localcategoryfield . ', can not create course: ' . $fields[$shortname]);
                     }
                     continue;
                 }
                 $course = new stdClass();
                 $course->fullname = $fields[$fullname];
                 $course->shortname = $fields[$shortname];
                 $course->idnumber = $idnumber ? $fields[$idnumber] : '';
                 $course->category = $category ? $coursecategory->id : NULL;
                 $createcourses[] = $course;
             }
         }
         $rs->Close();
     } else {
         mtrace('Error reading data from the external course table');
         $extdb->Close();
         return 4;
     }
     if ($createcourses) {
         require_once "{$CFG->dirroot}/course/lib.php";
         $templatecourse = $this->get_config('templatecourse');
         $defaultcategory = $this->get_config('defaultcategory');
         $template = false;
         if ($templatecourse) {
             if ($template = $DB->get_record('course', array('shortname' => $templatecourse))) {
                 unset($template->id);
                 unset($template->fullname);
                 unset($template->shortname);
                 unset($template->idnumber);
             } else {
                 if ($verbose) {
                     mtrace("  can not find template for new course!");
                 }
             }
         }
         if (!$template) {
             $courseconfig = get_config('moodlecourse');
             $template = new stdClass();
             $template->summary = '';
             $template->summaryformat = FORMAT_HTML;
             $template->format = $courseconfig->format;
             $template->numsections = $courseconfig->numsections;
             $template->hiddensections = $courseconfig->hiddensections;
             $template->newsitems = $courseconfig->newsitems;
             $template->showgrades = $courseconfig->showgrades;
             $template->showreports = $courseconfig->showreports;
             $template->maxbytes = $courseconfig->maxbytes;
             $template->groupmode = $courseconfig->groupmode;
             $template->groupmodeforce = $courseconfig->groupmodeforce;
             $template->visible = $courseconfig->visible;
             $template->lang = $courseconfig->lang;
             $template->groupmodeforce = $courseconfig->groupmodeforce;
         }
         if (!$DB->record_exists('course_categories', array('id' => $defaultcategory))) {
             if ($verbose) {
                 mtrace("  default course category does not exist!");
             }
             $categories = $DB->get_records('course_categories', array(), 'sortorder', 'id', 0, 1);
             $first = reset($categories);
             $defaultcategory = $first->id;
         }
         foreach ($createcourses as $fields) {
             $newcourse = clone $template;
             $newcourse->fullname = $fields->fullname;
             $newcourse->shortname = $fields->shortname;
             $newcourse->idnumber = $fields->idnumber;
             $newcourse->category = $fields->category ? $fields->category : $defaultcategory;
             $c = create_course($newcourse);
             if ($verbose) {
                 mtrace("  creating course: {$c->id}, {$c->fullname}, {$c->shortname}, {$c->idnumber}, {$c->category}");
             }
         }
         unset($createcourses);
         unset($template);
     }
     // close db connection
     $extdb->Close();
     if ($verbose) {
         mtrace('...course synchronisation finished.');
     }
     return 0;
 }
 if ($courseid == 0) {
     $data = array();
     $data['fullname'] = 'All Quizzes';
     $data['shortname'] = 'Reader';
     $data['summary'] = 'All Quizzes';
     $data['format'] = "topics";
     $data['numsections'] = count($sections);
     $data['startdate'] = time();
     $data['timecreated'] = time();
     $data['enrollable'] = 1;
     $data['password'] = '******';
     $data['visible'] = 1;
     $data['guest'] = 0;
     $category = $DB->get_record("course_categories", array("visible" => "1"));
     $data['category'] = $category->id;
     $coursedata = create_course($data);
     $courseid = $coursedata->id;
     print_string('process_courseadded', 'reader');
     $sectionnum = 1;
 } else {
     if ($sectionchoosing == 1) {
         $excoursedata = $DB->get_record('course', array('id' => $courseid));
         $DB->set_field('course', 'numsections', $excoursedata->numsections + count($sections), array('id' => $courseid));
         $sectionnum = $excoursedata->numsections + 1;
     }
 }
 $_SESSION['SESSION']->reader_downloadprocesscourseid = $courseid;
 $module = $DB->get_record("modules", array("name" => "quiz"));
 //Add quizzes
 foreach ($quizzestoadd as $quizzestoadd_) {
     if ($sectionchoosing == 1) {
 /**
  * Setup the DB fixture data
  */
 public function setup()
 {
     parent::setUp();
     $tables = array('block_instance', 'cache_flags', 'capabilities', 'context', 'context_temp', 'course', 'course_modules', 'course_categories', 'course_sections', 'files', 'files_cleanup', 'grade_items', 'grade_categories', 'groups', 'groups_members', 'modules', 'role', 'role_names', 'role_context_levels', 'role_assignments', 'role_capabilities', 'user');
     $this->create_test_tables($tables, 'lib');
     $this->create_test_table('forum', 'mod/forum');
     $this->switch_to_test_db();
     global $DB, $CFG;
     // Insert needed capabilities
     $DB->insert_record('capabilities', array('id' => 45, 'name' => 'moodle/course:update', 'cattype' => 'write', 'contextlevel' => 50, 'component' => 'moodle', 'riskbitmask' => 4));
     $DB->insert_record('capabilities', array('id' => 14, 'name' => 'moodle/site:backup', 'cattype' => 'write', 'contextlevel' => 50, 'component' => 'moodle', 'riskbitmask' => 28));
     $DB->insert_record('capabilities', array('id' => 17, 'name' => 'moodle/site:restore', 'cattype' => 'write', 'contextlevel' => 50, 'component' => 'moodle', 'riskbitmask' => 28));
     $DB->insert_record('capabilities', array('id' => 52, 'name' => 'moodle/course:managefiles', 'cattype' => 'write', 'contextlevel' => 50, 'component' => 'moodle', 'riskbitmask' => 4));
     $DB->insert_record('capabilities', array('id' => 73, 'name' => 'moodle/user:editownprofile', 'cattype' => 'write', 'contextlevel' => 10, 'component' => 'moodle', 'riskbitmask' => 16));
     // Insert system context
     $DB->insert_record('context', array('id' => 1, 'contextlevel' => 10, 'instanceid' => 0, 'path' => '/1', 'depth' => 1));
     $DB->insert_record('context', array('id' => 2, 'contextlevel' => 50, 'instanceid' => 1, 'path' => '/1/2', 'depth' => 2));
     // Insert site course
     $DB->insert_record('course', array('category' => 0, 'sortorder' => 1, 'fullname' => 'Test site', 'shortname' => 'test', 'format' => 'site', 'modinfo' => 'a:0:{}'));
     // User and capability stuff (stolen from testaccesslib.php)
     $syscontext = get_system_context(false);
     $adminrole = create_role(get_string('administrator'), 'admin', get_string('administratordescription'), 'moodle/legacy:admin');
     /// Now is the correct moment to install capabilities - after creation of legacy roles, but before assigning of roles
     assign_capability('moodle/site:doanything', CAP_ALLOW, $adminrole, $syscontext->id);
     update_capabilities('moodle');
     update_capabilities('mod/forum');
     $contexts = $this->load_test_data('context', array('contextlevel', 'instanceid', 'path', 'depth'), array(1 => array(40, 666, '', 2)));
     $contexts[0] = $syscontext;
     $contexts[1]->path = $contexts[0]->path . '/' . $contexts[1]->id;
     $this->testdb->set_field('context', 'path', $contexts[1]->path, array('id' => $contexts[1]->id));
     $users = $this->load_test_data('user', array('username', 'confirmed', 'deleted'), array('a' => array('a', 1, 0)));
     $admin = $this->testdb->get_record('role', array('shortname' => 'admin'));
     $ras = $this->load_test_data('role_assignments', array('userid', 'roleid', 'contextid'), array('a' => array($users['a']->id, $admin->id, $contexts[0]->id)));
     $this->switch_global_user_id(1);
     accesslib_clear_all_caches_for_unit_testing();
     // Create a coursecat
     $newcategory = new stdClass();
     $newcategory->name = 'test category';
     $newcategory->sortorder = 999;
     if (!($newcategory->id = $DB->insert_record('course_categories', $newcategory))) {
         print_error('cannotcreatecategory', '', '', format_string($newcategory->name));
     }
     $newcategory->context = get_context_instance(CONTEXT_COURSECAT, $newcategory->id);
     mark_context_dirty($newcategory->context->path);
     fix_course_sortorder();
     // Required to build course_categories.depth and .path.
     $this->coursecat = $DB->get_record('course_categories', array('id' => $newcategory->id));
     // Create a course
     $coursedata = new stdClass();
     $coursedata->category = $newcategory->id;
     $coursedata->shortname = 'testcourse';
     $coursedata->fullname = 'Test Course';
     try {
         $this->course = create_course($coursedata);
     } catch (moodle_exception $e) {
         // Most likely the result of an aborted unit test: the test course was not correctly deleted
         $this->course = $DB->get_record('course', array('shortname' => $coursedata->shortname));
     }
     // Create a user
     $this->user = new stdClass();
     $this->user->username = '******';
     $this->user->password = '******';
     $this->user->firstname = 'TestUser';
     $this->user->lastname = 'TestUser';
     $this->user->email = '*****@*****.**';
     try {
         $this->user->id = create_user($this->user);
     } catch (moodle_exception $e) {
         // Most likely the result of an aborted unit test: the test user was not correctly deleted
         $this->user->id = $DB->get_field('user', 'id', array('username' => $this->user->username));
     }
     // Assign user to course
     // role_assign(5, $this->user->id, 0, get_context_instance(CONTEXT_COURSE, $this->course->id)->id);
     // Create a module
     $module = new stdClass();
     $module->intro = 'Forum used for testing filelib API';
     $module->type = 'general';
     $module->forcesubscribe = 1;
     $module->format = 1;
     $module->name = 'Test Forum';
     $module->module = $DB->get_field('modules', 'id', array('name' => 'forum'));
     $module->modulename = 'forum';
     $module->add = 'forum';
     $module->cmidnumber = '';
     $module->course = $this->course->id;
     $module->instance = forum_add_instance($module, '');
     $this->section = get_course_section(1, $this->course->id);
     $module->section = $this->section->id;
     $module->coursemodule = add_course_module($module);
     add_mod_to_section($module);
     $module->cmidnumber = set_coursemodule_idnumber($module->coursemodule, '');
     rebuild_course_cache($this->course->id);
     $this->module = $DB->get_record('forum', array('id' => $module->instance));
     $this->module->instance = $module->instance;
     // Update local copy of course
     $this->course = $DB->get_record('course', array('id' => $this->course->id));
 }
Exemple #22
0
            default:
                if (!empty($course->id)) {
                    $url = new moodle_url($CFG->wwwroot.'/course/view.php', array('id'=>$course->id));
                } else {
                    $url = new moodle_url($CFG->wwwroot.'/course/');
                }
                break;
        }
        redirect($url);

} else if ($data = $editform->get_data()) {
    // process data if submitted

    if (empty($course->id)) {
        // In creating the course
        $course = create_course($data, $editoroptions);

        // Get the context of the newly created course
        $context = get_context_instance(CONTEXT_COURSE, $course->id, MUST_EXIST);

        if (!empty($CFG->creatornewroleid) and !is_viewing($context, NULL, 'moodle/role:assign') and !is_enrolled($context, NULL, 'moodle/role:assign')) {
            // deal with course creators - enrol them internally with default role
            enrol_try_internal_enrol($course->id, $USER->id, $CFG->creatornewroleid);

        }
        if (!is_enrolled($context)) {
            // Redirect to manual enrolment page if possible
            $instances = enrol_get_instances($course->id, true);
            foreach($instances as $instance) {
                if ($plugin = enrol_get_plugin($instance->enrol)) {
                    if ($plugin->get_manual_enrol_link($instance)) {
 /**
  * Validate that the export respects grade letter boundaries and the
  * existence of an associated Moodle course
  *
  * @param int $grade The enrolment grade
  * @param int $letter The expected enrolment grade letter
  * @dataProvider grade_letter_provider
  */
 public function test_exportrespects_gradeletters($grade, $letter)
 {
     global $CFG, $DB;
     require_once $CFG->dirroot . '/course/lib.php';
     require_once $CFG->dirroot . '/local/elisprogram/lib/setup.php';
     require_once elispm::lib('data/student.class.php');
     require_once elispm::lib('data/classmoodlecourse.class.php');
     // Setup.
     $this->load_csv_data();
     // Create a Moodle course category.
     $categorydata = new stdClass();
     $categorydata->name = 'testcategory';
     $categorydata->id = $DB->insert_record('course_categories', $categorydata);
     // Create a Moodle course.
     $coursedata = new stdClass();
     $coursedata->category = $categorydata->id;
     $coursedata->fullname = 'testcourse';
     $coursedata = create_course($coursedata);
     // Associate the PM class instance to the Moodle course.
     $classmoodle = new classmoodlecourse(array('classid' => 200, 'moodlecourseid' => $coursedata->id));
     $classmoodle->save();
     // Create grade letter mappings.
     $context = context_course::instance($coursedata->id);
     $mappings = array(10 => 1, 20 => 2, 30 => 3, 40 => 4, 50 => 5, 60 => 6, 70 => 7, 80 => 8, 90 => 9, 100 => 10);
     foreach ($mappings as $insertlowerboundary => $insertletter) {
         $record = new stdClass();
         $record->contextid = $context->id;
         $record->lowerboundary = $insertlowerboundary;
         $record->letter = $insertletter;
         $DB->insert_record('grade_letters', $record);
     }
     // Set the enrolment grade.
     $sql = "UPDATE {" . student::TABLE . "}\n                SET grade = ?";
     $params = array($grade);
     $DB->execute($sql, $params);
     $data = $this->get_export_data();
     // Validation.
     $this->assertEquals(2, count($data));
     $this->assertEquals((string) $letter, $data[1][9]);
 }
/** 
 *  Create a new Module on the Moodle installation based
 * upon the ID of the record in the course request system.
 * 
 */
function block_cmanager_create_new_course_by_record_id($mid, $sendMail)
{
    global $CFG, $DB;
    require_once "{$CFG->libdir}/formslib.php";
    require_once '../../../course/lib.php';
    require_once $CFG->libdir . '/completionlib.php';
    //** Create an object to hold our new course information
    $new_course = new block_cmanager_new_course();
    $new_course->format = get_config('moodlecourse', 'format');
    //Get the default timestamp for new courses
    $timestamp_startdate = $DB->get_field('block_cmanager_config', 'value', array('varname' => 'startdate'), IGNORE_MULTIPLE);
    $new_course->startdate = $timestamp_startdate;
    $new_course->newsitems = get_config('moodlecourse', 'newsitems');
    $new_course->showgrades = get_config('moodlecourse', 'showgrades');
    $new_course->showreports = get_config('moodlecourse', 'showreports');
    $new_course->maxbytes = get_config('moodlecourse', 'maxbytes');
    //Formatting
    $new_course->numsections = get_config('moodlecourse', 'numsections');
    $new_course->hiddensections = get_config('moodlecourse', 'hiddensections');
    // Groups
    $new_course->groupmode = get_config('moodlecourse', 'groupmode');
    $new_course->groupmodeforce = get_config('moodlecourse', 'groupmodeforce');
    //completion
    $new_course->enablecompletion = get_config('moodlecourse', 'enablecompletion');
    // Visible
    $new_course->visible = get_config('moodlecourse', 'visible');
    $new_course->lang = get_config('moodlecourse', 'lang');
    //is course mode enabled (page 1 optional dropdown)
    $mode = $DB->get_field('block_cmanager_config', 'value', array('varname' => 'page1_field3status'));
    // what naming mode is operating
    $naming = $DB->get_field('block_cmanager_config', 'value', array('varname' => 'naming'), IGNORE_MULTIPLE);
    //what short naming format is operating
    $snaming = $DB->get_field('block_cmanager_config', 'value', array('varname' => 'snaming'), IGNORE_MULTIPLE);
    //get the record for the request
    $rec = $DB->get_record('block_cmanager_records', array('id' => $mid));
    // Build up a course record based on the request.
    if (empty($rec->cate)) {
        $new_course->category = $CFG->defaultrequestcategory;
    } else {
        $new_course->category = $rec->cate;
    }
    // Fields we are carrying across
    if ($mode == "enabled" && $snaming == 2) {
        $newShortName = $rec->modcode . ' - ' . $rec->modmode;
    } else {
        $newShortName = $rec->modcode;
    }
    $new_course->shortname = $newShortName;
    $p_key = $rec->modkey;
    //course naming
    if ($naming == 1) {
        $new_course->fullname = $rec->modname;
    } else {
        if ($naming == 2) {
            $new_course->fullname = $rec->modcode . ' - ' . $rec->modname;
        } else {
            if ($naming == 3) {
                $new_course->fullname = $rec->modname . ' (' . $rec->modcode . ')';
                // Fullname, shortname
            } else {
                if ($naming == 4) {
                    $new_course->fullname = $rec->modcode . ' - ' . $rec->modname . ' (' . date("Y") . ')';
                    // Shortname, fullname (year)
                } else {
                    if ($naming == 5) {
                        $new_course->fullname = $rec->modname . ' (' . date("Y") . ')';
                    }
                }
            }
        }
    }
    // Enrollment key
    // if the key thats been set, otherwise auto gen a key
    if (isset($rec->modkey)) {
        $modkey = $rec->modkey;
    } else {
        $modkey = rand(999, 5000);
    }
    $categoryid = $new_course->category;
    $category = $DB->get_record('course_categories', array('id' => $categoryid));
    $catcontext = context_coursecat::instance($category->id);
    $contextobject = $catcontext;
    $editoroptions = array('maxfiles' => EDITOR_UNLIMITED_FILES, 'maxbytes' => $CFG->maxbytes, 'trusttext' => false, 'noclean' => true, 'content' => $contextobject);
    // Create the course
    $course = create_course($new_course, $editoroptions);
    // Forward to the course editing page to allow the admin to make
    // any changes to the course
    $nid = $course->id;
    if ($nid == null) {
        return $nid;
    }
    // Update the record to say that it is now complete
    $updatedRecord = new stdClass();
    $updatedRecord->id = $rec->id;
    $updatedRecord->status = 'COMPLETE';
    $DB->update_record('block_cmanager_records', $updatedRecord);
    // Try enroll the creator
    if (!empty($CFG->creatornewroleid)) {
        // deal with course creators - enrol them internally with default role
        enrol_try_internal_enrol($nid, $rec->createdbyid, $CFG->creatornewroleid);
    }
    // Check to see if auto create enrollment keys
    // is enabled. If this option is set, add an
    // enrollment key.
    $autoKey = $DB->get_field_select('block_cmanager_config', 'value', "varname = 'autoKey'");
    if ($autoKey == 0 || $autoKey == 1) {
        // Add enrollnent key
        $enrollmentRecord = new stdClass();
        $enrollmentRecord->enrol = 'self';
        $enrollmentRecord->status = 0;
        $enrollmentRecord->courseid = $nid;
        $enrollmentRecord->sortorder = 3;
        $enrollmentRecord->name = '';
        $enrollmentRecord->enrolperiod = 0;
        $enrollmentRecord->enrolenddate = 0;
        $enrollmentRecord->expirynotify = 0;
        $enrollmentRecord->expirythreshold = 0;
        $enrollmentRecord->notifyall = 0;
        $enrollmentRecord->password = $modkey;
        $enrollmentRecord->cost = NULL;
        $enrollmentRecord->currency = NULL;
        $enrollmentRecord->roleid = 5;
        $enrollmentRecord->customint1 = 0;
        $enrollmentRecord->customint2 = 0;
        $enrollmentRecord->customint3 = 0;
        $enrollmentRecord->customint4 = 1;
        if ($CFG->version >= 2013051400) {
            $enrollmentRecord->customint5 = NULL;
            $enrollmentRecord->customint6 = 1;
        }
        $enrollmentRecord->customchar1 = NULL;
        $enrollmentRecord->customchar2 = NULL;
        $enrollmentRecord->customdec1 = NULL;
        $enrollmentRecord->customdec2 = NULL;
        $enrollmentRecord->customtext1 = '';
        $enrollmentRecord->customtext2 = NULL;
        $enrollmentRecord->timecreated = time();
        $enrollmentRecord->timemodified = time();
        $DB->insert_record('enrol', $enrollmentRecord);
    }
    if ($sendMail == true) {
        block_cmanager_send_emails($nid, $new_course->shortname, $new_course->fullname, $modkey, $mid);
    }
    return $nid;
}
 /**
  * Create a test course
  * @param array|stdClass $record
  * @param array $options with keys:
  *      'createsections'=>bool precreate all sections
  * @return stdClass course record
  */
 function create_course($record = null, array $options = null)
 {
     global $DB, $CFG;
     require_once "{$CFG->dirroot}/course/lib.php";
     $this->coursecount++;
     $i = $this->coursecount;
     $record = (array) $record;
     if (!isset($record['fullname'])) {
         $record['fullname'] = 'Test course ' . $i;
     }
     if (!isset($record['shortname'])) {
         $record['shortname'] = 'tc_' . $i;
     }
     if (!isset($record['idnumber'])) {
         $record['idnumber'] = '';
     }
     if (!isset($record['format'])) {
         $record['format'] = 'topics';
     }
     if (!isset($record['newsitems'])) {
         $record['newsitems'] = 0;
     }
     if (!isset($record['numsections'])) {
         $record['numsections'] = 5;
     }
     if (!isset($record['summary'])) {
         $record['summary'] = "Test course {$i}\n{$this->loremipsum}";
     }
     if (!isset($record['summaryformat'])) {
         $record['summaryformat'] = FORMAT_MOODLE;
     }
     if (!isset($record['category'])) {
         $record['category'] = $DB->get_field_select('course_categories', "MIN(id)", "parent=0");
     }
     $course = create_course((object) $record);
     context_course::instance($course->id);
     if (!empty($options['createsections'])) {
         for ($i = 1; $i < $record['numsections']; $i++) {
             self::create_course_section(array('course' => $course->id, 'section' => $i));
         }
     }
     return $course;
 }
Exemple #26
0
<?php

$course_code = isset($_POST['course_code']) ? $_POST['course_code'] : '';
$course_name = isset($_POST['course_name']) ? $_POST['course_name'] : '';
if (isset($_POST['submit'])) {
    create_course($course_code, $course_name);
    sleep(1);
    header('location: ' . currentURL() . '?p=course/' . $course_code);
    print 'Course created. Click <a href="?p=course">here</a> to view created courses';
}
?>
<form id="form" method="post" action="">
	<table>
		<tr>
			<td><label for="course_code">Course code:</label></td>
			<td><input type="text" name="course_code" size="60" maxlength="128" class="required" /></td>
		</tr>
		<tr>
			<td><label for="course_name">Course name:</label></td>
			<td><input type="text" name="course_name" size="60" maxlength="128" class="required" /></td>
		</tr>
		<tr>
			<td><input type="submit" name="submit" value="Submit" /></td>
			<td><input type="reset" value="Reset" /></td>
		</tr>
	</table>
</form>
 /**
  * Create a course in Moodle (Migration)
  *
  * @global type $DB
  * @global type $CFG
  * @global type $USER
  * @param int $tiicourseid The course id on Turnitin
  * @param string $tiicoursetitle The course title on Turnitin
  * @param string $coursename The new course name on Moodle
  * @param int $coursecategory The category that the course is to be created in
  * @return mixed course object if created or 0 if failed
  */
 public static function create_moodle_course($tiicourseid, $tiicoursetitle, $coursename, $coursecategory)
 {
     global $DB, $CFG, $USER;
     require_once $CFG->dirroot . "/course/lib.php";
     $data = new stdClass();
     $data->category = $coursecategory;
     $data->fullname = $coursename;
     $data->shortname = "Turnitin (" . $tiicourseid . ")";
     $data->maxbytes = 2097152;
     if ($course = create_course($data)) {
         $turnitincourse = new stdClass();
         $turnitincourse->courseid = $course->id;
         $turnitincourse->turnitin_cid = $tiicourseid;
         $turnitincourse->turnitin_ctl = $tiicoursetitle;
         $turnitincourse->ownerid = $USER->id;
         $turnitincourse->course_type = 'TT';
         // Enrol user as instructor on course in moodle if they are not a site admin.
         if (!is_siteadmin()) {
             // Get the role id for a teacher.
             $roles1 = get_roles_with_capability('mod/turnitintooltwo:grade');
             $roles2 = get_roles_with_capability('mod/turnitintooltwo:addinstance');
             $roles = array_intersect_key($roles1, $roles2);
             $role = current($roles);
             // Enrol $USER in the courses using the manual plugin.
             $enrol = enrol_get_plugin('manual');
             $enrolinstances = enrol_get_instances($course->id, true);
             foreach ($enrolinstances as $courseenrolinstance) {
                 if ($courseenrolinstance->enrol == "manual") {
                     $instance = $courseenrolinstance;
                     break;
                 }
             }
             $enrol->enrol_user($instance, $USER->id, $role->id);
         } else {
             // Enrol admin as an instructor incase they are not on the account.
             $turnitintooltwouser = new turnitintooltwo_user($USER->id, "Instructor");
             $turnitintooltwouser->join_user_to_class($tiicourseid);
         }
         if (!($insertid = $DB->insert_record('turnitintooltwo_courses', $turnitincourse))) {
             turnitintooltwo_activitylog(get_string('migrationcoursecreatederror', 'turnitintooltwo', $tiicourseid) . ' - ' . $course->id, "REQUEST");
             return 0;
         } else {
             turnitintooltwo_activitylog(get_string('migrationcoursecreated', 'turnitintooltwo') . ' - ' . $course->id . ' (' . $tiicourseid . ')', "REQUEST");
             return $course;
         }
     } else {
         turnitintooltwo_activitylog(get_string('migrationcoursecreateerror', 'turnitintooltwo', $tiicourseid), "REQUEST");
         return 0;
     }
 }
Exemple #28
0
    }
} else {
    if ($data = $editform->get_data()) {
        $data->password = $data->enrolpassword;
        // we need some other name for password field MDL-9929
        /// process data if submitted
        //preprocess data
        if ($data->enrolstartdisabled) {
            $data->enrolstartdate = 0;
        }
        if ($data->enrolenddisabled) {
            $data->enrolenddate = 0;
        }
        $data->timemodified = time();
        if (empty($course)) {
            if (!($course = create_course($data))) {
                print_error('coursenotcreated');
            }
            $context = get_context_instance(CONTEXT_COURSE, $course->id);
            // assign default role to creator if not already having permission to manage course assignments
            if (!has_capability('moodle/course:view', $context) or !has_capability('moodle/role:assign', $context)) {
                role_assign($CFG->creatornewroleid, $USER->id, 0, $context->id);
            }
            // ensure we can use the course right after creating it
            // this means trigger a reload of accessinfo...
            mark_context_dirty($context->path);
            if ($data->metacourse and has_capability('moodle/course:managemetacourse', $context)) {
                // Redirect users with metacourse capability to student import
                redirect($CFG->wwwroot . "/course/importstudents.php?id={$course->id}");
            } else {
                // Redirect to roles assignment
 /**
  * Validate that class instance-moodle course associations can be created during a class instance update action.
  *
  * @param string $link The link attribute to use in the import, or 'auto' to auto-create from template.
  * @dataProvider link_course_provider
  */
 public function test_associate_moodle_course_during_class_update($link)
 {
     global $CFG, $DB, $USER;
     require_once $CFG->dirroot . '/course/lib.php';
     require_once $CFG->dirroot . '/local/elisprogram/lib/setup.php';
     require_once elispm::lib('data/classmoodlecourse.class.php');
     require_once elispm::lib('data/coursetemplate.class.php');
     require_once elispm::lib('data/course.class.php');
     require_once elispm::lib('data/pmclass.class.php');
     // Make sure $USER is set up for backup/restore.
     $USER->id = $DB->get_field_select('user', 'id', "username != 'guest' AND deleted = 0", array(), IGNORE_MULTIPLE);
     // Need the moodle/backup:backupcourse capability.
     $guestroleid = create_role('guestrole', 'guestrole', 'guestrole');
     set_config('guestroleid', $guestroleid);
     set_config('siteguest', '');
     $systemcontext = context_system::instance();
     $roleid = create_role('testrole', 'testrole', 'testrole');
     assign_capability('moodle/backup:backupcourse', CAP_ALLOW, $roleid, $systemcontext->id);
     role_assign($roleid, $USER->id, $systemcontext->id);
     $coursecategory = new stdClass();
     $coursecategory->name = 'testcoursecategoryname';
     $coursecategory->id = $DB->insert_record('course_categories', $coursecategory);
     $moodlecourse = new stdClass();
     $moodlecourse->category = $coursecategory->id;
     $moodlecourse->shortname = 'testcourseshortname';
     $moodlecourse->fullname = 'testcoursefullname';
     $moodlecourse = create_course($moodlecourse);
     $course = new course(array('name' => 'testcoursename', 'idnumber' => 'testcourseidnumber', 'syllabus' => ''));
     $course->save();
     $class = new pmclass(array('courseid' => $course->id, 'idnumber' => 'testclassidnumber'));
     $class->save();
     // Need this for the 'auto' case, at the very least.
     $coursetemplate = new coursetemplate(array('courseid' => $course->id, 'location' => $moodlecourse->id, 'templateclass' => 'moodlecourseurl'));
     $coursetemplate->save();
     // Run the class instance create action.
     $record = new stdClass();
     $record->idnumber = 'testclassidnumber';
     $record->assignment = 'testcourseidnumber';
     $record->link = $link;
     $importplugin = rlip_dataplugin_factory::factory('dhimport_version1elis');
     $importplugin->fslogger = new silent_fslogger(null);
     $importplugin->class_update($record, 'bogus');
     // Validation.
     if ($record->link == 'auto') {
         $moodlecourseid = $moodlecourse->id + 1;
     } else {
         $moodlecourseid = $moodlecourse->id;
     }
     $dbautocreated = $record->link == 'auto' ? 1 : 0;
     $this->assertTrue($DB->record_exists(classmoodlecourse::TABLE, array('classid' => $class->id, 'moodlecourseid' => $moodlecourseid, 'enroltype' => 0, 'enrolplugin' => 'crlm', 'autocreated' => $dbautocreated)));
     ini_set('max_execution_time', '0');
 }
Exemple #30
0
 public function generate_courses()
 {
     global $DB;
     $this->verbose("Generating " . $this->get('number_of_courses') . " courses...");
     $base_course = new stdClass();
     $next_course_id = $DB->get_field_sql("SELECT MAX(id) FROM {course}") + 1;
     $base_course->MAX_FILE_SIZE = '2097152';
     $base_course->category = '1';
     $base_course->summary = 'Blah Blah';
     $base_course->format = 'weeks';
     $base_course->numsections = '10';
     $base_course->startdate = mktime();
     $base_course->id = '0';
     $courses_count = 0;
     $courses = array();
     for ($i = 1; $i <= $this->get('number_of_courses'); $i++) {
         $newcourse = fullclone($base_course);
         $newcourse->fullname = "Test course {$next_course_id}";
         $newcourse->shortname = "Test {$next_course_id}";
         $newcourse->idnumber = $next_course_id;
         if (!($course = create_course($newcourse))) {
             $this->verbose("Error inserting a new course in the database!");
             if (!$this->get('ignore_errors')) {
                 die;
             }
         } else {
             $courses_count++;
             $next_course_id++;
             $courses[] = $course->id;
             $next_course_id = $course->id + 1;
             $this->verbose("Inserted {$course->fullname} into DB (idnumber={$course->idnumber}).");
         }
     }
     if (!$this->get('quiet')) {
         echo "{$courses_count} test courses correctly inserted into the database.{$this->eolchar}";
     }
     return $courses;
 }