diff --git a/lib/filestorage/stored_file.php b/lib/filestorage/stored_file.php index 3041a52a228..03653901501 100644 --- a/lib/filestorage/stored_file.php +++ b/lib/filestorage/stored_file.php @@ -142,8 +142,10 @@ class stored_file { } } - if ($field == 'referencefileid' or $field == 'referencelastsync' or $field == 'referencelifetime') { - $value = clean_param($value, PARAM_INT); + if ($field === 'referencefileid' or $field === 'referencelastsync' or $field === 'referencelifetime') { + if (!is_null($value) and !is_number($value)) { + throw new file_exception('storedfileproblem', 'Invalid reference info'); + } } // adding the field @@ -209,30 +211,33 @@ class stored_file { throw new coding_exception('An attempt to unlink a non-reference file.'); } - // Remove repository info. - $this->repository = null; - $transaction = $DB->start_delegated_transaction(); - // Remove reference info from DB. - $DB->delete_records('files_reference', array('id'=>$this->file_record->referencefileid)); + // 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)); + } - // Must refresh $this->file_record form DB - $filerecord = $DB->get_record('files', array('id'=>$this->get_id())); - // Update DB - $filerecord->referencelastsync = null; - $filerecord->referencelifetime = null; - $filerecord->referencefileid = null; - $this->update($filerecord); + // Update the underlying record in the database. + $update = new stdClass(); + $update->referencefileid = null; + $update->referencelastsync = null; + $update->referencelifetime = null; + $this->update($update); $transaction->allow_commit(); - // unset object variable - unset($this->file_record->repositoryid); - unset($this->file_record->reference); - unset($this->file_record->referencelastsync); - unset($this->file_record->referencelifetime); - unset($this->file_record->referencefileid); + // 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; + $this->file_record->referencelifetime = null; } /**