I need to upload files and folders within a Moodle course, these files come from a zip. I have been searching and I have found how to upload files, I have tried it and I am able to upload files correctly in the database and in the file repository of Moodle, but these files are not shown in the course when I go online.
The code I am testing is the following:
$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);
}
}
I have tried uploading files and folders manually from the Moodle website and I have noticed that the folders are sometimes created in another table called mdl_folder
and other times in the same table as the files, mdl_files
. I do not know what is the best way to create and relate the folders with the files so that after they can be viewed correctly from the web
If someone knows how to do it or has an example or documentation that can help me, it will be a great help for me.