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 Moodle file repository, but these files are not shown in the course when I enter via the web.
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 to upload files and folders manually from the Moodle website and I have realized 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 don't know what is the best way to create and relate the folders to the files so that later they can be seen 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.
I have found a solution that works for me, I don't know if it is the most suitable or not, if someone can take a look at it and tell me if it is correct or not, or what changes I could make I would be grateful.
The solution I found is the following:
Code:
And the function to create the folder that will contain the files is as follows: