File Handling

The moodle.org site has a reasonably good intro to the Moodle 2.0 file system: http://docs.moodle.org/en/Development:Using_the_file_API.

Here is a database schema for all Moodle tables relevant for the Moodle file system:

Please note that a given context record points to a file only if its contextlevel is 70 (i.e. a module).

(Schema created with http://ondras.zarovi.cz/sql/demo/)

Creating New Files

Use file_storage#create_file_from_string to store files in the Moodle file system.

        // get file as blob from external DB
        $rec = $SOURCE_DB->get_record_sql("SELECT * FROM documents WHERE id = 309933 ");
        $fs = get_file_storage();
         
        // Prepare file record object
        $fileinfo = array(
            'contextid' => 99999, // ID of context
            'component' => 'mod_resource',
            'filearea' => 'content',     
            'itemid' => 0,               
            'filepath' => '/',          
            'filename' => 'test3.pdf');

        // This works even if the second argument contains a blob instead of a string
        $fs->create_file_from_string($fileinfo, $rec->document);