public function delete_reference() {
        global $DB;

        if (!$this->is_external_file()) {
            throw new coding_exception('An attempt to unlink a non-reference file.');
        }

        $transaction = $DB->start_delegated_transaction();

        // Are we the only one referring to the original file? If so, delete the
        // referenced file record. Note we do not use file_storage::search_references_count()
        // here because we want to count draft files too and we are at a bit lower access level here.
        $countlinks = $DB->count_records('files',
            array('referencefileid' => $this->file_record->referencefileid));
        if ($countlinks == 1) {
            $DB->delete_records('files_reference', array('id' => $this->file_record->referencefileid));
        }

        // Update the underlying record in the database.
        $update = new stdClass();
        $update->referencefileid = null;
        $this->update($update);

        $transaction->allow_commit();

        // Update our properties and the record in the memory.
        $this->repository = null;
        $this->file_record->repositoryid = null;
        $this->file_record->reference = null;
        $this->file_record->referencefileid = null;
        $this->file_record->referencelastsync = null;
    }