2016-09-07 2 views
1

Мне нужно загрузить файлы и папки в курс в moodle из zip-файла, я искал, и я нашел, как загружать файлы. Я пытаюсь загрузить, и файлы загружаются правильно в базу данных и в репозиторий файлов, но эти файлы не отображаются в курсе, когда я вхожу в курс.Загрузка файлов и папок в курс программно в Moodle

ниже код, что я пытаюсь

$packer = get_file_packer('application/zip'); 
$files = $packer->extract_to_pathname($archivo_zip, $carpeta_unzip); 

foreach($files as $path => $status){ 
    $fs = get_file_storage();         
    $context = context_course::instance($courseid); 

    $filename = basename($path); 
    $path_directory = "/" . str_replace($filename, "", $path); 

    $author = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST); 

    $file_record = new stdClass; 
    $file_record->component = 'mod_folder';  //mod_resource 
    $file_record->contextid = $context->id;   
    $file_record->userid = $userid ;     
    $file_record->filearea = 'content';   //draft, attachment 
    $file_record->filename = $filename;    
    $file_record->filepath = $path_directory;  
    $file_record->itemid = 0;     
    $file_record->author = fullname($author); 
    $file_record->license = $CFG->sitedefaultlicense; 
    $file_record->source = $filename;    
    //$file_record->timecreated = time();    
    //$file_record->timemodified = time();   

    $existingfile = $fs->file_exists($file_record->contextid, $file_record->component, $file_record->filearea, 
    $file_record->itemid, $file_record->filepath, $file_record->filename); 

    if ($existingfile) { 
     //throw new file_exception('filenameexist'); 
    } else { 
     $stored_file = $fs->create_file_from_pathname($file_record, $path_upload); 
    } 
} 

Я пытаюсь загрузить файлы вручную через веб-сайт, и я заметил, что папки ара, созданные в другой таблице называется mdl_folder или в таблице под названием mdl_file, но я не знаю, как это сделать и как наилучшим образом создавать и связывать папки с файлами программно, а затем хорошо отображаться на веб-сайте.

Так что если кто-нибудь знает, как это сделать или есть примеры или документация, которые могут быть полезны, было бы полезно.

Заранее спасибо.

ответ

0

Я нашел решение, которое работает для меня, я не знаю, является ли оно наиболее подходящим или нет, если кто-то может взглянуть и сказать мне, правильно это или нет, или какие изменения могут сделать признательна.

Решение я нашел это:

  • Создать или получить его обратно в папку, который будет содержать файлы
  • Загрузить файлы

Код:

$packer = get_file_packer('application/zip'); 
    $files = $packer->extract_to_pathname($archivo_zip, $carpeta_unzip); 

    foreach($files as $path => $status){ 
     $fs = get_file_storage();  

     $folder = get_folder($courseid, 'Upload Test'); 

     $filename = basename($path); 
     $path_directory = "/" . str_replace($filename, "", $path); 

     $author = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST); 

     $file_record = new stdClass; 
     $file_record->component = 'mod_folder';  //mod_resource 
     $file_record->contextid = $folder->id;   
     $file_record->userid = $userid ;     
     $file_record->filearea = 'content';   //draft, attachment 
     $file_record->filename = $filename;    
     $file_record->filepath = $path_directory;  
     $file_record->itemid = 0;     
     $file_record->author = fullname($author); 
     $file_record->license = $CFG->sitedefaultlicense; 
     $file_record->source = $filename;    
     //$file_record->timecreated = time();    
     //$file_record->timemodified = time();   

     $existingfile = $fs->file_exists($file_record->contextid, $file_record->component, $file_record->filearea, 
     $file_record->itemid, $file_record->filepath, $file_record->filename); 

     if ($existingfile) { 
      //throw new file_exception('filenameexist'); 
     } else { 
      $stored_file = $fs->create_file_from_pathname($file_record, $path_upload); 
     } 
    } 

И функция для создания или возврата этой папки:

function get_folder($courseid, $resource_name) { 
    global $DB, $CFG; 

    //Comprobamos si la carpeta ya existe ya existe 

    $sql = "SELECT cm.id as cmid FROM {course_modules} cm, {folder} res 
     WHERE res.name = '" . $resource_name . "' 
     AND cm.course = " . $courseid . " 
     AND cm.instance = res.id"; 

    if (! $coursemodule = $DB->get_record_sql($sql)) {  
     require_once($CFG->dirroot.'/course/lib.php'); 

     echo "\tCreate new folder\n"; 

     $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST); 

     // get module id 
     $module = $DB->get_record('modules', array('name' => 'folder'), '*', MUST_EXIST); 

     // get course section 
     /*course_create_sections_if_missing($course->id, 0); 
     $modinfo = get_fast_modinfo($course->id); 
     $cw = $modinfo->get_section_info(0); 

     echo "section id: " . $cw->id;*/ 

     $sectionid = $DB->get_record('course_sections', array('course' => $course->id, 'name' => 'Recursos'), '*', MUST_EXIST); 

     $folder_data = new stdClass(); 
     $folder_data->course = $course->id; 
     $folder_data->name = $resource_name;    
     $folder_data->intro = '<p>'.$resource_name.'</p>'; 
     $folder_data->introformat = 1; 
     $folder_data->revision = 1; 
     $folder_data->timemodified = time(); 
     $folder_data->display = 0; 
     $folder_data->showexpanded = 1; 
     $folder_data->showdownloadfolder = 1; 

     $folder_id = $DB->insert_record('folder', $folder_data); 

     echo "folder id: " . $folder_id; 

     // add course module 
     $cm = new stdClass(); 
     $cm->course = $courseid; 
     $cm->module = $module->id; // should be retrieved from mdl_modules 
     $cm->instance = $folder_id; // from mdl_resource 
     $cm->section = $sectionid->id; // from mdl_course_sections 
     $cm->visible = 1; 
     $cm->visibleold = 1; 
     $cm->showavailability = 1; 
     $cm->added = time(); 

     $cmid = $DB->insert_record('course_modules', $cm); 

     // add module to course section so it'll be visible 
     if ($DB->record_exists('course_sections', array('course' => $courseid, 'section' => 1))) { 
      $sectionid = $DB->get_record('course_sections', array('course' => $courseid, 'section' => 1)); 

      // if sequence is not empty, add another course_module id 
      if (!empty($sectionid->sequence)) { 
       $sequence = $sectionid->sequence . ',' . $cmid; 
      } else { 
       // if sequence is empty, add course_module id 
       $sequence = $cmid; 
      } 

      $course_section = new stdClass(); 
      $course_section->id = $sectionid->id; 
      $course_section->course = $courseid; 
      $course_section->section = 1; 
      $course_section->sequence = $sequence; 
      $csid = $DB->update_record('course_sections', $course_section); 

     } else { 

      $sequence = $cmid; 

      $course_section = new stdClass(); 
      $course_section->course = $courseid; 
      $course_section->section = 1; 
      $course_section->sequence = $sequence; 

      $csid = $DB->insert_record('course_sections', $course_section); 
     } 

     rebuild_course_cache($courseid, true);  

     // get context again, this time with all resources present 
     $context = get_folder($courseid, $resource_name); 
     return $context; 

    } else { 
     $context = context_module::instance($coursemodule->cmid); 

     return $context; 
    } 
} // get_folder