How to create an alias/reference

How to create an alias/reference

by Renaat Debleu -
Number of replies: 1
Picture of Core developers Picture of Particularly helpful Moodlers Picture of Plugin developers

How to create an alias/reference to a local file?  The code below is working to create a copy of a file, but when I try to create a reference, I get a reference_error.

    $fs = get_file_storage();
    $originalfile = $fs->get_file_by_id($oldfileid);


    $filerecord = array(
        'contextid' => $file->contextid,
        'component' => $file->component,
        'filearea'  => $file->filearea,
        'itemid'    => $file->itemid,
        'filepath'  => $file->filepath,
        'filename'  => $file->filename,
    );

    $newfilerecord = array(
        'contextid' => $newcontextid,
        'component' => $file->component,
        'filearea'  => $file->filearea,
        'itemid'    => $newid,
        'filepath'  => $file->filepath,
        'filename'  => $file->filename,
    );

    NOT WORKING: (create reference -> reference error)
       $ref = $fs->pack_reference($filerecord);
       $newfile = $fs->create_file_from_reference($newfilerecord, $originalfile->get_repository_id(), $ref);

    WORKING (create copy)
        $newfile = $fs->create_file_from_string($newfilerecord, $originalfile->get_content());


Average of ratings: -
In reply to Renaat Debleu

Re: How to create an alias/reference

by Renaat Debleu -
Picture of Core developers Picture of Particularly helpful Moodlers Picture of Plugin developers

It is all about using the right repository:

        $args = array();
        $args['type'] = 'user';
        $repos = repository::get_instances($args);
        $userrepository = reset($repos);

        $newfile = $fs->create_file_from_reference($newfilerecord, $userrepository->id, $ref);