PluginProbe
ERP: Complete HR, Accounting & CRM Suite Built for WooCommerce / 1.3.13
ERP: Complete HR, Accounting & CRM Suite Built for WooCommerce v1.3.13
1.17.9 1.17.8 1.17.7 1.17.6 1.17.5 1.17.4 1.2.2 1.2.3 1.2.4 1.2.5 1.2.6 1.2.7 1.2.8 1.3.0 1.3.1 1.3.11 1.3.12 1.3.13 1.3.14 1.3.2 1.3.3 1.3.4 1.3.5 1.3.6 1.3.7 All 143 releases
erp / includes / functions.php

functions.php in ERP: Complete HR, Accounting & CRM Suite Built for WooCommerce 1.3.13, at includes/functions.php

2,619 lines 77.3 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 /**
4 * Processes all ERP actions sent via REQUEST by looking for the 'erp-action'
5 * request and running do_action() to call the function
6 *
7 * @return void
8 */
9 function erp_process_actions() {
10 if ( isset( $_REQUEST['erp-action'] ) ) {
11 do_action( 'erp_action_' . $_REQUEST['erp-action'], $_REQUEST );
12 }
13 }
14
15 /**
16 * Return the WP ERP version
17 *
18 * @return string The WP ERP version
19 */
20 function erp_get_version() {
21 return wperp()->version;
22 }
23
24 /**
25 * Maps various caps to built in WordPress caps
26 *
27 *
28 * @param array $caps Capabilities for meta capability
29 * @param string $cap Capability name
30 * @param int $user_id User id
31 * @param mixed $args Arguments
32 */
33 function erp_map_meta_caps( $caps = array(), $cap = '', $user_id = 0, $args = array() ) {
34 return apply_filters( 'erp_map_meta_caps', $caps, $cap, $user_id, $args );
35 }
36
37 /**
38 * Get full list of currency codes.
39 *
40 * @since 1.0.0
41 * @since 1.1.14 Add most of the current circulating currencies
42 *
43 * @return array
44 */
45 function erp_get_currencies() {
46 return apply_filters( 'erp_currencies', [
47 'AFN' => __( 'Afghan Afghani', 'erp' ),
48 'ALL' => __( 'Albanian Lek', 'erp' ),
49 'DZD' => __( 'Algerian Dinar', 'erp' ),
50 'ADP' => __( 'Andorran Peseta', 'erp' ),
51 'AOA' => __( 'Angolan Kwanza', 'erp' ),
52 'ARA' => __( 'Argentine Austral', 'erp' ),
53 'ARS' => __( 'Argentine Peso', 'erp' ),
54 'AMD' => __( 'Armenian Dram', 'erp' ),
55 'AWG' => __( 'Aruban Florin', 'erp' ),
56 'AUD' => __( 'Australian Dollar', 'erp' ),
57 'ATS' => __( 'Austrian Schilling', 'erp' ),
58 'AZN' => __( 'Azerbaijani Manat', 'erp' ),
59 'BSD' => __( 'Bahamian Dollar', 'erp' ),
60 'BHD' => __( 'Bahraini Dinar', 'erp' ),
61 'BDT' => __( 'Bangladeshi Taka', 'erp' ),
62 'BBD' => __( 'Barbadian Dollar', 'erp' ),
63 'BYR' => __( 'Belarusian Ruble', 'erp' ),
64 'BEF' => __( 'Belgian Franc', 'erp' ),
65 'BZD' => __( 'Belize Dollar', 'erp' ),
66 'BMD' => __( 'Bermudan Dollar', 'erp' ),
67 'BTN' => __( 'Bhutanese Ngultrum', 'erp' ),
68 'BOB' => __( 'Bolivian Boliviano', 'erp' ),
69 'BOV' => __( 'Bolivian Mvdol', 'erp' ),
70 'BOP' => __( 'Bolivian Peso', 'erp' ),
71 'BAM' => __( 'Bosnia-Herzegovina Convertible Mark', 'erp' ),
72 'BWP' => __( 'Botswanan Pula', 'erp' ),
73 'BRL' => __( 'Brazilian Real', 'erp' ),
74 'GBP' => __( 'British Pound Sterling', 'erp' ),
75 'BND' => __( 'Brunei Dollar', 'erp' ),
76 'BGN' => __( 'Bulgarian Lev', 'erp' ),
77 'BUK' => __( 'Burmese Kyat', 'erp' ),
78 'BIF' => __( 'Burundian Franc', 'erp' ),
79 'KHR' => __( 'Cambodian Riel', 'erp' ),
80 'CAD' => __( 'Canadian Dollar', 'erp' ),
81 'CVE' => __( 'Cape Verdean Escudo', 'erp' ),
82 'KYD' => __( 'Cayman Islands Dollar', 'erp' ),
83 'XOF' => __( 'CFA Franc BCEAO', 'erp' ),
84 'XAF' => __( 'CFA Franc BEAC', 'erp' ),
85 'XPF' => __( 'CFP Franc', 'erp' ),
86 'CLP' => __( 'Chilean Peso', 'erp' ),
87 'CNY' => __( 'Chinese Yuan', 'erp' ),
88 'COP' => __( 'Colombian Peso', 'erp' ),
89 'KMF' => __( 'Comorian Franc', 'erp' ),
90 'CDF' => __( 'Congolese Franc', 'erp' ),
91 'CRC' => __( 'Costa Rican Colón', 'erp' ),
92 'HRK' => __( 'Croatian Kuna', 'erp' ),
93 'CUP' => __( 'Cuban Peso', 'erp' ),
94 'CYP' => __( 'Cypriot Pound', 'erp' ),
95 'CZK' => __( 'Czech Republic Koruna', 'erp' ),
96 'DKK' => __( 'Danish Krone', 'erp' ),
97 'DJF' => __( 'Djiboutian Franc', 'erp' ),
98 'DOP' => __( 'Dominican Peso', 'erp' ),
99 'NLG' => __( 'Dutch Guilder', 'erp' ),
100 'XCD' => __( 'East Caribbean Dollar', 'erp' ),
101 'ECS' => __( 'Ecuadorian Sucre', 'erp' ),
102 'EGP' => __( 'Egyptian Pound', 'erp' ),
103 'GQE' => __( 'Equatorial Guinean Ekwele', 'erp' ),
104 'ERN' => __( 'Eritrean Nakfa', 'erp' ),
105 'EEK' => __( 'Estonian Kroon', 'erp' ),
106 'ETB' => __( 'Ethiopian Birr', 'erp' ),
107 'EUR' => __( 'Euro', 'erp' ),
108 'FKP' => __( 'Falkland Islands Pound', 'erp' ),
109 'FJD' => __( 'Fijian Dollar', 'erp' ),
110 'FIM' => __( 'Finnish Markka', 'erp' ),
111 'FRF' => __( 'French Franc', 'erp' ),
112 'GMD' => __( 'Gambian Dalasi', 'erp' ),
113 'GEL' => __( 'Georgian Lari', 'erp' ),
114 'DEM' => __( 'German Mark', 'erp' ),
115 'GHS' => __( 'Ghanaian Cedi', 'erp' ),
116 'GIP' => __( 'Gibraltar Pound', 'erp' ),
117 'GRD' => __( 'Greek Drachma', 'erp' ),
118 'GTQ' => __( 'Guatemalan Quetzal', 'erp' ),
119 'GWP' => __( 'Guinea-Bissau Peso', 'erp' ),
120 'GNF' => __( 'Guinean Franc', 'erp' ),
121 'GYD' => __( 'Guyanaese Dollar', 'erp' ),
122 'HTG' => __( 'Haitian Gourde', 'erp' ),
123 'HNL' => __( 'Honduran Lempira', 'erp' ),
124 'HKD' => __( 'Hong Kong Dollar', 'erp' ),
125 'HUF' => __( 'Hungarian Forint', 'erp' ),
126 'ISK' => __( 'Icelandic Króna', 'erp' ),
127 'INR' => __( 'Indian Rupee', 'erp' ),
128 'IDR' => __( 'Indonesian Rupiah', 'erp' ),
129 'IRR' => __( 'Iranian Rial', 'erp' ),
130 'IQD' => __( 'Iraqi Dinar', 'erp' ),
131 'IEP' => __( 'Irish Pound', 'erp' ),
132 'ILS' => __( 'Israeli New Sheqel', 'erp' ),
133 'ITL' => __( 'Italian Lira', 'erp' ),
134 'JMD' => __( 'Jamaican Dollar', 'erp' ),
135 'JPY' => __( 'Japanese Yen', 'erp' ),
136 'JOD' => __( 'Jordanian Dinar', 'erp' ),
137 'KZT' => __( 'Kazakhstani Tenge', 'erp' ),
138 'KES' => __( 'Kenyan Shilling', 'erp' ),
139 'KWD' => __( 'Kuwaiti Dinar', 'erp' ),
140 'KGS' => __( 'Kyrgystani Som', 'erp' ),
141 'LAK' => __( 'Laotian Kip', 'erp' ),
142 'LVL' => __( 'Latvian Lats', 'erp' ),
143 'LBP' => __( 'Lebanese Pound', 'erp' ),
144 'LSL' => __( 'Lesotho Loti', 'erp' ),
145 'LRD' => __( 'Liberian Dollar', 'erp' ),
146 'LYD' => __( 'Libyan Dinar', 'erp' ),
147 'LTL' => __( 'Lithuanian Litas', 'erp' ),
148 'LTT' => __( 'Lithuanian Talonas', 'erp' ),
149 'LUF' => __( 'Luxembourgian Franc', 'erp' ),
150 'MOP' => __( 'Macanese Pataca', 'erp' ),
151 'MKD' => __( 'Macedonian Denar', 'erp' ),
152 'MGA' => __( 'Malagasy Ariary', 'erp' ),
153 'MWK' => __( 'Malawian Kwacha', 'erp' ),
154 'MYR' => __( 'Malaysian Ringgit', 'erp' ),
155 'MVR' => __( 'Maldivian Rufiyaa', 'erp' ),
156 'MLF' => __( 'Malian Franc', 'erp' ),
157 'MTL' => __( 'Maltese Lira', 'erp' ),
158 'MRO' => __( 'Mauritanian Ouguiya', 'erp' ),
159 'MUR' => __( 'Mauritian Rupee', 'erp' ),
160 'MXN' => __( 'Mexican Peso', 'erp' ),
161 'MDL' => __( 'Moldovan Leu', 'erp' ),
162 'MCF' => __( 'Monegasque Franc', 'erp' ),
163 'MNT' => __( 'Mongolian Tugrik', 'erp' ),
164 'MAD' => __( 'Moroccan Dirham', 'erp' ),
165 'MZN' => __( 'Mozambican Metical', 'erp' ),
166 'MMK' => __( 'Myanmar Kyat', 'erp' ),
167 'NAD' => __( 'Namibian Dollar', 'erp' ),
168 'NPR' => __( 'Nepalese Rupee', 'erp' ),
169 'ANG' => __( 'Netherlands Antillean Guilder', 'erp' ),
170 'TWD' => __( 'New Taiwan Dollar', 'erp' ),
171 'NZD' => __( 'New Zealand Dollar', 'erp' ),
172 'NIO' => __( 'Nicaraguan Córdoba', 'erp' ),
173 'NGN' => __( 'Nigerian Naira', 'erp' ),
174 'KPW' => __( 'North Korean Won', 'erp' ),
175 'NOK' => __( 'Norwegian Krone', 'erp' ),
176 'OMR' => __( 'Omani Rial', 'erp' ),
177 'PKR' => __( 'Pakistani Rupee', 'erp' ),
178 'PAB' => __( 'Panamanian Balboa', 'erp' ),
179 'PGK' => __( 'Papua New Guinean Kina', 'erp' ),
180 'PYG' => __( 'Paraguayan Guarani', 'erp' ),
181 'PEI' => __( 'Peruvian Inti', 'erp' ),
182 'PHP' => __( 'Philippine Peso', 'erp' ),
183 'PLN' => __( 'Polish Zloty', 'erp' ),
184 'PTE' => __( 'Portuguese Escudo', 'erp' ),
185 'QAR' => __( 'Qatari Rial', 'erp' ),
186 'RHD' => __( 'Rhodesian Dollar', 'erp' ),
187 'RON' => __( 'Romanian Leu', 'erp' ),
188 'RUB' => __( 'Russian Ruble', 'erp' ),
189 'RWF' => __( 'Rwandan Franc', 'erp' ),
190 'SVC' => __( 'Salvadoran Colón', 'erp' ),
191 'WST' => __( 'Samoan Tala', 'erp' ),
192 'STD' => __( 'São Tomé & Príncipe Dobra', 'erp' ),
193 'SAR' => __( 'Saudi Riyal', 'erp' ),
194 'RSD' => __( 'Serbian Dinar', 'erp' ),
195 'SCR' => __( 'Seychellois Rupee', 'erp' ),
196 'SLL' => __( 'Sierra Leonean Leone', 'erp' ),
197 'SGD' => __( 'Singapore Dollar', 'erp' ),
198 'SKK' => __( 'Slovak Koruna', 'erp' ),
199 'SIT' => __( 'Slovenian Tolar', 'erp' ),
200 'SBD' => __( 'Solomon Islands Dollar', 'erp' ),
201 'SOS' => __( 'Somali Shilling', 'erp' ),
202 'ZAR' => __( 'South African Rand', 'erp' ),
203 'KRW' => __( 'South Korean Won', 'erp' ),
204 'SSP' => __( 'South Sudanese Pound', 'erp' ),
205 'ESP' => __( 'Spanish Peseta', 'erp' ),
206 'LKR' => __( 'Sri Lankan Rupee', 'erp' ),
207 'SHP' => __( 'St. Helena Pound', 'erp' ),
208 'SDG' => __( 'Sudanese Pound', 'erp' ),
209 'SRD' => __( 'Surinamese Dollar', 'erp' ),
210 'SZL' => __( 'Swazi Lilangeni', 'erp' ),
211 'SEK' => __( 'Swedish Krona', 'erp' ),
212 'CHF' => __( 'Swiss Franc', 'erp' ),
213 'SYP' => __( 'Syrian Pound', 'erp' ),
214 'TJS' => __( 'Tajikistani Somoni', 'erp' ),
215 'TZS' => __( 'Tanzanian Shilling', 'erp' ),
216 'THB' => __( 'Thai Baht', 'erp' ),
217 'TPE' => __( 'Timorese Escudo', 'erp' ),
218 'TOP' => __( 'Tongan Paʻanga', 'erp' ),
219 'TTD' => __( 'Trinidad & Tobago Dollar', 'erp' ),
220 'TND' => __( 'Tunisian Dinar', 'erp' ),
221 'TRY' => __( 'Turkish Lira', 'erp' ),
222 'TMT' => __( 'Turkmenistani Manat', 'erp' ),
223 'UGX' => __( 'Ugandan Shilling', 'erp' ),
224 'UAH' => __( 'Ukrainian Hryvnia', 'erp' ),
225 'AED' => __( 'United Arab Emirates Dirham', 'erp' ),
226 'UYU' => __( 'Uruguayan Peso', 'erp' ),
227 'USD' => __( 'US Dollar', 'erp' ),
228 'UZS' => __( 'Uzbekistan Som', 'erp' ),
229 'VUV' => __( 'Vanuatu Vatu', 'erp' ),
230 'VEF' => __( 'Venezuelan Bolívar', 'erp' ),
231 'VND' => __( 'Vietnamese Dong', 'erp' ),
232 'YER' => __( 'Yemeni Rial', 'erp' ),
233 'ZMW' => __( 'Zambian Kwacha', 'erp' ),
234 'ZWL' => __( 'Zimbabwean Dollar', 'erp' ),
235 ] );
236 }
237
238 /**
239 * Get full list of currency ISO with symbol label.
240 *
241 * @return array
242 */
243 function erp_get_currency_list_with_symbol() {
244 $currencies = erp_get_currencies();
245 $currency_symbols = erp_get_currency_symbol();
246 $currency_list = [];
247
248 foreach ( $currencies as $iso => $currency ) {
249 $symbol = isset( $currency_symbols[ $iso ] ) ? $currency_symbols[ $iso ] : $iso;
250
251 $currency_list[ $iso ] = sprintf( '%1$s (%2$s)', $currency, $symbol );
252 }
253
254 return $currency_list;
255 }
256
257 /**
258 * [erp_get_currencies_dropdown description]
259 *
260 * @param string [description]
261 *
262 * @return string
263 */
264 function erp_get_currencies_dropdown( $selected = '' ) {
265 $options = '';
266 $currencies = erp_get_currencies();
267
268 foreach ( $currencies as $key => $value ) {
269 $select = ( $key == $selected ) ? ' selected="selected"' : '';
270 $options .= sprintf( "<option value='%s'%s>%s</option>\n", esc_attr( $key ), $select, $value );
271 }
272
273 return $options;
274 }
275
276 /**
277 * Get global currency
278 *
279 * @since 1.1.6
280 *
281 * @return string
282 */
283 function erp_get_currency() {
284 return erp_get_option( 'erp_currency', 'erp_settings_general', 'USD' );
285 }
286
287
288 /**
289 * Get Currency symbol.
290 *
291 * @since 1.0.0
292 * @since 1.1.14 Add most of the current circulating currencies.
293 * If no $currency provided, full symbol list will be returned.
294 * @since 1.2.1 Fix symbol for South African rand
295 *
296 * @param string $currency
297 *
298 * @return string|array
299 */
300 function erp_get_currency_symbol( $currency = '' ) {
301
302 /**
303 * Source: https://en.wikipedia.org/wiki/List_of_circulating_currencies
304 *
305 * In wikipedia some of the symbols are in SVG image like 'AMD'
306 * or not supported by UTF-8 like 'GEL'. For those symbols currency codes
307 * are used as symbols
308 */
309
310 $currency_symbols = [
311 'AED' => 'د.إ',
312 'AFN' => '؋',
313 'ALL' => 'L',
314 'AMD' => 'AMD',
315 'ANG' => 'ƒ',
316 'AOA' => 'Kz',
317 'ARS' => '$',
318 'AUD' => '$',
319 'AWG' => 'ƒ',
320 'AZN' => '',
321 'BAM' => 'KM',
322 'BBD' => '$',
323 'BDT' => '',
324 'BGN' => 'лв',
325 'BHD' => '.د.ب',
326 'BIF' => 'Fr',
327 'BMD' => '$',
328 'BND' => '$',
329 'BOB' => 'Bs.',
330 'BRL' => 'R$',
331 'BSD' => '$',
332 'BTN' => 'Nu.',
333 'BWP' => 'P',
334 'BYN' => 'Br',
335 'BYR' => 'Br',
336 'BZD' => '$',
337 'CAD' => '$',
338 'CDF' => 'Fr',
339 'CHF' => 'Fr',
340 'CLP' => '$',
341 'CNY' => '¥',
342 'COP' => '$',
343 'CRC' => '',
344 'CUC' => '$',
345 'CUP' => '$',
346 'CVE' => '$',
347 'CZK' => '',
348 'DJF' => 'Fr',
349 'DKK' => 'kr',
350 'DOP' => '$',
351 'DZD' => 'د.ج',
352 'EGP' => '£',
353 'ERN' => 'Nfk',
354 'ETB' => 'Br',
355 'EUR' => '',
356 'FJD' => '$',
357 'FKP' => '£',
358 'GBP' => '£',
359 'GEL' => 'GEL',
360 'GGP' => '£',
361 'GHS' => '',
362 'GIP' => '£',
363 'GMD' => 'D',
364 'GNF' => 'Fr',
365 'GTQ' => 'Q',
366 'GYD' => '$',
367 'HKD' => '$',
368 'HNL' => 'L',
369 'HRK' => 'kn',
370 'HTG' => 'G',
371 'HUF' => 'Ft',
372 'IDR' => 'Rp',
373 'ILS' => '',
374 'IMP' => '£',
375 'INR' => '',
376 'IQD' => 'ع.د',
377 'IRR' => '',
378 'ISK' => 'kr',
379 'JEP' => '£',
380 'JMD' => '$',
381 'JOD' => 'د.ا',
382 'JPY' => '¥',
383 'KES' => 'Sh',
384 'KGS' => 'с',
385 'KHR' => '',
386 'KMF' => 'Fr',
387 'KPW' => '',
388 'KRW' => '',
389 'KWD' => 'د.ك',
390 'KYD' => '$',
391 'KZT' => 'KZT',
392 'LAK' => '',
393 'LBP' => 'ل.ل',
394 'LKR' => 'Rs',
395 'LRD' => '$',
396 'LSL' => 'L',
397 'LYD' => 'ل.د',
398 'MAD' => 'د.�
399 .',
400 'MDL' => 'L',
401 'MGA' => 'Ar',
402 'MKD' => 'ден',
403 'MMK' => 'Ks',
404 'MNT' => '',
405 'MOP' => 'P',
406 'MRO' => 'UM',
407 'MUR' => '',
408 'MVR' => 'MVR',
409 'MWK' => 'MK',
410 'MXN' => '$',
411 'MYR' => 'RM',
412 'MZN' => 'MT',
413 'NAD' => '$',
414 'NGN' => '',
415 'NIO' => 'C$',
416 'NOK' => 'kr',
417 'NPR' => '',
418 'NZD' => '$',
419 'OMR' => 'ر.ع.',
420 'PAB' => 'B/.',
421 'PEN' => 'S/.',
422 'PGK' => 'K',
423 'PHP' => '',
424 'PKR' => '',
425 'PLN' => '',
426 'PRB' => 'р.',
427 'PYG' => '',
428 'QAR' => 'ر.ق',
429 'RON' => 'lei',
430 'RSD' => 'дин',
431 'RUB' => '',
432 'RWF' => 'Fr',
433 'SAR' => 'ر.س',
434 'SBD' => '$',
435 'SCR' => '',
436 'SDG' => 'ج.س.',
437 'SEK' => 'kr',
438 'SGD' => '$',
439 'SHP' => '£',
440 'SLL' => 'Le',
441 'SOS' => 'Sh',
442 'SRD' => '$',
443 'SSP' => '£',
444 'STD' => 'Db',
445 'SYP' => '£',
446 'SZL' => 'L',
447 'THB' => '฿',
448 'TJS' => '�
449 М',
450 'TMT' => 'm',
451 'TND' => 'د.ت',
452 'TOP' => 'T$',
453 'TRY' => 'TRY',
454 'TTD' => '$',
455 'TVD' => '$',
456 'TWD' => '$',
457 'TZS' => 'Sh',
458 'UAH' => '',
459 'UGX' => 'Sh',
460 'USD' => '$',
461 'UYU' => '$',
462 'UZS' => 'UZS',
463 'VEF' => 'Bs',
464 'VND' => '',
465 'VUV' => 'Vt',
466 'WST' => 'T',
467 'XAF' => 'Fr',
468 'XCD' => '$',
469 'XOF' => 'Fr',
470 'XPF' => 'Fr',
471 'YER' => '',
472 'ZAR' => 'R',
473 'ZMW' => 'ZK',
474 'ZWL' => '$',
475 ];
476
477 if ( ! empty( $currency ) ) {
478 $symbol = ! empty( $currency_symbols[ $currency ] ) ? $currency_symbols[ $currency ] : $currency;
479
480 return apply_filters( 'erp_currency_symbol', $symbol, $currency );
481 } else {
482 return apply_filters( 'erp_currency_symbol_list', $currency_symbols );
483 }
484
485 }
486
487 /**
488 * Get default country
489 *
490 * @since 1.4.0
491 *
492 * @return string
493 */
494 function erp_get_country() {
495 return erp_get_option( 'erp_country', 'erp_settings_general', -1 );
496 }
497
498 /**
499 * Embed a JS template page with its ID
500 *
501 * @param string the file path of the file
502 * @param string the script id
503 *
504 * @return void
505 */
506 function erp_get_js_template( $file_path, $id ) {
507 if ( file_exists( $file_path ) ) {
508 echo '<script type="text/html" id="tmpl-' . $id . '">' . "\n";
509 include_once apply_filters( 'erp_crm_js_template_file_path', $file_path, $id );
510 echo "\n" . '</script>' . "\n";
511 }
512 }
513
514 /**
515 * Embed a Vue Component template page with its ID
516 *
517 * @param string the file path of the file
518 * @param string the script id
519 *
520 * @return void
521 */
522 function erp_get_vue_component_template( $file_path, $id ) {
523 if ( file_exists( $file_path ) ) {
524 echo '<script type="text/x-template" id="' . $id . '">' . "\n";
525 include_once $file_path;
526 echo "\n" . '</script>' . "\n";
527 }
528 }
529
530
531 if ( ! function_exists( 'strip_tags_deep' ) ) {
532
533 /**
534 * Strip tags from string or array
535 *
536 * @param mixed array or string to strip
537 *
538 * @return mixed stripped value
539 */
540 function strip_tags_deep( $value ) {
541 if ( is_array( $value ) ) {
542 foreach ( $value as $key => $val ) {
543 $value[ $key ] = strip_tags_deep( $val );
544 }
545 } elseif ( is_string( $value ) ) {
546 $value = strip_tags( $value );
547 }
548
549 return $value;
550 }
551 }
552
553 if ( ! function_exists( 'trim_deep' ) ) {
554
555 /**
556 * Trim from string or array
557 *
558 * @param mixed array or string to trim
559 *
560 * @return mixed timmed value
561 */
562 function trim_deep( $value ) {
563 if ( is_array( $value ) ) {
564 foreach ( $value as $key => $val ) {
565 $value[ $key ] = trim_deep( $val );
566 }
567 } elseif ( is_string( $value ) ) {
568 $value = trim( $value );
569 }
570
571 return $value;
572 }
573 }
574
575 /**
576 * Helper function to print a label and value with a separator
577 *
578 * @since 1.0.0
579 * @since 1.1.14 Add $type param
580 * @since 1.1.16 Apply if-else condition to set `$value`
581 *
582 * @param string $label the label
583 * @param string $value the value to print
584 * @param string $sep separator
585 * @param string $type field type
586 *
587 * @return void
588 */
589 function erp_print_key_value( $label, $value, $sep = ' : ', $type = 'text' ) {
590 if ( empty( $value ) ) {
591 $value = '&mdash;';
592
593 } else {
594 switch ( $type ) {
595 case 'email':
596 case 'url':
597 case 'phone':
598 $value = erp_get_clickable( $type, $value );
599 break;
600 }
601 }
602
603 printf( '<label>%s</label> <span class="sep">%s</span> <span class="value">%s</span>', $label, $sep, $value );
604 }
605
606 /**
607 * Get a clickable phone or email address link
608 *
609 * @param string type. e.g: email|phone|url
610 * @param string the value
611 *
612 * @return string the link
613 */
614 function erp_get_clickable( $type = 'email', $value = '' ) {
615 if ( 'email' == $type ) {
616 return sprintf( '<a href="mailto:%1$s">%1$s</a>', $value );
617 } elseif ( 'url' == $type ) {
618 return sprintf( '<a target="_blank" href="%1$s">%1$s</a>', $value );
619 } elseif ( 'phone' == $type ) {
620 return sprintf( '<a href="tel:%1$s">%1$s</a>', $value );
621 }
622 }
623
624 /**
625 * Get a formatted date from WordPress format
626 *
627 * @param string $date the date
628 *
629 * @return string formatted date
630 */
631 function erp_format_date( $date, $format = false ) {
632 if ( ! $format ) {
633 $format = erp_get_option( 'date_format', 'erp_settings_general', 'd-m-Y' );
634 }
635
636 $time = strtotime( $date );
637
638 return date_i18n( $format, $time );
639 }
640
641 /**
642 * Extract dates between two date range
643 *
644 * @param string $start_date example: 2016-12-16 00:00:00
645 * @param string $end_date example: 2016-12-16 23:59:59
646 *
647 * @return array
648 */
649 function erp_extract_dates( $start_date, $end_date ) {
650 // if start date has no time set, then add 00:00:00 or 12:00 AM
651 if ( ! preg_match( '/\d{2}:\d{2}:\d{2}$/', $start_date ) ) {
652 $start_date = $start_date . ' 00:00:00';
653 }
654
655 // if end date has no time set, then add 23:59:59 or 11:59 PM
656 if ( ! preg_match( '/\d{2}:\d{2}:\d{2}$/', $end_date ) ) {
657 $end_date = $end_date . ' 23:59:59';
658 }
659
660 $start_date = new DateTime( $start_date );
661 $end_date = new DateTime( $end_date );
662 $diff = $start_date->diff( $end_date );
663
664 // we got a negative date
665 if ( $diff->invert ) {
666 return new WP_Error( 'invalid-date', __( 'Invalid date provided', 'erp' ) );
667 }
668
669 $interval = DateInterval::createFromDateString( '1 day' );
670 $period = new DatePeriod( $start_date, $interval, $end_date );
671
672 // prepare the periods
673 $dates = array();
674 foreach ( $period as $dt ) {
675 $dates[] = $dt->format( 'Y-m-d' );
676 }
677
678 return $dates;
679 }
680
681 /**
682 * Convert an two dimentational array to one dimentional array object
683 *
684 * @param array $array array of arrays
685 *
686 * @return array
687 */
688 function erp_array_to_object( $array = [] ) {
689 $new_array = [];
690
691 if ( $array ) {
692 foreach ( $array as $key => $value ) {
693 $new_array[] = (object) $value;
694 }
695 }
696
697 return $new_array;
698 }
699
700 /**
701 * Check date in range or not
702 *
703 * @param date $start_date
704 * @param date $end_date
705 * @param date $date_from_user
706 *
707 * @return boolen
708 */
709 function erp_check_date_in_range( $start_date, $end_date, $date_from_user ) {
710 // Convert to timestamp
711 $start_ts = strtotime( $start_date );
712 $end_ts = strtotime( $end_date );
713 $user_ts = strtotime( $date_from_user );
714
715 // Check that user date is between start & end
716 if ( ( $user_ts >= $start_ts ) && ( $user_ts <= $end_ts ) ) {
717 return true;
718 }
719
720 return false;
721 }
722
723 /**
724 * Check date range any point in range or not
725 *
726 * @param date $start_date
727 * @param date $end_date
728 * @param date $user_date_start
729 * @param date $user_date_end
730 *
731 * @return boolen
732 */
733 function erp_check_date_range_in_range_exist( $start_date, $end_date, $user_date_start, $user_date_end ) {
734
735 if ( erp_check_date_in_range( $start_date, $end_date, $user_date_start ) ) {
736 return true;
737 }
738
739 if ( erp_check_date_in_range( $start_date, $end_date, $user_date_end ) ) {
740 return true;
741 }
742
743 return false;
744 }
745
746 /**
747 * Get durataion between two date
748 *
749 * @param date $start_date
750 * @param date $end_date
751 *
752 * @return integer
753 */
754 function erp_date_duration( $start_date, $end_date ) {
755 $diff = abs( strtotime( $start_date ) - strtotime( $end_date ) );
756 $hours_diff = ceil( $diff / ( 60 * 60 ) );
757
758 return ceil( $hours_diff / 24 );
759 }
760
761 /**
762 * Performance rating elemet
763 *
764 * @since 0.1
765 *
766 * @param string $selected
767 *
768 * @return array
769 */
770 function erp_performance_rating( $selected = '' ) {
771
772 $rating = apply_filters( 'erp_performance_rating', array(
773 '1' => __( 'Very Bad', 'erp' ),
774 '2' => __( 'Poor', 'erp' ),
775 '3' => __( 'Average', 'erp' ),
776 '4' => __( 'Good', 'erp' ),
777 '5' => __( 'Excellent', 'erp' )
778 ) );
779
780 if ( $selected ) {
781 return isset( $rating[ $selected ] ) ? $rating[ $selected ] : '';
782 }
783
784 return $rating;
785 }
786
787 /**
788 * Get erp option from settings framework
789 *
790 * @param sting $option_name name of the option
791 * @param string $section name of the section. if it's a separate option, don't provide any
792 * @param string $default default option
793 *
794 * @return string
795 */
796 function erp_get_option( $option_name, $section = false, $default = '' ) {
797
798 if ( $section ) {
799 $option = get_option( $section );
800
801 if ( isset( $option[ $option_name ] ) ) {
802 return $option[ $option_name ];
803 } else {
804 return $default;
805 }
806 } else {
807 return get_option( $option_name, $default );
808 }
809 }
810
811 /**
812 * Get erp logo
813 *
814 * @return string url of the logo
815 */
816 function erp_get_site_logo() {
817 $logo = (int) erp_get_option( 'logo', 'erp_settings_design' );
818
819 if ( $logo ) {
820 $logo_url = wp_get_attachment_url( $logo );
821
822 return $logo_url;
823 }
824 }
825
826 /**
827 * Get month array
828 *
829 * @param string $title
830 *
831 * @since 0.1
832 *
833 * @return array
834 */
835 function erp_months_dropdown( $title = false ) {
836
837 $months = [];
838
839 if ( $title ) {
840 $months['-1'] = $title;
841 }
842
843 for ( $m = 1; $m <= 12; $m ++ ) {
844 $months[ $m ] = date( 'F', mktime( 0, 0, 0, $m, 1 ) );
845 }
846
847 return $months;
848
849 }
850
851 /**
852 * Get Company financial start date
853 *
854 * @since 0.1
855 * @since 1.2.0 Using `erp_get_financial_year_dates` function
856 *
857 * @return string date
858 */
859 function erp_financial_start_date() {
860 $financial_year_dates = erp_get_financial_year_dates();
861
862 return $financial_year_dates['start'];
863 }
864
865 /**
866 * Get Company financial end date
867 *
868 * @since 0.1
869 * @since 1.2.0 Using `erp_get_financial_year_dates` function
870 *
871 * @return string date
872 */
873 function erp_financial_end_date() {
874 $financial_year_dates = erp_get_financial_year_dates();
875
876 return $financial_year_dates['end'];
877 }
878
879 /**
880 * Get all modules inserted in log table
881 *
882 * @since 0.1
883 *
884 * @return array
885 */
886 function erp_get_audit_log_modules() {
887 return \WeDevs\ERP\Admin\Models\Audit_Log::select( 'component' )->distinct()->get()->toArray();
888 }
889
890 /**
891 * Get all modules inserted in log table
892 *
893 * @since 0.1
894 *
895 * @return array
896 */
897 function erp_get_audit_log_sub_component() {
898 return \WeDevs\ERP\Admin\Models\Audit_Log::select( 'sub_component' )->distinct()->get()->toArray();
899 }
900
901 /**
902 * Erp Logging functions
903 *
904 * @since 0.1
905 *
906 * @return instance
907 */
908 function erp_log() {
909 return \WeDevs\ERP\Log::instance();
910 }
911
912 /**
913 * A file based logging function for debugging
914 *
915 * @since 0.1
916 *
917 * @param string $message
918 * @param string $type
919 *
920 * @return void
921 */
922 function erp_file_log( $message, $type = '' ) {
923 if ( ! empty( $type ) ) {
924 $message = sprintf( "[%s][%s] %s\n", date( 'd.m.Y h:i:s' ), $type, $message );
925 } else {
926 $message = sprintf( "[%s] %s\n", date( 'd.m.Y h:i:s' ), $message );
927 }
928
929 error_log( $message, 3, dirname( WPERP_FILE ) . '/debug.log' );
930 }
931
932 /**
933 * Get people types from various components
934 *
935 * @return array
936 */
937 function erp_get_people_types() {
938 return apply_filters( 'erp_people_types', [] );
939 }
940
941 /**
942 * Get Country name by country code
943 *
944 * @since 1.0
945 *
946 * @param string $code
947 *
948 * @return string
949 */
950 function erp_get_country_name( $country ) {
951
952 $load_cuntries_states = \WeDevs\ERP\Countries::instance();
953 $countries = $load_cuntries_states->countries;
954
955 // Handle full country name
956 if ( '-1' != $country ) {
957 $full_country = ( isset( $countries[ $country ] ) ) ? $countries[ $country ] : $country;
958 } else {
959 $full_country = '';
960 }
961
962 return $full_country;
963 }
964
965 /**
966 * Get State name by country and state code
967 *
968 * @since 1.0
969 *
970 * @param string $country
971 * @param string $state
972 *
973 * @return string
974 */
975 function erp_get_state_name( $country, $state ) {
976 $load_cuntries_states = \WeDevs\ERP\Countries::instance();
977 $states = $load_cuntries_states->states;
978
979 // Handle full state name
980 $full_state = ( $country && $state && isset( $states[ $country ][ $state ] ) ) ? $states[ $country ][ $state ] : $state;
981
982 return $full_state;
983 }
984
985 /**
986 * Cron Intervel
987 *
988 * @since 1.0
989 *
990 * @param array $schedules
991 *
992 * @return array
993 */
994 function erp_cron_intervals( $schedules ) {
995
996 $schedules['per_minute'] = array(
997 'interval' => MINUTE_IN_SECONDS,
998 'display' => __( 'Every Minute', 'erp' )
999 );
1000
1001 $schedules['two_min'] = array(
1002 'interval' => MINUTE_IN_SECONDS * 2,
1003 'display' => __( 'Every 2 Minutes', 'erp' )
1004 );
1005
1006 $schedules['five_min'] = array(
1007 'interval' => MINUTE_IN_SECONDS * 5,
1008 'display' => __( 'Every 5 Minutes', 'erp' )
1009 );
1010
1011 $schedules['ten_min'] = array(
1012 'interval' => MINUTE_IN_SECONDS * 10,
1013 'display' => __( 'Every 10 Minutes', 'erp' )
1014 );
1015
1016 $schedules['fifteen_min'] = array(
1017 'interval' => MINUTE_IN_SECONDS * 15,
1018 'display' => __( 'Every 15 Minutes', 'erp' )
1019 );
1020
1021 $schedules['thirty_min'] = array(
1022 'interval' => MINUTE_IN_SECONDS * 30,
1023 'display' => __( 'Every 30 Minutes', 'erp' )
1024 );
1025
1026 $schedules['weekly'] = array(
1027 'interval' => DAY_IN_SECONDS * 7,
1028 'display' => __( 'Once Weekly', 'erp' )
1029 );
1030
1031 return (array) $schedules;
1032 }
1033
1034 /**
1035 * Show user own media attachment
1036 *
1037 * @since 1.0
1038 *
1039 * @param string $query
1040 *
1041 * @return string
1042 */
1043 function erp_show_users_own_attachments( $query ) {
1044 if ( ! is_user_logged_in() ) {
1045 return $query;
1046 }
1047
1048 $id = get_current_user_id();
1049
1050 if ( ! current_user_can( 'manage_options' ) ) {
1051 if ( current_user_can( 'erp_hr_manager' )
1052 || current_user_can( 'employee' )
1053 || current_user_can( 'erp_crm_manager' )
1054 || current_user_can( 'erp_crm_agent' )
1055 ) {
1056 $query['author'] = $id;
1057 }
1058 }
1059
1060 return $query;
1061 }
1062
1063 /**
1064 * Get all registered addons for licensing
1065 *
1066 * @since 1.0
1067 *
1068 * @return array
1069 */
1070 function erp_addon_licenses() {
1071 $licenses = [];
1072
1073 return apply_filters( 'erp_settings_licenses', $licenses );
1074 }
1075
1076 /**
1077 * Show a readable message about the license status
1078 *
1079 * @since 1.0
1080 *
1081 * @param array $addon
1082 *
1083 * @return string
1084 */
1085 function erp_get_license_status( $addon ) {
1086 if ( ! is_object( $addon['status'] ) ) {
1087 return false;
1088 }
1089
1090 $messages = [];
1091 $html = '';
1092 $license = $addon['status'];
1093 $status_class = 'has-error';
1094
1095 if ( false === $license->success ) {
1096
1097 switch ( $license->error ) {
1098
1099 case 'expired' :
1100
1101 $messages[] = sprintf(
1102 __( 'Your license key expired on %s. Please <a href="%s" target="_blank" title="Renew your license key">renew your license key</a>.', 'erp' ),
1103 date_i18n( get_option( 'date_format' ), strtotime( $license->expires, current_time( 'timestamp' ) ) ),
1104 'https://wperp.com/checkout/?edd_license_key=' . $addon['license'] . '&utm_campaign=admin&utm_source=licenses&utm_medium=expired'
1105 );
1106 break;
1107
1108 case 'missing' :
1109
1110 $messages[] = sprintf(
1111 __( 'Invalid license. Please <a href="%s" target="_blank" title="Visit account page">visit your account page</a> and verify it.', 'erp' ),
1112 'https://wperp.com/my-account?utm_campaign=admin&utm_source=licenses&utm_medium=missing'
1113 );
1114 break;
1115
1116 case 'invalid' :
1117 case 'site_inactive' :
1118
1119 $messages[] = sprintf(
1120 __( 'Your %s is not active for this URL. Please <a href="%s" target="_blank" title="Visit account page">visit your account page</a> to manage your license key URLs.', 'erp' ),
1121 $addon['name'],
1122 'https://wperp.com/my-account?utm_campaign=admin&utm_source=licenses&utm_medium=invalid'
1123 );
1124 break;
1125
1126 case 'item_name_mismatch' :
1127
1128 $messages[] = sprintf( __( 'This is not a %s.', 'erp' ), $addon['name'] );
1129 break;
1130
1131 case 'no_activations_left':
1132 $messages[] = sprintf( __( 'Your license key has reached its activation limit. <a href="%s">View possible upgrades</a> now.', 'erp' ), 'https://wperp.com/my-account/' );
1133 break;
1134
1135 }
1136 } else {
1137
1138 switch ( $license->license ) {
1139 case 'expired' :
1140
1141 $messages[] = sprintf(
1142 __( 'Your license key expired on %s. Please <a href="%s" target="_blank" title="Renew your license key">renew your license key</a>.', 'erp' ),
1143 date_i18n( get_option( 'date_format' ), strtotime( $license->expires, current_time( 'timestamp' ) ) ),
1144 'https://wperp.com/checkout/?edd_license_key=' . $addon['license'] . '&utm_campaign=admin&utm_source=licenses&utm_medium=expired'
1145 );
1146 break;
1147
1148 case 'valid':
1149 $status_class = 'no-error';
1150 $now = current_time( 'timestamp' );
1151 $expiration = strtotime( $license->expires, current_time( 'timestamp' ) );
1152
1153 if ( 'lifetime' === $license->expires ) {
1154
1155 $messages[] = __( 'License key never expires.', 'erp' );
1156
1157 } elseif ( $expiration > $now && $expiration - $now < ( DAY_IN_SECONDS * 30 ) ) {
1158
1159 $messages[] = sprintf(
1160 __( 'Your license key expires soon! It expires on %s. <a href="%s" target="_blank" title="Renew license">Renew your license key</a>.', 'erp' ),
1161 date_i18n( get_option( 'date_format' ), strtotime( $license->expires, current_time( 'timestamp' ) ) ),
1162 'https://wperp.com/checkout/?edd_license_key=' . $value . '&utm_campaign=admin&utm_source=licenses&utm_medium=renew'
1163 );
1164
1165 } else {
1166
1167 $messages[] = sprintf(
1168 __( 'Your license key expires on %s.', 'erp' ),
1169 date_i18n( get_option( 'date_format' ), strtotime( $license->expires, current_time( 'timestamp' ) ) )
1170 );
1171
1172 }
1173 break;
1174 }
1175
1176 }
1177
1178 if ( ! empty( $messages ) ) {
1179 foreach ( $messages as $message ) {
1180
1181 $html .= '<div class="erp-license-status ' . $status_class . '">';
1182 $html .= '<p class="help">' . $message . '</p>';
1183 $html .= '</div>';
1184
1185 }
1186 }
1187
1188 return $html;
1189 }
1190
1191 /**
1192 * Get all fields for import/export operation.
1193 *
1194 * @return array
1195 */
1196 function erp_get_import_export_fields() {
1197 $erp_fields = [
1198 'contact' => [
1199 'required_fields' => [
1200 'first_name',
1201 ],
1202 'fields' => [
1203 'first_name',
1204 'last_name',
1205 'email',
1206 'phone',
1207 'mobile',
1208 'other',
1209 'website',
1210 'fax',
1211 'notes',
1212 'street_1',
1213 'street_2',
1214 'city',
1215 'state',
1216 'postal_code',
1217 'country',
1218 'currency',
1219 ]
1220 ],
1221 'company' => [
1222 'required_fields' => [
1223 'email',
1224 'company',
1225 ],
1226 'fields' => [
1227 'email',
1228 'company',
1229 'phone',
1230 'mobile',
1231 'other',
1232 'website',
1233 'fax',
1234 'notes',
1235 'street_1',
1236 'street_2',
1237 'city',
1238 'state',
1239 'postal_code',
1240 'country',
1241 'currency',
1242 ]
1243 ],
1244 'employee' => [
1245 'required_fields' => [
1246 'first_name',
1247 'last_name',
1248 'user_email',
1249 ],
1250 'fields' => [
1251 'first_name',
1252 'middle_name',
1253 'last_name',
1254 'user_email',
1255 'designation',
1256 'department',
1257 'location',
1258 'hiring_source',
1259 'hiring_date',
1260 'date_of_birth',
1261 'reporting_to',
1262 'pay_rate',
1263 'pay_type',
1264 'type',
1265 'status',
1266 'other_email',
1267 'phone',
1268 'work_phone',
1269 'mobile',
1270 'address',
1271 'gender',
1272 'marital_status',
1273 'nationality',
1274 'driving_license',
1275 'hobbies',
1276 'user_url',
1277 'description',
1278 'street_1',
1279 'street_2',
1280 'city',
1281 'country',
1282 'state',
1283 'postal_code',
1284 ]
1285 ]
1286 ];
1287
1288 return apply_filters( 'erp_import_export_csv_fields', $erp_fields );
1289 }
1290
1291 /**
1292 * ERP Import/Export JavaScript enqueue.
1293 *
1294 * @since 1.0
1295 *
1296 * @return void
1297 */
1298 function erp_import_export_javascript() {
1299 global $current_screen;
1300 $hook = str_replace( sanitize_title( __( 'ERP Settings', 'erp' ) ), 'erp-settings', $current_screen->base );
1301
1302 if ( 'erp-settings_page_erp-tools' !== $hook ) {
1303 return;
1304 }
1305
1306 if ( ! isset( $_GET['tab'] ) || ! in_array( $_GET['tab'], [ 'import', 'export' ] ) ) {
1307 return;
1308 }
1309
1310 $erp_fields = erp_get_import_export_fields();
1311 ?>
1312 <script type="text/javascript">
1313 jQuery(document).ready(function ($) {
1314
1315 function erp_str_title_case(string) {
1316 var str = string.replace(/_/g, ' ');
1317
1318 return str.toLowerCase().split(' ').map(function (word) {
1319 return (word.charAt(0).toUpperCase() + word.slice(1));
1320 }).join(' ');
1321 }
1322
1323 function erp_csv_field_mapper(file_selector, fields_selector) {
1324 var file = file_selector.files[0];
1325
1326 var reader = new FileReader();
1327
1328 var first5000 = file.slice(0, 5000);
1329 reader.readAsText(first5000);
1330
1331 reader.onload = function (e) {
1332 var csv = reader.result;
1333 // Split the input into lines
1334 lines = csv.split('\n'),
1335 // Extract column names from the first line
1336 columnNamesLine = lines[0];
1337 columnNames = columnNamesLine.split(',');
1338
1339 var html = '';
1340
1341 html += '<option value="">&mdash; Select Field &mdash;</option>';
1342 columnNames.forEach(function (item, index) {
1343 item = item.replace(/"/g, "");
1344
1345 html += '<option value="' + index + '">' + item + '</option>';
1346 });
1347
1348 if (html) {
1349 $(fields_selector).html(html);
1350
1351 var field, field_label;
1352 $(fields_selector).each(function () {
1353 field_label = $(this).parent().parent().find('label').text();
1354
1355 var options = $(this).find('option');
1356 var targetOption = $(options).filter(function () {
1357 var option_text = $(this).html();
1358
1359 var re = new RegExp(field_label, 'i');
1360
1361 return re.test(option_text);
1362 });
1363
1364 if (targetOption) {
1365 $(options).removeAttr("selected");
1366 $(this).val($(targetOption).val());
1367 }
1368 });
1369 }
1370 };
1371 }
1372
1373 function erp_csv_importer_field_handler(file_selector) {
1374 $('#fields_container').show();
1375
1376 var fields_html = '';
1377
1378 var type = $('form#import_form #type').val();
1379
1380 fields = erp_fields[type] ? erp_fields[type].fields : [];
1381 required_fields = erp_fields[type] ? erp_fields[type].required_fields : [];
1382
1383 var required = '';
1384 var red_span = '';
1385 for (var i = 0; i < fields.length; i++) {
1386
1387 if (required_fields.indexOf(fields[i]) !== -1) {
1388 required = 'required';
1389 red_span = ' <span class="required">*</span>';
1390 } else {
1391 required = '';
1392 red_span = '';
1393 }
1394
1395 fields_html += `
1396 <tr>
1397 <th>
1398 <label for="fields[` + fields[i] + `]" class="csv_field_labels">` + erp_str_title_case(fields[i]) + red_span + `</label>
1399 </th>
1400 <td>
1401 <select name="fields[` + fields[i] + `]" class="csv_fields" ` + required + `>
1402 </select>
1403 </td>
1404 </tr>`;
1405 }
1406
1407 $('#fields_container').html(fields_html);
1408
1409 erp_csv_field_mapper(file_selector, '.csv_fields');
1410 }
1411
1412 var fields = [];
1413 var required_fields = [];
1414
1415 var erp_fields = <?php echo json_encode( $erp_fields ); ?>;
1416
1417 var type = $('form#export_form #type').val();
1418
1419 fields = erp_fields[type] ? erp_fields[type].fields : [];
1420
1421 var html = '<ul class="erp-list list-inline">';
1422 for (var i = 0; i < fields.length; i++) {
1423 html += '<li><label><input type="checkbox" name="fields[]" value="' + fields[i] + '"> ' + erp_str_title_case(fields[i]) + '</label></li>';
1424 }
1425
1426 html += '<ul>';
1427
1428 if (html) {
1429 $('#fields').html(html);
1430 }
1431
1432 $('form#export_form #type').on('change', function (e) {
1433 e.preventDefault();
1434
1435 $("#export_form #selecctall").prop('checked', false);
1436 var type = $(this).val();
1437 fields = erp_fields[type] ? erp_fields[type].fields : [];
1438
1439 html = '<ul class="erp-list list-inline">';
1440 for (var i = 0; i < fields.length; i++) {
1441 html += '<li><label><input type="checkbox" name="fields[]" value="' + fields[i] + '"> ' + erp_str_title_case(fields[i]) + '</label></li>';
1442 }
1443
1444 html += '<ul>';
1445
1446 if (html) {
1447 $('form#export_form #fields').html(html);
1448 }
1449 });
1450
1451 $('form#import_form #csv_file').on('change', function (e) {
1452 e.preventDefault();
1453
1454 if (!this) {
1455 return;
1456 }
1457
1458 erp_csv_importer_field_handler(this);
1459 });
1460
1461 if ($('form#import_form').find('#type').val() == 'employee') {
1462 $('form#import_form').find('#crm_contact_lifestage_owner_wrap').hide();
1463 } else {
1464 $('form#import_form').find('#crm_contact_lifestage_owner_wrap').show();
1465 }
1466
1467 $('form#import_form #type').on('change', function (e) {
1468 $('#fields_container').html('');
1469 $('#fields_container').hide();
1470
1471 if ($(this).val() == 'employee') {
1472 $('form#import_form').find('#crm_contact_lifestage_owner_wrap').hide();
1473 } else {
1474 $('form#import_form').find('#crm_contact_lifestage_owner_wrap').show();
1475 }
1476
1477 var sample_csv_url = $('form#import_form').find('#download_sample_wrap input').val();
1478 $('form#import_form').find('#download_sample_wrap a').attr('href', sample_csv_url + '&type=' + $(this).val());
1479
1480 if ($('form#import_form #csv_file').val() == "") {
1481 return;
1482 } else {
1483 erp_csv_importer_field_handler($('form#import_form #csv_file').get(0));
1484 }
1485 });
1486
1487 $("#export_form #selecctall").change(function (e) {
1488 e.preventDefault();
1489
1490 $("#export_form #fields input[type=checkbox]").prop('checked', $(this).prop("checked"));
1491 });
1492
1493 $("#users_import_form").on('submit', function (e) {
1494 e.preventDefault();
1495 statusDiv = $("div#import-status-indicator");
1496
1497 statusDiv.show();
1498
1499 var form = $(this),
1500 submit = form.find('input[type=submit]');
1501 submit.attr('disabled', 'disabled');
1502
1503 var data = {
1504 'action': 'erp_import_users_as_contacts',
1505 'user_role': $(this).find('select[name=user_role]').val(),
1506 'contact_owner': $(this).find('select[name=contact_owner]').val(),
1507 'life_stage': $(this).find('select[name=life_stage]').val(),
1508 'contact_group': $(this).find('select[name=contact_group]').val(),
1509 '_wpnonce': $(this).find('input[name=_wpnonce]').val()
1510 };
1511
1512 var total_items = 0, left = 0, imported = 0, exists = 0, percent = 0, type = 'success', message = '';
1513
1514 $.post(ajaxurl, data, function (response) {
1515 if (response.success) {
1516 total_items = response.data.total_items;
1517 left = response.data.left;
1518 exists = response.data.exists;
1519 imported = total_items - left;
1520 done = imported - exists;
1521
1522 if (imported > 0 || total_items > 0) {
1523 percent = Math.floor((100 / total_items) * (imported));
1524
1525 type = 'success';
1526 message = 'Successfully imported all users!';
1527 } else {
1528 message = 'No users found to import!';
1529 type = 'error';
1530 }
1531
1532 statusDiv.find('#progress-total').html(percent + '%');
1533 statusDiv.find('#progressbar-total').val(percent);
1534 statusDiv.find('#completed-total').html('Imported ' + done + ' out of ' + response.data.total_items);
1535 if (exists > 0) {
1536 statusDiv.find('#failed-total').html('Already Exist ' + exists);
1537 }
1538
1539 if (response.data.left > 0) {
1540 form.submit();
1541 return;
1542 } else {
1543 submit.removeAttr('disabled');
1544
1545 swal({
1546 title: '',
1547 text: message,
1548 type: type,
1549 confirmButtonText: 'OK',
1550 confirmButtonColor: '#008ec2'
1551 });
1552 }
1553 }
1554 });
1555 });
1556
1557 });
1558 </script>
1559 <?php
1560 }
1561
1562 /**
1563 * Process or handle import/export submit.
1564 *
1565 * @since 1.0.0
1566 * @since 1.1.15 Declare `field_builder_contacts_fields` with empty an array
1567 * @since 1.1.18 Handle exporting when no field is given.
1568 * Introduce `ERP_IS_IMPORTING` while importing data
1569 * @since 1.1.19 Import partial people data in case of existing people
1570 *
1571 * @return void
1572 */
1573 function erp_process_import_export() {
1574 if ( ! isset( $_REQUEST['_wpnonce'] ) || ! wp_verify_nonce( $_REQUEST['_wpnonce'], 'erp-import-export-nonce' ) ) {
1575 return;
1576 }
1577
1578 $is_crm_activated = erp_is_module_active( 'crm' );
1579 $is_hrm_activated = erp_is_module_active( 'hrm' );
1580
1581 $departments = $is_hrm_activated ? erp_hr_get_departments_dropdown_raw() : [];
1582 $designations = $is_hrm_activated ? erp_hr_get_designation_dropdown_raw() : [];
1583
1584 $field_builder_contact_options = get_option( 'erp-contact-fields' );
1585 $field_builder_contacts_fields = [];
1586
1587 if ( ! empty( $field_builder_contact_options ) ) {
1588 foreach ( $field_builder_contact_options as $field ) {
1589 $field_builder_contacts_fields[] = $field['name'];
1590 }
1591 }
1592
1593 $field_builder_employee_options = get_option( 'erp-employee-fields' );
1594
1595 if ( ! empty( $field_builder_employee_options ) ) {
1596 foreach ( $field_builder_employee_options as $field ) {
1597 $field_builder_employees_fields[] = $field['name'];
1598 }
1599 }
1600
1601 if ( isset( $_POST['erp_import_csv'] ) ) {
1602 define( 'ERP_IS_IMPORTING', true );
1603
1604 $fields = ! empty( $_POST['fields'] ) ? $_POST['fields'] : [];
1605 $type = isset( $_POST['type'] ) ? $_POST['type'] : '';
1606
1607 if ( empty( $type ) ) {
1608 return;
1609 }
1610
1611 $data = [ 'type' => $type, 'fields' => $fields, 'file' => $_FILES['csv_file'] ];
1612
1613 do_action( 'erp_tool_import_csv_action', $data );
1614
1615 if ( ! in_array( $type, [ 'contact', 'company', 'employee' ] ) ) {
1616 return;
1617 }
1618
1619 $employee_fields = [
1620 'work' => [
1621 'designation',
1622 'department',
1623 'location',
1624 'hiring_source',
1625 'hiring_date',
1626 'date_of_birth',
1627 'reporting_to',
1628 'pay_rate',
1629 'pay_type',
1630 'type',
1631 'status',
1632 ],
1633 'personal' => [
1634 'photo_id',
1635 'user_id',
1636 'first_name',
1637 'middle_name',
1638 'last_name',
1639 'other_email',
1640 'phone',
1641 'work_phone',
1642 'mobile',
1643 'address',
1644 'gender',
1645 'marital_status',
1646 'nationality',
1647 'driving_license',
1648 'hobbies',
1649 'user_url',
1650 'description',
1651 'street_1',
1652 'street_2',
1653 'city',
1654 'country',
1655 'state',
1656 'postal_code',
1657 ]
1658 ];
1659
1660 require_once WPERP_INCLUDES . '/lib/parsecsv.lib.php';
1661
1662 $csv = new parseCSV( $_FILES['csv_file']['tmp_name'] );
1663
1664 if ( empty( $csv->data ) ) {
1665 wp_redirect( admin_url( "admin.php?page=erp-tools&tab=import" ) );
1666 exit;
1667 }
1668
1669 $csv_data = [];
1670
1671 $csv_data[] = array_keys( $csv->data[0] );
1672
1673 foreach ( $csv->data as $data_item ) {
1674 $csv_data[] = array_values( $data_item );
1675 }
1676
1677 if ( ! empty( $csv_data ) ) {
1678 $count = 0;
1679
1680 foreach ( $csv_data as $line ) {
1681 if ( empty( $line ) ) {
1682 continue;
1683 }
1684
1685 $line_data = [];
1686
1687 foreach ( $fields as $key => $value ) {
1688
1689 if ( ! empty( $line[ $value ] ) && is_numeric( $value ) ) {
1690 if ( $type == 'employee' ) {
1691 if ( in_array( $key, $employee_fields['work'] ) ) {
1692 if ( $key == 'designation' ) {
1693 $line_data['work'][ $key ] = array_search( $line[ $value ], $designations );
1694 } else if ( $key == 'department' ) {
1695 $line_data['work'][ $key ] = array_search( $line[ $value ], $departments );
1696 } else {
1697 $line_data['work'][ $key ] = $line[ $value ];
1698 }
1699
1700 } else if ( in_array( $key, $employee_fields['personal'] ) ) {
1701 $line_data['personal'][ $key ] = $line[ $value ];
1702 } else {
1703 $line_data[ $key ] = $line[ $value ];
1704 }
1705 } else {
1706 $line_data[ $key ] = isset( $line[ $value ] ) ? $line[ $value ] : '';
1707 $line_data['type'] = $type;
1708 }
1709 }
1710
1711 }
1712
1713 if ( $type == 'employee' && $is_hrm_activated ) {
1714 if ( ! isset( $line_data['work']['status'] ) ) {
1715 $line_data['work']['status'] = 'active';
1716 }
1717
1718
1719 $item_insert_id = erp_hr_employee_create( $line_data );
1720
1721 if ( is_wp_error( $item_insert_id ) ) {
1722 continue;
1723 }
1724 }
1725
1726 if ( ( $type == 'contact' || $type == 'company' ) && $is_crm_activated ) {
1727 $people = erp_insert_people( $line_data, true );
1728
1729 if ( is_wp_error( $people ) ) {
1730 continue;
1731 } else {
1732 $contact = new \WeDevs\ERP\CRM\Contact( absint( $people->id ), 'contact' );
1733 $contact_owner = isset( $_POST['contact_owner'] ) ? absint( $_POST['contact_owner'] ) : erp_crm_get_default_contact_owner();
1734 $life_stage = isset( $_POST['life_stage'] ) ? sanitize_key( $_POST['life_stage'] ) : '';
1735
1736 if ( ! $people->exists ) {
1737 $contact->update_life_stage( $life_stage );
1738 $contact->update_meta( 'contact_owner', $contact_owner );
1739
1740 } else {
1741 if ( ! $contact->get_life_stage() ) {
1742 $contact->update_life_stage( $life_stage );
1743 }
1744
1745 if ( ! $contact->get_contact_owner() ) {
1746 $contact->update_meta( 'contact_owner', $contact_owner );
1747 }
1748 }
1749
1750 if ( ! empty( $_POST['contact_group'] ) ) {
1751 $contact_group = absint( $_POST['contact_group'] );
1752
1753 $existing_data = \WeDevs\ERP\CRM\Models\ContactSubscriber::where( [
1754 'group_id' => $contact_group,
1755 'user_id' => $people->id
1756 ] )->first();
1757
1758 if ( empty( $existing_data ) ) {
1759 $hash = sha1( microtime() . 'erp-subscription-form' . $contact_group . $people->id );
1760
1761 erp_crm_create_new_contact_subscriber( [
1762 'group_id' => $contact_group,
1763 'user_id' => $people->id,
1764 'status' => 'subscribe',
1765 'subscribe_at' => current_time( 'mysql' ),
1766 'unsubscribe_at' => null,
1767 'hash' => $hash
1768 ] );
1769 }
1770 }
1771
1772
1773 if ( ! empty( $field_builder_contacts_fields ) ) {
1774 foreach ( $field_builder_contacts_fields as $field ) {
1775 if ( isset( $line_data[ $field ] ) ) {
1776 erp_people_update_meta( $people->id, $field, $line_data[ $field ] );
1777 }
1778 }
1779 }
1780 }
1781 }
1782
1783 ++ $count;
1784 }
1785
1786 }
1787
1788 wp_redirect( admin_url( "admin.php?page=erp-tools&tab=import&imported=$count" ) );
1789 exit;
1790 }
1791
1792 if ( isset( $_POST['erp_export_csv'] ) ) {
1793 if ( ! empty( $_POST['type'] ) && ! empty( $_POST['fields'] ) ) {
1794 $type = $_POST['type'];
1795 $fields = $_POST['fields'];
1796
1797 if ( $type == 'employee' && $is_hrm_activated ) {
1798 $args = [
1799 'number' => - 1,
1800 'status' => 'all'
1801 ];
1802
1803 $items = erp_hr_get_employees( $args );
1804 }
1805
1806 if ( ( $type == 'contact' || $type == 'company' ) && $is_crm_activated ) {
1807 $args = [
1808 'type' => $type,
1809 'count' => true,
1810 ];
1811 $total_items = erp_get_peoples( $args );
1812
1813 $args = [
1814 'type' => $type,
1815 'offset' => 0,
1816 'number' => - 1,
1817 ];
1818 $items = erp_get_peoples( $args );
1819 }
1820
1821 //@todo do_action()
1822
1823 $csv_items = [];
1824
1825 $x = 0;
1826 foreach ( $items as $item ) {
1827
1828 if ( empty( $fields ) ) {
1829 continue;
1830 }
1831
1832 foreach ( $fields as $field ) {
1833 if ( $type == 'employee' ) {
1834
1835 if ( in_array( $field, $field_builder_employees_fields ) ) {
1836 $csv_items[ $x ][ $field ] = get_user_meta( $item->id, $field, true );
1837 } else {
1838 switch ( $field ) {
1839 case 'department':
1840 $csv_items[ $x ][ $field ] = $item->get_department_title();
1841 break;
1842
1843 case 'designation':
1844 $csv_items[ $x ][ $field ] = $item->get_job_title();
1845 break;
1846
1847 default:
1848 $csv_items[ $x ][ $field ] = $item->{$field};
1849 break;
1850 }
1851 }
1852
1853 } else {
1854 if ( in_array( $field, $field_builder_contacts_fields ) ) {
1855 $csv_items[ $x ][ $field ] = erp_people_get_meta( $item->id, $field, true );
1856 } else {
1857 if ( isset( $item->{$field} ) ) {
1858 $csv_items[ $x ][ $field ] = $item->{$field};
1859 }
1860 }
1861 }
1862 }
1863
1864 $x ++;
1865 }
1866
1867 $file_name = 'export_' . date( 'd_m_Y' ) . '.csv';
1868
1869 erp_make_csv_file( $csv_items, $file_name );
1870
1871 } else {
1872 wp_redirect( admin_url( "admin.php?page=erp-tools&tab=export" ) );
1873 exit();
1874 }
1875 }
1876 }
1877
1878 /**
1879 * Display importer tool notice.
1880 *
1881 *
1882 * @return void
1883 */
1884 function erp_importer_notices() {
1885 if ( ! isset( $_REQUEST['page'] ) || $_REQUEST['page'] != 'erp-tools' || ! isset( $_REQUEST['tab'] ) || $_REQUEST['tab'] != 'import' ) {
1886 return;
1887 }
1888
1889 if ( isset( $_REQUEST['imported'] ) ) {
1890 if ( intval( $_REQUEST['imported'] ) == 0 ) {
1891 $message = __( 'Nothing to import or items are already exists.', 'erp' );
1892 echo "<div class='notice error'><p>{$message}</p></div>";
1893 } else {
1894 $message = sprintf( __( '%s items successfully imported.', 'erp' ), number_format_i18n( $_REQUEST['imported'] ) );
1895 echo "<div class='notice updated'><p>{$message}</p></div>";
1896 }
1897 }
1898 }
1899
1900 /**
1901 * Merge user defined arguments into defaults array.
1902 *
1903 * This function is similiar to wordpress wp_parse_args().
1904 * It's support multidimensional array.
1905 *
1906 * @param array $args
1907 * @param array $defaults Optional.
1908 *
1909 * @return array
1910 */
1911 function erp_parse_args_recursive( &$args, $defaults = [] ) {
1912 $args = (array) $args;
1913 $defaults = (array) $defaults;
1914 $r = $defaults;
1915
1916 foreach ( $args as $k => &$v ) {
1917 if ( is_array( $v ) && isset( $r[ $k ] ) ) {
1918 $r[ $k ] = erp_parse_args_recursive( $v, $r[ $k ] );
1919 } else {
1920 $r[ $k ] = $v;
1921 }
1922 }
1923
1924 return $r;
1925 }
1926
1927 /**
1928 * ERP Email sender
1929 *
1930 * @since 1.1.0
1931 * @since 1.1.17 Use site name instead of current user name for default From header
1932 * @since 1.2.0 Always return true during any importing process
1933 *
1934 * @param string|array $to
1935 * @param string $subject
1936 * @param string $message
1937 * @param string|array $headers
1938 * @param array $attachments
1939 * @param array $custom_headers
1940 *
1941 * @return boolean
1942 */
1943 function erp_mail( $to, $subject, $message, $headers = '', $attachments = [], $custom_headers = [] ) {
1944
1945 if ( defined( 'ERP_IS_IMPORTING' ) && ERP_IS_IMPORTING ) {
1946 return true;
1947 }
1948
1949 $callback = function ( $phpmailer ) use ( $custom_headers ) {
1950 $erp_email_settings = get_option( 'erp_settings_erp-email_general', [] );
1951 $erp_email_smtp_settings = get_option( 'erp_settings_erp-email_smtp', [] );
1952
1953 if ( ! isset( $erp_email_settings['from_email'] ) ) {
1954 $from_email = get_option( 'admin_email' );
1955 } else {
1956 $from_email = $erp_email_settings['from_email'];
1957 }
1958
1959 if ( ! isset( $erp_email_settings['from_name'] ) ) {
1960 $from_name = get_bloginfo( 'name' );
1961 } else {
1962 $from_name = $erp_email_settings['from_name'];
1963 }
1964
1965 $content_type = 'text/html';
1966
1967 $phpmailer->From = apply_filters( 'erp_mail_from', $from_email );
1968 $phpmailer->FromName = apply_filters( 'erp_mail_from_name', $from_name );
1969 $phpmailer->ContentType = apply_filters( 'erp_mail_content_type', $content_type );
1970
1971 //Return-Path
1972 $phpmailer->Sender = apply_filters( 'erp_mail_return_path', $phpmailer->From );
1973
1974 if ( ! empty( $custom_headers ) ) {
1975 foreach ( $custom_headers as $key => $value ) {
1976 $phpmailer->addCustomHeader( $key, $value );
1977 }
1978 }
1979
1980 if ( isset( $erp_email_smtp_settings['debug'] ) && $erp_email_smtp_settings['debug'] == 'yes' ) {
1981 $phpmailer->SMTPDebug = true;
1982 }
1983
1984 if ( isset( $erp_email_smtp_settings['enable_smtp'] ) && $erp_email_smtp_settings['enable_smtp'] == 'yes' ) {
1985 $phpmailer->Mailer = 'smtp'; //'smtp', 'mail', or 'sendmail'
1986
1987 $phpmailer->Host = $erp_email_smtp_settings['mail_server'];
1988 $phpmailer->SMTPSecure = ( $erp_email_smtp_settings['authentication'] != '' ) ? $erp_email_smtp_settings['authentication'] : 'smtp';
1989 $phpmailer->Port = $erp_email_smtp_settings['port'];
1990
1991 if ( $erp_email_smtp_settings['authentication'] != '' ) {
1992 $phpmailer->SMTPAuth = true;
1993 $phpmailer->Username = $erp_email_smtp_settings['username'];
1994 $phpmailer->Password = $erp_email_smtp_settings['password'];
1995 }
1996 }
1997 };
1998
1999 add_action( 'phpmailer_init', $callback );
2000
2001 ob_start();
2002 $is_mail_sent = wp_mail( $to, $subject, $message, $headers, $attachments );
2003 $debug_log = ob_get_clean();
2004 if ( ! $is_mail_sent ) {
2005 error_log( $debug_log );
2006 }
2007
2008 remove_action( 'phpmailer_init', $callback );
2009
2010 return $is_mail_sent;
2011 }
2012
2013 /**
2014 * Email JavaScript enqueue.
2015 *
2016 * @return void
2017 */
2018 function erp_email_settings_javascript() {
2019 wp_enqueue_style( 'erp-sweetalert' );
2020 wp_enqueue_script( 'erp-sweetalert' );
2021 ?>
2022 <script type="text/javascript">
2023 jQuery(document).ready(function ($) {
2024 $("a#smtp-test-connection").click(function (e) {
2025 e.preventDefault();
2026 $("a#smtp-test-connection").attr('disabled', 'disabled');
2027 $("a#smtp-test-connection").parent().find('.erp-loader').show();
2028
2029 var data = {
2030 'action': 'erp_smtp_test_connection',
2031 'enable_smtp': $('input[name=enable_smtp]:checked').val(),
2032 'mail_server': $('input[name=mail_server]').val(),
2033 'port': $('input[name=port]').val(),
2034 'authentication': $('select[name=authentication]').val(),
2035 'username': $('input[name=username]').val(),
2036 'password': $('input[name=password]').val(),
2037 'to': $('#smtp_test_email_address').val(),
2038 '_wpnonce': '<?php echo wp_create_nonce( "erp-smtp-test-connection-nonce" ); ?>'
2039 };
2040
2041 $.post(ajaxurl, data, function (response) {
2042 $("a#smtp-test-connection").removeAttr('disabled');
2043 $("a#smtp-test-connection").parent().find('.erp-loader').hide();
2044
2045 var type = response.success ? 'success' : 'error';
2046
2047 if (response.data) {
2048 swal({
2049 title: '',
2050 text: response.data,
2051 type: type,
2052 confirmButtonText: 'OK',
2053 confirmButtonColor: '#008ec2'
2054 });
2055 }
2056 });
2057 });
2058 });
2059
2060 jQuery(document).ready(function ($) {
2061 $("a#imap-test-connection").click(function (e) {
2062 e.preventDefault();
2063 $("a#imap-test-connection").attr('disabled', 'disabled');
2064 $("a#imap-test-connection").parent().find('.erp-loader').show();
2065
2066 var data = {
2067 'action': 'erp_imap_test_connection',
2068 'mail_server': $('input[name=mail_server]').val(),
2069 'username': $('input[name=username]').val(),
2070 'password': $('input[name=password]').val(),
2071 'protocol': $('select[name=protocol]').val(),
2072 'port': $('input[name=port]').val(),
2073 'authentication': $('select[name=authentication]').val(),
2074 '_wpnonce': '<?php echo wp_create_nonce( "erp-imap-test-connection-nonce" ); ?>'
2075 };
2076
2077 $.post(ajaxurl, data, function (response) {
2078 $("a#imap-test-connection").removeAttr('disabled');
2079 $("a#imap-test-connection").parent().find('.erp-loader').hide();
2080
2081 var type = response.success ? 'success' : 'error';
2082
2083 if (response.data) {
2084 var status = response.success ? 1 : 0;
2085 $('#imap_status').val(status);
2086
2087 swal({
2088 title: '',
2089 text: response.data,
2090 type: type,
2091 confirmButtonText: 'OK',
2092 confirmButtonColor: '#008ec2'
2093 });
2094 }
2095 });
2096 });
2097 });
2098 </script>
2099 <?php
2100 }
2101
2102 /**
2103 * Determine if the inbound/imap mail feature is active or not.
2104 *
2105 * @return boolean
2106 */
2107 function erp_is_imap_active() {
2108 $options = get_option( 'erp_settings_erp-email_imap', [] );
2109
2110 $imap_status = (boolean) isset( $options['imap_status'] ) ? $options['imap_status'] : 0;
2111 $enable_imap = ( isset( $options['enable_imap'] ) && $options['enable_imap'] == 'yes' ) ? true : false;
2112
2113 if ( $enable_imap && $imap_status ) {
2114 return true;
2115 }
2116
2117 return false;
2118 }
2119
2120 /**
2121 * Check if the ERP Email SMTP settings is enabled or not
2122 *
2123 * @since 1.1.6
2124 *
2125 * @return boolean
2126 */
2127 function erp_is_smtp_enabled() {
2128 $erp_email_smtp_settings = get_option( 'erp_settings_erp-email_smtp', [] );
2129
2130 if ( isset( $erp_email_smtp_settings['enable_smtp'] ) && filter_var( $erp_email_smtp_settings['enable_smtp'], FILTER_VALIDATE_BOOLEAN ) ) {
2131 return true;
2132 }
2133
2134 return false;
2135 }
2136
2137 /**
2138 * Determine if the module is active or not.
2139 *
2140 * @return boolean
2141 */
2142 function erp_is_module_active( $module_key ) {
2143 $modules = get_option( 'erp_modules', [] );
2144
2145 return isset( $modules[ $module_key ] );
2146 }
2147
2148 /**
2149 * Make csv file from array and force download
2150 *
2151 * @param array $items
2152 * @param boolean $field_data (optional)
2153 *
2154 * @param string $file_name
2155 */
2156 function erp_make_csv_file( $items, $file_name, $field_data = true ) {
2157 $file_name = ( ! empty( $file_name ) ) ? $file_name : 'csv_' . date( 'd_m_Y' ) . '.csv';
2158
2159 if ( empty( $items ) ) {
2160 return;
2161 }
2162
2163 $columns = array_keys( $items[0] );
2164
2165 header( 'Content-Type: text/csv; charset=utf-8' );
2166 header( 'Content-Disposition: attachment; filename=' . $file_name );
2167
2168 $output = fopen( 'php://output', 'w' );
2169
2170 $columns = array_map( function ( $column ) {
2171 $column = ucwords( str_replace( '_', ' ', $column ) );
2172
2173 return $column;
2174 }, $columns );
2175
2176 fputcsv( $output, $columns );
2177
2178 if ( $field_data ) {
2179 foreach ( $items as $item ) {
2180 $csv_row = array_map( function ( $item_val ) {
2181
2182 if ( is_array( $item_val ) ) {
2183 return implode( ', ', $item_val );
2184 }
2185
2186 return $item_val;
2187
2188 }, $item );
2189
2190 fputcsv( $output, $csv_row );
2191 }
2192 }
2193
2194 exit();
2195 }
2196
2197 /**
2198 * Import/Export sample CSV download action hook
2199 *
2200 * @param void
2201 */
2202 function erp_import_export_download_sample_action() {
2203
2204 $type = isset( $_POST['type'] ) ? $_POST['type'] : '';
2205
2206 if ( ! isset( $_GET['action'] ) || $_GET['action'] != 'download_sample' ) {
2207 return;
2208 }
2209
2210 if ( ! wp_verify_nonce( $_GET['_wpnonce'], 'erp-emport-export-sample-nonce' ) ) {
2211 return;
2212 }
2213
2214 if ( ! isset( $type ) ) {
2215 return;
2216 }
2217
2218 $type = strtolower( $type );
2219 $fields = erp_get_import_export_fields();
2220
2221 if ( isset( $fields[ $type ] ) ) {
2222 $keys = $fields[ $type ]['fields'];
2223 $keys = array_flip( $keys );
2224 $file_name = "sample_csv_{$type}.csv";
2225
2226 erp_make_csv_file( [ $keys ], $file_name, false );
2227 }
2228
2229 return;
2230 }
2231
2232 /**
2233 * Enqueue locale scripts for fullcalendar
2234 *
2235 * @since 1.0.0
2236 *
2237 * @return void
2238 */
2239 function enqueue_fullcalendar_locale() {
2240 $locale = get_locale();
2241 $script = '';
2242
2243 // no need to add locale for en_US
2244 if ( 'en_US' === $locale ) {
2245 return;
2246 }
2247
2248 $locale = explode( '_', $locale );
2249
2250 // make sure we have two segments - 1.lang, 2.country
2251 if ( count( $locale ) < 2 ) {
2252 return;
2253 }
2254
2255 $lang = $locale[0];
2256 $country = strtolower( $locale[1] );
2257
2258 if ( $lang === $country ) {
2259 $script = $lang;
2260 } else {
2261 $script = $lang . '-' . $country;
2262 }
2263
2264 if ( file_exists( WPERP_PATH . "/assets/vendor/fullcalendar/lang/{$script}.js" ) ) {
2265 wp_enqueue_script( 'erp-fullcalendar-locale', WPERP_ASSETS . "/vendor/fullcalendar/lang/{$script}.js", array( 'erp-fullcalendar' ), null, true );
2266 }
2267 }
2268
2269 /**
2270 * Generate random key
2271 *
2272 * @since 1.1.8
2273 *
2274 * @return string
2275 */
2276 function erp_generate_key() {
2277 if ( function_exists( 'openssl_random_pseudo_bytes' ) ) {
2278 $key = bin2hex( openssl_random_pseudo_bytes( 20 ) );
2279 } else {
2280 $key = sha1( wp_rand() );
2281 }
2282
2283 return $key;
2284 }
2285
2286 /**
2287 * Include required HTML form erp-popup
2288 *
2289 * @since 1.1.12
2290 *
2291 * @return void
2292 */
2293 function erp_include_popup_markup() {
2294 include_once WPERP_INCLUDES . '/admin/views/erp-modal.php';
2295 erp_get_js_template( WPERP_INCLUDES . '/admin/views/address.php', 'erp-address' );
2296 }
2297
2298 /**
2299 * Dequeue/Deregister select2 from other plugins
2300 *
2301 * @since 1.1.13
2302 *
2303 * @return void
2304 */
2305 function erp_dequeue_other_select2_sources() {
2306 // select2 handle is used by woocommerce
2307 wp_deregister_script( 'select2' );
2308 wp_dequeue_script( 'select2' );
2309 }
2310
2311 /**
2312 * Remove select2 enqueued by other plugins
2313 *
2314 * Whenever enqueue erp-select2, call this function to
2315 * make sure only one select2 is loaded
2316 *
2317 * @since 1.1.13
2318 *
2319 * @return void
2320 */
2321 function erp_remove_other_select2_sources() {
2322 add_action( 'admin_enqueue_scripts', 'erp_dequeue_other_select2_sources', 999999 );
2323 add_action( 'wp_enqueue_scripts', 'erp_dequeue_other_select2_sources', 999999 );
2324 }
2325
2326 /**
2327 * Returns a word in plural form.
2328 *
2329 * @since 1.1.16
2330 *
2331 * @param string $word The word in singular form.
2332 *
2333 * @return string The word in plural form.
2334 */
2335 function erp_pluralize( $word ) {
2336 return \Doctrine\Common\Inflector\Inflector::pluralize( $word );
2337 }
2338
2339 /**
2340 * Get the client IP address
2341 *
2342 * @since 1.1.16
2343 *
2344 * @return string
2345 */
2346 function erp_get_client_ip() {
2347 $ipaddress = '';
2348
2349 if ( isset( $_SERVER['HTTP_CLIENT_IP'] ) ) {
2350 $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
2351 } else if ( isset( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
2352 $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
2353 } else if ( isset( $_SERVER['HTTP_X_FORWARDED'] ) ) {
2354 $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
2355 } else if ( isset( $_SERVER['HTTP_FORWARDED_FOR'] ) ) {
2356 $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
2357 } else if ( isset( $_SERVER['HTTP_FORWARDED'] ) ) {
2358 $ipaddress = $_SERVER['HTTP_FORWARDED'];
2359 } else if ( isset( $_SERVER['REMOTE_ADDR'] ) ) {
2360 $ipaddress = $_SERVER['REMOTE_ADDR'];
2361 } else {
2362 $ipaddress = 'UNKNOWN';
2363 }
2364
2365 return $ipaddress;
2366 }
2367
2368 /**
2369 * Converts any value to boolean true or false
2370 *
2371 * @since 1.2.0
2372 *
2373 * @param mixed $value
2374 *
2375 * @return boolean
2376 */
2377 function erp_validate_boolean( $value ) {
2378 return filter_var( $value, FILTER_VALIDATE_BOOLEAN );
2379 }
2380
2381 /**
2382 * Get financial year start and end dates
2383 * @param $date
2384 * @since 1.2.0
2385 * since 1.3.0 $date added
2386 * @return array
2387 */
2388 function erp_get_financial_year_dates( $date = null ) {
2389 $start_month = erp_get_option( 'gen_financial_month', 'erp_settings_general', 1 );
2390 if ( $date == null ) {
2391 $year = date( 'Y' );
2392 $month = date( 'n' );
2393 } else {
2394 $year = date( 'Y', strtotime( $date ) );
2395 $month = date( 'n', strtotime( $date ) );
2396 }
2397
2398 /**
2399 * Suppose, $start_month is July and today is May 2017. Then we should get
2400 * start = 2016-07-01 00:00:00 and end = 2017-06-30 23:59:59.
2401 *
2402 * On the other hand, if $start_month = January, then we should get
2403 * start = 2017-01-01 00:00:00 and end = 2017-12-31 23:59:59.
2404 */
2405 if ( $month < $start_month ) {
2406 $year = $year - 1;
2407 }
2408
2409 $months = erp_months_dropdown();
2410 $start = date( 'Y-m-d 00:00:00', strtotime( "first day of $months[$start_month] $year" ) );
2411 $end = date( 'Y-m-d 23:59:59', strtotime( "$start + 12 months - 1 day" ) );
2412
2413 return [
2414 'start' => $start,
2415 'end' => $end
2416 ];
2417 }
2418
2419 /**
2420 * Get finanicial start and end years that a date belongs to
2421 *
2422 * @since 1.2.0
2423 *
2424 * @param string $date
2425 *
2426 * @return array
2427 */
2428 function get_financial_year_from_date( $date ) {
2429 $fy_start_month = erp_get_option( 'gen_financial_month', 'erp_settings_general', 1 );
2430 $fy_start_month = absint( $fy_start_month );
2431
2432 $date_timestamp = strtotime( $date );
2433 $date_year = absint( date( 'Y', $date_timestamp ) );
2434 $date_month = absint( date( 'n', $date_timestamp ) );
2435
2436 if ( 1 === $fy_start_month ) {
2437 return [
2438 'start' => $date_year,
2439 'end' => $date_year
2440 ];
2441
2442 } else if ( $date_month <= ( $fy_start_month - 1 ) ) {
2443 return [
2444 'start' => ( $date_year - 1 ),
2445 'end' => $date_year
2446 ];
2447
2448 } else {
2449 return [
2450 'start' => $date_year,
2451 'end' => ( $date_year + 1 )
2452 ];
2453 }
2454 }
2455
2456 /**
2457 * Redirect erp role based user to their page
2458 *
2459 * @since 1.2.5
2460 *
2461 * @param $redirect_to
2462 * @param $request
2463 * @param $user
2464 *
2465 * @return string
2466 */
2467 function erp_login_redirect_manager( $redirect_to, $request, $user ) {
2468 $is_erp_redirect = erp_get_option( 'role_based_login_redirection', 'erp_settings_general', false );
2469
2470 if ( $is_erp_redirect && isset( $user->roles ) && is_array( $user->roles ) && ! in_array( 'administrator', $user->roles ) ) {
2471 return $redirect_to = apply_filters( 'erp_login_redirect', $redirect_to, $user->roles );
2472 } else {
2473 return $redirect_to;
2474 }
2475 }
2476
2477 /**
2478 * Flatten any multi dimensional array
2479 *
2480 * @since 1.3.0
2481 *
2482 * @param $array
2483 *
2484 * @return array|bool
2485 */
2486 function erp_array_flatten( $array ) {
2487 if ( ! is_array( $array ) ) {
2488 return false;
2489 }
2490 $result = array();
2491 foreach ( $array as $key => $value ) {
2492 if ( is_array( $value ) ) {
2493 $result = array_merge( $result, erp_array_flatten( $value ) );
2494 } else {
2495 $result[ $key ] = $value;
2496 }
2497 }
2498
2499 return $result;
2500 }
2501
2502
2503
2504 /**
2505 * Fetch a filtered list of user roles that the current user is
2506 * allowed to edit.
2507 * @since 1.3.1 function has been from crm
2508 * @since 1.2.4
2509 *
2510 * @return array
2511 */
2512 function erp_get_editable_roles (){
2513 if(! function_exists('get_editable_roles')){
2514 require_once(ABSPATH . 'wp-admin/includes/user.php');
2515 }
2516 $wp_roles = get_editable_roles();
2517
2518 if( !current_user_can( 'administrator' ) ){
2519 unset( $wp_roles['administrator'] );
2520 }
2521
2522 $roles = apply_filters( 'erp_editable_roles', $wp_roles );
2523
2524 return $roles;
2525 }
2526
2527 /**
2528 * Get dates in range
2529 *
2530 * @since 1.3.2
2531 *
2532 * @param $first
2533 * @param $last
2534 * @param string $step
2535 * @param string $output_format
2536 *
2537 * @return array
2538 *
2539 */
2540 function erp_get_dates_in_range($first, $last, $step = '+1 day', $output_format = 'Y-m-d' ) {
2541
2542 $dates = array();
2543 $current = strtotime($first);
2544 $last = strtotime($last);
2545
2546 while( $current <= $last ) {
2547
2548 $dates[] = date($output_format, $current);
2549 $current = strtotime($step, $current);
2550 }
2551
2552 return $dates;
2553 }
2554
2555 /**
2556 * Sanitize a string destined to be a tooltip.
2557 * Tooltips are encoded with htmlspecialchars to prevent XSS. Should not be used in conjunction with esc_attr()
2558 *
2559 * @param string $var
2560 * @return string
2561 * @since 1.3.4
2562 */
2563 function erp_sanitize_tooltip( $var ) {
2564 return htmlspecialchars( wp_kses( html_entity_decode( $var ), array(
2565 'br' => array(),
2566 'em' => array(),
2567 'strong' => array(),
2568 'small' => array(),
2569 'span' => array(),
2570 'ul' => array(),
2571 'li' => array(),
2572 'ol' => array(),
2573 'p' => array(),
2574 ) ) );
2575 }
2576
2577 /**
2578 * Display an ERP help tip.
2579 *
2580 * @param string $tip Help tip text
2581 * @param bool $allow_html Allow sanitized HTML if true or escape
2582 * @return string
2583 * @since 1.3.4
2584 */
2585 function erp_help_tip( $tip, $allow_html = false ) {
2586 if ( $allow_html ) {
2587 $tip = erp_sanitize_tooltip( $tip );
2588 } else {
2589 $tip = esc_attr( $tip );
2590 }
2591
2592 return '<span class="erp-help-tip" data-tip="' . $tip . '"></span>';
2593 }
2594
2595 /**
2596 * Letter to number converter
2597 * @param $size
2598 * @return $ret
2599 * @since 1.3.4
2600 */
2601 function erp_let_to_num( $size ) {
2602 $l = substr( $size, -1 );
2603 $ret = substr( $size, 0, -1 );
2604 switch ( strtoupper( $l ) ) {
2605 case 'P':
2606 $ret *= 1024;
2607 case 'T':
2608 $ret *= 1024;
2609 case 'G':
2610 $ret *= 1024;
2611 case 'M':
2612 $ret *= 1024;
2613 case 'K':
2614 $ret *= 1024;
2615 }
2616
2617 return $ret;
2618 }
2619