dolibarr 21.0.0-alpha
functions2.lib.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2008-2011 Laurent Destailleur <eldy@users.sourceforge.net>
3 * Copyright (C) 2008-2012 Regis Houssin <regis.houssin@inodbox.com>
4 * Copyright (C) 2008 Raphael Bertrand (Resultic) <raphael.bertrand@resultic.fr>
5 * Copyright (C) 2014-2016 Marcos García <marcosgdf@gmail.com>
6 * Copyright (C) 2015 Ferran Marcet <fmarcet@2byte.es>
7 * Copyright (C) 2015-2016 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
8 * Copyright (C) 2017 Juanjo Menent <jmenent@2byte.es>
9 * Copyright (C) 2024 MDW <mdeweerd@users.noreply.github.com>
10 * Copyright (C) 2024 Frédéric France <frederic.france@free.fr>
11 *
12 * This program is free software; you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License as published by
14 * the Free Software Foundation; either version 3 of the License, or
15 * (at your option) any later version.
16 *
17 * This program is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU General Public License for more details.
21 *
22 * You should have received a copy of the GNU General Public License
23 * along with this program. If not, see <https://www.gnu.org/licenses/>.
24 * or see https://www.gnu.org/
25 */
26
33// Enable this line to trace path when function is called.
34//print xdebug_print_function_stack('Functions2.lib was called');exit;
35
42function jsUnEscape($source)
43{
44 $decodedStr = "";
45 $pos = 0;
46 $len = strlen($source);
47 while ($pos < $len) {
48 $charAt = substr($source, $pos, 1);
49 if ($charAt == '%') {
50 $pos++;
51 $charAt = substr($source, $pos, 1);
52 if ($charAt == 'u') {
53 // we got a unicode character
54 $pos++;
55 $unicodeHexVal = substr($source, $pos, 4);
56 $unicode = hexdec($unicodeHexVal);
57 $entity = "&#".$unicode.';';
58 $decodedStr .= mb_convert_encoding($entity, 'UTF-8', 'ISO-8859-1');
59 $pos += 4;
60 } else {
61 // we have an escaped ascii character
62 $hexVal = substr($source, $pos, 2);
63 $decodedStr .= chr(hexdec($hexVal));
64 $pos += 2;
65 }
66 } else {
67 $decodedStr .= $charAt;
68 $pos++;
69 }
70 }
71 return dol_html_entity_decode($decodedStr, ENT_COMPAT | ENT_HTML5);
72}
73
74
84function dolGetModulesDirs($subdir = '')
85{
86 global $conf;
87
88 $modulesdir = array();
89
90 foreach ($conf->file->dol_document_root as $type => $dirroot) {
91 // Default core/modules dir
92 if ($type === 'main') {
93 $modulesdir[$dirroot.'/core/modules'.$subdir.'/'] = $dirroot.'/core/modules'.$subdir.'/';
94 }
95
96 // Scan dir from external modules
97 $handle = @opendir($dirroot);
98 if (is_resource($handle)) {
99 while (($file = readdir($handle)) !== false) {
100 if (preg_match('/disabled/', $file)) {
101 continue; // We discard module if it contains disabled into name.
102 }
103
104 if (substr($file, 0, 1) != '.' && is_dir($dirroot.'/'.$file) && strtoupper(substr($file, 0, 3)) != 'CVS' && $file != 'includes') {
105 if (is_dir($dirroot.'/'.$file.'/core/modules'.$subdir.'/')) {
106 $modulesdir[$dirroot.'/'.$file.'/core/modules'.$subdir.'/'] = $dirroot.'/'.$file.'/core/modules'.$subdir.'/';
107 }
108 }
109 }
110 closedir($handle);
111 }
112 }
113 return $modulesdir;
114}
115
116
123function dol_getDefaultFormat($outputlangs = null)
124{
125 global $langs;
126
127 $selected = 'EUA4';
128 if (!$outputlangs) {
129 $outputlangs = $langs;
130 }
131
132 if ($outputlangs->defaultlang == 'ca_CA') {
133 $selected = 'CAP4'; // Canada
134 }
135 if ($outputlangs->defaultlang == 'en_US') {
136 $selected = 'USLetter'; // US
137 }
138 return $selected;
139}
140
141
150function dol_print_object_info($object, $usetable = 0)
151{
152 global $langs, $db;
153
154 // Load translation files required by the page
155 $langs->loadLangs(array('other', 'admin'));
156
157 include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
158
159 $deltadateforserver = getServerTimeZoneInt('now');
160 $deltadateforclient = ((int) $_SESSION['dol_tz'] + (int) $_SESSION['dol_dst']);
161 //$deltadateforcompany=((int) $_SESSION['dol_tz'] + (int) $_SESSION['dol_dst']);
162 $deltadateforuser = round($deltadateforclient - $deltadateforserver);
163 //print "x".$deltadateforserver." - ".$deltadateforclient." - ".$deltadateforuser;
164
165 if ($usetable) {
166 print '<table class="border tableforfield centpercent">';
167 }
168
169 // Import key
170 if (!empty($object->import_key)) {
171 if ($usetable) {
172 print '<tr><td class="titlefield">';
173 }
174 print $langs->trans("ImportedWithSet");
175 if ($usetable) {
176 print '</td><td>';
177 } else {
178 print ': ';
179 }
180 print $object->import_key;
181 if ($usetable) {
182 print '</td></tr>';
183 } else {
184 print '<br>';
185 }
186 }
187
188 // User creation (old method using already loaded object and not id is kept for backward compatibility)
189 if (!empty($object->user_creation) || !empty($object->user_creation_id)) {
190 if ($usetable) {
191 print '<tr><td class="titlefield">';
192 }
193 print $langs->trans("CreatedBy");
194 if ($usetable) {
195 print '</td><td>';
196 } else {
197 print ': ';
198 }
199 if (! empty($object->user_creation) && is_object($object->user_creation)) { // deprecated mode
200 if ($object->user_creation->id) {
201 print $object->user_creation->getNomUrl(-1, '', 0, 0, 0);
202 } else {
203 print $langs->trans("Unknown");
204 }
205 } else {
206 $userstatic = new User($db);
207 $userstatic->fetch($object->user_creation_id);
208 if ($userstatic->id) {
209 print $userstatic->getNomUrl(-1, '', 0, 0, 0);
210 } else {
211 print $langs->trans("Unknown");
212 }
213 }
214 if ($usetable) {
215 print '</td></tr>';
216 } else {
217 print '<br>';
218 }
219 }
220
221 // Date creation
222 if (!empty($object->date_creation)) {
223 if ($usetable) {
224 print '<tr><td class="titlefield">';
225 }
226 print $langs->trans("DateCreation");
227 if ($usetable) {
228 print '</td><td>';
229 } else {
230 print ': ';
231 }
232 print dol_print_date($object->date_creation, 'dayhour', 'tzserver');
233 if ($deltadateforuser) {
234 print ' <span class="opacitymedium">'.$langs->trans("CurrentHour").'</span> &nbsp; / &nbsp; '.dol_print_date($object->date_creation, "dayhour", "tzuserrel").' &nbsp;<span class="opacitymedium">'.$langs->trans("ClientHour").'</span>';
235 }
236 if ($usetable) {
237 print '</td></tr>';
238 } else {
239 print '<br>';
240 }
241 }
242
243 // User change (old method using already loaded object and not id is kept for backward compatibility)
244 if (!empty($object->user_modification) || !empty($object->user_modification_id)) {
245 if ($usetable) {
246 print '<tr><td class="titlefield">';
247 }
248 print $langs->trans("ModifiedBy");
249 if ($usetable) {
250 print '</td><td>';
251 } else {
252 print ': ';
253 }
254 if (is_object($object->user_modification)) {
255 if ($object->user_modification->id) {
256 print $object->user_modification->getNomUrl(-1, '', 0, 0, 0);
257 } else {
258 print $langs->trans("Unknown");
259 }
260 } else {
261 $userstatic = new User($db);
262 $userstatic->fetch($object->user_modification_id);
263 if ($userstatic->id) {
264 print $userstatic->getNomUrl(-1, '', 0, 0, 0);
265 } else {
266 print $langs->trans("Unknown");
267 }
268 }
269 if ($usetable) {
270 print '</td></tr>';
271 } else {
272 print '<br>';
273 }
274 }
275
276 // Date change
277 if (!empty($object->date_modification)) {
278 if ($usetable) {
279 print '<tr><td class="titlefield">';
280 }
281 print $langs->trans("DateLastModification");
282 if ($usetable) {
283 print '</td><td>';
284 } else {
285 print ': ';
286 }
287 print dol_print_date($object->date_modification, 'dayhour', 'tzserver');
288 if ($deltadateforuser) {
289 print ' <span class="opacitymedium">'.$langs->trans("CurrentHour").'</span> &nbsp; / &nbsp; '.dol_print_date($object->date_modification, "dayhour", "tzuserrel").' &nbsp;<span class="opacitymedium">'.$langs->trans("ClientHour").'</span>';
290 }
291 if ($usetable) {
292 print '</td></tr>';
293 } else {
294 print '<br>';
295 }
296 }
297
298 // User validation (old method using already loaded object and not id is kept for backward compatibility)
299 if (!empty($object->user_validation) || !empty($object->user_validation_id)) {
300 if ($usetable) {
301 print '<tr><td class="titlefield">';
302 }
303 print $langs->trans("ValidatedBy");
304 if ($usetable) {
305 print '</td><td>';
306 } else {
307 print ': ';
308 }
309 if (is_object($object->user_validation)) {
310 if ($object->user_validation->id) {
311 print $object->user_validation->getNomUrl(-1, '', 0, 0, 0);
312 } else {
313 print $langs->trans("Unknown");
314 }
315 } else {
316 $userstatic = new User($db);
317 $userstatic->fetch($object->user_validation_id ? $object->user_validation_id : $object->user_validation);
318 if ($userstatic->id) {
319 print $userstatic->getNomUrl(-1, '', 0, 0, 0);
320 } else {
321 print $langs->trans("Unknown");
322 }
323 }
324 if ($usetable) {
325 print '</td></tr>';
326 } else {
327 print '<br>';
328 }
329 }
330
331 // Date validation
332 if (!empty($object->date_validation)) {
333 if ($usetable) {
334 print '<tr><td class="titlefield">';
335 }
336 print $langs->trans("DateValidation");
337 if ($usetable) {
338 print '</td><td>';
339 } else {
340 print ': ';
341 }
342 print dol_print_date($object->date_validation, 'dayhour', 'tzserver');
343 if ($deltadateforuser) {
344 print ' <span class="opacitymedium">'.$langs->trans("CurrentHour").'</span> &nbsp; / &nbsp; '.dol_print_date($object->date_validation, "dayhour", 'tzuserrel').' &nbsp;<span class="opacitymedium">'.$langs->trans("ClientHour").'</span>';
345 }
346 if ($usetable) {
347 print '</td></tr>';
348 } else {
349 print '<br>';
350 }
351 }
352
353 // User approve (old method using already loaded object and not id is kept for backward compatibility)
354 if (!empty($object->user_approve) || !empty($object->user_approve_id)) {
355 if ($usetable) {
356 print '<tr><td class="titlefield">';
357 }
358 print $langs->trans("ApprovedBy");
359 if ($usetable) {
360 print '</td><td>';
361 } else {
362 print ': ';
363 }
364 // user_approve is not defined in Dolibarr code @phan-suppress-next-line PhanUndeclaredProperty
365 if (!empty($object->user_approve) && is_object($object->user_approve)) {
366 if ($object->user_approve->id) { // @phan-suppress-current-line PhanUndeclaredProperty
367 // @phan-suppress-next-line PhanUndeclaredProperty,PhanPluginUnknownObjectMethodCall
368 print $object->user_approve->getNomUrl(-1, '', 0, 0, 0);
369 } else {
370 print $langs->trans("Unknown");
371 }
372 } else {
373 $userstatic = new User($db);
374 $userstatic->fetch($object->user_approve_id ? $object->user_approve_id : $object->user_approve);
375 if ($userstatic->id) {
376 print $userstatic->getNomUrl(-1, '', 0, 0, 0);
377 } else {
378 print $langs->trans("Unknown");
379 }
380 }
381 if ($usetable) {
382 print '</td></tr>';
383 } else {
384 print '<br>';
385 }
386 }
387
388 // Date approve
389 if (!empty($object->date_approve) || !empty($object->date_approval)) {
390 '@phan-var-force ExpenseReport|CommandeFournisseur $object';
391 if ($usetable) {
392 print '<tr><td class="titlefield">';
393 }
394 print $langs->trans("DateApprove");
395 if ($usetable) {
396 print '</td><td>';
397 } else {
398 print ': ';
399 }
400 print dol_print_date($object->date_approve ? $object->date_approve : $object->date_approval, 'dayhour', 'tzserver');
401 if ($deltadateforuser) {
402 print ' <span class="opacitymedium">'.$langs->trans("CurrentHour").'</span> &nbsp; / &nbsp; '.dol_print_date($object->date_approve, "dayhour", 'tzuserrel').' &nbsp;<span class="opacitymedium">'.$langs->trans("ClientHour").'</span>';
403 }
404 if ($usetable) {
405 print '</td></tr>';
406 } else {
407 print '<br>';
408 }
409 }
410
411 // User approve
412 if (!empty($object->user_approve_id2)) {
413 '@phan-var-force CommandeFournisseur $object';
414 if ($usetable) {
415 print '<tr><td class="titlefield">';
416 }
417 print $langs->trans("ApprovedBy");
418 if ($usetable) {
419 print '</td><td>';
420 } else {
421 print ': ';
422 }
423 $userstatic = new User($db);
424 $userstatic->fetch($object->user_approve_id2);
425 if ($userstatic->id) {
426 print $userstatic->getNomUrl(-1, '', 0, 0, 0);
427 } else {
428 print $langs->trans("Unknown");
429 }
430 if ($usetable) {
431 print '</td></tr>';
432 } else {
433 print '<br>';
434 }
435 }
436
437 // Date approve
438 if (!empty($object->date_approve2)) {
439 if ($usetable) {
440 print '<tr><td class="titlefield">';
441 }
442 print $langs->trans("DateApprove2");
443 if ($usetable) {
444 print '</td><td>';
445 } else {
446 print ': ';
447 }
448 print dol_print_date($object->date_approve2, 'dayhour', 'tzserver');
449 if ($deltadateforuser) {
450 print ' <span class="opacitymedium">'.$langs->trans("CurrentHour").'</span> &nbsp; / &nbsp; '.dol_print_date($object->date_approve2, "dayhour", 'tzuserrel').' &nbsp;<span class="opacitymedium">'.$langs->trans("ClientHour").'</span>';
451 }
452 if ($usetable) {
453 print '</td></tr>';
454 } else {
455 print '<br>';
456 }
457 }
458
459 // User signature
460 if (!empty($object->user_signature) || !empty($object->user_signature_id)) {
461 '@phan-var-force Propal $object';
462 if ($usetable) {
463 print '<tr><td class="titlefield">';
464 }
465 print $langs->trans('SignedBy');
466 if ($usetable) {
467 print '</td><td>';
468 } else {
469 print ': ';
470 }
471 if (is_object($object->user_signature)) {
472 if ($object->user_signature->id) {
473 print $object->user_signature->getNomUrl(-1, '', 0, 0, 0);
474 } else {
475 print $langs->trans('Unknown');
476 }
477 } else {
478 $userstatic = new User($db);
479 $userstatic->fetch($object->user_signature_id ? $object->user_signature_id : $object->user_signature);
480 if ($userstatic->id) {
481 print $userstatic->getNomUrl(-1, '', 0, 0, 0);
482 } else {
483 print $langs->trans('Unknown');
484 }
485 }
486 if ($usetable) {
487 print '</td></tr>';
488 } else {
489 print '<br>';
490 }
491 }
492
493 // Date signature
494 if (!empty($object->date_signature)) {
495 if ($usetable) {
496 print '<tr><td class="titlefield">';
497 }
498 print $langs->trans('DateSigning');
499 if ($usetable) {
500 print '</td><td>';
501 } else {
502 print ': ';
503 }
504 print dol_print_date($object->date_signature, 'dayhour');
505 if ($deltadateforuser) {
506 print ' <span class="opacitymedium">'.$langs->trans('CurrentHour').'</span> &nbsp; / &nbsp; '.dol_print_date($object->date_signature, 'dayhour', 'tzuserrel').' &nbsp;<span class="opacitymedium">'.$langs->trans('ClientHour').'</span>';
507 }
508 if ($usetable) {
509 print '</td></tr>';
510 } else {
511 print '<br>';
512 }
513 }
514
515 // User close
516 if (!empty($object->user_closing_id)) {
517 if ($usetable) {
518 print '<tr><td class="titlefield">';
519 }
520 print $langs->trans("ClosedBy");
521 if ($usetable) {
522 print '</td><td>';
523 } else {
524 print ': ';
525 }
526 $userstatic = new User($db);
527 $userstatic->fetch($object->user_closing_id);
528 if ($userstatic->id) {
529 print $userstatic->getNomUrl(-1, '', 0, 0, 0);
530 } else {
531 print $langs->trans("Unknown");
532 }
533 if ($usetable) {
534 print '</td></tr>';
535 } else {
536 print '<br>';
537 }
538 }
539
540 // Date close
541 if (!empty($object->date_cloture) || !empty($object->date_closing)) {
542 if (isset($object->date_cloture) && !empty($object->date_cloture)) {
543 $object->date_closing = $object->date_cloture;
544 }
545 if ($usetable) {
546 print '<tr><td class="titlefield">';
547 }
548 print $langs->trans("DateClosing");
549 if ($usetable) {
550 print '</td><td>';
551 } else {
552 print ': ';
553 }
554 print dol_print_date($object->date_closing, 'dayhour', 'tzserver');
555 if ($deltadateforuser) {
556 print ' <span class="opacitymedium">'.$langs->trans("CurrentHour").'</span> &nbsp; / &nbsp; '.dol_print_date($object->date_closing, "dayhour", 'tzuserrel').' &nbsp;<span class="opacitymedium">'.$langs->trans("ClientHour").'</span>';
557 }
558 if ($usetable) {
559 print '</td></tr>';
560 } else {
561 print '<br>';
562 }
563 }
564
565 // User conciliate
566 if (!empty($object->user_rappro) || !empty($object->user_rappro_id)) {
567 '@phan-var-force Account $object';
568 if ($usetable) {
569 print '<tr><td class="titlefield">';
570 }
571 print $langs->trans("ReconciledBy");
572 if ($usetable) {
573 print '</td><td>';
574 } else {
575 print ': ';
576 }
577 if (is_object($object->user_rappro)) {
578 $user_rappro = $object->user_rappro;
579 '@phan-var-force User $user_rappro';
580 if ($user_rappro->id) {
581 print $user_rappro->getNomUrl(-1, '', 0, 0, 0);
582 } else {
583 print $langs->trans("Unknown");
584 }
585 } else {
586 $userstatic = new User($db);
587 $userstatic->fetch($object->user_rappro_id ? $object->user_rappro_id : $object->user_rappro);
588 if ($userstatic->id) {
589 print $userstatic->getNomUrl(1, '', 0, 0, 0);
590 } else {
591 print $langs->trans("Unknown");
592 }
593 }
594 if ($usetable) {
595 print '</td></tr>';
596 } else {
597 print '<br>';
598 }
599 }
600
601 // Date conciliate Note: date_rappro is not found on Dolibarr classes
602 if (!empty($object->date_rappro)) {
603 // Datte
604 if ($usetable) {
605 print '<tr><td class="titlefield">';
606 }
607 print $langs->trans("DateConciliating");
608 if ($usetable) {
609 print '</td><td>';
610 } else {
611 print ': ';
612 }
613 print dol_print_date($object->date_rappro, 'dayhour', 'tzserver'); // @phan-suppress-current-line PhanUndeclaredProperty
614 if ($deltadateforuser) {
615 print ' <span class="opacitymedium">'.$langs->trans("CurrentHour").'</span> &nbsp; / &nbsp; '.dol_print_date($object->date_rappro, "dayhour", 'tzuserrel').' &nbsp;<span class="opacitymedium">'.$langs->trans("ClientHour").'</span>'; // @phan-suppress-current-line PhanUndeclaredProperty
616 }
617 if ($usetable) {
618 print '</td></tr>';
619 } else {
620 print '<br>';
621 }
622 }
623
624 // Date send
625 if (!empty($object->date_envoi)) {
626 '@phan-var-force Mailing $object';
627 if ($usetable) {
628 print '<tr><td class="titlefield">';
629 }
630 print $langs->trans("DateLastSend");
631 if ($usetable) {
632 print '</td><td>';
633 } else {
634 print ': ';
635 }
636 print dol_print_date($object->date_envoi, 'dayhour', 'tzserver');
637 if ($deltadateforuser) {
638 print ' <span class="opacitymedium">'.$langs->trans("CurrentHour").'</span> &nbsp; / &nbsp; '.dol_print_date($object->date_envoi, "dayhour", 'tzuserrel').' &nbsp;<span class="opacitymedium">'.$langs->trans("ClientHour").'</span>';
639 }
640 if ($usetable) {
641 print '</td></tr>';
642 } else {
643 print '<br>';
644 }
645 }
646
647 if ($usetable) {
648 print '</table>';
649 }
650}
651
652
661function dolAddEmailTrackId($email, $trackingid)
662{
663 $tmp = explode('@', $email);
664 return $tmp[0].'+'.$trackingid.'@'.(isset($tmp[1]) ? $tmp[1] : '');
665}
666
673function isValidMailDomain($mail)
674{
675 list($user, $domain) = explode("@", $mail, 2);
676 return ($domain ? isValidMXRecord($domain) : 0);
677}
678
692function isValidUrl($url, $http = 0, $pass = 0, $port = 0, $path = 0, $query = 0, $anchor = 0)
693{
694 $ValidUrl = 0;
695 $urlregex = '';
696
697 // SCHEME
698 if ($http) {
699 $urlregex .= "^(http:\/\/|https:\/\/)";
700 }
701
702 // USER AND PASS
703 if ($pass) {
704 $urlregex .= "([a-z0-9+!*(),;?&=\$_.-]+(\:[a-z0-9+!*(),;?&=\$_.-]+)?@)";
705 }
706
707 // HOSTNAME OR IP
708 //$urlregex .= "[a-z0-9+\$_-]+(\.[a-z0-9+\$_-]+)*"; // x allowed (ex. http://localhost, http://routerlogin)
709 //$urlregex .= "[a-z0-9+\$_-]+(\.[a-z0-9+\$_-]+)+"; // x.x
710 $urlregex .= "([a-z0-9+\$_\\\:-])+(\.[a-z0-9+\$_-][a-z0-9+\$_-]+)*"; // x ou x.xx (2 x ou plus)
711 //use only one of the above
712
713 // PORT
714 if ($port) {
715 $urlregex .= "(\:[0-9]{2,5})";
716 }
717 // PATH
718 if ($path) {
719 $urlregex .= "(\/([a-z0-9+\$_-]\.?)+)*\/";
720 }
721 // GET Query
722 if ($query) {
723 $urlregex .= "(\?[a-z+&\$_.-][a-z0-9;:@\/&%=+\$_.-]*)";
724 }
725 // ANCHOR
726 if ($anchor) {
727 $urlregex .= "(#[a-z_.-][a-z0-9+\$_.-]*)$";
728 }
729
730 // check
731 if (preg_match('/'.$urlregex.'/i', $url)) {
732 $ValidUrl = 1;
733 }
734 //print $urlregex.' - '.$url.' - '.$ValidUrl;
735
736 return $ValidUrl;
737}
738
745function isValidVATID($company)
746{
747 if ($company->isInEEC()) { // Syntax check rules for EEC countries
748 /* Disabled because some companies can have an address in Irland and a vat number in France.
749 $vatprefix = $company->country_code;
750 if ($vatprefix == 'GR') $vatprefix = '(EL|GR)';
751 elseif ($vatprefix == 'MC') $vatprefix = 'FR'; // Monaco is using french VAT numbers
752 else $vatprefix = preg_quote($vatprefix, '/');*/
753 $vatprefix = '[a-zA-Z][a-zA-Z]';
754 if (!preg_match('/^'.$vatprefix.'[a-zA-Z0-9\-\.]{5,14}$/i', str_replace(' ', '', $company->tva_intra))) {
755 return 0;
756 }
757 }
758
759 return 1;
760}
761
769function clean_url($url, $http = 1)
770{
771 // Fixed by Matelli (see http://matelli.fr/showcases/patch%73-dolibarr/fix-cleaning-url.html)
772 // To include the minus sign in a char class, we must not escape it but put it at the end of the class
773 // Also, there's no need of escape a dot sign in a class
774 $regs = array();
775 if (preg_match('/^(https?:[\\/]+)?([0-9A-Z.-]+\.[A-Z]{2,4})(:[0-9]+)?/i', $url, $regs)) {
776 $proto = $regs[1];
777 $domain = $regs[2];
778 $port = isset($regs[3]) ? $regs[3] : '';
779 //print $url." -> ".$proto." - ".$domain." - ".$port;
780 //$url = dol_string_nospecial(trim($url));
781 $url = trim($url);
782
783 // Si http: defini on supprime le http (Si https on ne supprime pas)
784 $newproto = $proto;
785 if ($http == 0) {
786 if (preg_match('/^http:[\\/]+/i', $url)) {
787 $url = preg_replace('/^http:[\\/]+/i', '', $url);
788 $newproto = '';
789 }
790 }
791
792 // On passe le nom de domaine en minuscule
793 $CleanUrl = preg_replace('/^'.preg_quote($proto.$domain, '/').'/i', $newproto.strtolower($domain), $url);
794
795 return $CleanUrl;
796 } else {
797 return $url;
798 }
799}
800
801
802
814function dolObfuscateEmail($mail, $replace = "*", $nbreplace = 8, $nbdisplaymail = 4, $nbdisplaydomain = 3, $displaytld = true)
815{
816 if (!isValidEmail($mail)) {
817 return '';
818 }
819 $tab = explode('@', $mail);
820 $tab2 = explode('.', $tab[1]);
821 $string_replace = '';
822 $mail_name = $tab[0];
823 $mail_domaine = $tab2[0];
824 $mail_tld = '';
825
826 $nbofelem = count($tab2);
827 for ($i = 1; $i < $nbofelem && $displaytld; $i++) {
828 $mail_tld .= '.'.$tab2[$i];
829 }
830
831 for ($i = 0; $i < $nbreplace; $i++) {
832 $string_replace .= $replace;
833 }
834
835 if (strlen($mail_name) > $nbdisplaymail) {
836 $mail_name = substr($mail_name, 0, $nbdisplaymail);
837 }
838
839 if (strlen($mail_domaine) > $nbdisplaydomain) {
840 $mail_domaine = substr($mail_domaine, strlen($mail_domaine) - $nbdisplaydomain);
841 }
842
843 return $mail_name.$string_replace.$mail_domaine.$mail_tld;
844}
845
846
856function array2tr($data, $troptions = '', $tdoptions = '')
857{
858 $text = '<tr '.$troptions.'>';
859 foreach ($data as $key => $item) {
860 $text .= '<td '.$tdoptions.'>'.((string) $item).'</td>';
861 }
862 $text .= '</tr>';
863 return $text;
864}
865
876function array2table($data, $tableMarkup = 1, $tableoptions = '', $troptions = '', $tdoptions = '')
877{
878 $text = '';
879 if ($tableMarkup) {
880 $text = '<table '.$tableoptions.'>';
881 }
882 foreach ($data as $key => $item) {
883 if (is_array($item)) {
884 $text .= array2tr($item, $troptions, $tdoptions);
885 } else {
886 $text .= '<tr '.$troptions.'>';
887 $text .= '<td '.$tdoptions.'>'.((string) $key).'</td>';
888 $text .= '<td '.$tdoptions.'>'.((string) $item).'</td>';
889 $text .= '</tr>';
890 }
891 }
892 if ($tableMarkup) {
893 $text .= '</table>';
894 }
895 return $text;
896}
897
914function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $date = '', $mode = 'next', $bentityon = true, $objuser = null, $forceentity = null)
915{
916 global $user;
917
918 if (!is_object($objsoc)) {
919 $valueforccc = (string) $objsoc;
920 } elseif ($table == "commande_fournisseur" || $table == "facture_fourn" || $table == "paiementfourn") {
921 $valueforccc = dol_string_unaccent($objsoc->code_fournisseur);
922 } else {
923 $valueforccc = dol_string_unaccent($objsoc->code_client);
924 }
925
926 $sharetable = $table;
927 if ($table == 'facture' || $table == 'invoice') {
928 $sharetable = 'invoicenumber'; // for getEntity function
929 }
930
931 // Clean parameters
932 if ($date == '') {
933 $date = dol_now(); // We use local year and month of PHP server to search numbers
934 }
935 // but we should use local year and month of user
936
937 // For debugging
938 //dol_syslog("mask=".$mask, LOG_DEBUG);
939 //include_once(DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php');
940 //$mask='FA{yy}{mm}-{0000@99}';
941 //$date=dol_mktime(12, 0, 0, 1, 1, 1900);
942 //$date=dol_stringtotime('20130101');
943 $hasglobalcounter = false;
944 $maskrefclient_maskcounter = '';
945 $maskrefclient_clientcode = '';
946 $maskrefclient_maskclientcode = '';
947 $maskrefclient_maskoffset = '';
948
949 $reg = array();
950 // Extract value for mask counter, mask raz and mask offset
951 if (preg_match('/\{(0+)([@\+][0-9\-\+\=]+)?([@\+][0-9\-\+\=]+)?\}/i', $mask, $reg)) {
952 $masktri = $reg[1].(!empty($reg[2]) ? $reg[2] : '').(!empty($reg[3]) ? $reg[3] : '');
953 $maskcounter = $reg[1];
954 $hasglobalcounter = true;
955 } else {
956 // setting some defaults so the rest of the code won't fail if there is a third party counter
957 $masktri = '00000';
958 $maskcounter = '00000';
959 }
960
961 $maskraz = -1;
962 $maskoffset = 0;
963 $resetEveryMonth = false;
964 if (dol_strlen($maskcounter) < 3 && !getDolGlobalString('MAIN_COUNTER_WITH_LESS_3_DIGITS')) {
965 return 'ErrorCounterMustHaveMoreThan3Digits';
966 }
967
968 // Extract value for third party mask counter
969 $regClientRef = array();
970 if (preg_match('/\{(c+)(0*)\}/i', $mask, $regClientRef)) {
971 $maskrefclient = $regClientRef[1].$regClientRef[2];
972 $maskrefclient_maskclientcode = $regClientRef[1];
973 $maskrefclient_maskcounter = $regClientRef[2];
974 $maskrefclient_maskoffset = 0; //default value of maskrefclient_counter offset
975 $maskrefclient_clientcode = substr($valueforccc, 0, dol_strlen($maskrefclient_maskclientcode)); //get n first characters of client code where n is length in mask
976 $maskrefclient_clientcode = str_pad($maskrefclient_clientcode, dol_strlen($maskrefclient_maskclientcode), "#", STR_PAD_RIGHT); //padding maskrefclient_clientcode for having exactly n characters in maskrefclient_clientcode
977 $maskrefclient_clientcode = dol_string_nospecial($maskrefclient_clientcode); //sanitize maskrefclient_clientcode for sql insert and sql select like
978 if (dol_strlen($maskrefclient_maskcounter) > 0 && dol_strlen($maskrefclient_maskcounter) < 3) {
979 return 'ErrorCounterMustHaveMoreThan3Digits';
980 }
981 } else {
982 $maskrefclient = '';
983 }
984
985 // fail if there is neither a global nor a third party counter
986 if (!$hasglobalcounter && ($maskrefclient_maskcounter == '')) {
987 return 'ErrorBadMask';
988 }
989
990 // Extract value for third party type
991 $regType = array();
992 if (preg_match('/\{(t+)\}/i', $mask, $regType)) {
993 $masktype = $regType[1];
994 $masktype_value = dol_substr(preg_replace('/^TE_/', '', $objsoc->typent_code), 0, dol_strlen($regType[1])); // get n first characters of thirdparty typent_code (where n is length in mask)
995 $masktype_value = str_pad($masktype_value, dol_strlen($regType[1]), "#", STR_PAD_RIGHT); // we fill on right with # to have same number of char than into mask
996 } else {
997 $masktype = '';
998 $masktype_value = '';
999 }
1000
1001 // Extract value for user
1002 $regType = array();
1003 if (preg_match('/\{(u+)\}/i', $mask, $regType)) {
1004 $lastname = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
1005 if (is_object($objuser)) {
1006 $lastname = $objuser->lastname;
1007 }
1008
1009 $maskuser = $regType[1];
1010 $maskuser_value = substr($lastname, 0, dol_strlen($regType[1])); // get n first characters of user firstname (where n is length in mask)
1011 $maskuser_value = str_pad($maskuser_value, dol_strlen($regType[1]), "#", STR_PAD_RIGHT); // we fill on right with # to have same number of char than into mask
1012 } else {
1013 $maskuser = '';
1014 $maskuser_value = '';
1015 }
1016
1017 // Personalized field {XXX-1} à {XXX-99}
1018 $maskperso = array();
1019 $maskpersonew = array();
1020 $tmpmask = $mask;
1021 $regKey = array();
1022 while (preg_match('/\{([A-Z]+)\-([0-9]+)\}/', $tmpmask, $regKey)) {
1023 $maskperso[$regKey[1]] = '{'.$regKey[1].'-'.$regKey[2].'}';
1024 // @phan-suppress-next-line PhanParamSuspiciousOrder
1025 $maskpersonew[$regKey[1]] = str_pad('', (int) $regKey[2], '_', STR_PAD_RIGHT);
1026 $tmpmask = preg_replace('/\{'.$regKey[1].'\-'.$regKey[2].'\}/i', $maskpersonew[$regKey[1]], $tmpmask);
1027 }
1028
1029 if (strstr($mask, 'user_extra_')) {
1030 $start = "{user_extra_";
1031 $end = "\}";
1032 $extra = get_string_between($mask, "user_extra_", "}");
1033 if (!empty($user->array_options['options_'.$extra])) {
1034 $mask = preg_replace('#('.$start.')(.*?)('.$end.')#si', $user->array_options['options_'.$extra], $mask);
1035 }
1036 }
1037 $maskwithonlyymcode = $mask;
1038 $maskwithonlyymcode = preg_replace('/\{(0+)([@\+][0-9\-\+\=]+)?([@\+][0-9\-\+\=]+)?\}/i', $maskcounter, $maskwithonlyymcode);
1039 $maskwithonlyymcode = preg_replace('/\{dd\}/i', 'dd', $maskwithonlyymcode);
1040 $maskwithonlyymcode = preg_replace('/\{(c+)(0*)\}/i', $maskrefclient, $maskwithonlyymcode);
1041 $maskwithonlyymcode = preg_replace('/\{(t+)\}/i', $masktype_value, $maskwithonlyymcode);
1042 $maskwithonlyymcode = preg_replace('/\{(u+)\}/i', $maskuser_value, $maskwithonlyymcode);
1043 foreach ($maskperso as $key => $val) {
1044 $maskwithonlyymcode = preg_replace('/'.preg_quote($val, '/').'/i', $maskpersonew[$key], $maskwithonlyymcode);
1045 }
1046 $maskwithnocode = $maskwithonlyymcode;
1047 $maskwithnocode = preg_replace('/\{yyyy\}/i', 'yyyy', $maskwithnocode);
1048 $maskwithnocode = preg_replace('/\{yy\}/i', 'yy', $maskwithnocode);
1049 $maskwithnocode = preg_replace('/\{y\}/i', 'y', $maskwithnocode);
1050 $maskwithnocode = preg_replace('/\{mm\}/i', 'mm', $maskwithnocode);
1051 // Now maskwithnocode = 0000ddmmyyyyccc for example
1052 // and maskcounter = 0000 for example
1053 //print "maskwithonlyymcode=".$maskwithonlyymcode." maskwithnocode=".$maskwithnocode."\n<br>";
1054 //var_dump($reg);
1055
1056 // If an offset is asked
1057 if (!empty($reg[2]) && preg_match('/^\+/', $reg[2])) {
1058 $maskoffset = preg_replace('/^\+/', '', $reg[2]);
1059 }
1060 if (!empty($reg[3]) && preg_match('/^\+/', $reg[3])) {
1061 $maskoffset = preg_replace('/^\+/', '', $reg[3]);
1062 }
1063
1064 // Define $sqlwhere
1065 $sqlwhere = '';
1066 $yearoffset = 0; // Use year of current $date by default
1067 $yearoffsettype = false; // false: no reset, 0,-,=,+: reset at offset SOCIETE_FISCAL_MONTH_START, x=reset at offset x
1068
1069 // If a restore to zero after a month is asked we check if there is already a value for this year.
1070 if (!empty($reg[2]) && preg_match('/^@/', $reg[2])) {
1071 $yearoffsettype = preg_replace('/^@/', '', $reg[2]);
1072 }
1073 if (!empty($reg[3]) && preg_match('/^@/', $reg[3])) {
1074 $yearoffsettype = preg_replace('/^@/', '', $reg[3]);
1075 }
1076
1077 //print "yearoffset=".$yearoffset." yearoffsettype=".$yearoffsettype;
1078 if (is_numeric($yearoffsettype) && $yearoffsettype >= 1) {
1079 $maskraz = $yearoffsettype; // For backward compatibility
1080 } elseif ($yearoffsettype === '0' || (!empty($yearoffsettype) && !is_numeric($yearoffsettype) && getDolGlobalInt('SOCIETE_FISCAL_MONTH_START') > 1)) {
1081 $maskraz = getDolGlobalString('SOCIETE_FISCAL_MONTH_START');
1082 }
1083 //print "maskraz=".$maskraz; // -1=no reset
1084
1085 if ($maskraz > 0) { // A reset is required
1086 if ($maskraz == 99) {
1087 $maskraz = (int) date('m', $date);
1088 $resetEveryMonth = true;
1089 }
1090 if ($maskraz > 12) {
1091 return 'ErrorBadMaskBadRazMonth';
1092 }
1093
1094 // Define posy, posm and reg
1095 if ($maskraz > 1) { // if reset is not first month, we need month and year into mask
1096 if (preg_match('/^(.*)\{(y+)\}\{(m+)\}/i', $maskwithonlyymcode, $reg)) {
1097 $posy = 2;
1098 $posm = 3;
1099 } elseif (preg_match('/^(.*)\{(m+)\}\{(y+)\}/i', $maskwithonlyymcode, $reg)) {
1100 $posy = 3;
1101 $posm = 2;
1102 } else {
1103 return 'ErrorCantUseRazInStartedYearIfNoYearMonthInMask';
1104 }
1105
1106 if (dol_strlen($reg[$posy]) < 2) {
1107 return 'ErrorCantUseRazWithYearOnOneDigit';
1108 }
1109 } else { // if reset is for a specific month in year, we need year
1110 if (preg_match('/^(.*)\{(m+)\}\{(y+)\}/i', $maskwithonlyymcode, $reg)) {
1111 $posy = 3;
1112 $posm = 2;
1113 } elseif (preg_match('/^(.*)\{(y+)\}\{(m+)\}/i', $maskwithonlyymcode, $reg)) {
1114 $posy = 2;
1115 $posm = 3;
1116 } elseif (preg_match('/^(.*)\{(y+)\}/i', $maskwithonlyymcode, $reg)) {
1117 $posy = 2;
1118 $posm = 0;
1119 } else {
1120 return 'ErrorCantUseRazIfNoYearInMask';
1121 }
1122 }
1123 // Define length
1124 $yearlen = $posy ? dol_strlen($reg[$posy]) : 0;
1125 $monthlen = $posm ? dol_strlen($reg[$posm]) : 0;
1126 // Define pos
1127 $yearpos = (dol_strlen($reg[1]) + 1);
1128 $monthpos = ($yearpos + $yearlen);
1129 if ($posy == 3 && $posm == 2) { // if month is before year
1130 $monthpos = (dol_strlen($reg[1]) + 1);
1131 $yearpos = ($monthpos + $monthlen);
1132 }
1133 //print "xxx ".$maskwithonlyymcode." maskraz=".$maskraz." posy=".$posy." yearlen=".$yearlen." yearpos=".$yearpos." posm=".$posm." monthlen=".$monthlen." monthpos=".$monthpos." yearoffsettype=".$yearoffsettype." resetEveryMonth=".$resetEveryMonth."\n";
1134
1135 // Define $yearcomp and $monthcomp (that will be use in the select where to search max number)
1136 $monthcomp = $maskraz;
1137 $yearcomp = 0;
1138
1139 if (!empty($yearoffsettype) && !is_numeric($yearoffsettype) && $yearoffsettype != '=') { // $yearoffsettype is - or +
1140 $currentyear = (int) date("Y", $date);
1141 $fiscaldate = dol_mktime(0, 0, 0, $maskraz, 1, $currentyear);
1142 $newyeardate = dol_mktime(0, 0, 0, 1, 1, $currentyear);
1143 $nextnewyeardate = dol_mktime(0, 0, 0, 1, 1, $currentyear + 1);
1144 //echo 'currentyear='.$currentyear.' date='.dol_print_date($date, 'day').' fiscaldate='.dol_print_date($fiscaldate, 'day').'<br>';
1145
1146 // If after or equal of current fiscal date
1147 if ($date >= $fiscaldate) {
1148 // If before of next new year date
1149 if ($date < $nextnewyeardate && $yearoffsettype == '+') {
1150 $yearoffset = 1;
1151 }
1152 } elseif ($date >= $newyeardate && $yearoffsettype == '-') {
1153 // If after or equal of current new year date
1154 $yearoffset = -1;
1155 }
1156 } elseif ((int) date("m", $date) < $maskraz && empty($resetEveryMonth)) {
1157 // For backward compatibility
1158 $yearoffset = -1;
1159 } // If current month lower that month of return to zero, year is previous year
1160
1161 if ($yearlen == 4) {
1162 $yearcomp = sprintf("%04d", idate("Y", $date) + $yearoffset);
1163 } elseif ($yearlen == 2) {
1164 $yearcomp = sprintf("%02d", idate("y", $date) + $yearoffset);
1165 } elseif ($yearlen == 1) {
1166 $yearcomp = (int) substr(date('y', $date), 1, 1) + $yearoffset;
1167 }
1168 if ($monthcomp > 1 && empty($resetEveryMonth)) { // Test with month is useless if monthcomp = 0 or 1 (0 is same as 1) (regis: $monthcomp can't equal 0)
1169 if ($yearlen == 4) {
1170 $yearcomp1 = sprintf("%04d", idate("Y", $date) + $yearoffset + 1);
1171 } elseif ($yearlen == 2) {
1172 $yearcomp1 = sprintf("%02d", idate("y", $date) + $yearoffset + 1);
1173 } else {
1174 $yearcomp1 = '';
1175 }
1176
1177 $sqlwhere .= "(";
1178 $sqlwhere .= " (SUBSTRING(".$field.", ".$yearpos.", ".$yearlen.") = '".$db->escape($yearcomp)."'";
1179 $sqlwhere .= " AND SUBSTRING(".$field.", ".$monthpos.", ".$monthlen.") >= '".str_pad($monthcomp, $monthlen, '0', STR_PAD_LEFT)."')";
1180 $sqlwhere .= " OR";
1181 $sqlwhere .= " (SUBSTRING(".$field.", ".$yearpos.", ".$yearlen.") = '".$db->escape($yearcomp1)."'";
1182 $sqlwhere .= " AND SUBSTRING(".$field.", ".$monthpos.", ".$monthlen.") < '".str_pad($monthcomp, $monthlen, '0', STR_PAD_LEFT)."') ";
1183 $sqlwhere .= ')';
1184 } elseif ($resetEveryMonth) {
1185 $sqlwhere .= "(SUBSTRING(".$field.", ".$yearpos.", ".$yearlen.") = '".$db->escape($yearcomp)."'";
1186 $sqlwhere .= " AND SUBSTRING(".$field.", ".$monthpos.", ".$monthlen.") = '".str_pad($monthcomp, $monthlen, '0', STR_PAD_LEFT)."')";
1187 } else { // reset is done on january
1188 $sqlwhere .= "(SUBSTRING(".$field.", ".$yearpos.", ".$yearlen.") = '".$db->escape($yearcomp)."')";
1189 }
1190 }
1191 //print "sqlwhere=".$sqlwhere." yearcomp=".$yearcomp."<br>\n"; // sqlwhere and yearcomp defined only if we ask a reset
1192 //print "masktri=".$masktri." maskcounter=".$maskcounter." maskraz=".$maskraz." maskoffset=".$maskoffset."<br>\n";
1193
1194 // Define $sqlstring
1195 if (function_exists('mb_strrpos')) {
1196 $posnumstart = mb_strrpos($maskwithnocode, $maskcounter, 0, 'UTF-8');
1197 } else {
1198 $posnumstart = strrpos($maskwithnocode, $maskcounter);
1199 } // Pos of counter in final string (from 0 to ...)
1200 if ($posnumstart < 0) {
1201 return 'ErrorBadMaskFailedToLocatePosOfSequence';
1202 }
1203 $sqlstring = "SUBSTRING(".$field.", ".($posnumstart + 1).", ".dol_strlen($maskcounter).")";
1204
1205 // Define $maskLike
1206 $maskLike = dol_string_nospecial($mask);
1207 $maskLike = str_replace("%", "_", $maskLike);
1208
1209 // Replace protected special codes with matching number of _ as wild card character
1210 $maskLike = preg_replace('/\{yyyy\}/i', '____', $maskLike);
1211 $maskLike = preg_replace('/\{yy\}/i', '__', $maskLike);
1212 $maskLike = preg_replace('/\{y\}/i', '_', $maskLike);
1213 $maskLike = preg_replace('/\{mm\}/i', '__', $maskLike);
1214 $maskLike = preg_replace('/\{dd\}/i', '__', $maskLike);
1215 // @phan-suppress-next-line PhanParamSuspiciousOrder
1216 $maskLike = str_replace(dol_string_nospecial('{'.$masktri.'}'), str_pad("", dol_strlen($maskcounter), "_"), $maskLike);
1217 if ($maskrefclient) {
1218 // @phan-suppress-next-line PhanParamSuspiciousOrder
1219 $maskLike = str_replace(dol_string_nospecial('{'.$maskrefclient.'}'), str_pad("", dol_strlen($maskrefclient), "_"), $maskLike);
1220 }
1221 if ($masktype) {
1222 $maskLike = str_replace(dol_string_nospecial('{'.$masktype.'}'), $masktype_value, $maskLike);
1223 }
1224 if ($maskuser) {
1225 $maskLike = str_replace(dol_string_nospecial('{'.$maskuser.'}'), $maskuser_value, $maskLike);
1226 }
1227 foreach ($maskperso as $key => $val) {
1228 $maskLike = str_replace(dol_string_nospecial($maskperso[$key]), $maskpersonew[$key], $maskLike);
1229 }
1230
1231 // Get counter in database
1232 $counter = 0;
1233 $sql = "SELECT MAX(".$sqlstring.") as val";
1234 $sql .= " FROM ".MAIN_DB_PREFIX.$table;
1235 $sql .= " WHERE ".$field." LIKE '".$db->escape($maskLike) . (getDolGlobalString('SEARCH_FOR_NEXT_VAL_ON_START_ONLY') ? "%" : "") . "'";
1236 $sql .= " AND ".$field." NOT LIKE '(PROV%)'";
1237
1238 // To ensure that all variables within the MAX() brackets are integers
1239 // This avoid bad detection of max when data are noised with non numeric values at the position of the numero
1240 if (getDolGlobalInt('MAIN_NUMBERING_FILTER_ON_INT_ONLY')) {
1241 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
1242 $sql .= " AND ". $db->regexpsql($sqlstring, '^[0-9]+$', 1);
1243 }
1244
1245 if ($bentityon) { // only if entity enable
1246 $sql .= " AND entity IN (".getEntity($sharetable).")";
1247 } elseif (!empty($forceentity)) {
1248 $sql .= " AND entity IN (".$db->sanitize($forceentity).")";
1249 }
1250 if ($where) {
1251 $sql .= $where;
1252 }
1253 if ($sqlwhere) {
1254 $sql .= " AND ".$sqlwhere;
1255 }
1256
1257 //print $sql.'<br>';
1258 dol_syslog("functions2::get_next_value mode=".$mode, LOG_DEBUG);
1259 $resql = $db->query($sql);
1260 if ($resql) {
1261 $obj = $db->fetch_object($resql);
1262 $counter = $obj->val;
1263 } else {
1264 dol_print_error($db);
1265 }
1266
1267 // Check if we must force counter to maskoffset
1268 if (empty($counter)) {
1269 $counter = $maskoffset;
1270 } elseif (preg_match('/[^0-9]/i', $counter)) {
1271 dol_syslog("Error, the last counter found is '".$counter."' so is not a numeric value. We will restart to 1.", LOG_ERR);
1272 $counter = 0;
1273 } elseif ($counter < $maskoffset && !getDolGlobalString('MAIN_NUMBERING_OFFSET_ONLY_FOR_FIRST')) {
1274 $counter = $maskoffset;
1275 }
1276
1277 if ($mode == 'last') { // We found value for counter = last counter value. Now need to get corresponding ref of invoice.
1278 $counterpadded = str_pad($counter, dol_strlen($maskcounter), "0", STR_PAD_LEFT);
1279
1280 // Define $maskLike
1281 $maskLike = dol_string_nospecial($mask);
1282 $maskLike = str_replace("%", "_", $maskLike);
1283 // Replace protected special codes with matching number of _ as wild card character
1284 $maskLike = preg_replace('/\{yyyy\}/i', '____', $maskLike);
1285 $maskLike = preg_replace('/\{yy\}/i', '__', $maskLike);
1286 $maskLike = preg_replace('/\{y\}/i', '_', $maskLike);
1287 $maskLike = preg_replace('/\{mm\}/i', '__', $maskLike);
1288 $maskLike = preg_replace('/\{dd\}/i', '__', $maskLike);
1289 $maskLike = str_replace(dol_string_nospecial('{'.$masktri.'}'), $counterpadded, $maskLike);
1290 if ($maskrefclient) {
1291 // @phan-suppress-next-line PhanParamSuspiciousOrder
1292 $maskLike = str_replace(dol_string_nospecial('{'.$maskrefclient.'}'), str_pad("", dol_strlen($maskrefclient), "_"), $maskLike);
1293 }
1294 if ($masktype) {
1295 $maskLike = str_replace(dol_string_nospecial('{'.$masktype.'}'), $masktype_value, $maskLike);
1296 }
1297 if ($maskuser) {
1298 $maskLike = str_replace(dol_string_nospecial('{'.$maskuser.'}'), $maskuser_value, $maskLike);
1299 }
1300
1301 $ref = '';
1302 $sql = "SELECT ".$field." as ref";
1303 $sql .= " FROM ".MAIN_DB_PREFIX.$table;
1304 $sql .= " WHERE ".$field." LIKE '".$db->escape($maskLike) . (getDolGlobalString('SEARCH_FOR_NEXT_VAL_ON_START_ONLY') ? "%" : "") . "'";
1305 $sql .= " AND ".$field." NOT LIKE '%PROV%'";
1306 if ($bentityon) { // only if entity enable
1307 $sql .= " AND entity IN (".getEntity($sharetable).")";
1308 } elseif (!empty($forceentity)) {
1309 $sql .= " AND entity IN (".$db->sanitize($forceentity).")";
1310 }
1311 if ($where) {
1312 $sql .= $where;
1313 }
1314 if ($sqlwhere) {
1315 $sql .= " AND ".$sqlwhere;
1316 }
1317
1318 dol_syslog("functions2::get_next_value mode=".$mode, LOG_DEBUG);
1319 $resql = $db->query($sql);
1320 if ($resql) {
1321 $obj = $db->fetch_object($resql);
1322 if ($obj) {
1323 $ref = $obj->ref;
1324 }
1325 } else {
1326 dol_print_error($db);
1327 }
1328
1329 $numFinal = $ref;
1330 } elseif ($mode == 'next') {
1331 $counter++;
1332 $maskrefclient_counter = 0;
1333
1334 // If value for $counter has a length higher than $maskcounter chars
1335 if ($counter >= pow(10, dol_strlen($maskcounter))) {
1336 $counter = 'ErrorMaxNumberReachForThisMask';
1337 }
1338
1339 if (!empty($maskrefclient_maskcounter)) {
1340 //print "maskrefclient_maskcounter=".$maskrefclient_maskcounter." maskwithnocode=".$maskwithnocode." maskrefclient=".$maskrefclient."\n<br>";
1341
1342 // Define $sqlstring
1343 $maskrefclient_posnumstart = strpos($maskwithnocode, $maskrefclient_maskcounter, strpos($maskwithnocode, $maskrefclient)); // Pos of counter in final string (from 0 to ...)
1344 if ($maskrefclient_posnumstart <= 0) {
1345 return 'ErrorBadMask';
1346 }
1347 $maskrefclient_sqlstring = 'SUBSTRING('.$field.', '.($maskrefclient_posnumstart + 1).', '.dol_strlen($maskrefclient_maskcounter).')';
1348 //print "x".$sqlstring;
1349
1350 // Define $maskrefclient_maskLike
1351 $maskrefclient_maskLike = dol_string_nospecial($mask);
1352 $maskrefclient_maskLike = str_replace("%", "_", $maskrefclient_maskLike);
1353 // Replace protected special codes with matching number of _ as wild card character
1354 $maskrefclient_maskLike = str_replace(dol_string_nospecial('{yyyy}'), '____', $maskrefclient_maskLike);
1355 $maskrefclient_maskLike = str_replace(dol_string_nospecial('{yy}'), '__', $maskrefclient_maskLike);
1356 $maskrefclient_maskLike = str_replace(dol_string_nospecial('{y}'), '_', $maskrefclient_maskLike);
1357 $maskrefclient_maskLike = str_replace(dol_string_nospecial('{mm}'), '__', $maskrefclient_maskLike);
1358 $maskrefclient_maskLike = str_replace(dol_string_nospecial('{dd}'), '__', $maskrefclient_maskLike);
1359 // @phan-suppress-next-line PhanParamSuspiciousOrder
1360 $maskrefclient_maskLike = str_replace(dol_string_nospecial('{'.$masktri.'}'), str_pad("", dol_strlen($maskcounter), "_"), $maskrefclient_maskLike);
1361 // @phan-suppress-next-line PhanParamSuspiciousOrder
1362 $maskrefclient_maskLike = str_replace(dol_string_nospecial('{'.$maskrefclient.'}'), $maskrefclient_clientcode.str_pad("", dol_strlen($maskrefclient_maskcounter), "_"), $maskrefclient_maskLike);
1363
1364 // Get counter in database
1365 $maskrefclient_sql = "SELECT MAX(".$maskrefclient_sqlstring.") as val";
1366 $maskrefclient_sql .= " FROM ".MAIN_DB_PREFIX.$table;
1367 //$sql.= " WHERE ".$field." not like '(%'";
1368 $maskrefclient_sql .= " WHERE ".$field." LIKE '".$db->escape($maskrefclient_maskLike) . (getDolGlobalString('SEARCH_FOR_NEXT_VAL_ON_START_ONLY') ? "%" : "") . "'";
1369 if ($bentityon) { // only if entity enable
1370 $maskrefclient_sql .= " AND entity IN (".getEntity($sharetable).")";
1371 } elseif (!empty($forceentity)) {
1372 $maskrefclient_sql .= " AND entity IN (".$db->sanitize($forceentity).")";
1373 }
1374 if ($where) {
1375 $maskrefclient_sql .= $where; //use the same optional where as general mask
1376 }
1377 if ($sqlwhere) {
1378 $maskrefclient_sql .= ' AND '.$sqlwhere; //use the same sqlwhere as general mask
1379 }
1380 $maskrefclient_sql .= " AND (SUBSTRING(".$field.", ".(strpos($maskwithnocode, $maskrefclient) + 1).", ".dol_strlen($maskrefclient_maskclientcode).") = '".$db->escape($maskrefclient_clientcode)."')";
1381
1382 dol_syslog("functions2::get_next_value maskrefclient", LOG_DEBUG);
1383 $maskrefclient_resql = $db->query($maskrefclient_sql);
1384 if ($maskrefclient_resql) {
1385 $maskrefclient_obj = $db->fetch_object($maskrefclient_resql);
1386 $maskrefclient_counter = $maskrefclient_obj->val;
1387 } else {
1388 dol_print_error($db);
1389 }
1390
1391 if (empty($maskrefclient_counter) || preg_match('/[^0-9]/i', $maskrefclient_counter)) {
1392 $maskrefclient_counter = $maskrefclient_maskoffset;
1393 }
1394 $maskrefclient_counter++;
1395 }
1396
1397 // Build numFinal
1398 $numFinal = $mask;
1399
1400 // We replace special codes except refclient
1401 if (!empty($yearoffsettype) && !is_numeric($yearoffsettype) && $yearoffsettype != '=') { // yearoffsettype is - or +, so we don't want current year
1402 $numFinal = preg_replace('/\{yyyy\}/i', (string) ((int) date("Y", $date) + $yearoffset), $numFinal);
1403 $numFinal = preg_replace('/\{yy\}/i', (string) ((int) date("y", $date) + $yearoffset), $numFinal);
1404 $numFinal = preg_replace('/\{y\}/i', (string) ((int) substr((string) date("y", $date), 1, 1) + $yearoffset), $numFinal);
1405 } else { // we want yyyy to be current year
1406 $numFinal = preg_replace('/\{yyyy\}/i', date("Y", $date), $numFinal);
1407 $numFinal = preg_replace('/\{yy\}/i', date("y", $date), $numFinal);
1408 $numFinal = preg_replace('/\{y\}/i', substr(date("y", $date), 1, 1), $numFinal);
1409 }
1410 $numFinal = preg_replace('/\{mm\}/i', date("m", $date), $numFinal);
1411 $numFinal = preg_replace('/\{dd\}/i', date("d", $date), $numFinal);
1412
1413 // Now we replace the counter
1414 $maskbefore = '{'.$masktri.'}';
1415 $maskafter = str_pad($counter, dol_strlen($maskcounter), "0", STR_PAD_LEFT);
1416 //print 'x'.$numFinal.' - '.$maskbefore.' - '.$maskafter.'y';exit;
1417 $numFinal = str_replace($maskbefore, $maskafter, $numFinal);
1418
1419 // Now we replace the refclient
1420 if ($maskrefclient) {
1421 //print "maskrefclient=".$maskrefclient." maskrefclient_counter=".$maskrefclient_counter." maskwithonlyymcode=".$maskwithonlyymcode." maskwithnocode=".$maskwithnocode." maskrefclient_clientcode=".$maskrefclient_clientcode." maskrefclient_maskcounter=".$maskrefclient_maskcounter."\n<br>";exit;
1422 $maskrefclient_maskbefore = '{'.$maskrefclient.'}';
1423 $maskrefclient_maskafter = $maskrefclient_clientcode;
1424 if (dol_strlen($maskrefclient_maskcounter) > 0) {
1425 $maskrefclient_maskafter .= str_pad((string) $maskrefclient_counter, dol_strlen($maskrefclient_maskcounter), "0", STR_PAD_LEFT);
1426 }
1427 $numFinal = str_replace($maskrefclient_maskbefore, (string) $maskrefclient_maskafter, $numFinal);
1428 }
1429
1430 // Now we replace the type
1431 if ($masktype) {
1432 $masktype_maskbefore = '{'.$masktype.'}';
1433 $masktype_maskafter = $masktype_value;
1434 $numFinal = str_replace($masktype_maskbefore, $masktype_maskafter, $numFinal);
1435 }
1436
1437 // Now we replace the user
1438 if ($maskuser) {
1439 $maskuser_maskbefore = '{'.$maskuser.'}';
1440 $maskuser_maskafter = $maskuser_value;
1441 $numFinal = str_replace($maskuser_maskbefore, $maskuser_maskafter, $numFinal);
1442 }
1443 } else {
1444 $numFinal = "ErrorBadMode";
1445 dol_syslog("functions2::get_next_value ErrorBadMode '$mode'", LOG_ERR);
1446 }
1447
1448 dol_syslog("functions2::get_next_value return ".$numFinal, LOG_DEBUG);
1449 return $numFinal;
1450}
1451
1463function get_string_between($string, $start, $end)
1464{
1465 $ini = strpos($string, $start);
1466 if ($ini === false) {
1467 return '';
1468 }
1469 $ini += strlen($start);
1470 $endpos = strpos($string, $end, $ini);
1471 if ($endpos === false) {
1472 return '';
1473 }
1474 return substr($string, $ini, $endpos - $ini);
1475}
1476
1484function check_value($mask, $value)
1485{
1486 $result = 0;
1487
1488 $hasglobalcounter = false;
1489 $maskrefclient_maskcounter = '';
1490
1491 // Extract value for mask counter, mask raz and mask offset
1492 $reg = array();
1493 if (preg_match('/\{(0+)([@\+][0-9]+)?([@\+][0-9]+)?\}/i', $mask, $reg)) {
1494 $masktri = $reg[1].(isset($reg[2]) ? $reg[2] : '').(isset($reg[3]) ? $reg[3] : '');
1495 $maskcounter = $reg[1];
1496 $hasglobalcounter = true;
1497 } else {
1498 // setting some defaults so the rest of the code won't fail if there is a third party counter
1499 $masktri = '00000';
1500 $maskcounter = '00000';
1501 }
1502 $maskraz = -1;
1503 $maskoffset = 0;
1504 if (dol_strlen($maskcounter) < 3) {
1505 return 'ErrorCounterMustHaveMoreThan3Digits';
1506 }
1507
1508 // Extract value for third party mask counter
1509 $regClientRef = array();
1510 if (preg_match('/\{(c+)(0*)\}/i', $mask, $regClientRef)) {
1511 $maskrefclient = $regClientRef[1].$regClientRef[2];
1512 $maskrefclient_maskclientcode = $regClientRef[1];
1513 $maskrefclient_maskcounter = $regClientRef[2];
1514 $maskrefclient_maskoffset = 0; //default value of maskrefclient_counter offset
1515 $maskrefclient_clientcode = substr('', 0, dol_strlen($maskrefclient_maskclientcode)); //get n first characters of client code to form maskrefclient_clientcode
1516 $maskrefclient_clientcode = str_pad($maskrefclient_clientcode, dol_strlen($maskrefclient_maskclientcode), "#", STR_PAD_RIGHT); //padding maskrefclient_clientcode for having exactly n characters in maskrefclient_clientcode
1517 $maskrefclient_clientcode = dol_string_nospecial($maskrefclient_clientcode); //sanitize maskrefclient_clientcode for sql insert and sql select like
1518 if (dol_strlen($maskrefclient_maskcounter) > 0 && dol_strlen($maskrefclient_maskcounter) < 3) {
1519 return 'ErrorCounterMustHaveMoreThan3Digits';
1520 }
1521 } else {
1522 $maskrefclient = '';
1523 }
1524
1525 // fail if there is neither a global nor a third party counter
1526 if (!$hasglobalcounter && ($maskrefclient_maskcounter == '')) {
1527 return 'ErrorBadMask';
1528 }
1529
1530 $maskwithonlyymcode = $mask;
1531 $maskwithonlyymcode = preg_replace('/\{(0+)([@\+][0-9]+)?([@\+][0-9]+)?\}/i', $maskcounter, $maskwithonlyymcode);
1532 $maskwithonlyymcode = preg_replace('/\{dd\}/i', 'dd', $maskwithonlyymcode);
1533 $maskwithonlyymcode = preg_replace('/\{(c+)(0*)\}/i', $maskrefclient, $maskwithonlyymcode);
1534 $maskwithnocode = $maskwithonlyymcode;
1535 $maskwithnocode = preg_replace('/\{yyyy\}/i', 'yyyy', $maskwithnocode);
1536 $maskwithnocode = preg_replace('/\{yy\}/i', 'yy', $maskwithnocode);
1537 $maskwithnocode = preg_replace('/\{y\}/i', 'y', $maskwithnocode);
1538 $maskwithnocode = preg_replace('/\{mm\}/i', 'mm', $maskwithnocode);
1539 // Now maskwithnocode = 0000ddmmyyyyccc for example
1540 // and maskcounter = 0000 for example
1541 //print "maskwithonlyymcode=".$maskwithonlyymcode." maskwithnocode=".$maskwithnocode."\n<br>";
1542
1543 // If an offset is asked
1544 if (!empty($reg[2]) && preg_match('/^\+/', $reg[2])) {
1545 $maskoffset = preg_replace('/^\+/', '', $reg[2]);
1546 }
1547 if (!empty($reg[3]) && preg_match('/^\+/', $reg[3])) {
1548 $maskoffset = preg_replace('/^\+/', '', $reg[3]);
1549 }
1550
1551 // Define $sqlwhere
1552
1553 // If a restore to zero after a month is asked we check if there is already a value for this year.
1554 if (!empty($reg[2]) && preg_match('/^@/', $reg[2])) {
1555 $maskraz = preg_replace('/^@/', '', $reg[2]);
1556 }
1557 if (!empty($reg[3]) && preg_match('/^@/', $reg[3])) {
1558 $maskraz = preg_replace('/^@/', '', $reg[3]);
1559 }
1560 if ($maskraz >= 0) {
1561 if ($maskraz == 99) {
1562 $maskraz = (int) date('m');
1563 $resetEveryMonth = true;
1564 }
1565 if ($maskraz > 12) {
1566 return 'ErrorBadMaskBadRazMonth';
1567 }
1568
1569 // Define reg
1570 if ($maskraz > 1 && !preg_match('/^(.*)\{(y+)\}\{(m+)\}/i', $maskwithonlyymcode, $reg)) {
1571 return 'ErrorCantUseRazInStartedYearIfNoYearMonthInMask';
1572 }
1573 if ($maskraz <= 1 && !preg_match('/^(.*)\{(y+)\}/i', $maskwithonlyymcode, $reg)) {
1574 return 'ErrorCantUseRazIfNoYearInMask';
1575 }
1576 //print "x".$maskwithonlyymcode." ".$maskraz;
1577 }
1578 //print "masktri=".$masktri." maskcounter=".$maskcounter." maskwithonlyymcode=".$maskwithonlyymcode." maskwithnocode=".$maskwithnocode." maskraz=".$maskraz." maskoffset=".$maskoffset."<br>\n";
1579
1580 if (function_exists('mb_strrpos')) {
1581 $posnumstart = mb_strrpos($maskwithnocode, $maskcounter, 0, 'UTF-8');
1582 } else {
1583 $posnumstart = strrpos($maskwithnocode, $maskcounter);
1584 } // Pos of counter in final string (from 0 to ...)
1585 if ($posnumstart < 0) {
1586 return 'ErrorBadMaskFailedToLocatePosOfSequence';
1587 }
1588
1589 // Check we have a number in $value at position ($posnumstart+1).', '.dol_strlen($maskcounter)
1590 // TODO
1591
1592 // Check length
1593 $len = dol_strlen($maskwithnocode);
1594 if (dol_strlen($value) != $len) {
1595 $result = -1;
1596 }
1597
1598 dol_syslog("functions2::check_value result=".$result, LOG_DEBUG);
1599 return $result;
1600}
1601
1610function binhex($bin, $pad = false, $upper = false)
1611{
1612 $last = dol_strlen($bin) - 1;
1613 $x = 0;
1614 for ($i = 0; $i <= $last; $i++) {
1615 $x += ($bin[$last - $i] ? 1 : 0) << $i;
1616 }
1617 $x = dechex($x);
1618 if ($pad) {
1619 while (dol_strlen($x) < intval(dol_strlen($bin)) / 4) {
1620 $x = "0$x";
1621 }
1622 }
1623 if ($upper) {
1624 $x = strtoupper($x);
1625 }
1626 return $x;
1627}
1628
1635function hexbin($hexa)
1636{
1637 $bin = '';
1638 $strLength = dol_strlen($hexa);
1639 for ($i = 0; $i < $strLength; $i++) {
1640 $bin .= str_pad(decbin(hexdec($hexa[$i])), 4, '0', STR_PAD_LEFT);
1641 }
1642 return $bin;
1643}
1644
1651function numero_semaine($time)
1652{
1653 $stime = dol_print_date($time, '%Y-%m-%d');
1654
1655 if (preg_match('/^([0-9]+)\-([0-9]+)\-([0-9]+)\s?([0-9]+)?:?([0-9]+)?/i', $stime, $reg)) {
1656 // Date est au format 'YYYY-MM-DD' ou 'YYYY-MM-DD HH:MM:SS'
1657 $annee = (int) $reg[1];
1658 $mois = (int) $reg[2];
1659 $jour = (int) $reg[3];
1660 } else {
1661 $annee = 0;
1662 $mois = 0;
1663 $jour = 0;
1664 }
1665
1666 /*
1667 * Norme ISO-8601:
1668 * - Week 1 of the year contains Jan 4th, or contains the first Thursday of January.
1669 * - Most years have 52 weeks, but 53 weeks for years starting on a Thursday and bisectile years that start on a Wednesday.
1670 * - The first day of a week is Monday
1671 */
1672
1673 // Definition du Jeudi de la semaine
1674 if ((int) date("w", mktime(12, 0, 0, $mois, $jour, $annee)) == 0) { // Dimanche
1675 $jeudiSemaine = mktime(12, 0, 0, $mois, $jour, $annee) - 3 * 24 * 60 * 60;
1676 } elseif (date("w", mktime(12, 0, 0, $mois, $jour, $annee)) < 4) { // du Lundi au Mercredi
1677 $jeudiSemaine = mktime(12, 0, 0, $mois, $jour, $annee) + (4 - (int) date("w", mktime(12, 0, 0, $mois, $jour, $annee))) * 24 * 60 * 60;
1678 } elseif ((int) date("w", mktime(12, 0, 0, $mois, $jour, $annee)) > 4) { // du Vendredi au Samedi
1679 $jeudiSemaine = mktime(12, 0, 0, $mois, $jour, $annee) - ((int) date("w", mktime(12, 0, 0, $mois, $jour, $annee)) - 4) * 24 * 60 * 60;
1680 } else { // Jeudi
1681 $jeudiSemaine = mktime(12, 0, 0, $mois, $jour, $annee);
1682 }
1683
1684 // Definition du premier Jeudi de l'annee
1685 if ((int) date("w", mktime(12, 0, 0, 1, 1, (int) date("Y", $jeudiSemaine))) == 0) { // Dimanche
1686 $premierJeudiAnnee = mktime(12, 0, 0, 1, 1, (int) date("Y", $jeudiSemaine)) + 4 * 24 * 60 * 60;
1687 } elseif ((int) date("w", mktime(12, 0, 0, 1, 1, (int) date("Y", $jeudiSemaine))) < 4) { // du Lundi au Mercredi
1688 $premierJeudiAnnee = mktime(12, 0, 0, 1, 1, (int) date("Y", $jeudiSemaine)) + (4 - (int) date("w", mktime(12, 0, 0, 1, 1, (int) date("Y", $jeudiSemaine)))) * 24 * 60 * 60;
1689 } elseif ((int) date("w", mktime(12, 0, 0, 1, 1, (int) date("Y", $jeudiSemaine))) > 4) { // du Vendredi au Samedi
1690 $premierJeudiAnnee = mktime(12, 0, 0, 1, 1, (int) date("Y", $jeudiSemaine)) + (7 - ((int) date("w", mktime(12, 0, 0, 1, 1, (int) date("Y", $jeudiSemaine))) - 4)) * 24 * 60 * 60;
1691 } else { // Jeudi
1692 $premierJeudiAnnee = mktime(12, 0, 0, 1, 1, (int) date("Y", $jeudiSemaine));
1693 }
1694
1695 // Definition du numero de semaine: nb de jours entre "premier Jeudi de l'annee" et "Jeudi de la semaine";
1696 $numeroSemaine = (
1697 (
1698 (int) date("z", mktime(12, 0, 0, (int) date("m", $jeudiSemaine), (int) date("d", $jeudiSemaine), (int) date("Y", $jeudiSemaine)))
1699 -
1700 (int) date("z", mktime(12, 0, 0, (int) date("m", $premierJeudiAnnee), (int) date("d", $premierJeudiAnnee), (int) date("Y", $premierJeudiAnnee)))
1701 ) / 7
1702 ) + 1;
1703
1704 // Cas particulier de la semaine 53
1705 if ($numeroSemaine == 53) {
1706 // Les annees qui commencent un Jeudi et les annees bissextiles commencant un Mercredi en possedent 53
1707 if (
1708 ((int) date("w", mktime(12, 0, 0, 1, 1, (int) date("Y", $jeudiSemaine))) == 4)
1709 || (
1710 ((int) date("w", mktime(12, 0, 0, 1, 1, (int) date("Y", $jeudiSemaine))) == 3)
1711 && ((int) date("z", mktime(12, 0, 0, 12, 31, (int) date("Y", $jeudiSemaine))) == 365)
1712 )
1713 ) {
1714 $numeroSemaine = 53;
1715 } else {
1716 $numeroSemaine = 1;
1717 }
1718 }
1719
1720 //echo $jour."-".$mois."-".$annee." (".date("d-m-Y",$premierJeudiAnnee)." - ".date("d-m-Y",$jeudiSemaine).") -> ".$numeroSemaine."<BR>";
1721
1722 return sprintf("%02d", $numeroSemaine);
1723}
1724
1733function weight_convert($weight, &$from_unit, $to_unit)
1734{
1735 /* Pour convertire 320 gr en Kg appeler
1736 * $f = -3
1737 * weigh_convert(320, $f, 0) retournera 0.32
1738 *
1739 */
1740 $weight = is_numeric($weight) ? $weight : 0;
1741 while ($from_unit != $to_unit) {
1742 if ($from_unit > $to_unit) {
1743 $weight *= 10;
1744 $from_unit -= 1;
1745 $weight = weight_convert($weight, $from_unit, $to_unit);
1746 }
1747 if ($from_unit < $to_unit) {
1748 $weight /= 10;
1749 $from_unit += 1;
1750 $weight = weight_convert($weight, $from_unit, $to_unit);
1751 }
1752 }
1753
1754 return $weight;
1755}
1756
1768function dol_set_user_param($db, $conf, &$user, $tab)
1769{
1770 // Verification parameters
1771 if (count($tab) < 1) {
1772 return -1;
1773 }
1774
1775 $db->begin();
1776
1777 // We remove old parameters for all keys in $tab
1778 $sql = "DELETE FROM ".MAIN_DB_PREFIX."user_param";
1779 $sql .= " WHERE fk_user = ".((int) $user->id);
1780 $sql .= " AND entity = ".((int) $conf->entity);
1781 $sql .= " AND param in (";
1782 $i = 0;
1783 foreach ($tab as $key => $value) {
1784 if ($i > 0) {
1785 $sql .= ',';
1786 }
1787 $sql .= "'".$db->escape($key)."'";
1788 $i++;
1789 }
1790 $sql .= ")";
1791 dol_syslog("functions2.lib::dol_set_user_param", LOG_DEBUG);
1792
1793 $resql = $db->query($sql);
1794 if (!$resql) {
1795 dol_print_error($db);
1796 $db->rollback();
1797 return -1;
1798 }
1799
1800 foreach ($tab as $key => $value) {
1801 // Set new parameters
1802 $forcevalue = 0;
1803 if (is_array($value)) {
1804 if ($value["forcevalue"] == 1) {
1805 $forcevalue = 1;
1806 }
1807 $value = $value["value"];
1808 }
1809 if ($forcevalue == 1 || $value) {
1810 $sql = "INSERT INTO ".MAIN_DB_PREFIX."user_param(fk_user,entity,param,value)";
1811 $sql .= " VALUES (".((int) $user->id).",".((int) $conf->entity).",";
1812 $sql .= " '".$db->escape($key)."','".$db->escape($value)."')";
1813
1814 dol_syslog("functions2.lib::dol_set_user_param", LOG_DEBUG);
1815 $result = $db->query($sql);
1816 if (!$result) {
1817 dol_print_error($db);
1818 $db->rollback();
1819 return -1;
1820 }
1821 $user->conf->$key = $value;
1822 //print "key=".$key." user->conf->key=".$user->conf->$key;
1823 } else {
1824 unset($user->conf->$key);
1825 }
1826 }
1827
1828 $db->commit();
1829 return 1;
1830}
1831
1839function dol_print_reduction($reduction, $langs)
1840{
1841 $string = '';
1842 if ($reduction == 100) {
1843 $string = $langs->transnoentities("Offered");
1844 } else {
1845 $string = vatrate((string) $reduction, true);
1846 }
1847
1848 return $string;
1849}
1850
1858function version_os($option = '')
1859{
1860 if ($option == 'smr') {
1861 $osversion = php_uname('s').' '.php_uname('m').' '.php_uname('r');
1862 } else {
1863 $osversion = php_uname();
1864 }
1865 return $osversion;
1866}
1867
1874function version_php()
1875{
1876 return phpversion();
1877}
1878
1884function version_db()
1885{
1886 global $db;
1887 if (is_object($db) && method_exists($db, 'getVersion')) {
1888 return $db->getVersion();
1889 }
1890 return '';
1891}
1892
1900{
1901 return DOL_VERSION;
1902}
1903
1910{
1911 return $_SERVER["SERVER_SOFTWARE"];
1912}
1913
1922function getListOfModels($db, $type, $maxfilenamelength = 0)
1923{
1924 global $conf, $langs;
1925 $liste = array();
1926 $found = 0;
1927 $dirtoscan = '';
1928
1929 $sql = "SELECT nom as id, nom as doc_template_name, libelle as label, description as description";
1930 $sql .= " FROM ".MAIN_DB_PREFIX."document_model";
1931 $sql .= " WHERE type = '".$db->escape($type)."'";
1932 $sql .= " AND entity IN (0,".$conf->entity.")";
1933 $sql .= " ORDER BY description DESC";
1934
1935 dol_syslog('/core/lib/function2.lib.php::getListOfModels', LOG_DEBUG);
1936 $resql_models = $db->query($sql);
1937 if ($resql_models) {
1938 $num = $db->num_rows($resql_models);
1939 $i = 0;
1940 while ($i < $num) {
1941 $found = 1;
1942
1943 $obj = $db->fetch_object($resql_models);
1944
1945 // If this generation module needs to scan a directory, then description field is filled
1946 // with the constant that contains list of directories to scan (COMPANY_ADDON_PDF_ODT_PATH, ...).
1947 if (!empty($obj->description)) { // A list of directories to scan is defined
1948 include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1949
1950 $const = $obj->description;
1951 $dirtoscan = preg_replace('/[\r\n]+/', ',', trim(getDolGlobalString($const)));
1952
1953 $listoffiles = array();
1954
1955 // Now we add models found in directories scanned
1956 $listofdir = explode(',', $dirtoscan);
1957 foreach ($listofdir as $key => $tmpdir) {
1958 $tmpdir = trim($tmpdir);
1959 $tmpdir = preg_replace('/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir);
1960 if (!$tmpdir) {
1961 unset($listofdir[$key]);
1962 continue;
1963 }
1964 if (is_dir($tmpdir)) {
1965 // all type of template is allowed
1966 $tmpfiles = dol_dir_list($tmpdir, 'files', 0, '', array(), 'name', SORT_ASC, 0);
1967 if (count($tmpfiles)) {
1968 $listoffiles = array_merge($listoffiles, $tmpfiles);
1969 }
1970 }
1971 }
1972
1973 if (count($listoffiles)) {
1974 foreach ($listoffiles as $record) {
1975 $max = ($maxfilenamelength ? $maxfilenamelength : 28);
1976 $liste[$obj->id.':'.$record['fullname']] = dol_trunc($record['name'], $max, 'middle');
1977 }
1978 } else {
1979 $liste[0] = $obj->label.': '.$langs->trans("None");
1980 }
1981 } else {
1982 if ($type == 'member' && $obj->doc_template_name == 'standard') { // Special case, if member template, we add variant per format
1983 global $_Avery_Labels;
1984 include_once DOL_DOCUMENT_ROOT.'/core/lib/format_cards.lib.php';
1985 foreach ($_Avery_Labels as $key => $val) {
1986 $liste[$obj->id.':'.$key] = ($obj->label ? $obj->label : $obj->doc_template_name).' '.$val['name'];
1987 }
1988 } else {
1989 // Common usage
1990 $liste[$obj->id] = $obj->label ? $obj->label : $obj->doc_template_name;
1991 }
1992 }
1993 $i++;
1994 }
1995 } else {
1996 dol_print_error($db);
1997 return -1;
1998 }
1999
2000 if ($found) {
2001 return $liste;
2002 } else {
2003 return 0;
2004 }
2005}
2006
2014function is_ip($ip)
2015{
2016 // First we test if it is a valid IPv4
2017 if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
2018 // Then we test if it is a private range
2019 if (!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE)) {
2020 return 2;
2021 }
2022
2023 // Then we test if it is a reserved range
2024 if (!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_RES_RANGE)) {
2025 return 0;
2026 }
2027
2028 return 1;
2029 }
2030
2031 return 0;
2032}
2033
2041function dol_buildlogin($lastname, $firstname)
2042{
2043 //$conf->global->MAIN_BUILD_LOGIN_RULE = 'f.lastname';
2044 $charforseparator = getDolGlobalString("MAIN_USER_SEPARATOR_CHAR_FOR_GENERATED_LOGIN", '.');
2045 if ($charforseparator == 'none') {
2046 $charforseparator = '';
2047 }
2048
2049 if (getDolGlobalString('MAIN_BUILD_LOGIN_RULE') == 'f.lastname') { // f.lastname
2050 $login = strtolower(dol_string_unaccent(dol_trunc($firstname, 1, 'right', 'UTF-8', 1)));
2051 $login .= ($login ? $charforseparator : '');
2052 $login .= strtolower(dol_string_unaccent($lastname));
2053 $login = dol_string_nospecial($login, ''); // For special names
2054 } else { // firstname.lastname
2055 $login = strtolower(dol_string_unaccent($firstname));
2056 $login .= ($login ? $charforseparator : '');
2057 $login .= strtolower(dol_string_unaccent($lastname));
2058 $login = dol_string_nospecial($login, ''); // For special names
2059 }
2060
2061 // TODO Add a hook to allow external modules to suggest new rules
2062
2063 return $login;
2064}
2065
2072{
2073 global $conf;
2074
2075 $params = array();
2076 $proxyuse = getDolGlobalString('MAIN_PROXY_USE');
2077 $proxyhost = (!$proxyuse ? false : $conf->global->MAIN_PROXY_HOST);
2078 $proxyport = (!$proxyuse ? false : $conf->global->MAIN_PROXY_PORT);
2079 $proxyuser = (!$proxyuse ? false : $conf->global->MAIN_PROXY_USER);
2080 $proxypass = (!$proxyuse ? false : $conf->global->MAIN_PROXY_PASS);
2081 $timeout = getDolGlobalInt('MAIN_USE_CONNECT_TIMEOUT', 10); // Connection timeout
2082 $response_timeout = getDolGlobalInt('MAIN_USE_RESPONSE_TIMEOUT', 30); // Response timeout
2083 //print extension_loaded('soap');
2084 if ($proxyuse) {
2085 $params = array('connection_timeout' => $timeout,
2086 'response_timeout' => $response_timeout,
2087 'proxy_use' => 1,
2088 'proxy_host' => $proxyhost,
2089 'proxy_port' => $proxyport,
2090 'proxy_login' => $proxyuser,
2091 'proxy_password' => $proxypass,
2092 'trace' => 1
2093 );
2094 } else {
2095 $params = array('connection_timeout' => $timeout,
2096 'response_timeout' => $response_timeout,
2097 'proxy_use' => 0,
2098 'proxy_host' => false,
2099 'proxy_port' => false,
2100 'proxy_login' => false,
2101 'proxy_password' => false,
2102 'trace' => 1
2103 );
2104 }
2105 return $params;
2106}
2107
2108
2118function dolGetElementUrl($objectid, $objecttype, $withpicto = 0, $option = '')
2119{
2120 global $db, $conf, $langs;
2121
2122 $ret = '';
2123 $regs = array();
2124
2125 // If we ask a resource form external module (instead of default path)
2126 if (preg_match('/^([^@]+)@([^@]+)$/i', $objecttype, $regs)) {
2127 $myobject = $regs[1];
2128 $module = $regs[2];
2129 } else {
2130 // Parse $objecttype (ex: project_task)
2131 $module = $myobject = $objecttype;
2132 if (preg_match('/^([^_]+)_([^_]+)/i', $objecttype, $regs)) {
2133 $module = $regs[1];
2134 $myobject = $regs[2];
2135 }
2136 }
2137
2138 // Generic case for $classpath
2139 $classpath = $module.'/class';
2140
2141 // Special cases, to work with non standard path
2142 if ($objecttype == 'facture' || $objecttype == 'invoice') {
2143 $langs->load('bills');
2144 $classpath = 'compta/facture/class';
2145 $module = 'facture';
2146 $myobject = 'facture';
2147 } elseif ($objecttype == 'commande' || $objecttype == 'order') {
2148 $langs->load('orders');
2149 $classpath = 'commande/class';
2150 $module = 'commande';
2151 $myobject = 'commande';
2152 } elseif ($objecttype == 'propal') {
2153 $langs->load('propal');
2154 $classpath = 'comm/propal/class';
2155 } elseif ($objecttype == 'supplier_proposal') {
2156 $langs->load('supplier_proposal');
2157 $classpath = 'supplier_proposal/class';
2158 } elseif ($objecttype == 'shipping') {
2159 $langs->load('sendings');
2160 $classpath = 'expedition/class';
2161 $myobject = 'expedition';
2162 $module = 'expedition_bon';
2163 } elseif ($objecttype == 'delivery') {
2164 $langs->load('deliveries');
2165 $classpath = 'delivery/class';
2166 $myobject = 'delivery';
2167 $module = 'delivery_note';
2168 } elseif ($objecttype == 'contract') {
2169 $langs->load('contracts');
2170 $classpath = 'contrat/class';
2171 $module = 'contrat';
2172 $myobject = 'contrat';
2173 } elseif ($objecttype == 'member') {
2174 $langs->load('members');
2175 $classpath = 'adherents/class';
2176 $module = 'adherent';
2177 $myobject = 'adherent';
2178 } elseif ($objecttype == 'cabinetmed_cons') {
2179 $classpath = 'cabinetmed/class';
2180 $module = 'cabinetmed';
2181 $myobject = 'cabinetmedcons';
2182 } elseif ($objecttype == 'fichinter') {
2183 $langs->load('interventions');
2184 $classpath = 'fichinter/class';
2185 $module = 'ficheinter';
2186 $myobject = 'fichinter';
2187 } elseif ($objecttype == 'project') {
2188 $langs->load('projects');
2189 $classpath = 'projet/class';
2190 $module = 'projet';
2191 } elseif ($objecttype == 'task') {
2192 $langs->load('projects');
2193 $classpath = 'projet/class';
2194 $module = 'projet';
2195 $myobject = 'task';
2196 } elseif ($objecttype == 'stock') {
2197 $classpath = 'product/stock/class';
2198 $module = 'stock';
2199 $myobject = 'stock';
2200 } elseif ($objecttype == 'inventory') {
2201 $classpath = 'product/inventory/class';
2202 $module = 'stock';
2203 $myobject = 'inventory';
2204 } elseif ($objecttype == 'mo') {
2205 $classpath = 'mrp/class';
2206 $module = 'mrp';
2207 $myobject = 'mo';
2208 } elseif ($objecttype == 'productlot') {
2209 $classpath = 'product/stock/class';
2210 $module = 'stock';
2211 $myobject = 'productlot';
2212 }
2213
2214 // Generic case for $classfile and $classname
2215 $classfile = strtolower($myobject);
2216 $classname = ucfirst($myobject);
2217 //print "objecttype=".$objecttype." module=".$module." subelement=".$subelement." classfile=".$classfile." classname=".$classname." classpath=".$classpath;
2218
2219 if ($objecttype == 'invoice_supplier') {
2220 $classfile = 'fournisseur.facture';
2221 $classname = 'FactureFournisseur';
2222 $classpath = 'fourn/class';
2223 $module = 'fournisseur';
2224 } elseif ($objecttype == 'order_supplier') {
2225 $classfile = 'fournisseur.commande';
2226 $classname = 'CommandeFournisseur';
2227 $classpath = 'fourn/class';
2228 $module = 'fournisseur';
2229 } elseif ($objecttype == 'supplier_proposal') {
2230 $classfile = 'supplier_proposal';
2231 $classname = 'SupplierProposal';
2232 $classpath = 'supplier_proposal/class';
2233 $module = 'supplier_proposal';
2234 } elseif ($objecttype == 'stock') {
2235 $classpath = 'product/stock/class';
2236 $classfile = 'entrepot';
2237 $classname = 'Entrepot';
2238 } elseif ($objecttype == 'facturerec') {
2239 $classpath = 'compta/facture/class';
2240 $classfile = 'facture-rec';
2241 $classname = 'FactureRec';
2242 $module = 'facture';
2243 } elseif ($objecttype == 'mailing') {
2244 $classpath = 'comm/mailing/class';
2245 $classfile = 'mailing';
2246 $classname = 'Mailing';
2247 }
2248
2249 if (isModEnabled($module)) {
2250 $res = dol_include_once('/'.$classpath.'/'.$classfile.'.class.php');
2251 if ($res) {
2252 if (class_exists($classname)) {
2253 $object = new $classname($db);
2254 $res = $object->fetch($objectid);
2255 if ($res > 0) {
2256 $ret = $object->getNomUrl($withpicto, $option);
2257 } elseif ($res == 0) {
2258 $ret = $langs->trans('Deleted');
2259 }
2260 unset($object);
2261 } else {
2262 dol_syslog("Class with classname ".$classname." is unknown even after the include", LOG_ERR);
2263 }
2264 }
2265 }
2266 return $ret;
2267}
2268
2269
2278function cleanCorruptedTree($db, $tabletocleantree, $fieldfkparent)
2279{
2280 $totalnb = 0;
2281 $listofid = array();
2282 $listofparentid = array();
2283
2284 // Get list of all id in array listofid and all parents in array listofparentid
2285 $sql = "SELECT rowid, ".$fieldfkparent." as parent_id FROM ".MAIN_DB_PREFIX.$tabletocleantree;
2286 $resql = $db->query($sql);
2287 if ($resql) {
2288 $num = $db->num_rows($resql);
2289 $i = 0;
2290 while ($i < $num) {
2291 $obj = $db->fetch_object($resql);
2292 $listofid[] = $obj->rowid;
2293 if ($obj->parent_id > 0) {
2294 $listofparentid[$obj->rowid] = $obj->parent_id;
2295 }
2296 $i++;
2297 }
2298 } else {
2299 dol_print_error($db);
2300 }
2301
2302 if (count($listofid)) {
2303 print 'Code requested to clean tree (may be to solve data corruption), so we check/clean orphelins and loops.'."<br>\n";
2304
2305 // Check loops on each other
2306 $sql = "UPDATE ".MAIN_DB_PREFIX.$tabletocleantree." SET ".$fieldfkparent." = 0 WHERE ".$fieldfkparent." = rowid"; // So we update only records linked to themself
2307 $resql = $db->query($sql);
2308 if ($resql) {
2309 $nb = $db->affected_rows($resql);
2310 if ($nb > 0) {
2311 print '<br>Some record that were parent of themself were cleaned.';
2312 }
2313
2314 $totalnb += $nb;
2315 }
2316 //else dol_print_error($db);
2317
2318 // Check other loops
2319 $listofidtoclean = array();
2320 foreach ($listofparentid as $id => $pid) {
2321 // Check depth
2322 //print 'Analyse record id='.$id.' with parent '.$pid.'<br>';
2323
2324 $cursor = $id;
2325 $arrayidparsed = array(); // We start from child $id
2326 while ($cursor > 0) {
2327 $arrayidparsed[$cursor] = 1;
2328 if ($arrayidparsed[$listofparentid[$cursor]]) { // We detect a loop. A record with a parent that was already into child
2329 print 'Found a loop between id '.$id.' - '.$cursor.'<br>';
2330 unset($arrayidparsed);
2331 $listofidtoclean[$cursor] = $id;
2332 break;
2333 }
2334 // @phpstan-ignore-next-line PHPStan thinks this line is never reached
2335 $cursor = $listofparentid[$cursor];
2336 }
2337
2338 if (count($listofidtoclean)) {
2339 break;
2340 }
2341 }
2342
2343 $sql = "UPDATE ".MAIN_DB_PREFIX.$db->sanitize($tabletocleantree);
2344 $sql .= " SET ".$db->sanitize($fieldfkparent)." = 0";
2345 $sql .= " WHERE rowid IN (".$db->sanitize(implode(',', $listofidtoclean)).")"; // So we update only records detected wrong
2346 $resql = $db->query($sql);
2347 if ($resql) {
2348 $nb = $db->affected_rows($resql);
2349 if ($nb > 0) {
2350 // Removed orphelins records
2351 print '<br>Some records were detected to have parent that is a child, we set them as root record for id: ';
2352 print implode(',', $listofidtoclean);
2353 }
2354
2355 $totalnb += $nb;
2356 }
2357 //else dol_print_error($db);
2358
2359 // Check and clean orphelins
2360 $sql = "UPDATE ".MAIN_DB_PREFIX.$db->sanitize($tabletocleantree);
2361 $sql .= " SET ".$db->sanitize($fieldfkparent)." = 0";
2362 $sql .= " WHERE ".$db->sanitize($fieldfkparent)." NOT IN (".$db->sanitize(implode(',', $listofid), 1).")"; // So we update only records linked to a non existing parent
2363 $resql = $db->query($sql);
2364 if ($resql) {
2365 $nb = $db->affected_rows($resql);
2366 if ($nb > 0) {
2367 // Removed orphelins records
2368 print '<br>Some orphelins were found and modified to be parent so records are visible again for id: ';
2369 print implode(',', $listofid);
2370 }
2371
2372 $totalnb += $nb;
2373 }
2374 //else dol_print_error($db);
2375
2376 print '<br>We fixed '.$totalnb.' record(s). Some records may still be corrupted. New check may be required.';
2377 return $totalnb;
2378 }
2379 return -1;
2380}
2381
2382
2392function colorArrayToHex($arraycolor, $colorifnotfound = '888888')
2393{
2394 if (!is_array($arraycolor)) {
2395 return $colorifnotfound;
2396 }
2397 if (empty($arraycolor)) {
2398 return $colorifnotfound;
2399 }
2400 return sprintf("%02s", dechex($arraycolor[0])).sprintf("%02s", dechex($arraycolor[1])).sprintf("%02s", dechex($arraycolor[2]));
2401}
2402
2413function colorStringToArray($stringcolor, $colorifnotfound = array(88, 88, 88))
2414{
2415 if (is_array($stringcolor)) {
2416 return $stringcolor; // If already in the correct output format, we return as is
2417 }
2418 $reg = array();
2419 $tmp = preg_match('/^#?([0-9a-fA-F][0-9a-fA-F])([0-9a-fA-F][0-9a-fA-F])([0-9a-fA-F][0-9a-fA-F])$/', $stringcolor, $reg);
2420 if (!$tmp) {
2421 $tmp = array_map('intval', explode(',', $stringcolor));
2422 '@phan-var-force int[] $tmp';
2423 if (count($tmp) < 3) {
2424 return $colorifnotfound;
2425 }
2426 return $tmp;
2427 }
2428 return array(hexdec($reg[1]), hexdec($reg[2]), hexdec($reg[3]));
2429}
2430
2436function colorValidateHex($color, $allow_white = true)
2437{
2438 if (!$allow_white && ($color === '#fff' || $color === '#ffffff')) {
2439 return false;
2440 }
2441
2442 if (preg_match('/^#[a-f0-9]{6}$/i', $color)) { //hex color is valid
2443 return true;
2444 }
2445 return false;
2446}
2447
2457function colorAgressiveness($hex, $ratio = -50, $brightness = 0)
2458{
2459 if (empty($ratio)) {
2460 $ratio = 0; // To avoid null
2461 }
2462
2463 // Steps should be between -255 and 255. Negative = darker, positive = lighter
2464 $ratio = max(-100, min(100, $ratio));
2465
2466 // Normalize into a six character long hex string
2467 $hex = str_replace('#', '', $hex);
2468 if (strlen($hex) == 3) {
2469 $hex = str_repeat(substr($hex, 0, 1), 2).str_repeat(substr($hex, 1, 1), 2).str_repeat(substr($hex, 2, 1), 2);
2470 }
2471
2472 // Split into three parts: R, G and B
2473 $color_parts = str_split($hex, 2);
2474 $return = '#';
2475
2476 foreach ($color_parts as $color) {
2477 $color = hexdec($color); // Convert to decimal
2478 if ($ratio > 0) { // We increase aggressivity
2479 if ($color > 127) {
2480 $color += ((255 - $color) * ($ratio / 100));
2481 }
2482 if ($color < 128) {
2483 $color -= ($color * ($ratio / 100));
2484 }
2485 } else { // We decrease aggressiveness
2486 if ($color > 128) {
2487 $color -= (($color - 128) * (abs($ratio) / 100));
2488 }
2489 if ($color < 127) {
2490 $color += ((128 - $color) * (abs($ratio) / 100));
2491 }
2492 }
2493 if ($brightness > 0) {
2494 $color = ($color * (100 + abs($brightness)) / 100);
2495 } else {
2496 $color = ($color * (100 - abs($brightness)) / 100);
2497 }
2498
2499 $color = max(0, min(255, $color)); // Adjust color to stay into valid range
2500 $return .= str_pad(dechex($color), 2, '0', STR_PAD_LEFT); // Make two char hex code
2501 }
2502
2503 //var_dump($hex.' '.$ratio.' -> '.$return);
2504 return $return;
2505}
2506
2513function colorAdjustBrightness($hex, $steps)
2514{
2515 // Steps should be between -255 and 255. Negative = darker, positive = lighter
2516 $steps = max(-255, min(255, $steps));
2517
2518 // Normalize into a six character long hex string
2519 $hex = str_replace('#', '', $hex);
2520 if (strlen($hex) == 3) {
2521 $hex = str_repeat(substr($hex, 0, 1), 2).str_repeat(substr($hex, 1, 1), 2).str_repeat(substr($hex, 2, 1), 2);
2522 }
2523
2524 // Split into three parts: R, G and B
2525 $color_parts = str_split($hex, 2);
2526 $return = '#';
2527
2528 foreach ($color_parts as $color) {
2529 $color = hexdec($color); // Convert to decimal
2530 $color = max(0, min(255, $color + $steps)); // Adjust color
2531 $return .= str_pad(dechex($color), 2, '0', STR_PAD_LEFT); // Make two char hex code
2532 }
2533
2534 return $return;
2535}
2536
2542function colorDarker($hex, $percent)
2543{
2544 $steps = intval(255 * $percent / 100) * -1;
2545 return colorAdjustBrightness($hex, $steps);
2546}
2547
2553function colorLighten($hex, $percent)
2554{
2555 $steps = intval(255 * $percent / 100);
2556 return colorAdjustBrightness($hex, $steps);
2557}
2558
2559
2566function colorHexToRgb($hex, $alpha = false, $returnArray = false)
2567{
2568 $string = '';
2569 $hex = str_replace('#', '', $hex);
2570 $length = strlen($hex);
2571 $rgb = array();
2572 $rgb['r'] = hexdec($length == 6 ? substr($hex, 0, 2) : ($length == 3 ? str_repeat(substr($hex, 0, 1), 2) : 0));
2573 $rgb['g'] = hexdec($length == 6 ? substr($hex, 2, 2) : ($length == 3 ? str_repeat(substr($hex, 1, 1), 2) : 0));
2574 $rgb['b'] = hexdec($length == 6 ? substr($hex, 4, 2) : ($length == 3 ? str_repeat(substr($hex, 2, 1), 2) : 0));
2575 if ($alpha !== false) {
2576 $rgb['a'] = (float) $alpha;
2577 $string = 'rgba('.implode(',', array_map('strval', $rgb)).')';
2578 } else {
2579 $string = 'rgb('.implode(',', array_map('strval', $rgb)).')';
2580 }
2581
2582 if ($returnArray) {
2583 return $rgb;
2584 } else {
2585 return $string;
2586 }
2587}
2588
2597function colorHexToHsl($hex, $alpha = false, $returnArray = false)
2598{
2599 $hex = str_replace('#', '', $hex);
2600 $red = hexdec(substr($hex, 0, 2)) / 255;
2601 $green = hexdec(substr($hex, 2, 2)) / 255;
2602 $blue = hexdec(substr($hex, 4, 2)) / 255;
2603
2604 $cmin = min($red, $green, $blue);
2605 $cmax = max($red, $green, $blue);
2606 $delta = $cmax - $cmin;
2607
2608 if ($delta == 0) {
2609 $hue = 0;
2610 } elseif ($cmax === $red) {
2611 $hue = (($green - $blue) / $delta);
2612 } elseif ($cmax === $green) {
2613 $hue = ($blue - $red) / $delta + 2;
2614 } else {
2615 $hue = ($red - $green) / $delta + 4;
2616 }
2617
2618 $hue = round($hue * 60);
2619 if ($hue < 0) {
2620 $hue += 360;
2621 }
2622
2623 $lightness = (($cmax + $cmin) / 2);
2624 $saturation = $delta === 0 ? 0 : ($delta / (1 - abs(2 * $lightness - 1)));
2625 if ($saturation < 0) {
2626 $saturation += 1;
2627 }
2628
2629 $lightness = round($lightness * 100);
2630 $saturation = round($saturation * 100);
2631
2632 if ($returnArray) {
2633 return array(
2634 'h' => $hue,
2635 'l' => $lightness,
2636 's' => $saturation,
2637 'a' => $alpha === false ? 1 : $alpha
2638 );
2639 } elseif ($alpha) {
2640 return 'hsla('.$hue.', '.$saturation.', '.$lightness.' / '.$alpha.')';
2641 } else {
2642 return 'hsl('.$hue.', '.$saturation.', '.$lightness.')';
2643 }
2644}
2645
2653function cartesianArray(array $input)
2654{
2655 // filter out empty values
2656 $input = array_filter($input);
2657
2658 $result = array(array());
2659
2660 foreach ($input as $key => $values) {
2661 $append = array();
2662
2663 foreach ($result as $product) {
2664 foreach ($values as $item) {
2665 $product[$key] = $item;
2666 $append[] = $product;
2667 }
2668 }
2669
2670 $result = $append;
2671 }
2672
2673 return $result;
2674}
2675
2676
2683function getModuleDirForApiClass($moduleobject)
2684{
2685 $moduledirforclass = $moduleobject;
2686 if ($moduledirforclass != 'api') {
2687 $moduledirforclass = preg_replace('/api$/i', '', $moduledirforclass);
2688 }
2689
2690 if ($moduleobject == 'contracts') {
2691 $moduledirforclass = 'contrat';
2692 } elseif (in_array($moduleobject, array('admin', 'login', 'setup', 'access', 'status', 'tools', 'documents'))) {
2693 $moduledirforclass = 'api';
2694 } elseif ($moduleobject == 'contact' || $moduleobject == 'contacts' || $moduleobject == 'customer' || $moduleobject == 'thirdparty' || $moduleobject == 'thirdparties') {
2695 $moduledirforclass = 'societe';
2696 } elseif ($moduleobject == 'propale' || $moduleobject == 'proposals') {
2697 $moduledirforclass = 'comm/propal';
2698 } elseif ($moduleobject == 'agenda' || $moduleobject == 'agendaevents') {
2699 $moduledirforclass = 'comm/action';
2700 } elseif ($moduleobject == 'adherent' || $moduleobject == 'members' || $moduleobject == 'memberstypes' || $moduleobject == 'subscriptions') {
2701 $moduledirforclass = 'adherents';
2702 } elseif ($moduleobject == 'don' || $moduleobject == 'donations') {
2703 $moduledirforclass = 'don';
2704 } elseif ($moduleobject == 'banque' || $moduleobject == 'bankaccounts') {
2705 $moduledirforclass = 'compta/bank';
2706 } elseif ($moduleobject == 'category' || $moduleobject == 'categorie') {
2707 $moduledirforclass = 'categories';
2708 } elseif ($moduleobject == 'order' || $moduleobject == 'orders') {
2709 $moduledirforclass = 'commande';
2710 } elseif ($moduleobject == 'shipments') {
2711 $moduledirforclass = 'expedition';
2712 } elseif ($moduleobject == 'multicurrencies') {
2713 $moduledirforclass = 'multicurrency';
2714 } elseif ($moduleobject == 'facture' || $moduleobject == 'invoice' || $moduleobject == 'invoices') {
2715 $moduledirforclass = 'compta/facture';
2716 } elseif ($moduleobject == 'project' || $moduleobject == 'projects' || $moduleobject == 'task' || $moduleobject == 'tasks') {
2717 $moduledirforclass = 'projet';
2718 } elseif ($moduleobject == 'stock' || $moduleobject == 'stockmovements' || $moduleobject == 'warehouses') {
2719 $moduledirforclass = 'product/stock';
2720 } elseif ($moduleobject == 'supplierproposals' || $moduleobject == 'supplierproposal' || $moduleobject == 'supplier_proposal') {
2721 $moduledirforclass = 'supplier_proposal';
2722 } elseif ($moduleobject == 'fournisseur' || $moduleobject == 'supplierinvoices' || $moduleobject == 'supplierorders') {
2723 $moduledirforclass = 'fourn';
2724 } elseif ($moduleobject == 'ficheinter' || $moduleobject == 'interventions') {
2725 $moduledirforclass = 'fichinter';
2726 } elseif ($moduleobject == 'mos') {
2727 $moduledirforclass = 'mrp';
2728 } elseif ($moduleobject == 'workstations') {
2729 $moduledirforclass = 'workstation';
2730 } elseif ($moduleobject == 'accounting') {
2731 $moduledirforclass = 'accountancy';
2732 } elseif (in_array($moduleobject, array('products', 'expensereports', 'users', 'tickets', 'boms', 'receptions', 'partnerships', 'recruitments'))) {
2733 $moduledirforclass = preg_replace('/s$/', '', $moduleobject);
2734 } elseif ($moduleobject == 'paymentsalaries') {
2735 $moduledirforclass = 'salaries';
2736 } elseif ($moduleobject == 'paymentexpensereports') {
2737 $moduledirforclass = 'expensereport';
2738 }
2739
2740 return $moduledirforclass;
2741}
2742
2750function randomColorPart($min = 0, $max = 255)
2751{
2752 return str_pad(dechex(mt_rand($min, $max)), 2, '0', STR_PAD_LEFT);
2753}
2754
2762function randomColor($min = 0, $max = 255)
2763{
2764 return randomColorPart($min, $max).randomColorPart($min, $max).randomColorPart($min, $max);
2765}
2766
2767
2768if (!function_exists('dolEscapeXML')) {
2775 function dolEscapeXML($string)
2776 {
2777 return strtr($string, array('\'' => '&apos;', '"' => '&quot;', '&' => '&amp;', '<' => '&lt;', '>' => '&gt;'));
2778 }
2779}
2780
2781
2789{
2790 global $dolibarr_main_url_root;
2791 // Define $urlwithroot
2792 $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
2793 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
2794 //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
2795 $notetoshow = preg_replace('/src="[a-zA-Z0-9_\/\-\.]*(viewimage\.php\?modulepart=medias[^"]*)"/', 'src="'.$urlwithroot.'/\1"', $notetoshow);
2796 return $notetoshow;
2797}
2798
2807function price2fec($amount)
2808{
2809 global $conf;
2810
2811 // Clean parameters
2812 if (empty($amount)) {
2813 $amount = 0; // To have a numeric value if amount not defined or = ''
2814 }
2815 $amount = (is_numeric($amount) ? $amount : 0); // Check if amount is numeric, for example, an error occurred when amount value = o (letter) instead 0 (number)
2816
2817 // Output decimal number by default
2818 $nbdecimal = (!getDolGlobalString('ACCOUNTING_FEC_DECIMAL_LENGTH') ? 2 : $conf->global->ACCOUNTING_FEC_DECIMAL_LENGTH);
2819
2820 // Output separators by default
2821 $dec = (!getDolGlobalString('ACCOUNTING_FEC_DECIMAL_SEPARATOR') ? ',' : $conf->global->ACCOUNTING_FEC_DECIMAL_SEPARATOR);
2822 $thousand = (!getDolGlobalString('ACCOUNTING_FEC_THOUSAND_SEPARATOR') ? '' : $conf->global->ACCOUNTING_FEC_THOUSAND_SEPARATOR);
2823
2824 // Format number
2825 $output = number_format($amount, $nbdecimal, $dec, $thousand);
2826
2827 return $output;
2828}
2829
2836function phpSyntaxError($code)
2837{
2838 if (!defined("CR")) {
2839 define("CR", "\r");
2840 }
2841 if (!defined("LF")) {
2842 define("LF", "\n");
2843 }
2844 if (!defined("CRLF")) {
2845 define("CRLF", "\r\n");
2846 }
2847
2848 $braces = 0;
2849 $inString = 0;
2850 foreach (token_get_all('<?php '.$code) as $token) {
2851 if (is_array($token)) {
2852 switch ($token[0]) {
2853 case T_CURLY_OPEN:
2854 case T_DOLLAR_OPEN_CURLY_BRACES:
2855 case T_START_HEREDOC:
2856 ++$inString;
2857 break;
2858 case T_END_HEREDOC:
2859 --$inString;
2860 break;
2861 }
2862 } elseif ($inString & 1) {
2863 switch ($token) {
2864 case '`':
2865 case '\'':
2866 case '"':
2867 --$inString;
2868 break;
2869 }
2870 } else {
2871 switch ($token) {
2872 case '`':
2873 case '\'':
2874 case '"':
2875 ++$inString;
2876 break;
2877 case '{':
2878 ++$braces;
2879 break;
2880 case '}':
2881 if ($inString) {
2882 --$inString;
2883 } else {
2884 --$braces;
2885 if ($braces < 0) {
2886 break 2;
2887 }
2888 }
2889 break;
2890 }
2891 }
2892 }
2893 $inString = @ini_set('log_errors', false);
2894 $token = @ini_set('display_errors', true);
2895 ob_start();
2896 $code = substr($code, strlen('<?php '));
2897 $braces || $code = "if(0){{$code}\n}";
2898 // @phan-suppress-next-line PhanPluginUnsafeEval
2899 if (eval($code) === false) {
2900 if ($braces) {
2901 $braces = PHP_INT_MAX;
2902 } else {
2903 false !== strpos($code, CR) && $code = strtr(str_replace(CRLF, LF, $code), CR, LF);
2904 $braces = substr_count($code, LF);
2905 }
2906 $code = ob_get_clean();
2907 $code = strip_tags($code);
2908 if (preg_match("'syntax error, (.+) in .+ on line (\d+)$'s", $code, $code)) {
2909 $code[2] = (int) $code[2];
2910 $code = $code[2] <= $braces
2911 ? array($code[1], $code[2])
2912 : array('unexpected $end'.substr($code[1], 14), $braces);
2913 } else {
2914 $code = array('syntax error', 0);
2915 }
2916 } else {
2917 ob_end_clean();
2918 $code = false;
2919 }
2920 @ini_set('display_errors', $token);
2921 @ini_set('log_errors', $inString);
2922 return $code;
2923}
2924
2925
2932{
2933 global $user;
2934
2935 // If $acceptlocallinktomedia is true, we can add link media files int email templates (we already can do this into HTML editor of an email).
2936 // Note that local link to a file into medias are replaced with a real link by email in CMailFile.class.php with value $urlwithroot defined like this:
2937 // $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
2938 // $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
2939 $acceptlocallinktomedia = getDolGlobalInt('MAIN_DISALLOW_MEDIAS_IN_EMAIL_TEMPLATES') ? 0 : 1;
2940 if ($acceptlocallinktomedia) {
2941 global $dolibarr_main_url_root;
2942 $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
2943
2944 // Parse $newUrl
2945 $newUrlArray = parse_url($urlwithouturlroot);
2946 $hosttocheck = $newUrlArray['host'];
2947 $hosttocheck = str_replace(array('[', ']'), '', $hosttocheck); // Remove brackets of IPv6
2948
2949 if (function_exists('gethostbyname')) {
2950 $iptocheck = gethostbyname($hosttocheck);
2951 } else {
2952 $iptocheck = $hosttocheck;
2953 }
2954
2955 //var_dump($iptocheck.' '.$acceptlocallinktomedia);
2956 $allowParamName = 'MAIN_ALLOW_WYSIWYG_LOCAL_MEDIAS_ON_PRIVATE_NETWORK';
2957 $allowPrivateNetworkIP = getDolGlobalInt($allowParamName);
2958 if (!$allowPrivateNetworkIP && !filter_var($iptocheck, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
2959 // If ip of public url is a private network IP, we do not allow this.
2960 $acceptlocallinktomedia = 0;
2961 //dol_syslog("WYSIWYG Editor : local media not allowed (checked IP: {$iptocheck}). Use {$allowParamName} = 1 to allow local URL into WYSIWYG html content");
2962 }
2963
2964 if (preg_match('/http:/i', $urlwithouturlroot)) {
2965 // If public url is not a https, we do not allow to add medias link. It will generate security alerts when email will be sent.
2966 $acceptlocallinktomedia = 0;
2967 // TODO Show a warning
2968 }
2969
2970 if (!empty($user->socid)) {
2971 $acceptlocallinktomedia = 0;
2972 }
2973 }
2974
2975 //return 1;
2976 return $acceptlocallinktomedia;
2977}
2978
2979
2987{
2988 $string = trim($string);
2989
2990 // If string does not start and end with parenthesis, we return $string as is.
2991 if (! preg_match('/^\‍(.*\‍)$/', $string)) {
2992 return $string;
2993 }
2994
2995 $nbofchars = dol_strlen($string);
2996 $i = 0;
2997 $g = 0;
2998 $countparenthesis = 0;
2999 while ($i < $nbofchars) {
3000 $char = dol_substr($string, $i, 1);
3001 if ($char == '(') {
3002 $countparenthesis++;
3003 } elseif ($char == ')') {
3004 $countparenthesis--;
3005 if ($countparenthesis <= 0) { // We reach the end of an independent group of parenthesis
3006 $g++;
3007 }
3008 }
3009 $i++;
3010 }
3011
3012 if ($g <= 1) {
3013 return preg_replace('/^\‍(/', '', preg_replace('/\‍)$/', '', $string));
3014 }
3015
3016 return $string;
3017}
3018
3019
3027{
3028 $arrayofcommonemoji = array(
3029 'misc' => array('2600', '26FF'), // Miscellaneous Symbols
3030 'ding' => array('2700', '27BF'), // Dingbats
3031 '????' => array('9989', '9989'), // Variation Selectors
3032 'vars' => array('FE00', 'FE0F'), // Variation Selectors
3033 'pict' => array('1F300', '1F5FF'), // Miscellaneous Symbols and Pictographs
3034 'emot' => array('1F600', '1F64F'), // Emoticons
3035 'tran' => array('1F680', '1F6FF'), // Transport and Map Symbols
3036 'flag' => array('1F1E0', '1F1FF'), // Flags (note: may be 1F1E6 instead of 1F1E0)
3037 'supp' => array('1F900', '1F9FF'), // Supplemental Symbols and Pictographs
3038 );
3039
3040 return $arrayofcommonemoji;
3041}
3042
3050function removeEmoji($text, $allowedemoji = 1)
3051{
3052 // $allowedemoji can be
3053 // 0=no emoji, 1=exclude the main known emojis (default), 2=keep only the main known (not implemented), 3=accept all
3054 // Note that to accept emoji in database, you must use utf8mb4, utf8mb3 is not enough.
3055
3056 if ($allowedemoji == 0) {
3057 // For a large removal:
3058 $text = preg_replace('/[\x{2600}-\x{FFFF}]/u', '', $text);
3059 $text = preg_replace('/[\x{10000}-\x{10FFFF}]/u', '', $text);
3060 }
3061
3062 // Delete emoji chars with a regex
3063 // See https://www.unicode.org/emoji/charts/full-emoji-list.html
3064 if ($allowedemoji == 1) {
3065 $arrayofcommonemoji = getArrayOfEmojiBis();
3066
3067 foreach ($arrayofcommonemoji as $key => $valarray) {
3068 $text = preg_replace('/[\x{'.$valarray[0].'}-\x{'.$valarray[1].'}]/u', '', $text);
3069 }
3070 }
3071
3072 if ($allowedemoji == 2) {
3073 // TODO Not yet implemented
3074 }
3075
3076 return $text;
3077}
3078
3079
3088function csvClean($newvalue, $charset = '', $separator = '')
3089{
3090 global $langs;
3091
3092 $addquote = 0;
3093
3094 if (empty($charset)) {
3095 $charset = getDolGlobalString('EXPORT_CSV_FORCE_CHARSET');
3096 }
3097 if (empty($separator)) {
3098 $separator = getDolGlobalString('EXPORT_CSV_SEPARATOR_TO_USE');
3099 }
3100
3101
3102 $newvalue = $langs->convToOutputCharset($newvalue, 'UTF-8', $charset); // newvalue is now encoded into $charset
3103
3104
3105 // Rule Dolibarr: No HTML
3106 //print $charset.' '.$newvalue."\n";
3107 //$newvalue=dol_string_nohtmltag($newvalue,0,$charset);
3108 $newvalue = dol_htmlcleanlastbr($newvalue);
3109 //print $charset.' '.$newvalue."\n";
3110
3111 // Rule 1 CSV: No CR, LF in cells (except if USE_STRICT_CSV_RULES is 1, we can keep record as it is but we must add quotes)
3112 $oldvalue = $newvalue;
3113 $newvalue = str_replace("\r", '', $newvalue);
3114 $newvalue = str_replace("\n", '\n', $newvalue);
3115 if (getDolGlobalString('USE_STRICT_CSV_RULES') && $oldvalue != $newvalue) {
3116 // If we must use enclusure on text with CR/LF)
3117 if (getDolGlobalInt('USE_STRICT_CSV_RULES') == 1) {
3118 // If we use strict CSV rules (original value must remain but we add quote)
3119 $newvalue = $oldvalue;
3120 }
3121 $addquote = 1;
3122 }
3123
3124 // Rule 2 CSV: If value contains ", we must escape with ", and add "
3125 if (preg_match('/"/', $newvalue)) {
3126 $addquote = 1;
3127 $newvalue = str_replace('"', '""', $newvalue);
3128 }
3129
3130 // Rule 3 CSV: If value contains separator, we must add "
3131 if (preg_match('/'.$separator.'/', $newvalue)) {
3132 $addquote = 1;
3133 }
3134
3135 return ($addquote ? '"' : '').$newvalue.($addquote ? '"' : '');
3136}
$id
Definition account.php:39
if( $user->socid > 0) if(! $user->hasRight('accounting', 'chartofaccount')) $object
Definition card.php:58
Class to manage Dolibarr users.
getServerTimeZoneInt($refgmtdate='now')
Return server timezone int.
Definition date.lib.php:86
dol_dir_list($utf8_path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0, $nbsecondsold=0)
Scan a directory and return a list of files/directories.
Definition files.lib.php:63
array2table($data, $tableMarkup=1, $tableoptions='', $troptions='', $tdoptions='')
Return an html table from an array.
dol_buildlogin($lastname, $firstname)
Build a login from lastname, firstname.
if(!function_exists( 'dolEscapeXML')) convertBackOfficeMediasLinksToPublicLinks($notetoshow)
Convert links to local wrapper to medias files into a string into a public external URL readable on i...
getArrayOfEmojiBis()
Return array of Emojis for miscellaneous use.
colorHexToRgb($hex, $alpha=false, $returnArray=false)
get_string_between($string, $start, $end)
Get string from "$start" up to "$end".
dolObfuscateEmail($mail, $replace="*", $nbreplace=8, $nbdisplaymail=4, $nbdisplaydomain=3, $displaytld=true)
Returns an email value with obfuscated parts.
version_webserver()
Return web server version.
getModuleDirForApiClass($moduleobject)
Get name of directory where the api_...class.php file is stored.
phpSyntaxError($code)
Check the syntax of some PHP code.
dolGetModulesDirs($subdir='')
Return list of directories that contain modules.
array2tr($data, $troptions='', $tdoptions='')
Return lines of an html table from an array Used by array2table function only.
version_dolibarr()
Return Dolibarr version.
binhex($bin, $pad=false, $upper=false)
Convert a binary data to string that represent hexadecimal value.
colorAgressiveness($hex, $ratio=-50, $brightness=0)
Change color to make it less aggressive (ratio is negative) or more aggressive (ratio is positive)
removeGlobalParenthesis($string)
Remove first and last parenthesis but only if first is the opening and last the closing of the same g...
cartesianArray(array $input)
Applies the Cartesian product algorithm to an array Source: http://stackoverflow.com/a/15973172.
getSoapParams()
Return array to use for SoapClient constructor.
colorAdjustBrightness($hex, $steps)
cleanCorruptedTree($db, $tabletocleantree, $fieldfkparent)
Clean corrupted database tree (orphelins linked to a not existing parent), record linked to themself,...
colorArrayToHex($arraycolor, $colorifnotfound='888888')
Convert an array with RGB value into hex RGB value.
dol_print_reduction($reduction, $langs)
Returns formatted reduction.
colorStringToArray($stringcolor, $colorifnotfound=array(88, 88, 88))
Convert a string RGB value ('FFFFFF', '255,255,255') into an array RGB array(255,255,...
acceptLocalLinktoMedia()
Check the syntax of some PHP code.
randomColor($min=0, $max=255)
Return hexadecimal color randomly.
is_ip($ip)
This function evaluates a string that should be a valid IPv4 Note: For ip 169.254....
check_value($mask, $value)
Check value.
weight_convert($weight, &$from_unit, $to_unit)
Convertit une masse d'une unite vers une autre unite.
clean_url($url, $http=1)
Clean an url string.
version_php()
Return PHP version.
colorHexToHsl($hex, $alpha=false, $returnArray=false)
Color Hex to Hsl (used for style)
dol_getDefaultFormat($outputlangs=null)
Try to guess default paper format according to language into $langs.
hexbin($hexa)
Convert an hexadecimal string into a binary string.
dol_set_user_param($db, $conf, &$user, $tab)
Save personal parameter.
numero_semaine($time)
Retourne le numero de la semaine par rapport a une date.
randomColorPart($min=0, $max=255)
Return 2 hexa code randomly.
colorDarker($hex, $percent)
dolGetElementUrl($objectid, $objecttype, $withpicto=0, $option='')
Return link url to an object.
getListOfModels($db, $type, $maxfilenamelength=0)
Return list of activated modules usable for document generation.
dol_print_object_info($object, $usetable=0)
Show information on an object TODO Move this into html.formother.
get_next_value($db, $mask, $table, $field, $where='', $objsoc='', $date='', $mode='next', $bentityon=true, $objuser=null, $forceentity=null)
Return last or next value for a mask (according to area we should not reset)
isValidUrl($url, $http=0, $pass=0, $port=0, $path=0, $query=0, $anchor=0)
Url string validation <http[s]> :// [user[:pass]@] hostname [port] [/path] [?getquery] [anchor].
version_db()
Return DB version.
isValidMailDomain($mail)
Return true if email has a domain name that can be resolved to MX type.
dolAddEmailTrackId($email, $trackingid)
Return an email formatted to include a tracking id For example myemail@example.com becom myemail+trac...
colorLighten($hex, $percent)
isValidVATID($company)
Check if VAT numero is valid (check done on syntax only, no database or remote access)
version_os($option='')
Return OS version.
price2fec($amount)
Function to format a value into a defined format for French administration (no thousand separator & d...
csvClean($newvalue, $charset='', $separator='')
Clean a cell to respect rules of CSV file cells.
removeEmoji($text, $allowedemoji=1)
Remove EMoji from email content.
jsUnEscape($source)
Same function than javascript unescape() function but in PHP.
colorValidateHex($color, $allow_white=true)
dol_html_entity_decode($a, $b, $c='UTF-8', $keepsomeentities=0)
Replace html_entity_decode functions to manage errors.
dol_mktime($hour, $minute, $second, $month, $day, $year, $gm='auto', $check=1)
Return a timestamp date built from detailed information (by default a local PHP server timestamp) Rep...
vatrate($rate, $addpercent=false, $info_bits=0, $usestarfornpr=0, $html=0)
Return a string with VAT rate label formatted for view output Used into pdf and HTML pages.
dol_string_nospecial($str, $newstr='_', $badcharstoreplace='', $badcharstoremove='', $keepspaces=0)
Clean a string from all punctuation characters to use it as a ref or login.
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
isValidMXRecord($domain)
Return if the domain name has a valid MX record.
dol_now($mode='auto')
Return date for now.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
if(!function_exists( 'dol_getprefix')) dol_include_once($relpath, $classname='')
Make an include_once using default root and alternate root if it fails.
dol_string_unaccent($str)
Clean a string from all accent characters to be used as ref, login or by dol_sanitizeFileName.
dol_htmlcleanlastbr($stringtodecode)
This function remove all ending and br at end.
dol_substr($string, $start, $length=null, $stringencoding='', $trunconbytes=0)
Make a substring.
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
dol_trunc($string, $size=40, $trunc='right', $stringencoding='UTF-8', $nodot=0, $display=0)
Truncate a string to a particular length adding '…' if string larger than length.
isValidEmail($address, $acceptsupervisorkey=0, $acceptuserkey=0)
Return true if email syntax is ok.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.