PluginProbe
Bit Form – Contact Form, Payment Forms, Multi Step Forms, Calculator & Custom Form Builder / 2.17.6
Bit Form – Contact Form, Payment Forms, Multi Step Forms, Calculator & Custom Form Builder v2.17.6
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 / Admin / Form / Helpers.php

Helpers.php in Bit Form – Contact Form, Payment Forms, Multi Step Forms, Calculator & Custom Form Builder 2.17.6, at includes/Admin/Form/Helpers.php

318 lines 8.4 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 namespace BitCode\BitForm\Admin\Form;
4
5 use BitCode\BitForm\Core\Cryptography\Cryptography;
6 use BitCode\BitForm\Core\Database\FormEntryModel;
7 use BitCode\BitForm\Core\Util\Log;
8 use Exception;
9
10 class Helpers
11 {
12 private static $encryptEntryIds = [];
13
14 public static $file_upload_types = ['file-up', 'advanced-file-up'];
15
16 public static $repeated_array_type_data_fields = ['check', 'image-select'];
17
18 public static function filterNullEntries($entries)
19 {
20 $filteredEntries = [];
21 foreach ($entries as $entry) {
22 foreach ($entry as $key => $value) {
23 if (is_null($value)) {
24 unset($entry->$key);
25 }
26 }
27 if (count((array) $entry)) {
28 $filteredEntries[] = $entry;
29 }
30 }
31 return $filteredEntries;
32 }
33
34 public static function scriptLoader($src, $id, $instanceObj = null, $selector = '', $attrs = [], $integrity = null, $contentId = '')
35 {
36 $attributes = wp_json_encode($attrs);
37 $instObj = '';
38 if ($instanceObj) {
39 $instObj .= <<<INST
40 script.onload = function () {
41 bfSelect('#{$contentId}').querySelectorAll('{$selector}').forEach(function(fld){
42 $instanceObj;
43 });
44 }
45 INST;
46 }
47 return <<<LOAD_SECRIPT
48 var script = document.createElement('script'), integrity = '$integrity', attrs = $attributes, id = '$id';
49 script.src = '$src';
50 script.id = id;
51 if(integrity){
52 script.integrity = integrity;
53 script.crossOrigin = 'anonymous';
54 }
55 if(attrs){
56 Object.entries(attrs).forEach(function([key, val]){
57 script.setAttribute(key,val);
58 })
59 }
60 $instObj;
61 var bodyElm = document.body;
62 var alreadyExistScriptElm = bodyElm ? bodyElm.querySelector('script#$id'):null;
63 if(alreadyExistScriptElm){
64 bodyElm.removeChild(alreadyExistScriptElm)
65 }
66 if(!(window.recaptcha && id === 'g-recaptcha-script')){
67 bodyElm.appendChild(script);
68 }
69 LOAD_SECRIPT;
70 }
71
72 public static function minifyJs($input)
73 {
74 if ('' === trim($input)) {
75 return $input;
76 }
77 return preg_replace(
78 [
79 '/ {2,}/',
80 '/\s*=\s*/',
81 '/\s*,\s*/',
82 '/\s+(?=\(|\{|\:|\?)|\t|(?:\r?\n[ \t]*)+/s'
83 ],
84 [' ', '=', ',', ''],
85 $input
86 );
87 }
88
89 /**
90 * @method name : saveFile
91 * @description : save js/css field to disk
92 * @param : $path => like(dirName/css), $fileName => main.css, $script
93 * @return : boolean
94 */
95 public static function saveFile($path, $fileName, $script, $fileOpenMode = 'a')
96 {
97 try {
98 $rootDir = BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR;
99 $path = trim($path, '/');
100 $pathArr = explode('/', $path); // like "fieldname/user => [Fieldname, user]
101 foreach ($pathArr as $d) {
102 $rootDir .= $d . DIRECTORY_SEPARATOR;
103 if (!realpath($rootDir)) {
104 mkdir($rootDir);
105 }
106 }
107 $fullPath = $rootDir . $fileName;
108 $file = fopen($fullPath, $fileOpenMode);
109 if (false === $file) {
110 throw new Exception("Failed to open file: $fullPath");
111 }
112 if (false === fwrite($file, $script)) {
113 throw new Exception("Failed to write to file: $fullPath");
114 }
115 if (false === fclose($file)) {
116 throw new Exception("Failed to close file: $fullPath");
117 }
118 return true;
119 } catch (\Exception $e) {
120 Log::debug_log($e->getMessage());
121 return false;
122 }
123 }
124
125 /**
126 * @method name : generatePathDirOrFile
127 * @dscription : generate path for js/css file
128 * @params : $path => like(dirName/css)
129 * @return : a string of full path
130 */
131 public static function generatePathDirOrFile($path)
132 {
133 $rootDir = BITFORMS_CONTENT_DIR . DIRECTORY_SEPARATOR;
134 $path = trim($path, '/');
135 $pathArr = explode('/', $path); // like "fieldname/user => [Fieldname, user]
136 foreach ($pathArr as $d) {
137 $rootDir .= $d . DIRECTORY_SEPARATOR;
138 }
139 return rtrim($rootDir, DIRECTORY_SEPARATOR);
140 }
141
142 public static function fileRead($filePath)
143 {
144 $fileContent = '';
145 if (file_exists($filePath)) {
146 $file = fopen($filePath, 'r');
147 $fileContent .= fread($file, filesize($filePath));
148 fclose($file);
149 }
150 return $fileContent;
151 }
152
153 public static function getDataFromNestedPath($data, $key)
154 {
155 $keys = explode('->', $key);
156 $lastKey = array_pop($keys);
157 $dataType = is_array($data) ? 'array' : (is_object($data) ? 'object' : '');
158 if ('array' === $dataType) {
159 return self::accessFromArray($data, $keys, $lastKey);
160 }
161 if ('object' === $dataType) {
162 return self::accessFromObject($data, $keys, $lastKey);
163 }
164 }
165
166 private static function accessFromObject($data, $keys, $lastKey)
167 {
168 foreach ($keys as $k) {
169 if (!property_exists($data, $k)) {
170 return null;
171 }
172 $data = $data->$k;
173 }
174 return isset($data->$lastKey) ? $data->$lastKey : null;
175 }
176
177 private static function accessFromArray($data, $keys, $lastKey)
178 {
179 foreach ($keys as $k) {
180 if (!array_key_exists($k, $data)) {
181 return null;
182 }
183 $data = $data[$k];
184 }
185 return isset($data[$lastKey]) ? $data[$lastKey] : null;
186 }
187
188 public static function setDataToNestedPath($data, $key, $value)
189 {
190 $keys = explode('->', $key);
191 $lastKey = array_pop($keys);
192 foreach ($keys as $k) {
193 if (!array_key_exists($k, $data)) {
194 $data->$k = (object) [];
195 }
196 $data = $data->$k;
197 }
198 $data->$lastKey = json_decode(wp_json_encode($value));
199 ;
200 return $data;
201 }
202
203 public static function property_exists_nested($obj, $path = '', $valToCheck = null, $checkNegativeVal = 0)
204 {
205 $path = explode('->', $path);
206 $current = $obj;
207 foreach ($path as $key) {
208 if (is_object($current)) {
209 if (property_exists($current, $key)) {
210 $current = $current->{$key};
211 } else {
212 return false;
213 }
214 } else {
215 return false;
216 }
217 }
218 if (isset($valToCheck)) {
219 if ($checkNegativeVal) {
220 return $current !== $valToCheck;
221 }
222 return $current === $valToCheck;
223 }
224 return true;
225 }
226
227 public static function validateEntryTokenAndUser($entryToken, $entryId)
228 {
229 // check if the user is logged in
230 if (is_user_logged_in()) {
231 $user = wp_get_current_user();
232 if (in_array('administrator', $user->roles) || current_user_can('manage_bitform')) {
233 return true;
234 }
235 $entryModel = new FormEntryModel();
236 $entry = $entryModel->get(
237 'id, user_id, form_id',
238 [
239 'id' => $entryId,
240 'user_id' => $user->ID
241 ]
242 );
243 if (!is_wp_error($entry) && !empty($entry)) {
244 return true;
245 }
246 }
247 // check if the entry token is valid
248 if (isset($entryToken) && $entryToken) {
249 $decryptEntryId = Cryptography::decrypt($entryToken, AUTH_SALT);
250 if ($decryptEntryId === $entryId) {
251 return true;
252 }
253 }
254
255 return false;
256 }
257
258 public static function validateFormEntryEditPermission($formId, $entryId)
259 {
260 if (is_user_logged_in()) {
261 if (current_user_can('manage_bitform') || current_user_can('bitform_entry_edit') || current_user_can('edit_posts')) {
262 return true;
263 }
264 }
265 return false;
266 }
267
268 public static function honeypotEncryptedToken($str)
269 {
270 $token = base64_encode(base64_encode($str));
271 return $token;
272 }
273
274 public static function csrfEecrypted()
275 {
276 $secretKey = get_option('bf_csrf_secret');
277 if (!$secretKey) {
278 $secretKey = 'bf-' . time();
279 update_option('bf_csrf_secret', $secretKey);
280 }
281 $tIdenty = base64_encode(random_bytes(32));
282 $csrf = \base64_encode(\hash_hmac('sha256', $tIdenty, $secretKey, true));
283 return ['csrf' => $csrf, 't_identity' => $tIdenty];
284 }
285
286 public static function csrfDecrypted($identy, $token)
287 {
288 $secretKey = get_option('bf_csrf_secret');
289 return \hash_equals(
290 \base64_encode(\hash_hmac('sha256', $identy, $secretKey, true)),
291 $token
292 );
293 }
294
295 public static function checkIsIntArr($arr)
296 {
297 $filteredArray = array_filter($arr, 'is_numeric');
298 $intArray = array_map('intval', $filteredArray);
299 $result = count($arr) === count($intArray);
300
301 return $result;
302 }
303
304 public static function getTruncatedEncryptToken($str, $length = 20)
305 {
306 $token = hash_hmac('sha256', $str, AUTH_SALT);
307 return substr($token, 0, $length);
308 }
309
310 public static function getEncryptedEntryId($entryId)
311 {
312 if (!isset(self::$encryptEntryIds[$entryId])) {
313 self::$encryptEntryIds[$entryId] = self::getTruncatedEncryptToken($entryId);
314 }
315 return self::$encryptEntryIds[$entryId];
316 }
317 }
318