PluginProbe
Bit Form – Contact Form, Payment Forms, Multi Step Forms, Calculator & Custom Form Builder / 2.0
Bit Form – Contact Form, Payment Forms, Multi Step Forms, Calculator & Custom Form Builder v2.0
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 2.10.1 2.10.2 All 137 releases
bit-form / includes / Core / Database / FormEntryMetaModel.php

FormEntryMetaModel.php in Bit Form – Contact Form, Payment Forms, Multi Step Forms, Calculator & Custom Form Builder 2.0, at includes/Core/Database/FormEntryMetaModel.php

527 lines 19.3 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 /**
4 * Provides Base Model Class
5 */
6
7 namespace BitCode\BitForm\Core\Database;
8
9 /**
10 * Undocumented class
11 */
12
13 class FormEntryMetaModel extends Model {
14 protected static $table = 'bitforms_form_entrymeta';
15
16 public function duplicateEntryMeta($data) {
17 $values[] = $data['duplicateID'];
18 $values[] = $data['entryID'];
19 $sql = "INSERT INTO $this->table_name (bitforms_form_entry_id,meta_key,meta_value)"
20 . ' SELECT %d as bitforms_form_entry_id,meta_key,meta_value'
21 . " FROM `$this->table_name` WHERE bitforms_form_entry_id = %d";
22 return $this->execute($sql, $values)->getResult();
23 }
24
25 public function update(array $data, array $condition) {
26 $entryID = $condition['bitforms_form_entry_id'];
27 if (empty($entryID)) {
28 return false;
29 }
30 $formEntryMeta = $this->get(
31 [
32 'meta_key',
33 'meta_value',
34 ],
35 [
36 'bitforms_form_entry_id' => $entryID,
37 ]
38 );
39 $oldEntries = [];
40 foreach ($formEntryMeta as $oldKey => $oldValue) {
41 $oldEntries[$oldValue->meta_key] = $oldValue->meta_value;
42 }
43 $updatedData = [];
44 $oldEntriesKey = array_keys($oldEntries);
45 foreach ($data as $upKey => $upValue) {
46 $updatedData[$upKey] = is_string($upValue) ?
47 $upValue :
48 wp_json_encode($upValue);
49 if (!\in_array($upKey, $oldEntriesKey)) {
50 $this->insert(
51 [
52 'bitforms_form_entry_id' => $entryID,
53 'meta_key' => $upKey,
54 'meta_value' => $updatedData[$upKey],
55 ]
56 );
57 unset($data[$upKey]);
58 }
59 }
60 if (empty($data)) {
61 return $updatedData;
62 }
63 $checkCondition = $this->checkCondition($condition);
64 if (is_wp_error($checkCondition)) {
65 return $checkCondition;
66 }
67 $case_part = ' ';
68 $all_values = [];
69 $condition['meta_key'] = array_keys($data);
70 foreach ($data as $key => $value) {
71 $value = is_string($value) ? $value : wp_json_encode($value);
72 $case_part .= "
73 WHEN '$key' THEN " . $this->getFieldFormat($value);
74 $all_values[] = $value;
75 }
76 $formattedCondition = $this->getFormatedCondition($condition);
77 if ($formattedCondition) {
78 $condition_to_check = $formattedCondition['conditions'];
79 $all_values = array_merge($all_values, $formattedCondition['values']);
80 } else {
81 $condition_to_check = null;
82 }
83
84 $sql = "UPDATE $this->table_name
85 SET meta_value = ( CASE meta_key
86 $case_part
87 END
88 )";
89 $sql .= ' ' . $condition_to_check;
90 $status = $this->execute($sql, $all_values)->getResult();
91 if (is_wp_error($status) && 'result_empty' !== $status->get_error_code()) {
92 return $status;
93 }
94 return $updatedData;
95 }
96
97 public function validQueryCondition($conditions) {
98 foreach ($conditions as $index => $condition) {
99 if (is_object($condition)) {
100 if (empty($condition->field) || empty($condition->logic) || empty($condition->val) && !in_array($condition->val, ['0', 0, 0.0], true)) {
101 unset($conditions[$index], $conditions[$index + 1]);
102 }
103 }
104 }
105 return $conditions;
106 }
107
108 public function sqlQryGenerateByFldCondition($conditions) {
109 $dbHelper = new Helper();
110 $sql = '';
111
112 $dateQuery = $dbHelper->dateQueryList();
113
114 $validCondtions = $this->validQueryCondition($conditions);
115
116 foreach ($validCondtions as $condition) {
117 if (is_object($condition)) {
118 if (is_array($condition->val)) {
119 $value = $dbHelper->arrValueModifyByLogic($condition->logic, $condition->val);
120 } else {
121 $value = $dbHelper->strValueModifyByLogic($condition->logic, $condition->val);
122 }
123
124 $operator = $dbHelper->convertToSqlOperator($condition->logic);
125
126 if (isset($dateQuery[$condition->val])) {
127 $sql .= $dbHelper->fieldQueryByDate($condition->field, $operator, $value, $condition->logic);
128 } else {
129 if (!is_int($value)) {
130 $value = "'" . $value . "'";
131 }
132
133 $sql .= "`$condition->field` $operator $value";
134 }
135 } else {
136 $sql .= ' ' . $condition;
137 }
138 }
139
140 return trim($sql);
141 }
142
143 public function queryRecount($selectedMeta, $groupedCondition, $orderCondition, $all_values) {
144 $entry_table = $this->app_db->prefix . 'bitforms_form_entries';
145 $sql = 'SELECT count(*) as count FROM (';
146 $sql .= "SELECT $selectedMeta FROM `$this->table_name` em";
147 $sql .= " INNER JOIN $entry_table e on e.id = em.bitforms_form_entry_id ";
148 $sql .= $groupedCondition . $orderCondition;
149 $sql .= ') as retrievedData';
150 $countResult = $this->execute($sql, $all_values)->getResult();
151 return $countResult[0]->count;
152 }
153
154 public function selectedEntryMeta($formFields, $fieldCount) {
155 $all_values = [];
156 $formFieldsNames = [];
157 $metaChecker = 0;
158 $selectedMeta = '`bitforms_form_entry_id` as entry_id,';
159 $selectedMeta .= "e.user_id as '__user_id',";
160 $selectedMeta .= "e.user_ip as '__user_ip',";
161 $selectedMeta .= "e.status as '__entry_status',";
162 $selectedMeta .= "e.user_location as '__user_location',";
163 $selectedMeta .= "e.user_device as '__user_device',";
164 $selectedMeta .= "e.referer as '__referer',";
165 $selectedMeta .= "e.created_at as '__created_at',";
166 $selectedMeta .= "e.updated_at as '__updated_at'";
167
168 if ($fieldCount > 0) {
169 $selectedMeta .= ',';
170 }
171
172 foreach ($formFields as $fieldDetails) {
173 $fieldFormat = $this->getFieldFormat($fieldDetails['key']);
174 $selectedMeta .= "GROUP_CONCAT(
175 CASE
176 `meta_key`
177 WHEN '$fieldFormat' THEN `meta_value`
178 END
179 ) AS '$fieldFormat'";
180 $metaChecker += 1;
181 $all_values[] = $fieldDetails['key'];
182 $all_values[] = $fieldDetails['key'];
183 $formFieldsNames[] = $fieldDetails['key'];
184 if ($metaChecker < $fieldCount) {
185 $selectedMeta .= ',';
186 }
187 //#unused code commented by me##
188 // if ( !empty( $filter['global'] ) ) {
189 // $globalFilterString .= " `" . $fieldDetails['key'] . "` LIKE '%%" . $this->getFieldFormat( $filter['global'] ) . "%%' ";
190 // if ( $metaChecker < $fieldCount ) {
191 // $globalFilterString .= " OR ";
192 // }
193 // $globalFilterValues[] = $filter['global'];
194 // }
195 }
196
197 return [
198 'selected_meta' => $selectedMeta,
199 'form_fields_names' => $formFieldsNames,
200 'all_values' => $all_values,
201 ];
202 }
203
204 public function groupedCondition($condition, $all_values, $fieldConditions) {
205 $isFldCondition = false;
206 $formattedCondition = $this->getFormatedCondition($condition);
207 if ($formattedCondition) {
208 $groupedCondition = $formattedCondition['conditions'] . 'GROUP BY
209 `bitforms_form_entry_id` ';
210 $all_values = array_merge($all_values, $formattedCondition['values']);
211 } else {
212 $groupedCondition = null;
213 }
214 //#unused code commented by me##
215 //$isRecount = false;
216
217 // if ( !empty( $filter['field'] ) ) {
218 // $isRecount = true;
219 // $filterFieldCount = count( $filter['field'] );
220 // $filterFieldChecker = 0;
221 // if ( $filterFieldCount > 0 ) {
222 // $groupedCondition .= " HAVING ";
223 // }
224 // foreach ( $filter['field'] as $filterFieldKey => $filterFieldDetails ) {
225 // $groupedCondition .= " `$filterFieldDetails->id` ='%%" . $this->getFieldFormat( $filterFieldDetails->value ) . "%%'";
226 // $all_values[] = $filterFieldDetails->value;
227 // if ( $filterFieldChecker < $filterFieldCount ) {
228 // $groupedCondition .= " AND ";
229 // }
230 // }
231 // }
232
233 // if ( !empty( $filter['global'] ) && !empty( $globalFilterString ) && !empty( $globalFilterValues ) ) {
234 // $isRecount = true;
235 // if ( !empty( $filter['field'] ) ) {
236 // $groupedCondition .= " AND (" . $globalFilterString . ") ";
237 // } else {
238 // $groupedCondition .= " HAVING $globalFilterString ";
239 // }
240 // $offset = 0;
241 // $all_values = array_merge( $all_values, $globalFilterValues );
242 // }
243
244 // if ( !empty( $dateBetweenFilter ) && !empty( $dateBetweenFilter->start_date ) && !empty( $dateBetweenFilter->end_date ) ) {
245 // if ( strpos( $groupedCondition, 'HAVING' ) !== false ) {
246 // $groupedCondition .= " AND `__created_at` BETWEEN '" . $dateBetweenFilter->start_date . "' AND '" . $dateBetweenFilter->end_date . "' ";
247 // } else {
248 // $groupedCondition .= " HAVING `__created_at` BETWEEN '" . $dateBetweenFilter->start_date . "' AND '" . $dateBetweenFilter->end_date . "' ";
249 // }
250 // }
251
252 $sqlQryByFldCondtion = $this->sqlQryGenerateByFldCondition($fieldConditions);
253
254 if (!empty($sqlQryByFldCondtion)) {
255 $isFldCondition = true;
256 if (false !== strpos($groupedCondition, 'HAVING')) {
257 $groupedCondition .= ' AND (' . $sqlQryByFldCondtion . ') ';
258 } else {
259 $groupedCondition .= ' HAVING (' . $sqlQryByFldCondtion . ') ';
260 }
261 }
262 return [
263 'groupedCondition' => $groupedCondition,
264 'all_values' => $all_values,
265 'isFldCondition' => $isFldCondition,
266 ];
267 }
268
269 public function orderCondition($formFieldsNames, $sortBy) {
270 $orderCondition = null;
271 if (!empty($sortBy)) {
272 $sortableFieldCount = count($sortBy);
273 $sortableFieldChecker = 0;
274 if ($sortableFieldCount > 0) {
275 $orderCondition .= ' ORDER BY ';
276 }
277 $orderList = '';
278 foreach ($sortBy as $sortableFieldKey => $sortableFieldDetails) {
279 // $orderCondition .=" ".$this->getFieldFormat($sortableFieldDetails->id);
280 $sortableFieldChecker += 1;
281 if (in_array($sortableFieldDetails->id, $formFieldsNames)) {
282 $orderList .= " `$sortableFieldDetails->id` ";
283 $orderFollow = $sortableFieldDetails->desc ? ' DESC ' : ' ASC ';
284 $orderList .= ' ' . $orderFollow;
285 if ($sortableFieldChecker < $sortableFieldCount) {
286 $orderList .= ', ';
287 }
288 }
289 }
290 if (empty($orderList)) {
291 $orderCondition = null;
292 } else {
293 $orderCondition .= $orderList;
294 }
295 }
296 $orderCondition .= empty($orderCondition) ? ' ORDER BY `bitforms_form_entry_id` DESC ' : ',`bitforms_form_entry_id` DESC ';
297 return $orderCondition;
298 }
299
300 public function isEntryMetaExist($conditions) {
301 $existMetaData = $this->get(
302 [
303 'meta_key',
304 'meta_value',
305 ],
306 $conditions
307 );
308 if (!is_wp_error($existMetaData) && count($existMetaData) > 0) {
309 return true;
310 }
311 return false;
312 }
313
314 public function getEntryMeta($formFields, $entries, $limit = null, $offset = null, $filter = null, $sortBy = null, $fieldConditions = null, $dateBetweenFilter = null) {
315 $entry_table = $this->app_db->prefix . 'bitforms_form_entries';
316 $fieldCount = count($formFields);
317 $getSelectedMetaFldValue = $this->selectedEntryMeta($formFields, $fieldCount);
318
319 $selectedMeta = $getSelectedMetaFldValue['selected_meta'];
320 $formFieldsNames = $getSelectedMetaFldValue['form_fields_names'];
321 $all_values = $getSelectedMetaFldValue['all_values'];
322 $entryIDs = [];
323 $entryCount = count($entries);
324 // $paginateEntry = empty($sortBy) && empty($filter['field']) && empty($filter['global']);
325 // $entries = $paginateEntry ? array_slice($entries, $offset, $limit) : $entries;
326 $paginateEntry = false;
327 foreach ($entries as $entryDetail) {
328 $entryIDs[] = $entryDetail->id;
329 }
330 if (empty($entryIDs)) {
331 return [
332 'count' => 0,
333 'entries' => [],
334 ];
335 }
336 $condition['bitforms_form_entry_id'] = $entryIDs;
337 $group = $this->groupedCondition($condition, $all_values, $fieldConditions);
338 $groupedCondition = $group['groupedCondition'];
339 $all_values = $group['all_values'];
340 $isFldCondition = $group['isFldCondition'];
341 $orderCondition = $this->orderCondition($formFieldsNames, $sortBy);
342
343 $paginate = null;
344 if (!\is_null($limit)) {
345 $limit = \intval($limit);
346 $paginate .= " LIMIT $limit ";
347 }
348 if (!\is_null($offset)) {
349 $offset = \intval($offset);
350 $paginate .= " OFFSET $offset ";
351 }
352 $sql = "SELECT $selectedMeta FROM `$this->table_name` em";
353 $sql .= " INNER JOIN $entry_table e on e.id = em.bitforms_form_entry_id ";
354 if ($dateBetweenFilter) {
355 $startDate = $dateBetweenFilter->start_date;
356 $endDate = $dateBetweenFilter->end_date;
357 if ($startDate && $endDate) {
358 $sql .= " AND DATE(e.created_at) BETWEEN '$startDate' AND '$endDate' ";
359 } elseif ($startDate) {
360 $sql .= " AND DATE(e.created_at) >= '$startDate' ";
361 } elseif ($endDate) {
362 $sql .= " AND DATE(e.created_at) <= '$endDate' ";
363 }
364 }
365 $sql .= $groupedCondition . $orderCondition . $paginate;
366 $result = $this->execute($sql, $all_values)->getResult();
367 if (is_wp_error($result)) {
368 return [
369 'count' => $paginateEntry ? $entryCount : 0,
370 'entries' => [],
371 'error' => $result->get_error_message()
372 ];
373 }
374 if ($isFldCondition) {
375 $condition['bitforms_form_entry_id'] = $entryIDs;
376 $group = $this->groupedCondition($condition, $all_values, $fieldConditions);
377 $all_values = $group['all_values'];
378 $entryCount = $this->queryRecount($selectedMeta, $group['groupedCondition'], $orderCondition, $all_values);
379 }
380 $resultedEntries = [
381 'count' => $entryCount,
382 'entries' => $result,
383 ];
384 return $resultedEntries;
385 }
386
387 private function csvInjectionPrevent($value) {
388 $formula = ['=', '-', '+', '@', "\t", "\r"];
389 $valueFilter = preg_replace('/[\]["]/i', '', $value);
390 if (\in_array(substr($value, 0, 1), $formula, true)) {
391 $valueFilter = "'" . trim($valueFilter);
392 }
393
394 return $valueFilter;
395 }
396
397 public function getExportEntry($formFields, $entries, $formId, $fieldLabels, $limit = null, $sortBy = null, $sortByField = null) {
398 $entry_table = $this->app_db->prefix . 'bitforms_form_entries';
399 $selectedEntryMeta = '`bitforms_form_entry_id` as entry_id,';
400 $selectedEntryMeta .= "e.user_id as '__user_id',";
401 $selectedEntryMeta .= "e.status as '__entry_status',";
402 $selectedEntryMeta .= "e.user_ip as '__user_ip',";
403 $selectedEntryMeta .= "e.user_location as '__user_location',";
404 $selectedEntryMeta .= "e.user_device as '__user_device',";
405 $selectedEntryMeta .= "e.referer as '__referer',";
406 $selectedEntryMeta .= "e.created_at as '__created_at',";
407 $selectedEntryMeta .= "e.updated_at as '__updated_at',";
408 $metaChecker = 0;
409
410 $entryInfo = ['__user_id', '__user_ip', /* '__user_location', */'__user_device',
411 '__referer', '__created_at', '__updated_at'];
412 $all_values = [];
413 if ([] === $formFields) {
414 $data = [
415 'count' => 0,
416 'entries' => [],
417 ];
418 wp_send_json_success($data, 200);
419 }
420 $fieldCount = count($formFields) - count(array_intersect($formFields, $entryInfo));
421 $formFieldsNames = [];
422 foreach ($formFields as $fldKey) {
423 $formFieldsNames[] = $fldKey;
424 if (in_array($fldKey, $entryInfo)) {
425 continue;
426 }
427 $fieldFormat = $this->getFieldFormat($fldKey);
428 $selectedEntryMeta .= "GROUP_CONCAT(
429 CASE
430 `meta_key`
431 WHEN '$fieldFormat' THEN `meta_value`
432 END
433 ) AS '$fieldFormat'";
434 $metaChecker += 1;
435 $all_values[] = $fldKey;
436 $all_values[] = $fldKey;
437 if ($metaChecker < $fieldCount) {
438 $selectedEntryMeta .= ',';
439 }
440 }
441 $entryIDs = [];
442 foreach ($entries as $entryDetail) {
443 $entryIDs[] = $entryDetail->id;
444 }
445 if (empty($entryIDs)) {
446 return [
447 'count' => 0,
448 'entries' => [],
449 ];
450 }
451 $condition['bitforms_form_entry_id'] = $entryIDs;
452 $formattedCondition = $this->getFormatedCondition($condition);
453 $groupedCondition = null;
454 if ($formattedCondition) {
455 $groupedCondition = $formattedCondition['conditions'] . ' GROUP BY
456 `bitforms_form_entry_id` ';
457 $all_values = array_merge($all_values, $formattedCondition['values']);
458 }
459 $order = \is_null($sortBy) ? 'DESC ' : "$sortBy";
460 $orderField = \is_null($sortByField) ? 'bitforms_form_entry_id' : "`$sortByField`";
461
462 $orderCondition = "ORDER BY $orderField $order ";
463 if (!\is_null($limit)) {
464 $limitInt = \intval($limit);
465 $limit = " LIMIT $limitInt ";
466 }
467 $sql = "SELECT $selectedEntryMeta FROM `$this->table_name` em";
468 $sql .= " INNER JOIN $entry_table e on e.id = em.bitforms_form_entry_id ";
469 $sql .= $groupedCondition . $orderCondition . $limit;
470
471 $result = $this->execute($sql, $all_values)->getResult();
472 $allData = [];
473 $entry_id = 'entry_id';
474 $users = get_users(['fields' => ['ID', 'display_name']]);
475 $userNames = [];
476 foreach ($users as $key => $value) {
477 $userNames[$value->ID] = $value->display_name;
478 }
479 foreach ($result as $key => $value) {
480 foreach ($formFieldsNames as $formFieldName) {
481 $allData[$key]['entry_id'] = preg_replace('/[\]["]/i', '', $value->$entry_id);
482 if ('__user_id' === $formFieldName && intval($value->$formFieldName) > 0) {
483 $allData[$key][$formFieldName] = $userNames[$value->$formFieldName];
484 } elseif ('__user_ip' === $formFieldName) {
485 $allData[$key][$formFieldName] = long2ip($value->$formFieldName);
486 } else {
487 $allData[$key][$formFieldName] = preg_replace('/[\]["]/i', '', $value->$formFieldName);
488 }
489 }
490 }
491
492 if (is_wp_error($result)) {
493 wp_send_json_error('Internal server error', 500);
494 } else {
495 foreach ($fieldLabels as $field) {
496 foreach ($allData as $index => $entry) {
497 if (array_key_exists($field['key'], $entry) && 'file-up' === $field['type']) {
498 $key = $field['key'];
499 if (empty($entry[$key])) {
500 continue;
501 }
502 $_upload_dir = BITFORMS_UPLOAD_DIR . DIRECTORY_SEPARATOR . $formId . DIRECTORY_SEPARATOR . $entry['entry_id'];
503 if (is_array(explode(',', $entry[$key]))) {
504 $fileData = [];
505 foreach (explode(',', $entry[$key]) as $file) {
506 $uploadedFile = explode('_', $file);
507 $path = "bitforms/bitforms-file/?formID=$formId&entryID=" . $entry['entry_id'] . "&fileID=$uploadedFile[0]";
508 if (file_exists($_upload_dir . DIRECTORY_SEPARATOR . $uploadedFile[0])) {
509 $fileData[] = site_url($path, null);
510 }
511 }
512 $allData[$index][$key] = implode(',', $fileData);
513 } else {
514 $uploadedFile = explode('_', $entry[$key]);
515 $path = "bitforms/bitforms-file/?formID=$formId&entryID=" . $entry['entry_id'] . '&fileID=' . $uploadedFile[0];
516 if (file_exists($_upload_dir . DIRECTORY_SEPARATOR . $uploadedFile[0])) {
517 $allData[$index][$key] = site_url($path, null);
518 }
519 }
520 }
521 }
522 }
523 wp_send_json_success($allData, 200);
524 }
525 }
526 }
527