PluginProbe
Bit Form – Contact Form, Payment Forms, Multi Step Forms, Calculator & Custom Form Builder / V3.3.2
Bit Form – Contact Form, Payment Forms, Multi Step Forms, Calculator & Custom Form Builder vV3.3.2
V3.3.2 3.3.1 V-3.3.0 3.2.2 3.2.1 3.2.0 3.1.4 3.1.3 3.1.2 3.1.1 3.1.0 V3.0.3 V3.0.2 -3.0.1 V_3.0.0 1.1.1 1.1.8 1.2 1.3 1.4 1.4.18 1.5.2 1.9 2.0 2.10.0 All 139 releases
← All changes | includes/Core/Database/FormEntryMetaModel.php +256 -161 2.10.0 → V3.3.2 View file →
@@ -5,10 +5,13 @@
5 5 */
6 6
7 7 namespace BitCode\BitForm\Core\Database;
8 8
9 +use BitCode\BitForm\Core\Util\FileHandler;
10 +use BitCode\BitForm\Core\Util\IpTool;
11 +
9 12 /**
10 - * Undocumented class
13 + * Manages entry meta (per-field values) for each form submission.
11 14 */
12 15
13 16 class FormEntryMetaModel extends Model
14 17 {
@@ -18,10 +21,10 @@
18 21 {
19 22 $values[] = $data['duplicateID'];
20 23 $values[] = $data['entryID'];
21 24 $sql = "INSERT INTO $this->table_name (bitforms_form_entry_id,meta_key,meta_value)"
22 - . ' SELECT %d as bitforms_form_entry_id,meta_key,meta_value'
23 - . " FROM `$this->table_name` WHERE bitforms_form_entry_id = %d";
25 + . ' SELECT %d as bitforms_form_entry_id,meta_key,meta_value'
26 + . " FROM `$this->table_name` WHERE bitforms_form_entry_id = %d";
24 27 return $this->execute($sql, $values)->getResult();
25 28 }
26 29
27 30 public function update(array $data, array $condition)
@@ -29,8 +32,9 @@
29 32 $entryID = $condition['bitforms_form_entry_id'];
30 33 if (empty($entryID)) {
31 34 return false;
32 35 }
36 + // Form entry meta lookup; meta_key/meta_value query required to map dynamic field keys per entry.
33 37 $formEntryMeta = $this->get(
34 38 [
35 39 'meta_key',
36 40 'meta_value',
@@ -46,11 +50,11 @@
46 50 $updatedData = [];
47 51 $oldEntriesKey = array_keys($oldEntries);
48 52 foreach ($data as $upKey => $upValue) {
49 53 $updatedData[$upKey] = is_string($upValue) ?
50 - $upValue :
51 - wp_json_encode($upValue);
52 - if (!\in_array($upKey, $oldEntriesKey)) {
54 + $upValue :
55 + wp_json_encode($upValue);
56 + if (!in_array($upKey, $oldEntriesKey, true)) {
53 57 $this->insert(
54 58 [
55 59 'bitforms_form_entry_id' => $entryID,
56 60 'meta_key' => $upKey,
@@ -72,9 +76,9 @@
72 76 $condition['meta_key'] = array_keys($data);
73 77 foreach ($data as $key => $value) {
74 78 $value = is_string($value) ? $value : wp_json_encode($value);
75 79 $case_part .= "
76 - WHEN '$key' THEN " . $this->getFieldFormat($value);
80 + WHEN '" . esc_sql($key) . "' THEN " . $this->getFieldFormat($value);
77 81 $all_values[] = $value;
78 82 }
79 83 $formattedCondition = $this->getFormatedCondition($condition);
80 84 if ($formattedCondition) {
@@ -116,11 +120,17 @@
116 120
117 121 $dateQuery = $dbHelper->dateQueryList();
118 122
119 123 $validCondtions = $this->validQueryCondition($conditions);
124 + $safeOperators = ['=', '!=', '>', '<', '>=', '<=', 'LIKE', 'NOT LIKE'];
120 125
121 126 foreach ($validCondtions as $condition) {
122 127 if (is_object($condition)) {
128 + $field = sanitize_key($condition->field);
129 + if (empty($field)) {
130 + continue;
131 + }
132 +
123 133 if (is_array($condition->val)) {
124 134 $value = $dbHelper->arrValueModifyByLogic($condition->logic, $condition->val);
125 135 } else {
126 136 $value = $dbHelper->strValueModifyByLogic($condition->logic, $condition->val);
@@ -126,20 +136,23 @@
126 136 $value = $dbHelper->strValueModifyByLogic($condition->logic, $condition->val);
127 137 }
128 138
129 139 $operator = $dbHelper->convertToSqlOperator($condition->logic);
140 + if (!in_array($operator, $safeOperators, true)) {
141 + continue;
142 + }
130 143
131 - if (isset($dateQuery[$condition->val])) {
132 - $sql .= $dbHelper->fieldQueryByDate($condition->field, $operator, $value, $condition->logic);
144 + if (!is_array($condition->val) && isset($dateQuery[$condition->val])) {
145 + $sql .= $dbHelper->fieldQueryByDate($field, $operator, $value, $condition->logic);
133 146 } else {
134 147 if (!is_int($value)) {
135 - $value = "'" . $value . "'";
148 + $value = "'" . esc_sql($value) . "'";
136 149 }
137 150
138 - $sql .= "`$condition->field` $operator $value";
151 + $sql .= "`{$field}` $operator $value";
139 152 }
140 - } else {
141 - $sql .= ' ' . $condition;
153 + } elseif (in_array(strtoupper(trim((string) $condition)), ['AND', 'OR'], true)) {
154 + $sql .= ' ' . strtoupper(trim((string) $condition));
142 155 }
143 156 }
144 157
145 158 return trim($sql);
@@ -156,12 +169,14 @@
156 169 $countResult = $this->execute($sql, $all_values)->getResult();
157 170 return $countResult[0]->count;
158 171 }
159 172
160 - public function selectedEntryMeta($formFields, $fieldCount)
173 + public function selectedEntryMeta($formFields, $fieldCount, $filter = null)
161 174 {
162 175 $all_values = [];
163 176 $formFieldsNames = [];
177 + $globalFilterString = '';
178 + $globalFilterValues = [];
164 179 $metaChecker = 0;
165 180 $selectedMeta = '`bitforms_form_entry_id` as entry_id,';
166 181 $selectedMeta .= "e.user_id as '__user_id',";
167 182 $selectedMeta .= "e.user_ip as '__user_ip',";
@@ -176,9 +191,10 @@
176 191 $selectedMeta .= ',';
177 192 }
178 193
179 194 foreach ($formFields as $fieldDetails) {
180 - $fieldFormat = $this->getFieldFormat($fieldDetails['key']);
195 + $safeFieldKey = sanitize_key($fieldDetails['key']);
196 + $fieldFormat = $this->getFieldFormat($safeFieldKey);
181 197 $selectedMeta .= "GROUP_CONCAT(
182 198 CASE
183 199 `meta_key`
184 200 WHEN '$fieldFormat' THEN `meta_value`
@@ -184,32 +200,33 @@
184 200 WHEN '$fieldFormat' THEN `meta_value`
185 201 END
186 202 ) AS '$fieldFormat'";
187 203 $metaChecker += 1;
188 - $all_values[] = $fieldDetails['key'];
189 - $all_values[] = $fieldDetails['key'];
190 - $formFieldsNames[] = $fieldDetails['key'];
204 + $all_values[] = $safeFieldKey;
205 + $all_values[] = $safeFieldKey;
206 + $formFieldsNames[] = $safeFieldKey;
191 207 if ($metaChecker < $fieldCount) {
192 208 $selectedMeta .= ',';
193 209 }
194 - //#unused code commented by me##
195 - // if ( !empty( $filter['global'] ) ) {
196 - // $globalFilterString .= " `" . $fieldDetails['key'] . "` LIKE '%%" . $this->getFieldFormat( $filter['global'] ) . "%%' ";
197 - // if ( $metaChecker < $fieldCount ) {
198 - // $globalFilterString .= " OR ";
199 - // }
200 - // $globalFilterValues[] = $filter['global'];
201 - // }
210 + if (!empty($filter['global'])) {
211 + $globalFilterString .= ' `' . $safeFieldKey . '` LIKE %s ';
212 + if ($metaChecker < $fieldCount) {
213 + $globalFilterString .= ' OR ';
214 + }
215 + $globalFilterValues[] = '%' . $this->app_db->esc_like($filter['global']) . '%';
216 + }
202 217 }
203 218
204 219 return [
205 - 'selected_meta' => $selectedMeta,
206 - 'form_fields_names' => $formFieldsNames,
207 - 'all_values' => $all_values,
220 + 'selected_meta' => $selectedMeta,
221 + 'form_fields_names' => $formFieldsNames,
222 + 'all_values' => $all_values,
223 + 'global_filter_string' => $globalFilterString,
224 + 'global_filter_values' => $globalFilterValues,
208 225 ];
209 226 }
210 227
211 - public function groupedCondition($condition, $all_values, $fieldConditions)
228 + public function groupedCondition($condition, $all_values, $fieldConditions, $filter = null, $globalFilterString = '', $globalFilterValues = [])
212 229 {
213 230 $isFldCondition = false;
214 231 $formattedCondition = $this->getFormatedCondition($condition);
215 232 if ($formattedCondition) {
@@ -218,51 +235,23 @@
218 235 $all_values = array_merge($all_values, $formattedCondition['values']);
219 236 } else {
220 237 $groupedCondition = null;
221 238 }
222 - //#unused code commented by me##
223 - //$isRecount = false;
239 + if (!empty($filter['global']) && !empty($globalFilterString) && !empty($globalFilterValues)) {
240 + $isFldCondition = true;
241 + if ($groupedCondition && false !== strpos($groupedCondition, 'HAVING')) {
242 + $groupedCondition .= ' AND (' . $globalFilterString . ') ';
243 + } else {
244 + $groupedCondition .= ' HAVING (' . $globalFilterString . ') ';
245 + }
246 + $all_values = array_merge($all_values, $globalFilterValues);
247 + }
224 248
225 - // if ( !empty( $filter['field'] ) ) {
226 - // $isRecount = true;
227 - // $filterFieldCount = count( $filter['field'] );
228 - // $filterFieldChecker = 0;
229 - // if ( $filterFieldCount > 0 ) {
230 - // $groupedCondition .= " HAVING ";
231 - // }
232 - // foreach ( $filter['field'] as $filterFieldKey => $filterFieldDetails ) {
233 - // $groupedCondition .= " `$filterFieldDetails->id` ='%%" . $this->getFieldFormat( $filterFieldDetails->value ) . "%%'";
234 - // $all_values[] = $filterFieldDetails->value;
235 - // if ( $filterFieldChecker < $filterFieldCount ) {
236 - // $groupedCondition .= " AND ";
237 - // }
238 - // }
239 - // }
240 -
241 - // if ( !empty( $filter['global'] ) && !empty( $globalFilterString ) && !empty( $globalFilterValues ) ) {
242 - // $isRecount = true;
243 - // if ( !empty( $filter['field'] ) ) {
244 - // $groupedCondition .= " AND (" . $globalFilterString . ") ";
245 - // } else {
246 - // $groupedCondition .= " HAVING $globalFilterString ";
247 - // }
248 - // $offset = 0;
249 - // $all_values = array_merge( $all_values, $globalFilterValues );
250 - // }
251 -
252 - // if ( !empty( $dateBetweenFilter ) && !empty( $dateBetweenFilter->start_date ) && !empty( $dateBetweenFilter->end_date ) ) {
253 - // if ( strpos( $groupedCondition, 'HAVING' ) !== false ) {
254 - // $groupedCondition .= " AND `__created_at` BETWEEN '" . $dateBetweenFilter->start_date . "' AND '" . $dateBetweenFilter->end_date . "' ";
255 - // } else {
256 - // $groupedCondition .= " HAVING `__created_at` BETWEEN '" . $dateBetweenFilter->start_date . "' AND '" . $dateBetweenFilter->end_date . "' ";
257 - // }
258 - // }
259 -
260 249 $sqlQryByFldCondtion = $this->sqlQryGenerateByFldCondition($fieldConditions);
261 250
262 251 if (!empty($sqlQryByFldCondtion)) {
263 252 $isFldCondition = true;
264 - if (false !== strpos($groupedCondition, 'HAVING')) {
253 + if ($groupedCondition && false !== strpos($groupedCondition, 'HAVING')) {
265 254 $groupedCondition .= ' AND (' . $sqlQryByFldCondtion . ') ';
266 255 } else {
267 256 $groupedCondition .= ' HAVING (' . $sqlQryByFldCondtion . ') ';
268 257 }
@@ -284,12 +273,12 @@
284 273 $orderCondition .= ' ORDER BY ';
285 274 }
286 275 $orderList = '';
287 276 foreach ($sortBy as $sortableFieldKey => $sortableFieldDetails) {
288 - // $orderCondition .=" ".$this->getFieldFormat($sortableFieldDetails->id);
289 277 $sortableFieldChecker += 1;
290 - if (in_array($sortableFieldDetails->id, $formFieldsNames)) {
291 - $orderList .= " `$sortableFieldDetails->id` ";
278 + if (in_array($sortableFieldDetails->id, $formFieldsNames, true)) {
279 + $safeId = sanitize_key($sortableFieldDetails->id);
280 + $orderList .= " `$safeId` ";
292 281 $orderFollow = $sortableFieldDetails->desc ? ' DESC ' : ' ASC ';
293 282 $orderList .= ' ' . $orderFollow;
294 283 if ($sortableFieldChecker < $sortableFieldCount) {
295 284 $orderList .= ', ';
@@ -324,20 +313,18 @@
324 313 public function getEntryMeta($formFields, $entries, $limit = null, $offset = null, $filter = null, $sortBy = null, $fieldConditions = null, $dateBetweenFilter = null)
325 314 {
326 315 $entry_table = $this->app_db->prefix . 'bitforms_form_entries';
327 316 $fieldCount = count($formFields);
328 - $getSelectedMetaFldValue = $this->selectedEntryMeta($formFields, $fieldCount);
329 -
317 + $getSelectedMetaFldValue = $this->selectedEntryMeta($formFields, $fieldCount, $filter);
330 318 $selectedMeta = $getSelectedMetaFldValue['selected_meta'];
331 319 $formFieldsNames = $getSelectedMetaFldValue['form_fields_names'];
332 320 $all_values = $getSelectedMetaFldValue['all_values'];
321 + $globalFilterString = $getSelectedMetaFldValue['global_filter_string'];
322 + $globalFilterValues = $getSelectedMetaFldValue['global_filter_values'];
333 323 $entryIDs = [];
334 324 $entryCount = count($entries);
335 - // $paginateEntry = empty($sortBy) && empty($filter['field']) && empty($filter['global']);
336 - // $entries = $paginateEntry ? array_slice($entries, $offset, $limit) : $entries;
337 - $paginateEntry = false;
338 325 foreach ($entries as $entryDetail) {
339 - $entryIDs[] = $entryDetail->id;
326 + $entryIDs[] = $entryDetail->id ?? $entryDetail;
340 327 }
341 328 if (empty($entryIDs)) {
342 329 return [
343 330 'count' => 0,
@@ -344,34 +331,36 @@
344 331 'entries' => [],
345 332 ];
346 333 }
347 334 $condition['bitforms_form_entry_id'] = $entryIDs;
348 - $group = $this->groupedCondition($condition, $all_values, $fieldConditions);
335 + $group = $this->groupedCondition($condition, $all_values, $fieldConditions, $filter, $globalFilterString, $globalFilterValues);
349 336 $groupedCondition = $group['groupedCondition'];
350 337 $all_values = $group['all_values'];
351 338 $isFldCondition = $group['isFldCondition'];
352 - $orderCondition = $this->orderCondition($formFieldsNames, $sortBy);
339 + $orderCondition = $this->orderCondition($formFieldsNames, (array) $sortBy);
353 340
354 341 $paginate = null;
355 - if (!\is_null($limit)) {
356 - $limit = \intval($limit);
342 + if (!is_null($limit)) {
343 + $limit = intval($limit);
357 344 $paginate .= " LIMIT $limit ";
358 345 }
359 - if (!\is_null($offset)) {
360 - $offset = \intval($offset);
361 - $paginate .= " OFFSET $offset ";
346 + if (!is_null($offset)) {
347 + $offset = intval($offset);
348 + $paginate .= " OFFSET $offset ";
362 349 }
350 +
363 351 $sql = "SELECT $selectedMeta FROM `$this->table_name` em";
364 352 $sql .= " INNER JOIN $entry_table e on e.id = em.bitforms_form_entry_id ";
365 353 if ($dateBetweenFilter) {
366 - $startDate = $dateBetweenFilter->start_date;
367 - $endDate = $dateBetweenFilter->end_date;
354 + $startDate = sanitize_text_field($dateBetweenFilter->start_date ?? '');
355 + $endDate = sanitize_text_field($dateBetweenFilter->end_date ?? '');
356 +
368 357 if ($startDate && $endDate) {
369 - $sql .= " AND DATE(e.created_at) BETWEEN '$startDate' AND '$endDate' ";
358 + $sql .= $this->app_db->prepare(' AND e.created_at BETWEEN %s AND %s', $startDate . ' 00:00:00', $endDate . ' 23:59:59');
370 359 } elseif ($startDate) {
371 - $sql .= " AND DATE(e.created_at) >= '$startDate' ";
360 + $sql .= $this->app_db->prepare(' AND e.created_at >= %s', $startDate . ' 00:00:00');
372 361 } elseif ($endDate) {
373 - $sql .= " AND DATE(e.created_at) <= '$endDate' ";
362 + $sql .= $this->app_db->prepare(' AND e.created_at <= %s', $endDate . ' 23:59:59');
374 363 }
375 364 }
376 365 $sql .= $groupedCondition . $orderCondition . $paginate;
377 366 $result = $this->execute($sql, $all_values)->getResult();
@@ -376,18 +365,15 @@
376 365 $sql .= $groupedCondition . $orderCondition . $paginate;
377 366 $result = $this->execute($sql, $all_values)->getResult();
378 367 if (is_wp_error($result)) {
379 368 return [
380 - 'count' => $paginateEntry ? $entryCount : 0,
369 + 'count' => 0,
381 370 'entries' => [],
382 371 'error' => $result->get_error_message()
383 372 ];
384 373 }
385 374 if ($isFldCondition) {
386 - $condition['bitforms_form_entry_id'] = $entryIDs;
387 - $group = $this->groupedCondition($condition, $all_values, $fieldConditions);
388 - $all_values = $group['all_values'];
389 - $entryCount = $this->queryRecount($selectedMeta, $group['groupedCondition'], $orderCondition, $all_values);
375 + $entryCount = $this->queryRecount($selectedMeta, $groupedCondition, $orderCondition, $all_values);
390 376 }
391 377 $resultedEntries = [
392 378 'count' => $entryCount,
393 379 'entries' => $result,
@@ -394,13 +380,37 @@
394 380 ];
395 381 return $resultedEntries;
396 382 }
397 383
398 - private function csvInjectionPrevent($value)
384 + public function getSingleEntryMeta($formFields, $entryId)
399 385 {
386 + $entry_table = $this->app_db->prefix . 'bitforms_form_entries';
387 + $fieldCount = count($formFields);
388 + $getSelectedMetaFldValue = $this->selectedEntryMeta($formFields, $fieldCount);
389 + $selectedMeta = $getSelectedMetaFldValue['selected_meta'];
390 + $formFieldsNames = $getSelectedMetaFldValue['form_fields_names'];
391 + $all_values = $getSelectedMetaFldValue['all_values'];
392 + $condition['bitforms_form_entry_id'] = [$entryId];
393 + $group = $this->groupedCondition($condition, $all_values, []);
394 + $groupedCondition = $group['groupedCondition'];
395 + $all_values = $group['all_values'];
396 + $orderCondition = $this->orderCondition($formFieldsNames, null);
397 + $sql = "SELECT $selectedMeta FROM `$this->table_name` em";
398 + $sql .= " INNER JOIN $entry_table e on e.id = em.bitforms_form_entry_id ";
399 + $sql .= $groupedCondition . $orderCondition;
400 + $result = $this->execute($sql, $all_values)->getResult();
401 +
402 + if (is_wp_error($result)) {
403 + return [];
404 + }
405 + return $result;
406 + }
407 +
408 + private static function csvInjectionPrevent($value)
409 + {
400 410 $formula = ['=', '-', '+', '@', "\t", "\r"];
401 411 $valueFilter = preg_replace('/[\]["]/i', '', $value);
402 - if (\in_array(substr($value, 0, 1), $formula, true)) {
412 + if (in_array(substr($valueFilter, 0, 1), $formula, true)) {
403 413 $valueFilter = "'" . trim($valueFilter);
404 414 }
405 415
406 416 return $valueFilter;
@@ -405,37 +415,83 @@
405 415
406 416 return $valueFilter;
407 417 }
408 418
409 - public function getExportEntry($formFields, $entries, $formId, $fieldLabels, $limit = null, $sortBy = null, $sortByField = null)
419 + private static function unescapeString($str)
410 420 {
421 + if (is_string($str) && '' !== $str) {
422 + $decoded = json_decode('"' . str_replace('"', '\\"', $str) . '"');
423 + return (null !== $decoded) ? $decoded : $str;
424 + }
425 + return $str;
426 + }
427 +
428 + private static function formatRepeaterValue($rawValue, $fieldMap)
429 + {
430 + if (empty($rawValue)) {
431 + return '';
432 + }
433 + $rows = [];
434 + preg_match_all('/\{([^}]+)\}/', $rawValue, $matches);
435 +
436 + foreach ($matches[1] as $row) {
437 + $pairs = explode(',', $row);
438 + $formattedPairs = [];
439 +
440 + foreach ($pairs as $pair) {
441 + if (false === strpos($pair, ':')) {
442 + continue;
443 + }
444 + [$childKey, $value] = explode(':', $pair, 2);
445 + $childKey = trim($childKey);
446 + $value = trim($value);
447 +
448 + // Get label from fieldMap or use key
449 + $label = $fieldMap[$childKey]['adminLbl'] ?? $childKey;
450 + $formattedPairs[] = "$label: " . self::csvInjectionPrevent(self::unescapeString($value));
451 + }
452 +
453 + $rows[] = implode(', ', $formattedPairs);
454 + }
455 +
456 + return implode('; ', $rows);
457 + }
458 +
459 + public function getExportEntry($formFields, $entries, $formId, $fieldLabels, $limit = null, $sortBy = null, $sortByField = null, $offset = null, $entryConditions = null)
460 + {
411 461 $entry_table = $this->app_db->prefix . 'bitforms_form_entries';
412 462 $selectedEntryMeta = '`bitforms_form_entry_id` as entry_id,';
413 - $selectedEntryMeta .= "e.user_id as '__user_id',";
414 - $selectedEntryMeta .= "e.status as '__entry_status',";
415 - $selectedEntryMeta .= "e.user_ip as '__user_ip',";
416 - $selectedEntryMeta .= "e.user_location as '__user_location',";
417 - $selectedEntryMeta .= "e.user_device as '__user_device',";
418 - $selectedEntryMeta .= "e.referer as '__referer',";
419 - $selectedEntryMeta .= "e.created_at as '__created_at',";
420 - $selectedEntryMeta .= "e.updated_at as '__updated_at',";
463 + $selectedEntryMeta .= 'e.user_id as `__user_id`,';
464 + $selectedEntryMeta .= 'e.status as `__entry_status`,';
465 + $selectedEntryMeta .= 'e.user_ip as `__user_ip`,';
466 + $selectedEntryMeta .= 'e.user_location as `__user_location`,';
467 + $selectedEntryMeta .= 'e.user_device as `__user_device`,';
468 + $selectedEntryMeta .= 'e.referer as `__referer`,';
469 + $selectedEntryMeta .= 'e.created_at as `__created_at`,';
470 + $selectedEntryMeta .= 'e.updated_at as `__updated_at`,';
421 471 $metaChecker = 0;
422 472
423 - $entryInfo = ['__user_id', '__user_ip', /* '__user_location', */'__user_device',
424 - '__referer', '__created_at', '__updated_at'];
473 + $entryInfo = [
474 + '__user_id',
475 + '__user_ip', /* '__user_location', */
476 + '__user_device',
477 + '__entry_status',
478 + '__referer',
479 + '__created_at',
480 + '__updated_at'
481 + ];
425 482 $all_values = [];
426 483 if ([] === $formFields) {
427 - $data = [
484 + return [
428 485 'count' => 0,
429 486 'entries' => [],
430 487 ];
431 - wp_send_json_success($data, 200);
432 488 }
433 489 $fieldCount = count($formFields) - count(array_intersect($formFields, $entryInfo));
434 490 $formFieldsNames = [];
435 491 foreach ($formFields as $fldKey) {
436 492 $formFieldsNames[] = $fldKey;
437 - if (in_array($fldKey, $entryInfo)) {
493 + if (in_array($fldKey, $entryInfo, true)) {
438 494 continue;
439 495 }
440 496 $fieldFormat = $this->getFieldFormat($fldKey);
441 497 $selectedEntryMeta .= "GROUP_CONCAT(
@@ -461,42 +517,66 @@
461 517 'entries' => [],
462 518 ];
463 519 }
464 520 $condition['bitforms_form_entry_id'] = $entryIDs;
465 - $formattedCondition = $this->getFormatedCondition($condition);
466 - $groupedCondition = null;
467 - if ($formattedCondition) {
468 - $groupedCondition = $formattedCondition['conditions'] . ' GROUP BY
469 - `bitforms_form_entry_id` ';
470 - $all_values = array_merge($all_values, $formattedCondition['values']);
471 - }
472 - $order = \is_null($sortBy) ? 'DESC ' : "$sortBy";
473 - $orderField = \is_null($sortByField) ? 'bitforms_form_entry_id' : "`$sortByField`";
521 + $grpCon = $this->groupedCondition($condition, $all_values, $entryConditions);
522 + $groupedCondition = $grpCon['groupedCondition'];
523 + $all_values = $grpCon['all_values'];
474 524
525 + $order = 'DESC' === $sortBy ? 'DESC ' : 'ASC ';
526 + $validSortFields = array_column($fieldLabels, 'key');
527 + $orderField = (!is_null($sortByField) && in_array($sortByField, $validSortFields, true))
528 + ? '`' . sanitize_key($sortByField) . '`'
529 + : '`bitforms_form_entry_id`';
530 +
475 531 $orderCondition = "ORDER BY $orderField $order ";
476 - if (!\is_null($limit)) {
477 - $limitInt = \intval($limit);
478 - $limit = " LIMIT $limitInt ";
532 + $limitClause = '';
533 + if (!is_null($limit)) {
534 + $limitInt = intval($limit);
535 + $limitClause = " LIMIT $limitInt ";
536 + if (!is_null($offset)) {
537 + $offsetInt = intval($offset);
538 + $limitClause .= " OFFSET $offsetInt ";
539 + }
479 540 }
541 +
542 + $this->app_db->query('SET SESSION group_concat_max_len = 10000');
480 543 $sql = "SELECT $selectedEntryMeta FROM `$this->table_name` em";
481 544 $sql .= " INNER JOIN $entry_table e on e.id = em.bitforms_form_entry_id ";
482 - $sql .= $groupedCondition . $orderCondition . $limit;
545 + $sql .= $groupedCondition . $orderCondition . $limitClause;
546 + $result = $this->execute($sql, $all_values)->getResult();
547 + if (is_wp_error($result)) {
548 + return new \WP_Error('db_error', 'Internal server error');
549 + }
483 550
484 - $result = $this->execute($sql, $all_values)->getResult();
485 551 $allData = [];
486 - $entry_id = 'entry_id';
487 - $users = get_users(['fields' => ['ID', 'display_name']]);
552 + $entryStatus = [
553 + '0' => 'Read',
554 + '1' => 'Unread',
555 + '2' => 'Unconfirmed',
556 + '3' => 'Confirmed',
557 + '9' => 'Draft',
558 + ];
559 + $userIds = array_unique(array_filter(
560 + array_map(static fn ($row) => (int) $row->__user_id, (array) $result),
561 + static fn ($id) => $id > 0
562 + ));
488 563 $userNames = [];
489 - foreach ($users as $key => $value) {
490 - $userNames[$value->ID] = $value->display_name;
564 + if (!empty($userIds)) {
565 + $users = get_users(['include' => $userIds, 'fields' => ['ID', 'display_name']]);
566 + foreach ($users as $user) {
567 + $userNames[$user->ID] = $user->display_name;
568 + }
491 569 }
492 570 foreach ($result as $key => $value) {
493 571 foreach ($formFieldsNames as $formFieldName) {
494 - $allData[$key]['entry_id'] = preg_replace('/[\]["]/i', '', $value->$entry_id);
572 + $allData[$key]['entry_id'] = preg_replace('/[\]["]/i', '', $value->entry_id);
495 573 if ('__user_id' === $formFieldName && intval($value->$formFieldName) > 0) {
496 - $allData[$key][$formFieldName] = $userNames[$value->$formFieldName];
574 + $allData[$key][$formFieldName] = $userNames[$value->$formFieldName] ?? '';
497 575 } elseif ('__user_ip' === $formFieldName) {
498 - $allData[$key][$formFieldName] = long2ip($value->$formFieldName);
576 + $allData[$key][$formFieldName] = IpTool::displayValue($value->$formFieldName);
577 + } elseif ('__entry_status' === $formFieldName) {
578 + $allData[$key][$formFieldName] = $entryStatus[$value->{$formFieldName}] ?? '';
499 579 } else {
500 580 $allData[$key][$formFieldName] = preg_replace('/[\]["]/i', '', $value->$formFieldName);
501 581 }
502 582 }
@@ -501,40 +581,55 @@
501 581 }
502 582 }
503 583 }
504 584
505 - if (is_wp_error($result)) {
506 - wp_send_json_error('Internal server error', 500);
507 - } else {
508 - $downloadableFieldType = ['file-up', 'signature', 'advanced-file-up'];
509 - foreach ($fieldLabels as $field) {
510 - foreach ($allData as $index => $entry) {
511 - if (array_key_exists($field['key'], $entry) && in_array($field['type'], $downloadableFieldType, true)) {
512 - $key = $field['key'];
513 - if (empty($entry[$key])) {
514 - continue;
515 - }
516 - $_upload_dir = BITFORMS_UPLOAD_DIR . DIRECTORY_SEPARATOR . $formId . DIRECTORY_SEPARATOR . $entry['entry_id'];
517 - $imageArray = explode(',', $entry[$key]);
518 - if (is_array($imageArray)) {
519 - $fileData = [];
520 - foreach ($imageArray as $file) {
521 - $path = "bitforms/bitforms-file-$formId/?formID=$formId&entryID=" . $entry['entry_id'] . "&fileID=$file";
522 - if (file_exists($_upload_dir . DIRECTORY_SEPARATOR . $file)) {
523 - $fileData[] = site_url($path, null);
524 - }
525 - }
526 - $allData[$index][$key] = implode(',', $fileData);
527 - } else {
528 - $uploadedFile = explode('_', $entry[$key]);
529 - $path = "bitforms/bitforms-file-$formId/?formID=$formId&entryID=" . $entry['entry_id'] . '&fileID=' . $uploadedFile[0];
530 - if (file_exists($_upload_dir . DIRECTORY_SEPARATOR . $uploadedFile[0])) {
531 - $allData[$index][$key] = site_url($path, null);
532 - }
533 - }
585 + $fieldMap = [];
586 + $repeaterFields = [];
587 + $fileFields = [];
588 + $downloadableFieldType = ['file-up', 'signature', 'advanced-file-up'];
589 +
590 + foreach ($fieldLabels as $field) {
591 + $key = $field['key'];
592 + $fieldMap[$key] = $field;
593 + if ('repeater' === $field['type']) {
594 + $repeaterFields[] = $key;
595 + } elseif (in_array($field['type'], $downloadableFieldType, true)) {
596 + $fileFields[] = $key;
597 + }
598 + }
599 +
600 + foreach ($allData as &$entry) {
601 + foreach ($entry as $key => &$value) {
602 + if (is_string($value)) {
603 + $value = self::csvInjectionPrevent(self::unescapeString($value));
604 + }
605 + if (in_array($key, $repeaterFields, true)) {
606 + $value = self::formatRepeaterValue($value, $fieldMap);
607 + }
608 + }
609 + unset($value);
610 + }
611 + unset($entry, $value);
612 +
613 + foreach ($allData as &$entry) {
614 + $entryId = $entry['entry_id'];
615 + $_upload_dir = FileHandler::getEntriesFileUploadDir($formId, $entryId);
616 + foreach ($fileFields as $fileKey) {
617 + if (empty($entry[$fileKey])) {
618 + continue;
619 + }
620 + $fileIds = explode(',', $entry[$fileKey]);
621 + $urls = [];
622 + foreach ($fileIds as $fileId) {
623 + $path = "bitforms/bitforms-file/?formID=$formId&entryID=$entryId&fileID=$fileId";
624 + if (file_exists($_upload_dir . DIRECTORY_SEPARATOR . $fileId)) {
625 + $urls[] = site_url($path);
534 626 }
535 627 }
628 + $entry[$fileKey] = implode(',', $urls);
536 629 }
537 - wp_send_json_success($allData, 200);
538 630 }
631 + unset($entry);
632 +
633 + return $allData;
539 634 }
540 635 }