PluginProbe
ERP: Complete HR, Accounting & CRM Suite Built for WooCommerce / 1.2.6
ERP: Complete HR, Accounting & CRM Suite Built for WooCommerce v1.2.6
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.2.6, at includes/functions.php

2,449 lines 74.0 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 return apply_filters( 'erp_currency_symbol', $symbol, $currency );
480 } else {
481 return apply_filters( 'erp_currency_symbol_list', $currency_symbols );
482 }
483
484 }
485
486 /**
487 * Embed a JS template page with its ID
488 *
489 * @param string the file path of the file
490 * @param string the script id
491 *
492 * @return void
493 */
494 function erp_get_js_template( $file_path, $id ) {
495 if ( file_exists( $file_path ) ) {
496 echo '<script type="text/html" id="tmpl-' . $id . '">' . "\n";
497 include_once apply_filters( 'erp_crm_js_template_file_path', $file_path, $id );
498 echo "\n" . '</script>' . "\n";
499 }
500 }
501
502 /**
503 * Embed a Vue Component template page with its ID
504 *
505 * @param string the file path of the file
506 * @param string the script id
507 *
508 * @return void
509 */
510 function erp_get_vue_component_template( $file_path, $id ) {
511 if ( file_exists( $file_path ) ) {
512 echo '<script type="text/x-template" id="'. $id . '">' . "\n";
513 include_once $file_path;
514 echo "\n" . '</script>' . "\n";
515 }
516 }
517
518
519 if ( ! function_exists( 'strip_tags_deep' ) ) {
520
521 /**
522 * Strip tags from string or array
523 *
524 * @param mixed array or string to strip
525 *
526 * @return mixed stripped value
527 */
528 function strip_tags_deep( $value ) {
529 if ( is_array( $value ) ) {
530 foreach ($value as $key => $val) {
531 $value[ $key ] = strip_tags_deep( $val );
532 }
533 } elseif ( is_string( $value ) ) {
534 $value = strip_tags( $value );
535 }
536
537 return $value;
538 }
539 }
540
541 if ( ! function_exists( 'trim_deep' ) ) {
542
543 /**
544 * Trim from string or array
545 *
546 * @param mixed array or string to trim
547 *
548 * @return mixed timmed value
549 */
550 function trim_deep( $value ) {
551 if ( is_array( $value ) ) {
552 foreach ($value as $key => $val) {
553 $value[ $key ] = trim_deep( $val );
554 }
555 } elseif ( is_string( $value ) ) {
556 $value = trim( $value );
557 }
558
559 return $value;
560 }
561 }
562
563 /**
564 * Helper function to print a label and value with a separator
565 *
566 * @since 1.0.0
567 * @since 1.1.14 Add $type param
568 * @since 1.1.16 Apply if-else condition to set `$value`
569 *
570 * @param string $label the label
571 * @param string $value the value to print
572 * @param string $sep separator
573 * @param string $type field type
574 *
575 * @return void
576 */
577 function erp_print_key_value( $label, $value, $sep = ' : ', $type = 'text' ) {
578 if ( empty( $value ) ) {
579 $value = '&mdash;';
580
581 } else {
582 switch ( $type ) {
583 case 'email':
584 case 'url':
585 case 'phone':
586 $value = erp_get_clickable( $type, $value );
587 break;
588 }
589 }
590
591 printf( '<label>%s</label> <span class="sep">%s</span> <span class="value">%s</span>', $label, $sep, $value );
592 }
593
594 /**
595 * Get a clickable phone or email address link
596 *
597 * @param string type. e.g: email|phone|url
598 * @param string the value
599 *
600 * @return string the link
601 */
602 function erp_get_clickable( $type = 'email', $value = '' ) {
603 if ( 'email' == $type ) {
604 return sprintf( '<a href="mailto:%1$s">%1$s</a>', $value );
605 } elseif ( 'url' == $type ) {
606 return sprintf( '<a target="_blank" href="%1$s">%1$s</a>', $value );
607 } elseif ( 'phone' == $type ) {
608 return sprintf( '<a href="tel:%1$s">%1$s</a>', $value );
609 }
610 }
611
612 /**
613 * Get a formatted date from WordPress format
614 *
615 * @param string $date the date
616 *
617 * @return string formatted date
618 */
619 function erp_format_date( $date, $format = false ) {
620 if ( ! $format ) {
621 $format = erp_get_option( 'date_format', 'erp_settings_general', 'd-m-Y' );
622 }
623
624 $time = strtotime( $date );
625
626 return date_i18n( $format, $time );
627 }
628
629 /**
630 * Extract dates between two date range
631 *
632 * @param string $start_date example: 2016-12-16 00:00:00
633 * @param string $end_date example: 2016-12-16 23:59:59
634 *
635 * @return array
636 */
637 function erp_extract_dates( $start_date, $end_date ) {
638 // if start date has no time set, then add 00:00:00 or 12:00 AM
639 if ( ! preg_match( '/\d{2}:\d{2}:\d{2}$/' , $start_date ) ) {
640 $start_date = $start_date . ' 00:00:00';
641 }
642
643 // if end date has no time set, then add 23:59:59 or 11:59 PM
644 if ( ! preg_match( '/\d{2}:\d{2}:\d{2}$/' , $end_date ) ) {
645 $end_date = $end_date . ' 23:59:59';
646 }
647
648 $start_date = new DateTime( $start_date );
649 $end_date = new DateTime( $end_date );
650 $diff = $start_date->diff( $end_date );
651
652 // we got a negative date
653 if ( $diff->invert ) {
654 return new WP_Error( 'invalid-date', __( 'Invalid date provided', 'erp' ) );
655 }
656
657 $interval = DateInterval::createFromDateString( '1 day' );
658 $period = new DatePeriod( $start_date, $interval, $end_date );
659
660 // prepare the periods
661 $dates = array();
662 foreach ( $period as $dt ) {
663 $dates[] = $dt->format( 'Y-m-d' );
664 }
665
666 return $dates;
667 }
668
669 /**
670 * Convert an two dimentational array to one dimentional array object
671 *
672 * @param array $array array of arrays
673 *
674 * @return array
675 */
676 function erp_array_to_object( $array = [] ) {
677 $new_array = [];
678
679 if ( $array ) {
680 foreach ($array as $key => $value) {
681 $new_array[] = (object) $value;
682 }
683 }
684
685 return $new_array;
686 }
687
688 /**
689 * Check date in range or not
690 *
691 * @param date $start_date
692 * @param date $end_date
693 * @param date $date_from_user
694 *
695 * @return boolen
696 */
697 function erp_check_date_in_range( $start_date, $end_date, $date_from_user ) {
698 // Convert to timestamp
699 $start_ts = strtotime( $start_date );
700 $end_ts = strtotime( $end_date );
701 $user_ts = strtotime( $date_from_user );
702
703 // Check that user date is between start & end
704 if ( ($user_ts >= $start_ts) && ($user_ts <= $end_ts) ) {
705 return true;
706 }
707
708 return false;
709 }
710
711 /**
712 * Check date range any point in range or not
713 *
714 * @param date $start_date
715 * @param date $end_date
716 * @param date $user_date_start
717 * @param date $user_date_end
718 *
719 * @return boolen
720 */
721 function erp_check_date_range_in_range_exist( $start_date, $end_date, $user_date_start, $user_date_end ) {
722
723 if ( erp_check_date_in_range( $start_date, $end_date, $user_date_start ) ) {
724 return true;
725 }
726
727 if ( erp_check_date_in_range( $start_date, $end_date, $user_date_end ) ) {
728 return true;
729 }
730
731 return false;
732 }
733
734 /**
735 * Get durataion between two date
736 *
737 * @param date $start_date
738 * @param date $end_date
739 *
740 * @return integer
741 */
742 function erp_date_duration( $start_date, $end_date ) {
743 $datetime1 = new DateTime( $start_date );
744 $datetime2 = new DateTime( $end_date );
745 $interval = $datetime1->diff( $datetime2 );
746
747 return $interval->format('%a');
748 }
749
750 /**
751 * Performance rating elemet
752 *
753 * @since 0.1
754 *
755 * @param string $selected
756 *
757 * @return array
758 */
759 function erp_performance_rating( $selected = '' ) {
760
761 $rating = apply_filters( 'erp_performance_rating', array(
762 '1' => __( 'Very Bad', 'erp' ),
763 '2' => __( 'Poor', 'erp' ),
764 '3' => __( 'Average', 'erp' ),
765 '4' => __( 'Good', 'erp' ),
766 '5' => __( 'Excellent', 'erp' )
767 ) );
768
769 if ( $selected ) {
770 return isset( $rating[$selected] ) ? $rating[$selected] : '';
771 }
772
773 return $rating;
774 }
775
776 /**
777 * Get erp option from settings framework
778 *
779 * @param sting $option_name name of the option
780 * @param string $section name of the section. if it's a separate option, don't provide any
781 * @param string $default default option
782 *
783 * @return string
784 */
785 function erp_get_option( $option_name, $section = false, $default = '' ) {
786
787 if ( $section ) {
788 $option = get_option( $section );
789
790 if ( isset( $option[$option_name] ) ) {
791 return $option[$option_name];
792 } else {
793 return $default;
794 }
795 } else {
796 return get_option( $option_name, $default );
797 }
798 }
799
800 /**
801 * Get erp logo
802 *
803 * @return string url of the logo
804 */
805 function erp_get_site_logo() {
806 $logo = (int) erp_get_option( 'logo', 'erp_settings_design' );
807
808 if ( $logo ) {
809 $logo_url = wp_get_attachment_url( $logo );
810
811 return $logo_url;
812 }
813 }
814
815 /**
816 * Get month array
817 *
818 * @param string $title
819 *
820 * @since 0.1
821 *
822 * @return array
823 */
824 function erp_months_dropdown( $title = false ) {
825
826 $months = [];
827
828 if ( $title ) {
829 $months['-1'] = $title;
830 }
831
832 for ( $m = 1; $m <= 12; $m++ ) {
833 $months[$m] = date( 'F', mktime( 0, 0, 0, $m ) );
834 }
835
836 return $months;
837
838 }
839
840 /**
841 * Get Company financial start date
842 *
843 * @since 0.1
844 * @since 1.2.0 Using `erp_get_financial_year_dates` function
845 *
846 * @return string date
847 */
848 function erp_financial_start_date() {
849 $financial_year_dates = erp_get_financial_year_dates();
850 return $financial_year_dates['start'];
851 }
852
853 /**
854 * Get Company financial end date
855 *
856 * @since 0.1
857 * @since 1.2.0 Using `erp_get_financial_year_dates` function
858 *
859 * @return string date
860 */
861 function erp_financial_end_date() {
862 $financial_year_dates = erp_get_financial_year_dates();
863 return $financial_year_dates['end'];
864 }
865
866 /**
867 * Get all modules inserted in log table
868 *
869 * @since 0.1
870 *
871 * @return array
872 */
873 function erp_get_audit_log_modules() {
874 return \WeDevs\ERP\Admin\Models\Audit_Log::select( 'component' )->distinct()->get()->toArray();
875 }
876
877 /**
878 * Get all modules inserted in log table
879 *
880 * @since 0.1
881 *
882 * @return array
883 */
884 function erp_get_audit_log_sub_component() {
885 return \WeDevs\ERP\Admin\Models\Audit_Log::select( 'sub_component' )->distinct()->get()->toArray();
886 }
887
888 /**
889 * Erp Logging functions
890 *
891 * @since 0.1
892 *
893 * @return instance
894 */
895 function erp_log() {
896 return \WeDevs\ERP\Log::instance();
897 }
898
899 /**
900 * A file based logging function for debugging
901 *
902 * @since 0.1
903 *
904 * @param string $message
905 * @param string $type
906 *
907 * @return void
908 */
909 function erp_file_log( $message, $type = '' ) {
910 if ( ! empty( $type ) ) {
911 $message = sprintf( "[%s][%s] %s\n", date( 'd.m.Y h:i:s' ), $type, $message );
912 } else {
913 $message = sprintf( "[%s] %s\n", date( 'd.m.Y h:i:s' ), $message );
914 }
915
916 error_log( $message, 3, dirname( WPERP_FILE ) . '/debug.log' );
917 }
918
919 /**
920 * Get people types from various components
921 *
922 * @return array
923 */
924 function erp_get_people_types() {
925 return apply_filters( 'erp_people_types', [] );
926 }
927
928 /**
929 * Get Country name by country code
930 *
931 * @since 1.0
932 *
933 * @param string $code
934 *
935 * @return string
936 */
937 function erp_get_country_name( $country ) {
938
939 $load_cuntries_states = \WeDevs\ERP\Countries::instance();
940 $countries = $load_cuntries_states->countries;
941
942 // Handle full country name
943 if ( '-1' != $country ) {
944 $full_country = ( isset( $countries[ $country ] ) ) ? $countries[ $country ] : $country;
945 } else {
946 $full_country = '';
947 }
948
949 return $full_country;
950 }
951
952 /**
953 * Get State name by country and state code
954 *
955 * @since 1.0
956 *
957 * @param string $country
958 * @param string $state
959 *
960 * @return string
961 */
962 function erp_get_state_name( $country, $state ) {
963 $load_cuntries_states = \WeDevs\ERP\Countries::instance();
964 $states = $load_cuntries_states->states;
965
966 // Handle full state name
967 $full_state = ( $country && $state && isset( $states[ $country ][ $state ] ) ) ? $states[ $country ][ $state ] : $state;
968
969 return $full_state;
970 }
971
972 /**
973 * Cron Intervel
974 *
975 * @since 1.0
976 *
977 * @param array $schedules
978 *
979 * @return array
980 */
981 function erp_cron_intervals( $schedules ) {
982
983 $schedules['per_minute'] = array(
984 'interval' => MINUTE_IN_SECONDS,
985 'display' => __( 'Every Minute', 'erp' )
986 );
987
988 $schedules['two_min'] = array(
989 'interval' => MINUTE_IN_SECONDS * 2,
990 'display' => __( 'Every 2 Minutes', 'erp' )
991 );
992
993 $schedules['five_min'] = array(
994 'interval' => MINUTE_IN_SECONDS * 5,
995 'display' => __( 'Every 5 Minutes', 'erp' )
996 );
997
998 $schedules['ten_min'] = array(
999 'interval' => MINUTE_IN_SECONDS * 10,
1000 'display' => __( 'Every 10 Minutes', 'erp' )
1001 );
1002
1003 $schedules['fifteen_min'] = array(
1004 'interval' => MINUTE_IN_SECONDS * 15,
1005 'display' => __( 'Every 15 Minutes', 'erp' )
1006 );
1007
1008 $schedules['thirty_min'] = array(
1009 'interval' => MINUTE_IN_SECONDS * 30,
1010 'display' => __( 'Every 30 Minutes', 'erp' )
1011 );
1012
1013 $schedules['weekly'] = array(
1014 'interval' => DAY_IN_SECONDS * 7,
1015 'display' => __( 'Once Weekly', 'erp' )
1016 );
1017
1018 return (array)$schedules;
1019 }
1020
1021 /**
1022 * Show user own media attachment
1023 *
1024 * @since 1.0
1025 *
1026 * @param string $query
1027 *
1028 * @return string
1029 */
1030 function erp_show_users_own_attachments( $query ) {
1031 if ( ! is_user_logged_in() ) {
1032 return $query;
1033 }
1034
1035 $id = get_current_user_id();
1036
1037 if ( ! current_user_can( 'manage_options' ) ) {
1038 if ( current_user_can( 'erp_hr_manager' )
1039 || current_user_can( 'employee' )
1040 || current_user_can( 'erp_crm_manager' )
1041 || current_user_can( 'erp_crm_agent' )
1042 ) {
1043 $query['author'] = $id;
1044 }
1045 }
1046
1047 return $query;
1048 }
1049
1050 /**
1051 * Get all registered addons for licensing
1052 *
1053 * @since 1.0
1054 *
1055 * @return array
1056 */
1057 function erp_addon_licenses() {
1058 $licenses = [];
1059
1060 return apply_filters( 'erp_settings_licenses', $licenses );
1061 }
1062
1063 /**
1064 * Show a readable message about the license status
1065 *
1066 * @since 1.0
1067 *
1068 * @param array $addon
1069 *
1070 * @return string
1071 */
1072 function erp_get_license_status( $addon ) {
1073 if ( ! is_object( $addon['status'] ) ) {
1074 return false;
1075 }
1076
1077 $messages = [];
1078 $html = '';
1079 $license = $addon['status'];
1080 $status_class = 'has-error';
1081
1082 if ( false === $license->success ) {
1083
1084 switch( $license->error ) {
1085
1086 case 'expired' :
1087
1088 $messages[] = sprintf(
1089 __( 'Your license key expired on %s. Please <a href="%s" target="_blank" title="Renew your license key">renew your license key</a>.', 'erp' ),
1090 date_i18n( get_option( 'date_format' ), strtotime( $license->expires, current_time( 'timestamp' ) ) ),
1091 'https://wperp.com/checkout/?edd_license_key=' . $addon['license'] . '&utm_campaign=admin&utm_source=licenses&utm_medium=expired'
1092 );
1093 break;
1094
1095 case 'missing' :
1096
1097 $messages[] = sprintf(
1098 __( 'Invalid license. Please <a href="%s" target="_blank" title="Visit account page">visit your account page</a> and verify it.', 'erp' ),
1099 'https://wperp.com/my-account?utm_campaign=admin&utm_source=licenses&utm_medium=missing'
1100 );
1101 break;
1102
1103 case 'invalid' :
1104 case 'site_inactive' :
1105
1106 $messages[] = sprintf(
1107 __( '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' ),
1108 $addon['name'],
1109 'https://wperp.com/my-account?utm_campaign=admin&utm_source=licenses&utm_medium=invalid'
1110 );
1111 break;
1112
1113 case 'item_name_mismatch' :
1114
1115 $messages[] = sprintf( __( 'This is not a %s.', 'erp' ), $addon['name'] );
1116 break;
1117
1118 case 'no_activations_left':
1119 $messages[] = sprintf( __( 'Your license key has reached its activation limit. <a href="%s">View possible upgrades</a> now.', 'erp' ), 'https://wperp.com/my-account/' );
1120 break;
1121
1122 }
1123 } else {
1124
1125 switch( $license->license ) {
1126 case 'expired' :
1127
1128 $messages[] = sprintf(
1129 __( 'Your license key expired on %s. Please <a href="%s" target="_blank" title="Renew your license key">renew your license key</a>.', 'erp' ),
1130 date_i18n( get_option( 'date_format' ), strtotime( $license->expires, current_time( 'timestamp' ) ) ),
1131 'https://wperp.com/checkout/?edd_license_key=' . $addon['license'] . '&utm_campaign=admin&utm_source=licenses&utm_medium=expired'
1132 );
1133 break;
1134
1135 case 'valid':
1136 $status_class = 'no-error';
1137 $now = current_time( 'timestamp' );
1138 $expiration = strtotime( $license->expires, current_time( 'timestamp' ) );
1139
1140 if ( 'lifetime' === $license->expires ) {
1141
1142 $messages[] = __( 'License key never expires.', 'erp' );
1143
1144 } elseif( $expiration > $now && $expiration - $now < ( DAY_IN_SECONDS * 30 ) ) {
1145
1146 $messages[] = sprintf(
1147 __( 'Your license key expires soon! It expires on %s. <a href="%s" target="_blank" title="Renew license">Renew your license key</a>.', 'erp' ),
1148 date_i18n( get_option( 'date_format' ), strtotime( $license->expires, current_time( 'timestamp' ) ) ),
1149 'https://wperp.com/checkout/?edd_license_key=' . $value . '&utm_campaign=admin&utm_source=licenses&utm_medium=renew'
1150 );
1151
1152 } else {
1153
1154 $messages[] = sprintf(
1155 __( 'Your license key expires on %s.', 'erp' ),
1156 date_i18n( get_option( 'date_format' ), strtotime( $license->expires, current_time( 'timestamp' ) ) )
1157 );
1158
1159 }
1160 break;
1161 }
1162
1163 }
1164
1165 if ( ! empty( $messages ) ) {
1166 foreach( $messages as $message ) {
1167
1168 $html .= '<div class="erp-license-status ' . $status_class . '">';
1169 $html .= '<p class="help">' . $message . '</p>';
1170 $html .= '</div>';
1171
1172 }
1173 }
1174
1175 return $html;
1176 }
1177
1178 /**
1179 * Get all fields for import/export operation.
1180 *
1181 * @return array
1182 */
1183 function erp_get_import_export_fields() {
1184 $erp_fields = [
1185 'contact' => [
1186 'required_fields' => [
1187 'first_name',
1188 ],
1189 'fields' => [
1190 'first_name',
1191 'last_name',
1192 'email',
1193 'phone',
1194 'mobile',
1195 'other',
1196 'website',
1197 'fax',
1198 'notes',
1199 'street_1',
1200 'street_2',
1201 'city',
1202 'state',
1203 'postal_code',
1204 'country',
1205 'currency',
1206 ]
1207 ],
1208 'company' => [
1209 'required_fields' => [
1210 'email',
1211 'company',
1212 ],
1213 'fields' => [
1214 'email',
1215 'company',
1216 'phone',
1217 'mobile',
1218 'other',
1219 'website',
1220 'fax',
1221 'notes',
1222 'street_1',
1223 'street_2',
1224 'city',
1225 'state',
1226 'postal_code',
1227 'country',
1228 'currency',
1229 ]
1230 ],
1231 'employee' => [
1232 'required_fields' => [
1233 'first_name',
1234 'last_name',
1235 'user_email',
1236 ],
1237 'fields' => [
1238 'first_name',
1239 'middle_name',
1240 'last_name',
1241 'user_email',
1242 'designation',
1243 'department',
1244 'location',
1245 'hiring_source',
1246 'hiring_date',
1247 'date_of_birth',
1248 'reporting_to',
1249 'pay_rate',
1250 'pay_type',
1251 'type',
1252 'status',
1253 'other_email',
1254 'phone',
1255 'work_phone',
1256 'mobile',
1257 'address',
1258 'gender',
1259 'marital_status',
1260 'nationality',
1261 'driving_license',
1262 'hobbies',
1263 'user_url',
1264 'description',
1265 'street_1',
1266 'street_2',
1267 'city',
1268 'country',
1269 'state',
1270 'postal_code',
1271 ]
1272 ]
1273 ];
1274
1275 return apply_filters( 'erp_import_export_csv_fields', $erp_fields );
1276 }
1277
1278 /**
1279 * ERP Import/Export JavaScript enqueue.
1280 *
1281 * @since 1.0
1282 *
1283 * @return void
1284 */
1285 function erp_import_export_javascript() {
1286 global $current_screen;
1287 $hook = str_replace( sanitize_title( __( 'ERP Settings', 'erp' ) ) , 'erp-settings', $current_screen->base );
1288
1289 if ( 'erp-settings_page_erp-tools' !== $hook ) {
1290 return;
1291 }
1292
1293 if ( ! isset( $_GET['tab'] ) || ! in_array( $_GET['tab'], ['import', 'export'] ) ) {
1294 return;
1295 }
1296
1297 $erp_fields = erp_get_import_export_fields();
1298 ?>
1299 <script type="text/javascript">
1300 jQuery( document ).ready( function( $ ) {
1301
1302 function erp_str_title_case( string ) {
1303 var str = string.replace( /_/g, ' ' );
1304
1305 return str.toLowerCase().split( ' ' ).map( function ( word ) {
1306 return ( word.charAt( 0 ).toUpperCase() + word.slice( 1 ) );
1307 } ).join(' ');
1308 }
1309
1310 function erp_csv_field_mapper( file_selector, fields_selector ) {
1311 var file = file_selector.files[0];
1312
1313 var reader = new FileReader();
1314
1315 var first5000 = file.slice( 0, 5000 );
1316 reader.readAsText( first5000 );
1317
1318 reader.onload = function( e ) {
1319 var csv = reader.result;
1320 // Split the input into lines
1321 lines = csv.split('\n'),
1322 // Extract column names from the first line
1323 columnNamesLine = lines[0];
1324 columnNames = columnNamesLine.split(',');
1325
1326 var html = '';
1327
1328 html += '<option value="">&mdash; Select Field &mdash;</option>';
1329 columnNames.forEach( function( item, index ) {
1330 item = item.replace( /"/g, "" );
1331
1332 html += '<option value="' + index + '">' + item + '</option>';
1333 } );
1334
1335 if ( html ) {
1336 $( fields_selector ).html( html );
1337
1338 var field, field_label;
1339 $( fields_selector ).each( function() {
1340 field_label = $( this ).parent().parent().find( 'label' ).text();
1341
1342 var options = $( this ).find( 'option' );
1343 var targetOption = $( options ).filter ( function () {
1344 var option_text = $( this ).html();
1345
1346 var re = new RegExp( field_label, 'i' );
1347
1348 return re.test( option_text );
1349 } );
1350
1351 if ( targetOption ) {
1352 $( options ).removeAttr( "selected" );
1353 $( this ).val( $( targetOption ).val() );
1354 }
1355 } );
1356 }
1357 };
1358 }
1359
1360 function erp_csv_importer_field_handler( file_selector ) {
1361 $( '#fields_container' ).show();
1362
1363 var fields_html = '';
1364
1365 var type = $( 'form#import_form #type' ).val();
1366
1367 fields = erp_fields[ type ] ? erp_fields[ type ].fields : [];
1368 required_fields = erp_fields[ type ] ? erp_fields[ type ].required_fields : [];
1369
1370 var required = '';
1371 var red_span = '';
1372 for ( var i = 0; i < fields.length; i++ ) {
1373
1374 if ( required_fields.indexOf( fields[i] ) !== -1 ) {
1375 required = 'required';
1376 red_span = ' <span class="required">*</span>';
1377 } else {
1378 required = '';
1379 red_span = '';
1380 }
1381
1382 fields_html += `
1383 <tr>
1384 <th>
1385 <label for="fields[` + fields[i] + `]" class="csv_field_labels">` + erp_str_title_case( fields[i] ) + red_span + `</label>
1386 </th>
1387 <td>
1388 <select name="fields[` + fields[i] + `]" class="csv_fields" ` + required + `>
1389 </select>
1390 </td>
1391 </tr>`;
1392 }
1393
1394 $( '#fields_container' ).html( fields_html );
1395
1396 erp_csv_field_mapper( file_selector, '.csv_fields' );
1397 }
1398
1399 var fields = [];
1400 var required_fields = [];
1401
1402 var erp_fields = <?php echo json_encode( $erp_fields ) ; ?>;
1403
1404 var type = $( 'form#export_form #type' ).val();
1405
1406 fields = erp_fields[ type ] ? erp_fields[ type ].fields : [];
1407
1408 var html = '<ul class="erp-list list-inline">';
1409 for ( var i = 0; i < fields.length; i++ ) {
1410 html += '<li><label><input type="checkbox" name="fields[]" value="' + fields[i] + '"> ' + erp_str_title_case( fields[i] ) + '</label></li>';
1411 }
1412
1413 html += '<ul>';
1414
1415 if ( html ) {
1416 $( '#fields' ).html( html );
1417 }
1418
1419 $( 'form#export_form #type' ).on( 'change', function( e ) {
1420 e.preventDefault();
1421
1422 $( "#export_form #selecctall" ).prop( 'checked', false );
1423 var type = $( this ).val();
1424 fields = erp_fields[ type ] ? erp_fields[ type ].fields : [];
1425
1426 html = '<ul class="erp-list list-inline">';
1427 for ( var i = 0; i < fields.length; i++ ) {
1428 html += '<li><label><input type="checkbox" name="fields[]" value="' + fields[i] + '"> ' + erp_str_title_case( fields[i] ) + '</label></li>';
1429 }
1430
1431 html += '<ul>';
1432
1433 if ( html ) {
1434 $( 'form#export_form #fields' ).html( html );
1435 }
1436 });
1437
1438 $( 'form#import_form #csv_file' ).on( 'change', function( e ) {
1439 e.preventDefault();
1440
1441 if ( ! this ) {
1442 return;
1443 }
1444
1445 erp_csv_importer_field_handler( this );
1446 });
1447
1448 if ( $( 'form#import_form' ).find( '#type' ).val() == 'employee' ) {
1449 $( 'form#import_form' ).find( '#crm_contact_lifestage_owner_wrap' ).hide();
1450 } else {
1451 $( 'form#import_form' ).find( '#crm_contact_lifestage_owner_wrap' ).show();
1452 }
1453
1454 $( 'form#import_form #type' ).on( 'change', function( e ) {
1455 $( '#fields_container' ).html( '' );
1456 $( '#fields_container' ).hide();
1457
1458 if ( $( this ).val() == 'employee' ) {
1459 $( 'form#import_form' ).find( '#crm_contact_lifestage_owner_wrap' ).hide();
1460 } else {
1461 $( 'form#import_form' ).find( '#crm_contact_lifestage_owner_wrap' ).show();
1462 }
1463
1464 var sample_csv_url = $( 'form#import_form' ).find( '#download_sample_wrap input' ).val();
1465 $( 'form#import_form' ).find( '#download_sample_wrap a' ).attr( 'href', sample_csv_url + '&type=' + $( this ).val() );
1466
1467 if ( $( 'form#import_form #csv_file' ).val() == "" ) {
1468 return;
1469 } else {
1470 erp_csv_importer_field_handler( $( 'form#import_form #csv_file' ).get(0) );
1471 }
1472 } );
1473
1474 $( "#export_form #selecctall" ).change( function(e) {
1475 e.preventDefault();
1476
1477 $( "#export_form #fields input[type=checkbox]" ).prop( 'checked', $(this).prop( "checked" ) );
1478 });
1479
1480 $( "#users_import_form" ).on( 'submit', function(e) {
1481 e.preventDefault();
1482 statusDiv = $( "div#import-status-indicator" );
1483
1484 statusDiv.show();
1485
1486 var form = $(this),
1487 submit = form.find( 'input[type=submit]' );
1488 submit.attr( 'disabled', 'disabled' );
1489
1490 var data = {
1491 'action': 'erp_import_users_as_contacts',
1492 'user_role': $(this).find('select[name=user_role]').val(),
1493 'contact_owner': $(this).find('select[name=contact_owner]').val(),
1494 'life_stage': $(this).find('select[name=life_stage]').val(),
1495 'contact_group': $(this).find('select[name=contact_group]').val(),
1496 '_wpnonce': $(this).find('input[name=_wpnonce]').val()
1497 };
1498
1499 var total_items = 0, left = 0, imported = 0, exists = 0, percent = 0, type = 'success', message = '';
1500
1501 $.post( ajaxurl, data, function(response) {
1502 if ( response.success ) {
1503 total_items = response.data.total_items;
1504 left = response.data.left;
1505 exists = response.data.exists;
1506 imported = total_items - left;
1507 done = imported - exists;
1508
1509 if ( imported > 0 || total_items > 0 ) {
1510 percent = Math.floor( ( 100 / total_items ) * ( imported ) );
1511
1512 type = 'success';
1513 message = 'Successfully imported all users!';
1514 } else {
1515 message = 'No users found to import!';
1516 type = 'error';
1517 }
1518
1519 statusDiv.find( '#progress-total' ).html( percent + '%' );
1520 statusDiv.find( '#progressbar-total' ).val( percent );
1521 statusDiv.find( '#completed-total' ).html( 'Imported ' + done + ' out of ' + response.data.total_items );
1522 if ( exists > 0 ) {
1523 statusDiv.find( '#failed-total' ).html( 'Already Exist ' + exists );
1524 }
1525
1526 if ( response.data.left > 0 ) {
1527 form.submit();
1528 return;
1529 } else {
1530 submit.removeAttr( 'disabled' );
1531
1532 swal({
1533 title: '',
1534 text: message,
1535 type: type,
1536 confirmButtonText: 'OK',
1537 confirmButtonColor: '#008ec2'
1538 });
1539 }
1540 }
1541 });
1542 });
1543
1544 });
1545 </script>
1546 <?php
1547 }
1548
1549 /**
1550 * Process or handle import/export submit.
1551 *
1552 * @since 1.0.0
1553 * @since 1.1.15 Declare `field_builder_contacts_fields` with empty an array
1554 * @since 1.1.18 Handle exporting when no field is given.
1555 * Introduce `ERP_IS_IMPORTING` while importing data
1556 * @since 1.1.19 Import partial people data in case of existing people
1557 *
1558 * @return void
1559 */
1560 function erp_process_import_export() {
1561 if ( ! isset( $_REQUEST['_wpnonce'] ) || ! wp_verify_nonce( $_REQUEST['_wpnonce'], 'erp-import-export-nonce' ) ) {
1562 return;
1563 }
1564
1565 $is_crm_activated = erp_is_module_active( 'crm' );
1566 $is_hrm_activated = erp_is_module_active( 'hrm' );
1567
1568 $departments = $is_hrm_activated ? erp_hr_get_departments_dropdown_raw() : [];
1569 $designations = $is_hrm_activated ? erp_hr_get_designation_dropdown_raw() : [];
1570
1571 $field_builder_contact_options = get_option( 'erp-contact-fields' );
1572 $field_builder_contacts_fields = [];
1573
1574 if ( ! empty( $field_builder_contact_options ) ) {
1575 foreach ( $field_builder_contact_options as $field ) {
1576 $field_builder_contacts_fields[] = $field['name'];
1577 }
1578 }
1579
1580 $field_builder_employee_options = get_option( 'erp-employee-fields' );
1581
1582 if ( ! empty( $field_builder_employee_options ) ) {
1583 foreach ( $field_builder_employee_options as $field ) {
1584 $field_builder_employees_fields[] = $field['name'];
1585 }
1586 }
1587
1588 if ( isset( $_POST['erp_import_csv'] ) ) {
1589 define( 'ERP_IS_IMPORTING' , true );
1590
1591 $fields = ! empty( $_POST['fields'] ) ? $_POST['fields'] : [];
1592 $type = isset( $_POST['type'] ) ? $_POST['type'] : '';
1593
1594 if ( empty( $type ) ) {
1595 return;
1596 }
1597
1598 $data = ['type' => $type, 'fields' => $fields, 'file' => $_FILES['csv_file'] ];
1599
1600 do_action( 'erp_tool_import_csv_action', $data );
1601
1602 if ( ! in_array( $type, ['contact', 'company', 'employee'] ) ) {
1603 return;
1604 }
1605
1606 $employee_fields = [
1607 'work' => [
1608 'designation',
1609 'department',
1610 'location',
1611 'hiring_source',
1612 'hiring_date',
1613 'date_of_birth',
1614 'reporting_to',
1615 'pay_rate',
1616 'pay_type',
1617 'type',
1618 'status',
1619 ],
1620 'personal' => [
1621 'photo_id',
1622 'user_id',
1623 'first_name',
1624 'middle_name',
1625 'last_name',
1626 'other_email',
1627 'phone',
1628 'work_phone',
1629 'mobile',
1630 'address',
1631 'gender',
1632 'marital_status',
1633 'nationality',
1634 'driving_license',
1635 'hobbies',
1636 'user_url',
1637 'description',
1638 'street_1',
1639 'street_2',
1640 'city',
1641 'country',
1642 'state',
1643 'postal_code',
1644 ]
1645 ];
1646
1647 require_once WPERP_INCLUDES . '/lib/parsecsv.lib.php';
1648
1649 $csv = new parseCSV( $_FILES['csv_file']['tmp_name'] );
1650
1651 if ( empty( $csv->data ) ) {
1652 wp_redirect( admin_url( "admin.php?page=erp-tools&tab=import" ) );
1653 exit;
1654 }
1655
1656 $csv_data = [];
1657
1658 $csv_data[] = array_keys( $csv->data[0] );
1659
1660 foreach ( $csv->data as $data_item ) {
1661 $csv_data[] = array_values( $data_item );
1662 }
1663
1664 if ( ! empty( $csv_data ) ) {
1665 $count = 0;
1666
1667 foreach ( $csv_data as $line ){
1668 if ( empty( $line ) ) {
1669 continue;
1670 }
1671
1672 $line_data = [];
1673
1674 foreach ( $fields as $key => $value ) {
1675
1676 if ( ! empty( $line[ $value ] ) && is_numeric( $value ) ) {
1677 if ( $type == 'employee' ) {
1678 if ( in_array( $key, $employee_fields['work'] ) ) {
1679 if ( $key == 'designation' ) {
1680 $line_data['work'][ $key ] = array_search( $line[ $value ], $designations );
1681 } else if ( $key == 'department' ) {
1682 $line_data['work'][ $key ] = array_search( $line[ $value ], $departments );
1683 } else {
1684 $line_data['work'][ $key ] = $line[ $value ];
1685 }
1686
1687 } else if ( in_array( $key, $employee_fields['personal'] ) ) {
1688 $line_data['personal'][ $key ] = $line[ $value ];
1689 } else {
1690 $line_data[ $key ] = $line[ $value ];
1691 }
1692 } else {
1693 $line_data[ $key ] = isset( $line[ $value ] ) ? $line[ $value ] : '';
1694 $line_data['type'] = $type;
1695 }
1696 }
1697
1698 }
1699
1700 if ( $type == 'employee' && $is_hrm_activated ) {
1701 if ( ! isset( $line_data['work']['status'] ) ) {
1702 $line_data['work']['status'] = 'active';
1703 }
1704
1705 $item_insert_id = erp_hr_employee_create( $line_data );
1706
1707 if ( is_wp_error( $item_insert_id ) ) {
1708 continue;
1709 }
1710 }
1711
1712 if ( ( $type == 'contact' || $type == 'company' ) && $is_crm_activated ) {
1713 $people = erp_insert_people( $line_data, true );
1714
1715 if ( is_wp_error( $people ) ) {
1716 continue;
1717 } else {
1718 $contact = new \WeDevs\ERP\CRM\Contact( absint( $people->id ), 'contact' );
1719 $contact_owner = isset( $_POST['contact_owner'] ) ? absint( $_POST['contact_owner'] ) : erp_crm_get_default_contact_owner();
1720 $life_stage = isset( $_POST['life_stage'] ) ? sanitize_key( $_POST['life_stage'] ) : '';
1721
1722 if ( ! $people->existing ) {
1723 $contact->update_meta( 'life_stage', $life_stage );
1724 $contact->update_meta( 'contact_owner', $contact_owner );
1725
1726 } else {
1727 if ( ! $contact->get_life_stage() ) {
1728 $contact->update_meta( 'life_stage', $life_stage );
1729 }
1730
1731 if ( ! $contact->get_contact_owner() ) {
1732 $contact->update_meta( 'contact_owner', $contact_owner );
1733 }
1734 }
1735
1736 if ( ! empty( $_POST['contact_group'] ) ) {
1737 $contact_group = absint( $_POST['contact_group'] );
1738
1739 $existing_data = \WeDevs\ERP\CRM\Models\ContactSubscriber::where( [ 'group_id' => $contact_group, 'user_id' => $people->id ] )->first();
1740
1741 if ( empty( $existing_data ) ) {
1742 $hash = sha1( microtime() . 'erp-subscription-form' . $contact_group . $people->id );
1743
1744 erp_crm_create_new_contact_subscriber([
1745 'group_id' => $contact_group,
1746 'user_id' => $people->id,
1747 'status' => 'subscribe',
1748 'subscribe_at' => current_time( 'mysql' ),
1749 'unsubscribe_at' => null,
1750 'hash' => $hash
1751 ]);
1752 }
1753 }
1754
1755
1756 if ( ! empty( $field_builder_contacts_fields ) ) {
1757 foreach ( $field_builder_contacts_fields as $field ) {
1758 if ( isset( $line_data[ $field ] ) ) {
1759 erp_people_update_meta( $people->id, $field, $line_data[ $field ] );
1760 }
1761 }
1762 }
1763 }
1764 }
1765
1766 ++$count;
1767 }
1768
1769 }
1770
1771 wp_redirect( admin_url( "admin.php?page=erp-tools&tab=import&imported=$count" ) );
1772 exit;
1773 }
1774
1775 if ( isset( $_POST['erp_export_csv'] ) ) {
1776 if ( ! empty( $_POST['type'] ) && ! empty( $_POST['fields'] ) ) {
1777 $type = $_POST['type'];
1778 $fields = $_POST['fields'];
1779
1780 if ( $type == 'employee' && $is_hrm_activated ) {
1781 $args = [
1782 'number' => -1,
1783 'status' => 'all'
1784 ];
1785
1786 $items = erp_hr_get_employees( $args );
1787 }
1788
1789 if( ($type == 'contact' || $type == 'company') && $is_crm_activated ) {
1790 $args = [
1791 'type' => $type,
1792 'count' => true,
1793 ];
1794 $total_items = erp_get_peoples( $args );
1795
1796 $args = [
1797 'type' => $type,
1798 'offset' => 0,
1799 'number' => -1,
1800 ];
1801 $items = erp_get_peoples( $args );
1802 }
1803
1804 //@todo do_action()
1805
1806 $csv_items = [];
1807
1808 $x = 0;
1809 foreach ( $items as $item ) {
1810
1811 if ( empty( $fields ) ) {
1812 continue;
1813 }
1814
1815 foreach ( $fields as $field ) {
1816 if ( $type == 'employee' ) {
1817
1818 if ( in_array( $field, $field_builder_employees_fields ) ) {
1819 $csv_items[ $x ][ $field ] = get_user_meta( $item->id, $field, true );
1820 } else {
1821 switch ( $field ) {
1822 case 'department':
1823 $csv_items[ $x ][ $field ] = $item->get_department_title();
1824 break;
1825
1826 case 'designation':
1827 $csv_items[ $x ][ $field ] = $item->get_job_title();
1828 break;
1829
1830 default:
1831 $csv_items[ $x ][ $field ] = $item->{$field};
1832 break;
1833 }
1834 }
1835
1836 } else {
1837 if ( in_array( $field, $field_builder_contacts_fields ) ) {
1838 $csv_items[ $x ][ $field ] = erp_people_get_meta( $item->id, $field, true );
1839 } else {
1840 if ( isset( $item->{$field} ) ) {
1841 $csv_items[ $x ][ $field ] = $item->{$field};
1842 }
1843 }
1844 }
1845 }
1846
1847 $x++;
1848 }
1849
1850 $file_name = 'export_' . date( 'd_m_Y' ) . '.csv';
1851
1852 erp_make_csv_file( $csv_items, $file_name );
1853
1854 } else {
1855 wp_redirect( admin_url( "admin.php?page=erp-tools&tab=export" ) );
1856 exit();
1857 }
1858 }
1859 }
1860
1861 /**
1862 * Display importer tool notice.
1863 *
1864 *
1865 * @return void
1866 */
1867 function erp_importer_notices() {
1868 if ( ! isset( $_REQUEST['page'] ) || $_REQUEST['page'] != 'erp-tools' || ! isset( $_REQUEST['tab'] ) || $_REQUEST['tab'] != 'import' ) {
1869 return;
1870 }
1871
1872 if ( isset( $_REQUEST['imported'] ) ) {
1873 if ( intval( $_REQUEST['imported'] ) == 0 ) {
1874 $message = __( 'Nothing to import or items are already exists.', 'erp' );
1875 echo "<div class='notice error'><p>{$message}</p></div>";
1876 } else {
1877 $message = sprintf( __( '%s items successfully imported.', 'erp' ), number_format_i18n( $_REQUEST['imported'] ) );
1878 echo "<div class='notice updated'><p>{$message}</p></div>";
1879 }
1880 }
1881 }
1882
1883 /**
1884 * Merge user defined arguments into defaults array.
1885 *
1886 * This function is similiar to wordpress wp_parse_args().
1887 * It's support multidimensional array.
1888 *
1889 * @param array $args
1890 * @param array $defaults Optional.
1891 *
1892 * @return array
1893 */
1894 function erp_parse_args_recursive( &$args, $defaults = [] ) {
1895 $args = (array) $args;
1896 $defaults = (array) $defaults;
1897 $r = $defaults;
1898
1899 foreach ( $args as $k => &$v ) {
1900 if ( is_array( $v ) && isset( $r[ $k ] ) ) {
1901 $r[ $k ] = erp_parse_args_recursive( $v, $r[ $k ] );
1902 } else {
1903 $r[ $k ] = $v;
1904 }
1905 }
1906
1907 return $r;
1908 }
1909
1910 /**
1911 * ERP Email sender
1912 *
1913 * @since 1.1.0
1914 * @since 1.1.17 Use site name instead of current user name for default From header
1915 * @since 1.2.0 Always return true during any importing process
1916 *
1917 * @param string|array $to
1918 * @param string $subject
1919 * @param string $message
1920 * @param string|array $headers
1921 * @param array $attachments
1922 * @param array $custom_headers
1923 *
1924 * @return boolean
1925 */
1926 function erp_mail( $to, $subject, $message, $headers = '', $attachments = [], $custom_headers = [] ) {
1927
1928 if ( defined( 'ERP_IS_IMPORTING' ) && ERP_IS_IMPORTING ) {
1929 return true;
1930 }
1931
1932 $callback = function( $phpmailer ) use( $custom_headers ) {
1933 $erp_email_settings = get_option( 'erp_settings_erp-email_general', [] );
1934 $erp_email_smtp_settings = get_option( 'erp_settings_erp-email_smtp', [] );
1935
1936 if ( ! isset( $erp_email_settings['from_email'] ) ) {
1937 $from_email = get_option( 'admin_email' );
1938 } else {
1939 $from_email = $erp_email_settings['from_email'];
1940 }
1941
1942 if ( ! isset( $erp_email_settings['from_name'] ) ) {
1943 $from_name = get_bloginfo( 'name' );
1944 } else {
1945 $from_name = $erp_email_settings['from_name'];
1946 }
1947
1948 $content_type = 'text/html';
1949
1950 $phpmailer->From = apply_filters( 'erp_mail_from', $from_email );
1951 $phpmailer->FromName = apply_filters( 'erp_mail_from_name', $from_name );
1952 $phpmailer->ContentType = apply_filters( 'erp_mail_content_type', $content_type );
1953
1954 //Return-Path
1955 $phpmailer->Sender = apply_filters( 'erp_mail_return_path', $phpmailer->From );
1956
1957 if ( ! empty( $custom_headers ) ) {
1958 foreach ( $custom_headers as $key => $value ) {
1959 $phpmailer->addCustomHeader( $key, $value );
1960 }
1961 }
1962
1963 if ( isset( $erp_email_smtp_settings['debug'] ) && $erp_email_smtp_settings['debug'] == 'yes' ) {
1964 $phpmailer->SMTPDebug = true;
1965 }
1966
1967 if ( isset( $erp_email_smtp_settings['enable_smtp'] ) && $erp_email_smtp_settings['enable_smtp'] == 'yes' ) {
1968 $phpmailer->Mailer = 'smtp'; //'smtp', 'mail', or 'sendmail'
1969
1970 $phpmailer->Host = $erp_email_smtp_settings['mail_server'];
1971 $phpmailer->SMTPSecure = ( $erp_email_smtp_settings['authentication'] != '' ) ? $erp_email_smtp_settings['authentication'] : 'smtp';
1972 $phpmailer->Port = $erp_email_smtp_settings['port'];
1973
1974 if ( $erp_email_smtp_settings['authentication'] != '' ) {
1975 $phpmailer->SMTPAuth = true;
1976 $phpmailer->Username = $erp_email_smtp_settings['username'];
1977 $phpmailer->Password = $erp_email_smtp_settings['password'];
1978 }
1979 }
1980 };
1981
1982 add_action( 'phpmailer_init', $callback );
1983
1984 ob_start();
1985 $is_mail_sent = wp_mail( $to, $subject, $message, $headers, $attachments );
1986 $debug_log = ob_get_clean();
1987 if ( ! $is_mail_sent ) {
1988 error_log( $debug_log );
1989 }
1990
1991 remove_action( 'phpmailer_init', $callback );
1992
1993 return $is_mail_sent;
1994 }
1995
1996 /**
1997 * Email JavaScript enqueue.
1998 *
1999 * @return void
2000 */
2001 function erp_email_settings_javascript() {
2002 wp_enqueue_style( 'erp-sweetalert' );
2003 wp_enqueue_script( 'erp-sweetalert' );
2004 ?>
2005 <script type="text/javascript">
2006 jQuery( document ).ready( function($) {
2007 $( "a#smtp-test-connection" ).click( function(e) {
2008 e.preventDefault();
2009 $( "a#smtp-test-connection" ).attr( 'disabled', 'disabled' );
2010 $( "a#smtp-test-connection" ).parent().find( '.erp-loader' ).show();
2011
2012 var data = {
2013 'action': 'erp_smtp_test_connection',
2014 'enable_smtp': $('input[name=enable_smtp]:checked').val(),
2015 'mail_server': $('input[name=mail_server]').val(),
2016 'port': $('input[name=port]').val(),
2017 'authentication': $('select[name=authentication]').val(),
2018 'username': $('input[name=username]').val(),
2019 'password': $('input[name=password]').val(),
2020 'to' : $('#smtp_test_email_address').val(),
2021 '_wpnonce': '<?php echo wp_create_nonce( "erp-smtp-test-connection-nonce" ); ?>'
2022 };
2023
2024 $.post( ajaxurl, data, function(response) {
2025 $( "a#smtp-test-connection" ).removeAttr( 'disabled' );
2026 $( "a#smtp-test-connection" ).parent().find( '.erp-loader' ).hide();
2027
2028 var type = response.success ? 'success' : 'error';
2029
2030 if (response.data) {
2031 swal({
2032 title: '',
2033 text: response.data,
2034 type: type,
2035 confirmButtonText: 'OK',
2036 confirmButtonColor: '#008ec2'
2037 });
2038 }
2039 });
2040 });
2041 });
2042
2043 jQuery( document ).ready( function($) {
2044 $( "a#imap-test-connection" ).click( function(e) {
2045 e.preventDefault();
2046 $( "a#imap-test-connection" ).attr( 'disabled', 'disabled' );
2047 $( "a#imap-test-connection" ).parent().find( '.erp-loader' ).show();
2048
2049 var data = {
2050 'action': 'erp_imap_test_connection',
2051 'mail_server': $('input[name=mail_server]').val(),
2052 'username': $('input[name=username]').val(),
2053 'password': $('input[name=password]').val(),
2054 'protocol': $('select[name=protocol]').val(),
2055 'port': $('input[name=port]').val(),
2056 'authentication': $('select[name=authentication]').val(),
2057 '_wpnonce': '<?php echo wp_create_nonce( "erp-imap-test-connection-nonce" ); ?>'
2058 };
2059
2060 $.post( ajaxurl, data, function(response) {
2061 $( "a#imap-test-connection" ).removeAttr( 'disabled' );
2062 $( "a#imap-test-connection" ).parent().find( '.erp-loader' ).hide();
2063
2064 var type = response.success ? 'success' : 'error';
2065
2066 if ( response.data ) {
2067 var status = response.success ? 1 : 0;
2068 $('#imap_status').val(status);
2069
2070 swal({
2071 title: '',
2072 text: response.data,
2073 type: type,
2074 confirmButtonText: 'OK',
2075 confirmButtonColor: '#008ec2'
2076 });
2077 }
2078 });
2079 });
2080 });
2081 </script>
2082 <?php
2083 }
2084
2085 /**
2086 * Determine if the inbound/imap mail feature is active or not.
2087 *
2088 * @return boolean
2089 */
2090 function erp_is_imap_active() {
2091 $options = get_option( 'erp_settings_erp-email_imap', [] );
2092
2093 $imap_status = (boolean) isset( $options['imap_status'] ) ? $options['imap_status'] : 0;
2094 $enable_imap = ( isset( $options['enable_imap'] ) && $options['enable_imap'] == 'yes' ) ? true : false;
2095
2096 if ( $enable_imap && $imap_status ) {
2097 return true;
2098 }
2099
2100 return false;
2101 }
2102
2103 /**
2104 * Check if the ERP Email SMTP settings is enabled or not
2105 *
2106 * @since 1.1.6
2107 *
2108 * @return boolean
2109 */
2110 function erp_is_smtp_enabled() {
2111 $erp_email_smtp_settings = get_option( 'erp_settings_erp-email_smtp', [] );
2112
2113 if ( isset( $erp_email_smtp_settings['enable_smtp'] ) && filter_var( $erp_email_smtp_settings['enable_smtp'], FILTER_VALIDATE_BOOLEAN ) ) {
2114 return true;
2115 }
2116
2117 return false;
2118 }
2119
2120 /**
2121 * Determine if the module is active or not.
2122 *
2123 * @return boolean
2124 */
2125 function erp_is_module_active( $module_key ) {
2126 $modules = get_option( 'erp_modules', [] );
2127
2128 return isset( $modules[ $module_key ] );
2129 }
2130
2131 /**
2132 * Make csv file from array and force download
2133 *
2134 * @param array $items
2135 * @param boolean $field_data (optional)
2136 *
2137 * @param string $file_name
2138 */
2139 function erp_make_csv_file( $items, $file_name, $field_data = true ) {
2140 $file_name = ( ! empty( $file_name ) ) ? $file_name : 'csv_' . date( 'd_m_Y' ) . '.csv';
2141
2142 if ( empty( $items ) ) {
2143 return;
2144 }
2145
2146 $columns = array_keys( $items[0] );
2147
2148 header( 'Content-Type: text/csv; charset=utf-8' );
2149 header( 'Content-Disposition: attachment; filename=' . $file_name );
2150
2151 $output = fopen( 'php://output', 'w' );
2152
2153 $columns = array_map( function( $column ) {
2154 $column = ucwords( str_replace( '_', ' ', $column ) );
2155
2156 return $column;
2157 }, $columns );
2158
2159 fputcsv( $output, $columns );
2160
2161 if ( $field_data ) {
2162 foreach ( $items as $item ) {
2163 $csv_row = array_map( function ( $item_val ) {
2164
2165 if ( is_array( $item_val ) ) {
2166 return implode( ', ' , $item_val );
2167 }
2168
2169 return $item_val;
2170
2171 }, $item );
2172
2173 fputcsv( $output, $csv_row );
2174 }
2175 }
2176
2177 exit();
2178 }
2179
2180 /**
2181 * Import/Export sample CSV download action hook
2182 *
2183 * @param void
2184 */
2185 function erp_import_export_download_sample_action() {
2186 if ( ! isset( $_GET['action'] ) || $_GET['action'] != 'download_sample' ) {
2187 return;
2188 }
2189
2190 if ( ! wp_verify_nonce( $_GET['_wpnonce'], 'erp-emport-export-sample-nonce' ) ) {
2191 return;
2192 }
2193
2194 if ( ! isset( $_GET['type'] ) ) {
2195 return;
2196 }
2197
2198 $type = strtolower( $_GET['type'] );
2199 $fields = erp_get_import_export_fields();
2200
2201 if ( isset( $fields[ $type ] ) ) {
2202 $keys = $fields[ $type ]['fields'];
2203 $keys = array_flip( $keys );
2204 $file_name = "sample_csv_{$type}.csv";
2205
2206 erp_make_csv_file( [ $keys ], $file_name, false );
2207 }
2208
2209 return;
2210 }
2211
2212 /**
2213 * Enqueue locale scripts for fullcalendar
2214 *
2215 * @since 1.0.0
2216 *
2217 * @return void
2218 */
2219 function enqueue_fullcalendar_locale() {
2220 $locale = get_locale();
2221 $script = '';
2222
2223 // no need to add locale for en_US
2224 if ( 'en_US' === $locale ) {
2225 return;
2226 }
2227
2228 $locale = explode( '_', $locale );
2229
2230 // make sure we have two segments - 1.lang, 2.country
2231 if ( count( $locale ) < 2 ) {
2232 return;
2233 }
2234
2235 $lang = $locale[0];
2236 $country = strtolower( $locale[1] );
2237
2238 if ( $lang === $country ) {
2239 $script = $lang;
2240 } else {
2241 $script = $lang . '-' . $country;
2242 }
2243
2244 if ( file_exists( WPERP_PATH . "/assets/vendor/fullcalendar/lang/{$script}.js" ) ) {
2245 wp_enqueue_script( 'erp-fullcalendar-locale', WPERP_ASSETS . "/vendor/fullcalendar/lang/{$script}.js", array( 'erp-fullcalendar' ), null, true );
2246 }
2247 }
2248
2249 /**
2250 * Generate random key
2251 *
2252 * @since 1.1.8
2253 *
2254 * @return string
2255 */
2256 function erp_generate_key() {
2257 if ( function_exists( 'openssl_random_pseudo_bytes' ) ) {
2258 $key = bin2hex( openssl_random_pseudo_bytes( 20 ) );
2259 } else {
2260 $key = sha1( wp_rand() );
2261 }
2262
2263 return $key;
2264 }
2265
2266 /**
2267 * Include required HTML form erp-popup
2268 *
2269 * @since 1.1.12
2270 *
2271 * @return void
2272 */
2273 function erp_include_popup_markup() {
2274 include_once WPERP_INCLUDES . '/admin/views/erp-modal.php';
2275 erp_get_js_template( WPERP_INCLUDES . '/admin/views/address.php', 'erp-address' );
2276 }
2277
2278 /**
2279 * Dequeue/Deregister select2 from other plugins
2280 *
2281 * @since 1.1.13
2282 *
2283 * @return void
2284 */
2285 function erp_dequeue_other_select2_sources() {
2286 // select2 handle is used by woocommerce
2287 wp_deregister_script( 'select2' );
2288 wp_dequeue_script( 'select2' );
2289 }
2290
2291 /**
2292 * Remove select2 enqueued by other plugins
2293 *
2294 * Whenever enqueue erp-select2, call this function to
2295 * make sure only one select2 is loaded
2296 *
2297 * @since 1.1.13
2298 *
2299 * @return void
2300 */
2301 function erp_remove_other_select2_sources() {
2302 add_action( 'admin_enqueue_scripts', 'erp_dequeue_other_select2_sources', 999999 );
2303 add_action( 'wp_enqueue_scripts', 'erp_dequeue_other_select2_sources', 999999 );
2304 }
2305
2306 /**
2307 * Returns a word in plural form.
2308 *
2309 * @since 1.1.16
2310 *
2311 * @param string $word The word in singular form.
2312 *
2313 * @return string The word in plural form.
2314 */
2315 function erp_pluralize( $word ) {
2316 return \Doctrine\Common\Inflector\Inflector::pluralize( $word );
2317 }
2318
2319 /**
2320 * Get the client IP address
2321 *
2322 * @since 1.1.16
2323 *
2324 * @return string
2325 */
2326 function erp_get_client_ip() {
2327 $ipaddress = '';
2328
2329 if ( isset($_SERVER['HTTP_CLIENT_IP'] ) ) {
2330 $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
2331 } else if ( isset( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
2332 $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
2333 } else if ( isset( $_SERVER['HTTP_X_FORWARDED'] ) ) {
2334 $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
2335 } else if ( isset( $_SERVER['HTTP_FORWARDED_FOR'] ) ) {
2336 $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
2337 } else if ( isset( $_SERVER['HTTP_FORWARDED'] ) ) {
2338 $ipaddress = $_SERVER['HTTP_FORWARDED'];
2339 } else if ( isset( $_SERVER['REMOTE_ADDR'] ) ) {
2340 $ipaddress = $_SERVER['REMOTE_ADDR'];
2341 } else {
2342 $ipaddress = 'UNKNOWN';
2343 }
2344
2345 return $ipaddress;
2346 }
2347
2348 /**
2349 * Converts any value to boolean true or false
2350 *
2351 * @since 1.2.0
2352 *
2353 * @param mixed $value
2354 *
2355 * @return boolean
2356 */
2357 function erp_validate_boolean( $value ) {
2358 return filter_var( $value, FILTER_VALIDATE_BOOLEAN );
2359 }
2360
2361 /**
2362 * Get financial year start and end dates
2363 *
2364 * @since 1.2.0
2365 *
2366 * @return array
2367 */
2368 function erp_get_financial_year_dates() {
2369 $start_month = erp_get_option( 'gen_financial_month', 'erp_settings_general', 1 );
2370
2371 $year = date( 'Y' );
2372 $current_month = date( 'n' );
2373
2374 /**
2375 * Suppose, $start_month is July and today is May 2017. Then we should get
2376 * start = 2016-07-01 00:00:00 and end = 2017-06-30 23:59:59.
2377 *
2378 * On the other hand, if $start_month = January, then we should get
2379 * start = 2017-01-01 00:00:00 and end = 2017-12-31 23:59:59.
2380 */
2381 if ( $current_month < $start_month ) {
2382 $year = $year - 1;
2383 }
2384
2385 $months = erp_months_dropdown();
2386 $start = date( 'Y-m-d 00:00:00', strtotime( "first day of $months[$start_month] $year" ) );
2387 $end = date( 'Y-m-d 23:59:59', strtotime( "$start + 12 months - 1 day" ) );
2388
2389 return [
2390 'start' => $start,
2391 'end' => $end
2392 ];
2393 }
2394
2395 /**
2396 * Get finanicial start and end years that a date belongs to
2397 *
2398 * @since 1.2.0
2399 *
2400 * @param string $date
2401 *
2402 * @return array
2403 */
2404 function get_financial_year_from_date( $date ) {
2405 $fy_start_month = erp_get_option( 'gen_financial_month', 'erp_settings_general', 1 );
2406 $fy_start_month = absint( $fy_start_month );
2407
2408 $date_timestamp = strtotime( $date );
2409 $date_year = absint( date( 'Y', $date_timestamp ) );
2410 $date_month = absint( date( 'n', $date_timestamp ) );
2411
2412 if ( 1 === $fy_start_month ) {
2413 return [
2414 'start' => $date_year, 'end' => $date_year
2415 ];
2416
2417 } else if ( $date_month <= ( $fy_start_month - 1 ) ) {
2418 return [
2419 'start' => ( $date_year - 1 ), 'end' => $date_year
2420 ];
2421
2422 } else {
2423 return [
2424 'start' => $date_year, 'end' => ( $date_year + 1 )
2425 ];
2426 }
2427 }
2428
2429 /**
2430 * Redirect erp role based user to their page
2431 *
2432 * @since 1.2.5
2433 *
2434 * @param $redirect_to
2435 * @param $request
2436 * @param $user
2437 *
2438 * @return string
2439 */
2440 function erp_login_redirect_manager( $redirect_to, $request, $user ) {
2441 $is_erp_redirect = erp_get_option( 'role_based_login_redirection', 'erp_settings_general', false );
2442
2443 if ( $is_erp_redirect && isset( $user->roles ) && is_array( $user->roles ) && ! in_array( 'administrator', $user->roles ) ) {
2444 return $redirect_to = apply_filters( 'erp_login_redirect', $redirect_to, $user->roles );
2445 } else {
2446 return $redirect_to;
2447 }
2448 }
2449