@@ -43,9 +43,12 @@ public static function answers_from_webform($responsedata, $question) {
43
43
$ record ->responseid = $ responsedata ->rid ;
44
44
$ record ->questionid = $ question ->id ;
45
45
46
- file_save_draft_area_files ($ val , $ question ->context ->id , 'mod_questionnaire ' , 'file ' , $ question ->id );
46
+ file_save_draft_area_files ($ val , $ question ->context ->id ,
47
+ 'mod_questionnaire ' , 'file ' , $ val ,
48
+ \mod_questionnaire \question \file::get_file_manager_option ());
47
49
$ fs = get_file_storage ();
48
- $ files = $ fs ->get_area_files ($ question ->context ->id , 'mod_questionnaire ' , 'file ' , $ question ->id ,
50
+ $ files = $ fs ->get_area_files ($ question ->context ->id , 'mod_questionnaire ' ,
51
+ 'file ' , $ val ,
49
52
"itemid, filepath, filename " ,
50
53
false );
51
54
if (!empty ($ files )) {
@@ -132,10 +135,44 @@ public function insert_response($responsedata) {
132
135
$ record ->question_id = $ this ->question ->id ;
133
136
$ record ->fileid = intval (clean_text ($ response ->answers [$ this ->question ->id ][0 ]->value ));
134
137
135
- return $ DB ->insert_record (static ::response_table (), $ record );
136
- } else {
137
- return false ;
138
+ // When saving the draft file, the itemid was the same as the draftfileid. This must now be
139
+ // corrected to the primary key that is questionaire_response_file.id to have a correct reference.
140
+ $ recordid = $ DB ->insert_record (static ::response_table (), $ record );
141
+ if ($ recordid ) {
142
+ $ olditem = $ DB ->get_record ('files ' , ['id ' => $ record ->fileid ], 'itemid ' );
143
+ if (!$ olditem ) {
144
+ return false ;
145
+ }
146
+ $ siblings = $ DB ->get_records ('files ' ,
147
+ ['component ' => 'mod_questionnaire ' , 'itemid ' => $ olditem ->itemid ]);
148
+ foreach ($ siblings as $ sibling ) {
149
+ if (!$ this ->fix_file_itemid ($ recordid , $ sibling )) {
150
+ return false ;
151
+ }
152
+ }
153
+ return $ recordid ;
154
+ }
138
155
}
156
+ return false ;
157
+ }
158
+
159
+ /**
160
+ * Update records in the table file with the new given itemid. To do this, the pathnamehash
161
+ * needs to be recalculated as well.
162
+ * @param int $recordid
163
+ * @param \stdClass $filerecord
164
+ * @return bool
165
+ * @throws \dml_exception
166
+ */
167
+ protected function fix_file_itemid (int $ recordid , \stdClass $ filerecord ): bool {
168
+ global $ DB ;
169
+ $ fs = get_file_storage ();
170
+ $ file = $ fs ->get_file_instance ($ filerecord );
171
+ $ newhash = $ fs ->get_pathname_hash ($ filerecord ->contextid , $ filerecord ->component ,
172
+ $ filerecord ->filearea , $ recordid , $ file ->get_filepath (), $ file ->get_filename ());
173
+ $ filerecord ->itemid = $ recordid ;
174
+ $ filerecord ->pathnamehash = $ newhash ;
175
+ return $ DB ->update_record ('files ' , $ filerecord );
139
176
}
140
177
141
178
/**
0 commit comments