dolibarr 23.0.3
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-2025 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 // Creation
189 if (!empty($object->user_creation_id) || !empty($object->date_creation)) {
190 if ($usetable) {
191 print '<tr><td class="titlefield">';
192 }
193 print $langs->trans("Creation");
194 if ($usetable) {
195 print '</td><td>';
196 } else {
197 print ': ';
198 }
199 print '<div class="valignmiddle inline-block">';
200 if ($object->user_creation_id > 0) {
201 $userstatic = new User($db);
202 $userstatic->fetch($object->user_creation_id);
203 print $userstatic->getNomUrl(-1, '', 0, 0, 0);
204 } else {
205 print $langs->trans("Unknown");
206 }
207 print '</div>';
208
209 if (!empty($object->date_creation)) {
210 print ' - ';
211 print '<div class="valignmiddle inline-block">';
212 print dol_print_date($object->date_creation, 'dayhour', 'tzserver');
213 if ($deltadateforuser) {
214 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>';
215 }
216 print '</div>';
217 }
218
219 if ($usetable) {
220 print '</td></tr>';
221 } else {
222 print '<br>';
223 }
224 }
225
226 // Last modification
227 if (!empty($object->user_modification_id) || !empty($object->date_modification)) {
228 if ($usetable) {
229 print '<tr><td class="titlefield">';
230 }
231 print $langs->trans("LastModified");
232 if ($usetable) {
233 print '</td><td>';
234 } else {
235 print ': ';
236 }
237 print '<div class="valignmiddle inline-block">';
238 if ($object->user_modification_id > 0) {
239 $userstatic = new User($db);
240 $userstatic->fetch($object->user_modification_id);
241 print $userstatic->getNomUrl(-1, '', 0, 0, 0);
242 } else {
243 print $langs->trans("Unknown");
244 }
245 print '</div>';
246
247 if (!empty($object->date_modification)) {
248 print ' - ';
249 print '<div class="valignmiddle inline-block">';
250 print dol_print_date($object->date_modification, 'dayhour', 'tzserver');
251 if ($deltadateforuser) {
252 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>';
253 }
254 print '</div>';
255 }
256
257 if ($usetable) {
258 print '</td></tr>';
259 } else {
260 print '<br>';
261 }
262 }
263
264 // Validation
265 if (!empty($object->user_validation_id) || !empty($object->date_validation)) {
266 if ($usetable) {
267 print '<tr><td class="titlefield">';
268 }
269 print $langs->trans("Validation");
270 if ($usetable) {
271 print '</td><td>';
272 } else {
273 print ': ';
274 }
275 $userstatic = new User($db);
276 $userstatic->fetch($object->user_validation_id ? $object->user_validation_id : $object->user_validation);
277 if ($userstatic->id) {
278 print $userstatic->getNomUrl(-1, '', 0, 0, 0);
279 } else {
280 print $langs->trans("Unknown");
281 }
282
283 if (!empty($object->date_validation)) {
284 print ' - ';
285 print '<div class="valignmiddle inline-block">';
286 print dol_print_date($object->date_validation, 'dayhour', 'tzserver');
287 if ($deltadateforuser) {
288 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>';
289 }
290 print '</div>';
291 }
292
293 if ($usetable) {
294 print '</td></tr>';
295 } else {
296 print '<br>';
297 }
298 }
299
300 // Approval (old method using already loaded object and not id is kept for backward compatibility)
301 if (!empty($object->user_approve) || !empty($object->user_approve_id) || !empty($object->date_approve) || !empty($object->date_approval)) {
302 if ($usetable) {
303 print '<tr><td class="titlefield">';
304 }
305 print $langs->trans("Approval");
306 if ($usetable) {
307 print '</td><td>';
308 } else {
309 print ': ';
310 }
311 // user_approve is not defined in Dolibarr code @phan-suppress-next-line PhanUndeclaredProperty
312 if (!empty($object->user_approve) && is_object($object->user_approve)) {
313 if ($object->user_approve->id) { // @phan-suppress-current-line PhanUndeclaredProperty
314 // @phan-suppress-next-line PhanUndeclaredProperty,PhanPluginUnknownObjectMethodCall
315 print $object->user_approve->getNomUrl(-1, '', 0, 0, 0);
316 } else {
317 print $langs->trans("Unknown");
318 }
319 } else {
320 $userstatic = new User($db);
321 $userstatic->fetch($object->user_approve_id ? $object->user_approve_id : $object->user_approve);
322 if ($userstatic->id) {
323 print $userstatic->getNomUrl(-1, '', 0, 0, 0);
324 } else {
325 print $langs->trans("Unknown");
326 }
327 }
328
329 if (!empty($object->date_approve) || !empty($object->date_approval)) {
330 print ' - ';
331 print '<div class="valignmiddle inline-block">';
332 print dol_print_date($object->date_approve ? $object->date_approve : $object->date_approval, 'dayhour', 'tzserver');
333 if ($deltadateforuser) {
334 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>';
335 }
336 print '</div>';
337 }
338
339 if ($usetable) {
340 print '</td></tr>';
341 } else {
342 print '<br>';
343 }
344 }
345
346 // Approval
347 if (!empty($object->user_approve_id2) || !empty($object->date_approve2)) {
348 '@phan-var-force CommandeFournisseur $object';
349 if ($usetable) {
350 print '<tr><td class="titlefield">';
351 }
352 print $langs->trans("Approval");
353 if ($usetable) {
354 print '</td><td>';
355 } else {
356 print ': ';
357 }
358 $userstatic = new User($db);
359 $userstatic->fetch($object->user_approve_id2);
360 if ($userstatic->id) {
361 print $userstatic->getNomUrl(-1, '', 0, 0, 0);
362 } else {
363 print $langs->trans("Unknown");
364 }
365
366 if (!empty($object->date_approve2)) {
367 print ' - ';
368 print '<div class="valignmiddle inline-block">';
369 print dol_print_date($object->date_approve2, 'dayhour', 'tzserver');
370 if ($deltadateforuser) {
371 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>';
372 }
373 print '</div>';
374 }
375
376 if ($usetable) {
377 print '</td></tr>';
378 } else {
379 print '<br>';
380 }
381 }
382
383 // Signature
384 if (!empty($object->user_signature) || !empty($object->user_signature_id) || !empty($object->date_signature)) {
385 '@phan-var-force Propal $object';
386 if ($usetable) {
387 print '<tr><td class="titlefield">';
388 }
389 print $langs->trans('Signature');
390 if ($usetable) {
391 print '</td><td>';
392 } else {
393 print ': ';
394 }
395 if (is_object($object->user_signature)) {
396 if ($object->user_signature->id) {
397 print $object->user_signature->getNomUrl(-1, '', 0, 0, 0);
398 } else {
399 print $langs->trans('Unknown');
400 }
401 } else {
402 $userstatic = new User($db);
403 $userstatic->fetch($object->user_signature_id ? $object->user_signature_id : $object->user_signature);
404 if ($userstatic->id) {
405 print $userstatic->getNomUrl(-1, '', 0, 0, 0);
406 } else {
407 print $langs->trans('Unknown');
408 }
409 }
410
411 if (!empty($object->date_signature)) {
412 print ' - ';
413 print '<div class="valignmiddle inline-block">';
414 print dol_print_date($object->date_signature, 'dayhour');
415 if ($deltadateforuser) {
416 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>';
417 }
418 print '</div>';
419 }
420
421 if ($usetable) {
422 print '</td></tr>';
423 } else {
424 print '<br>';
425 }
426 }
427
428 // Closing
429 if (!empty($object->user_closing_id) || !empty($object->date_cloture) || !empty($object->date_closing)) {
430 if ($usetable) {
431 print '<tr><td class="titlefield">';
432 }
433 print $langs->trans("Closing");
434 if ($usetable) {
435 print '</td><td>';
436 } else {
437 print ': ';
438 }
439 $userstatic = new User($db);
440 $userstatic->fetch($object->user_closing_id);
441 if ($userstatic->id) {
442 print $userstatic->getNomUrl(-1, '', 0, 0, 0);
443 } else {
444 print $langs->trans("Unknown");
445 }
446
447 if (!empty($object->date_cloture) || !empty($object->date_closing)) {
448 if (isset($object->date_cloture) && !empty($object->date_cloture)) {
449 $object->date_closing = $object->date_cloture;
450 }
451 print ' - ';
452 print '<div class="valignmiddle inline-block">';
453 print dol_print_date($object->date_closing, 'dayhour', 'tzserver');
454 if ($deltadateforuser) {
455 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>';
456 }
457 print '</div>';
458 }
459
460 if ($usetable) {
461 print '</td></tr>';
462 } else {
463 print '<br>';
464 }
465 }
466
467 // Reconciliation
468 if (!empty($object->user_rappro) || !empty($object->user_rappro_id) || !empty($object->date_rappro)) {
469 '@phan-var-force Account $object';
470 if ($usetable) {
471 print '<tr><td class="titlefield">';
472 }
473 print $langs->trans("Reconciliation");
474 if ($usetable) {
475 print '</td><td>';
476 } else {
477 print ': ';
478 }
479 if (is_object($object->user_rappro)) {
480 $user_rappro = $object->user_rappro;
481 '@phan-var-force User $user_rappro';
482 if ($user_rappro->id) {
483 print $user_rappro->getNomUrl(-1, '', 0, 0, 0);
484 } else {
485 print $langs->trans("Unknown");
486 }
487 } else {
488 $userstatic = new User($db);
489 $userstatic->fetch($object->user_rappro_id ? $object->user_rappro_id : $object->user_rappro);
490 if ($userstatic->id) {
491 print $userstatic->getNomUrl(1, '', 0, 0, 0);
492 } else {
493 print $langs->trans("Unknown");
494 }
495 }
496
497 if (!empty($object->date_rappro)) { // Note: date_rappro is not found on Dolibarr classes
498 print ' - ';
499 print '<div class="valignmiddle inline-block">';
500 print dol_print_date($object->date_rappro, 'dayhour', 'tzserver'); // @phan-suppress-current-line PhanUndeclaredProperty
501 if ($deltadateforuser) {
502 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
503 }
504 print '</div>';
505 }
506
507 if ($usetable) {
508 print '</td></tr>';
509 } else {
510 print '<br>';
511 }
512 }
513
514 // Last sending
515 if (!empty($object->date_envoi)) {
516 '@phan-var-force Mailing $object';
517 if ($usetable) {
518 print '<tr><td class="titlefield">';
519 }
520 print $langs->trans("LastSending");
521 if ($usetable) {
522 print '</td><td>';
523 } else {
524 print ': ';
525 }
526 print dol_print_date($object->date_envoi, 'dayhour', 'tzserver');
527 if ($deltadateforuser) {
528 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>';
529 }
530 if ($usetable) {
531 print '</td></tr>';
532 } else {
533 print '<br>';
534 }
535 }
536
537 if ($usetable) {
538 print '</table>';
539 }
540}
541
542
551function dolAddEmailTrackId($email, $trackingid)
552{
553 $tmp = explode('@', $email);
554 return $tmp[0].'+'.$trackingid.'@'.(isset($tmp[1]) ? $tmp[1] : '');
555}
556
563function isValidMailDomain($mail)
564{
565 list($user, $domain) = explode("@", $mail, 2);
566 return ($domain ? isValidMXRecord($domain) : 0);
567}
568
582function isValidUrl($url, $http = 0, $pass = 0, $port = 0, $path = 0, $query = 0, $anchor = 0)
583{
584 $ValidUrl = 0;
585 $urlregex = '';
586
587 // SCHEME
588 if ($http) {
589 $urlregex .= "^(http:\/\/|https:\/\/)";
590 }
591
592 // USER AND PASS
593 if ($pass) {
594 $urlregex .= "([a-z0-9+!*(),;?&=\$_.-]+(\:[a-z0-9+!*(),;?&=\$_.-]+)?@)";
595 }
596
597 // HOSTNAME OR IP
598 //$urlregex .= "[a-z0-9+\$_-]+(\.[a-z0-9+\$_-]+)*"; // x allowed (ex. http://localhost, http://routerlogin)
599 //$urlregex .= "[a-z0-9+\$_-]+(\.[a-z0-9+\$_-]+)+"; // x.x
600 $urlregex .= "([a-z0-9+\$_\\\:-])+(\.[a-z0-9+\$_-][a-z0-9+\$_-]+)*"; // x ou x.xx (2 x ou plus)
601 //use only one of the above
602
603 // PORT
604 if ($port) {
605 $urlregex .= "(\:[0-9]{2,5})";
606 }
607 // PATH
608 if ($path) {
609 $urlregex .= "(\/([a-z0-9+\$_-]\.?)+)*\/";
610 }
611 // GET Query
612 if ($query) {
613 $urlregex .= "(\?[a-z+&\$_.-][a-z0-9;:@\/&%=+\$_.-]*)";
614 }
615 // ANCHOR
616 if ($anchor) {
617 $urlregex .= "(#[a-z_.-][a-z0-9+\$_.-]*)$";
618 }
619
620 // check
621 if (preg_match('/'.$urlregex.'/i', $url)) {
622 $ValidUrl = 1;
623 }
624 //print $urlregex.' - '.$url.' - '.$ValidUrl;
625
626 return $ValidUrl;
627}
628
635function isValidVATID($company)
636{
637 if ($company->isInEEC()) { // Syntax check rules for EEC countries
638 /* Disabled because some companies can have an address in Irland and a vat number in France.
639 $vatprefix = $company->country_code;
640 if ($vatprefix == 'GR') $vatprefix = '(EL|GR)';
641 elseif ($vatprefix == 'MC') $vatprefix = 'FR'; // Monaco is using french VAT numbers
642 else $vatprefix = preg_quote($vatprefix, '/');*/
643 $vatprefix = '[a-zA-Z][a-zA-Z]';
644 if (!preg_match('/^'.$vatprefix.'[a-zA-Z0-9\-\.]{5,14}$/i', str_replace(' ', '', $company->tva_intra))) {
645 return 0;
646 }
647 }
648
649 return 1;
650}
651
659function clean_url($url, $http = 1)
660{
661 // Fixed by Matelli (see http://matelli.fr/showcases/patch%73-dolibarr/fix-cleaning-url.html)
662 // To include the minus sign in a char class, we must not escape it but put it at the end of the class
663 // Also, there's no need of escape a dot sign in a class
664 $regs = array();
665 if (preg_match('/^(https?:[\\/]+)?([0-9A-Z.-]+\.[A-Z]{2,4})(:[0-9]+)?/i', $url, $regs)) {
666 $proto = $regs[1];
667 $domain = $regs[2];
668 $port = isset($regs[3]) ? $regs[3] : '';
669 //print $url." -> ".$proto." - ".$domain." - ".$port;
670 //$url = dol_string_nospecial(trim($url));
671 $url = trim($url);
672
673 // Si http: defini on supprime le http (Si https on ne supprime pas)
674 $newproto = $proto;
675 if ($http == 0) {
676 if (preg_match('/^http:[\\/]+/i', $url)) {
677 $url = preg_replace('/^http:[\\/]+/i', '', $url);
678 $newproto = '';
679 }
680 }
681
682 // On passe le nom de domaine en minuscule
683 $CleanUrl = preg_replace('/^'.preg_quote($proto.$domain, '/').'/i', $newproto.strtolower($domain), $url);
684
685 return $CleanUrl;
686 } else {
687 return $url;
688 }
689}
690
691
692
704function dolObfuscateEmail($mail, $replace = "*", $nbreplace = 8, $nbdisplaymail = 4, $nbdisplaydomain = 3, $displaytld = true)
705{
706 if (!isValidEmail($mail)) {
707 return '';
708 }
709 $tab = explode('@', $mail);
710 $tab2 = explode('.', $tab[1]);
711 $string_replace = '';
712 $mail_name = $tab[0];
713 $mail_domaine = $tab2[0];
714 $mail_tld = '';
715
716 $nbofelem = count($tab2);
717 for ($i = 1; $i < $nbofelem && $displaytld; $i++) {
718 $mail_tld .= '.'.$tab2[$i];
719 }
720
721 for ($i = 0; $i < $nbreplace; $i++) {
722 $string_replace .= $replace;
723 }
724
725 if (strlen($mail_name) > $nbdisplaymail) {
726 $mail_name = substr($mail_name, 0, $nbdisplaymail);
727 }
728
729 if (strlen($mail_domaine) > $nbdisplaydomain) {
730 $mail_domaine = substr($mail_domaine, strlen($mail_domaine) - $nbdisplaydomain);
731 }
732
733 return $mail_name.$string_replace.$mail_domaine.$mail_tld;
734}
735
736
746function array2tr($data, $troptions = '', $tdoptions = '')
747{
748 $text = '<tr '.$troptions.'>';
749 foreach ($data as $key => $item) {
750 $text .= '<td '.$tdoptions.'>'.((string) $item).'</td>';
751 }
752 $text .= '</tr>';
753 return $text;
754}
755
766function array2table($data, $tableMarkup = 1, $tableoptions = '', $troptions = '', $tdoptions = '')
767{
768 $text = '';
769 if ($tableMarkup) {
770 $text = '<table '.$tableoptions.'>';
771 }
772 foreach ($data as $key => $item) {
773 if (is_array($item)) {
774 $text .= array2tr($item, $troptions, $tdoptions);
775 } else {
776 $text .= '<tr '.$troptions.'>';
777 $text .= '<td '.$tdoptions.'>'.((string) $key).'</td>';
778 $text .= '<td '.$tdoptions.'>'.((string) $item).'</td>';
779 $text .= '</tr>';
780 }
781 }
782 if ($tableMarkup) {
783 $text .= '</table>';
784 }
785 return $text;
786}
787
805function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $date = '', $mode = 'next', $bentityon = true, $objuser = null, $forceentity = null, $objbookkeeping = null)
806{
807 global $user;
808
809 if (!is_object($objsoc)) {
810 $valueforccc = (string) $objsoc;
811 } elseif ($table == "commande_fournisseur" || $table == "facture_fourn" || $table == "paiementfourn") {
812 $valueforccc = dol_string_unaccent($objsoc->code_fournisseur);
813 } else {
814 $valueforccc = dol_string_unaccent($objsoc->code_client);
815 }
816
817 $sharetable = $table;
818 if ($table == 'facture' || $table == 'invoice') {
819 $sharetable = 'invoicenumber'; // for getEntity function
820 }
821
822 // Clean parameters
823 if ($date == '') {
824 $date = dol_now(); // We use local year and month of PHP server to search numbers
825 }
826 // but we should use local year and month of user
827
828 // For debugging
829 //dol_syslog("mask=".$mask, LOG_DEBUG);
830 //include_once(DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php');
831 //$mask='FA{yy}{mm}-{0000@99}';
832 //$date=dol_mktime(12, 0, 0, 1, 1, 1900);
833 //$date=dol_stringtotime('20130101');
834 $hasglobalcounter = false;
835 $maskrefclient_maskcounter = '';
836 $maskrefclient_clientcode = '';
837 $maskrefclient_maskclientcode = '';
838 $maskrefclient_maskoffset = '';
839
840 $reg = array();
841 // Extract value for mask counter, mask raz and mask offset
842 if (preg_match('/\{(0+)([@\+][0-9\-\+\=]+)?([@\+][0-9\-\+\=]+)?\}/i', $mask, $reg)) {
843 $masktri = $reg[1].(!empty($reg[2]) ? $reg[2] : '').(!empty($reg[3]) ? $reg[3] : '');
844 $maskcounter = $reg[1];
845 $hasglobalcounter = true;
846 } else {
847 // setting some defaults so the rest of the code won't fail if there is a third party counter
848 $masktri = '00000';
849 $maskcounter = '00000';
850 }
851
852 $maskraz = -1;
853 $maskoffset = 0;
854 $resetEveryMonth = false;
855 if (dol_strlen($maskcounter) < 3 && !getDolGlobalString('MAIN_COUNTER_WITH_LESS_3_DIGITS')) {
856 return 'ErrorCounterMustHaveMoreThan3Digits';
857 }
858
859 // Extract value for third party mask counter
860 $regClientRef = array();
861 if (preg_match('/\{(c+)(0*)\}/i', $mask, $regClientRef)) {
862 $maskrefclient = $regClientRef[1].$regClientRef[2];
863 $maskrefclient_maskclientcode = $regClientRef[1];
864 $maskrefclient_maskcounter = $regClientRef[2];
865 $maskrefclient_maskoffset = 0; //default value of maskrefclient_counter offset
866 $maskrefclient_clientcode = substr($valueforccc, 0, dol_strlen($maskrefclient_maskclientcode)); //get n first characters of client code where n is length in mask
867 $maskrefclient_clientcode = str_pad($maskrefclient_clientcode, dol_strlen($maskrefclient_maskclientcode), "#", STR_PAD_RIGHT); //padding maskrefclient_clientcode for having exactly n characters in maskrefclient_clientcode
868 $maskrefclient_clientcode = dol_string_nospecial($maskrefclient_clientcode); //sanitize maskrefclient_clientcode for sql insert and sql select like
869 if (dol_strlen($maskrefclient_maskcounter) > 0 && dol_strlen($maskrefclient_maskcounter) < 3) {
870 return 'ErrorCounterMustHaveMoreThan3Digits';
871 }
872 } else {
873 $maskrefclient = '';
874 }
875
876 // fail if there is neither a global nor a third party counter
877 if (!$hasglobalcounter && ($maskrefclient_maskcounter == '')) {
878 return 'ErrorBadMask';
879 }
880
881 // Extract value for third party type
882 $regType = array();
883 if (preg_match('/\{(t+)\}/i', $mask, $regType)) {
884 $masktype = $regType[1];
885 $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)
886 $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
887 } else {
888 $masktype = '';
889 $masktype_value = '';
890 }
891
892 // Extract value for user
893 $regUser = array();
894 if (preg_match('/\{(u+)\}/i', $mask, $regUser)) {
895 $lastname = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
896 if (is_object($objuser)) {
897 $lastname = $objuser->lastname;
898 }
899
900 $maskuser = $regUser[1];
901 $maskuser_value = substr($lastname, 0, dol_strlen($regUser[1])); // get n first characters of user firstname (where n is length in mask)
902 $maskuser_value = str_pad($maskuser_value, dol_strlen($regUser[1]), "#", STR_PAD_RIGHT); // we fill on right with # to have same number of char than into mask
903 } else {
904 $maskuser = '';
905 $maskuser_value = '';
906 }
907
908 // Extract value for journal code
909 $regJournal = array();
910 if (preg_match('/\{(jj+)\}/i', $mask, $regJournal)) {
911 $journalcode = 'JJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJ';
912 if (is_object($objbookkeeping)) {
913 $journalcode = (string) $objbookkeeping->code_journal;
914 }
915
916 $maskjournal = $regJournal[1];
917 $maskjournal_value = substr($journalcode, 0, dol_strlen($regJournal[1])); // get n first characters of journal code (where n is length in mask)
918 $maskjournal_value = str_pad($maskjournal_value, dol_strlen($regJournal[1]), "#", STR_PAD_RIGHT); // we fill on right with # to have same number of char than into mask
919 } else {
920 $maskjournal = '';
921 $maskjournal_value = '';
922 }
923
924 // Personalized field {XXX-1} à {XXX-99}
925 $maskperso = array();
926 $maskpersonew = array();
927 $tmpmask = $mask;
928 $regKey = array();
929 while (preg_match('/\{([A-Z]+)\-([0-9]+)\}/', $tmpmask, $regKey)) {
930 $maskperso[$regKey[1]] = '{'.$regKey[1].'-'.$regKey[2].'}';
931 // @phan-suppress-next-line PhanParamSuspiciousOrder
932 $maskpersonew[$regKey[1]] = str_pad('', (int) $regKey[2], '_', STR_PAD_RIGHT);
933 $tmpmask = preg_replace('/\{'.$regKey[1].'\-'.$regKey[2].'\}/i', $maskpersonew[$regKey[1]], $tmpmask);
934 }
935
936 if (strstr($mask, 'user_extra_')) {
937 $start = "{user_extra_";
938 $end = "\}";
939 $extra = get_string_between($mask, "user_extra_", "}");
940 if (!empty($user->array_options['options_'.$extra])) {
941 $mask = preg_replace('#('.$start.')(.*?)('.$end.')#si', $user->array_options['options_'.$extra], $mask);
942 }
943 }
944
945 // Now define value for all alternative $mask variable we will need to work
946 $maskwithonlyymcode = $mask;
947 $maskwithonlyymcode = preg_replace('/\{(0+)([@\+][0-9\-\+\=]+)?([@\+][0-9\-\+\=]+)?\}/i', $maskcounter, $maskwithonlyymcode);
948 $maskwithonlyymcode = preg_replace('/\{dd\}/i', 'dd', $maskwithonlyymcode);
949 $maskwithonlyymcode = preg_replace('/\{(c+)(0*)\}/i', $maskrefclient, $maskwithonlyymcode);
950 $maskwithonlyymcode = preg_replace('/\{(t+)\}/i', $masktype_value, $maskwithonlyymcode);
951 $maskwithonlyymcode = preg_replace('/\{(u+)\}/i', $maskuser_value, $maskwithonlyymcode);
952 $maskwithonlyymcode = preg_replace('/\{(j+)\}/i', $maskjournal_value, $maskwithonlyymcode);
953 foreach ($maskperso as $key => $val) {
954 $maskwithonlyymcode = preg_replace('/'.preg_quote($val, '/').'/i', $maskpersonew[$key], $maskwithonlyymcode);
955 }
956 $maskwithnocode = $maskwithonlyymcode;
957 $maskwithnocode = preg_replace('/\{yyyy\}/i', 'yyyy', $maskwithnocode);
958 $maskwithnocode = preg_replace('/\{yy\}/i', 'yy', $maskwithnocode);
959 $maskwithnocode = preg_replace('/\{y\}/i', 'y', $maskwithnocode);
960 $maskwithnocode = preg_replace('/\{mm\}/i', 'mm', $maskwithnocode);
961 // Now maskwithnocode = 0000ddmmyyyyccc for example
962 // and maskcounter = 0000 for example
963 //print "maskwithonlyymcode=".$maskwithonlyymcode." maskwithnocode=".$maskwithnocode."\n<br>";
964 //var_dump($reg);
965
966 // If an offset is asked ($reg is parsed from the counter mask)
967 if (!empty($reg[2]) && preg_match('/^\+/', $reg[2])) {
968 $maskoffset = preg_replace('/^\+/', '', $reg[2]);
969 }
970 if (!empty($reg[3]) && preg_match('/^\+/', $reg[3])) {
971 $maskoffset = preg_replace('/^\+/', '', $reg[3]);
972 }
973
974 // Define $sqlwhere
975 $sqlwhere = '';
976 $yearoffset = 0; // Use year of current $date by default
977 $yearoffsettype = false; // false: no reset, 0,-,=,+: reset at offset month SOCIETE_FISCAL_MONTH_START, x=reset at offset month x
978
979 // If a restore to zero after a month is asked we check if there is already a value for this year ($reg is parsed from the counter mask)
980 if (!empty($reg[2]) && preg_match('/^@/', $reg[2])) {
981 $yearoffsettype = preg_replace('/^@/', '', $reg[2]);
982 }
983 if (!empty($reg[3]) && preg_match('/^@/', $reg[3])) {
984 $yearoffsettype = preg_replace('/^@/', '', $reg[3]);
985 }
986
987 //print "yearoffset=".$yearoffset." yearoffsettype=".$yearoffsettype;
988 if (is_numeric($yearoffsettype) && $yearoffsettype >= 1) {
989 $maskraz = $yearoffsettype; // For backward compatibility
990 } elseif ($yearoffsettype === '0' || (!empty($yearoffsettype) && !is_numeric($yearoffsettype) && getDolGlobalInt('SOCIETE_FISCAL_MONTH_START') > 1)) {
991 $maskraz = getDolGlobalString('SOCIETE_FISCAL_MONTH_START');
992 }
993 //print "maskraz=".$maskraz; // -1=no reset
994
995 $monthcomp = 0;
996 $yearcomp = '';
997
998 if ($maskraz > 0) { // A reset is required
999 if ($maskraz == 99) {
1000 $maskraz = (int) date('m', $date);
1001 $resetEveryMonth = true;
1002 }
1003 if ($maskraz > 12) {
1004 return 'ErrorBadMaskBadRazMonth';
1005 }
1006
1007 // Define posy, posm and reg
1008 if ($maskraz > 1) { // if reset is not first month, we need month and year into mask
1009 if (preg_match('/^(.*)\{(y+)\}\{(m+)\}/i', $maskwithonlyymcode, $reg)) {
1010 $posy = 2;
1011 $posm = 3;
1012 } elseif (preg_match('/^(.*)\{(m+)\}\{(y+)\}/i', $maskwithonlyymcode, $reg)) {
1013 $posy = 3;
1014 $posm = 2;
1015 } else {
1016 return 'ErrorCantUseRazInStartedYearIfNoYearMonthInMask';
1017 }
1018
1019 if (dol_strlen($reg[$posy]) < 2) {
1020 return 'ErrorCantUseRazWithYearOnOneDigit';
1021 }
1022 } else { // if reset is for a specific month in year, we need year
1023 if (preg_match('/^(.*)\{(m+)\}\{(y+)\}/i', $maskwithonlyymcode, $reg)) {
1024 $posy = 3; //index in regex
1025 $posm = 2;
1026 } elseif (preg_match('/^(.*)\{(y+)\}\{(m+)\}/i', $maskwithonlyymcode, $reg)) {
1027 $posy = 2; //index in regex
1028 $posm = 3;
1029 } elseif (preg_match('/^(.*)\{(y+)\}/i', $maskwithonlyymcode, $reg)) {
1030 $posy = 2; //index in regex
1031 $posm = 0;
1032 } else {
1033 return 'ErrorCantUseRazIfNoYearInMask';
1034 }
1035 }
1036 // Define length
1037 $yearlen = $posy ? dol_strlen($reg[$posy]) : 0;
1038 $monthlen = $posm ? dol_strlen($reg[$posm]) : 0;
1039 // Define pos
1040 $yearpos = (dol_strlen($reg[1]) + 1);
1041 $monthpos = ($yearpos + $yearlen);
1042 if ($posy == 3 && $posm == 2) { // if month is before year
1043 $monthpos = (dol_strlen($reg[1]) + 1);
1044 $yearpos = ($monthpos + $monthlen);
1045 }
1046 //print "xxx ".$maskwithonlyymcode." maskraz=".$maskraz." posy=".$posy." yearlen=".$yearlen." yearpos=".$yearpos." posm=".$posm." monthlen=".$monthlen." monthpos=".$monthpos." yearoffsettype=".$yearoffsettype." resetEveryMonth=".$resetEveryMonth."\n";
1047
1048 // Define $yearcomp and $monthcomp (that will be use in the select where to search max number)
1049 $monthcomp = $maskraz;
1050 $yearcomp = '';
1051
1052 if (!empty($yearoffsettype) && !is_numeric($yearoffsettype) && $yearoffsettype != '=') { // $yearoffsettype is - or +
1053 $currentyear = (int) date("Y", $date);
1054 $fiscaldate = dol_mktime(0, 0, 0, $maskraz, 1, $currentyear);
1055 $newyeardate = dol_mktime(0, 0, 0, 1, 1, $currentyear);
1056 $nextnewyeardate = dol_mktime(0, 0, 0, 1, 1, $currentyear + 1);
1057 //echo 'currentyear='.$currentyear.' date='.dol_print_date($date, 'day').' fiscaldate='.dol_print_date($fiscaldate, 'day').'<br>';
1058
1059 // If after or equal of current fiscal date
1060 if ($date >= $fiscaldate) {
1061 // If before of next new year date
1062 if ($date < $nextnewyeardate && $yearoffsettype == '+') {
1063 $yearoffset = 1;
1064 }
1065 } elseif ($date >= $newyeardate && $yearoffsettype == '-') {
1066 // If after or equal of current new year date
1067 $yearoffset = -1;
1068 }
1069 } elseif ((int) date("m", $date) < $maskraz && empty($resetEveryMonth)) {
1070 // For backward compatibility
1071 $yearoffset = -1;
1072 } // If current month lower that month of return to zero, year is previous year
1073
1074 if ($yearlen == 4) {
1075 $yearcomp = sprintf("%04d", idate("Y", $date) + $yearoffset);
1076 } elseif ($yearlen == 2) {
1077 $yearcomp = sprintf("%02d", idate("y", $date) + $yearoffset);
1078 } elseif ($yearlen == 1) {
1079 $yearcomp = (string) ((int) substr(date('y', $date), 1, 1) + $yearoffset);
1080 }
1081 if ($monthcomp > 1 && empty($resetEveryMonth)) { // Test with month is useless if monthcomp = 1 (0 is same as 1)
1082 if ($yearlen == 4) {
1083 $yearcomp1 = sprintf("%04d", idate("Y", $date) + $yearoffset + 1);
1084 } elseif ($yearlen == 2) {
1085 $yearcomp1 = sprintf("%02d", idate("y", $date) + $yearoffset + 1);
1086 } else {
1087 $yearcomp1 = '';
1088 }
1089
1090 $sqlwhere .= "(";
1091 $sqlwhere .= " (SUBSTRING(".$field.", ".$yearpos.", ".$yearlen.") = '".$db->escape($yearcomp)."'";
1092 $sqlwhere .= " AND SUBSTRING(".$field.", ".$monthpos.", ".$monthlen.") >= '".str_pad($monthcomp, $monthlen, '0', STR_PAD_LEFT)."')";
1093 $sqlwhere .= " OR";
1094 $sqlwhere .= " (SUBSTRING(".$field.", ".$yearpos.", ".$yearlen.") = '".$db->escape($yearcomp1)."'";
1095 $sqlwhere .= " AND SUBSTRING(".$field.", ".$monthpos.", ".$monthlen.") < '".str_pad($monthcomp, $monthlen, '0', STR_PAD_LEFT)."') ";
1096 $sqlwhere .= ')';
1097 } elseif ($resetEveryMonth) {
1098 $sqlwhere .= "(SUBSTRING(".$field.", ".$yearpos.", ".$yearlen.") = '".$db->escape($yearcomp)."'";
1099 $sqlwhere .= " AND SUBSTRING(".$field.", ".$monthpos.", ".$monthlen.") = '".str_pad($monthcomp, $monthlen, '0', STR_PAD_LEFT)."')";
1100 } else { // reset is done on january
1101 $sqlwhere .= "(SUBSTRING(".$field.", ".$yearpos.", ".$yearlen.") = '".$db->escape($yearcomp)."')";
1102 }
1103 }
1104 //print "sqlwhere=".$sqlwhere." yearcomp=".$yearcomp."<br>\n"; // sqlwhere and yearcomp defined only if we ask a reset
1105 //print "masktri=".$masktri." maskcounter=".$maskcounter." maskraz=".$maskraz." maskoffset=".$maskoffset."<br>\n";
1106
1107 // Define $sqlstring
1108 if (function_exists('mb_strrpos')) {
1109 $posnumstart = mb_strrpos($maskwithnocode, $maskcounter, 0, 'UTF-8');
1110 } else {
1111 $posnumstart = strrpos($maskwithnocode, $maskcounter);
1112 } // Pos of counter in final string (from 0 to ...)
1113 if ($posnumstart < 0) {
1114 return 'ErrorBadMaskFailedToLocatePosOfSequence';
1115 }
1116 $sqlstring = "SUBSTRING(".$field.", ".($posnumstart + 1).", ".dol_strlen($maskcounter).")";
1117
1118 // Define $maskLike
1119 $maskLike = dol_string_nospecial($mask);
1120 $maskLike = str_replace("%", "_", $maskLike);
1121
1122 // Replace protected special codes with matching number of _ as wild card character
1123 if ($resetEveryMonth && $yearcomp && $monthcomp) { // Perf optimization, when a reset is requested at each month, we can include the year and month inside the filter
1124 $maskLike = preg_replace('/\{yyyy\}/i', $yearcomp, $maskLike);
1125 $maskLike = preg_replace('/\{yy\}/i', $yearcomp, $maskLike);
1126 $maskLike = preg_replace('/\{y\}/i', $yearcomp, $maskLike);
1127 $maskLike = preg_replace('/\{mm\}/i', sprintf("%02d", $monthcomp), $maskLike);
1128 } elseif ($maskraz == 1 && $yearcomp) { // Perf optimization, when a reset is requested at first month, we can include the year inside the filter, but not the month
1129 $maskLike = preg_replace('/\{yyyy\}/i', $yearcomp, $maskLike);
1130 $maskLike = preg_replace('/\{yy\}/i', $yearcomp, $maskLike);
1131 $maskLike = preg_replace('/\{y\}/i', $yearcomp, $maskLike);
1132 $maskLike = preg_replace('/\{mm\}/i', '__', $maskLike); // we can't include the month in the filter
1133 } else {
1134 $maskLike = preg_replace('/\{yyyy\}/i', '____', $maskLike);
1135 $maskLike = preg_replace('/\{yy\}/i', '__', $maskLike);
1136 $maskLike = preg_replace('/\{y\}/i', '_', $maskLike);
1137 $maskLike = preg_replace('/\{mm\}/i', '__', $maskLike);
1138 }
1139 $maskLike = preg_replace('/\{dd\}/i', '__', $maskLike);
1140 // @phan-suppress-next-line PhanParamSuspiciousOrder
1141 $maskLike = str_replace(dol_string_nospecial('{'.$masktri.'}'), str_pad("", dol_strlen($maskcounter), "_"), $maskLike);
1142 if ($maskrefclient) {
1143 // @phan-suppress-next-line PhanParamSuspiciousOrder
1144 $maskLike = str_replace(dol_string_nospecial('{'.$maskrefclient.'}'), str_pad("", dol_strlen($maskrefclient), "_"), $maskLike);
1145 }
1146 if ($masktype) {
1147 $maskLike = str_replace(dol_string_nospecial('{'.$masktype.'}'), $masktype_value, $maskLike);
1148 }
1149 if ($maskuser) {
1150 $maskLike = str_replace(dol_string_nospecial('{'.$maskuser.'}'), $maskuser_value, $maskLike);
1151 }
1152 if ($maskjournal) {
1153 $maskLike = str_replace(dol_string_nospecial('{'.$maskjournal.'}'), $maskjournal_value, $maskLike);
1154 }
1155 foreach ($maskperso as $key => $val) {
1156 $maskLike = str_replace(dol_string_nospecial($maskperso[$key]), $maskpersonew[$key], $maskLike);
1157 }
1158
1159 // Get counter in database
1160 $counter = 0;
1161 $sql = "SELECT MAX(".$sqlstring.") as val";
1162 $sql .= " FROM ".MAIN_DB_PREFIX.$db->sanitize($table);
1163 $sql .= " WHERE ".$db->sanitize($field)." LIKE '".$db->escape($maskLike) . (getDolGlobalString('SEARCH_FOR_NEXT_VAL_ON_START_ONLY') ? "%" : "") . "'";
1164 $sql .= " AND ".$db->sanitize($field)." NOT LIKE '(PROV%)'";
1165
1166 // To ensure that all variables within the MAX() brackets are integers
1167 // This avoid bad detection of max when data are noised with non numeric values at the position of the numero
1168 if (getDolGlobalInt('MAIN_NUMBERING_FILTER_ON_INT_ONLY')) {
1169 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
1170 $sql .= " AND ". $db->regexpsql($sqlstring, '^[0-9]+$', 1);
1171 }
1172
1173 if ($bentityon) { // only if entity enable
1174 $sql .= " AND entity IN (".getEntity($sharetable).")";
1175 } elseif (!empty($forceentity)) {
1176 $sql .= " AND entity IN (".$db->sanitize($forceentity).")";
1177 }
1178 if ($where) {
1179 $sql .= $where;
1180 }
1181 if ($sqlwhere) {
1182 $sql .= " AND ".$sqlwhere;
1183 }
1184
1185 //print $sql.'<br>';
1186 dol_syslog("functions2::get_next_value mode=".$mode, LOG_DEBUG);
1187 $resql = $db->query($sql);
1188 if ($resql) {
1189 $obj = $db->fetch_object($resql);
1190 $counter = $obj->val;
1191 } else {
1192 dol_print_error($db);
1193 }
1194
1195 // Check if we must force counter to maskoffset
1196 if (empty($counter)) {
1197 $counter = $maskoffset;
1198 } elseif (preg_match('/[^0-9]/i', $counter)) {
1199 dol_syslog("Error, the last counter found is '".$counter."' so is not a numeric value. We will restart to 1.", LOG_ERR);
1200 $counter = 0;
1201 } elseif ($counter < $maskoffset && !getDolGlobalString('MAIN_NUMBERING_OFFSET_ONLY_FOR_FIRST')) {
1202 $counter = $maskoffset;
1203 }
1204
1205 if ($mode == 'last') { // We found value for counter = last counter value. Now need to get corresponding ref of invoice.
1206 $counterpadded = str_pad($counter, dol_strlen($maskcounter), "0", STR_PAD_LEFT);
1207
1208 // Define $maskLike
1209 $maskLike = dol_string_nospecial($mask);
1210 $maskLike = str_replace("%", "_", $maskLike);
1211 // Replace protected special codes with matching number of _ as wild card character
1212 $maskLike = preg_replace('/\{yyyy\}/i', '____', $maskLike);
1213 $maskLike = preg_replace('/\{yy\}/i', '__', $maskLike);
1214 $maskLike = preg_replace('/\{y\}/i', '_', $maskLike);
1215 $maskLike = preg_replace('/\{mm\}/i', '__', $maskLike);
1216 $maskLike = preg_replace('/\{dd\}/i', '__', $maskLike);
1217 $maskLike = str_replace(dol_string_nospecial('{'.$masktri.'}'), $counterpadded, $maskLike);
1218 if ($maskrefclient) {
1219 // @phan-suppress-next-line PhanParamSuspiciousOrder
1220 $maskLike = str_replace(dol_string_nospecial('{'.$maskrefclient.'}'), str_pad("", dol_strlen($maskrefclient), "_"), $maskLike);
1221 }
1222 if ($masktype) {
1223 $maskLike = str_replace(dol_string_nospecial('{'.$masktype.'}'), $masktype_value, $maskLike);
1224 }
1225 if ($maskuser) {
1226 $maskLike = str_replace(dol_string_nospecial('{'.$maskuser.'}'), $maskuser_value, $maskLike);
1227 }
1228
1229 $ref = '';
1230 $sql = "SELECT ".$db->sanitize($field)." as ref";
1231 $sql .= " FROM ".MAIN_DB_PREFIX.$db->sanitize($table);
1232 $sql .= " WHERE ".$db->sanitize($field)." LIKE '".$db->escape($maskLike) . (getDolGlobalString('SEARCH_FOR_NEXT_VAL_ON_START_ONLY') ? "%" : "") . "'";
1233 $sql .= " AND ".$db->sanitize($field)." NOT LIKE '%PROV%'";
1234 if ($bentityon) { // only if entity enable
1235 $sql .= " AND entity IN (".getEntity($sharetable).")";
1236 } elseif (!empty($forceentity)) {
1237 $sql .= " AND entity IN (".$db->sanitize($forceentity).")";
1238 }
1239 if ($where) {
1240 $sql .= $where;
1241 }
1242 if ($sqlwhere) {
1243 $sql .= " AND ".$sqlwhere;
1244 }
1245
1246 dol_syslog("functions2::get_next_value mode=".$mode, LOG_DEBUG);
1247 $resql = $db->query($sql);
1248 if ($resql) {
1249 $obj = $db->fetch_object($resql);
1250 if ($obj) {
1251 $ref = $obj->ref;
1252 }
1253 } else {
1254 dol_print_error($db);
1255 }
1256
1257 $numFinal = $ref;
1258 } elseif ($mode == 'next') {
1259 $counter++;
1260 $maskrefclient_counter = 0;
1261
1262 // If value for $counter has a length higher than $maskcounter chars
1263 if ($counter >= pow(10, dol_strlen($maskcounter))) {
1264 $counter = 'ErrorMaxNumberReachForThisMask';
1265 }
1266
1267 if (!empty($maskrefclient_maskcounter)) {
1268 //print "maskrefclient_maskcounter=".$maskrefclient_maskcounter." maskwithnocode=".$maskwithnocode." maskrefclient=".$maskrefclient."\n<br>";
1269
1270 // Define $sqlstring
1271 $maskrefclient_posnumstart = strpos($maskwithnocode, $maskrefclient_maskcounter, strpos($maskwithnocode, $maskrefclient)); // Pos of counter in final string (from 0 to ...)
1272 if ($maskrefclient_posnumstart <= 0) {
1273 return 'ErrorBadMask';
1274 }
1275 $maskrefclient_sqlstring = 'SUBSTRING('.$field.', '.($maskrefclient_posnumstart + 1).', '.dol_strlen($maskrefclient_maskcounter).')';
1276 //print "x".$sqlstring;
1277
1278 // Define $maskrefclient_maskLike
1279 $maskrefclient_maskLike = dol_string_nospecial($mask);
1280 $maskrefclient_maskLike = str_replace("%", "_", $maskrefclient_maskLike);
1281 // Replace protected special codes with matching number of _ as wild card character
1282 $maskrefclient_maskLike = str_replace(dol_string_nospecial('{yyyy}'), '____', $maskrefclient_maskLike);
1283 $maskrefclient_maskLike = str_replace(dol_string_nospecial('{yy}'), '__', $maskrefclient_maskLike);
1284 $maskrefclient_maskLike = str_replace(dol_string_nospecial('{y}'), '_', $maskrefclient_maskLike);
1285 $maskrefclient_maskLike = str_replace(dol_string_nospecial('{mm}'), '__', $maskrefclient_maskLike);
1286 $maskrefclient_maskLike = str_replace(dol_string_nospecial('{dd}'), '__', $maskrefclient_maskLike);
1287 // @phan-suppress-next-line PhanParamSuspiciousOrder
1288 $maskrefclient_maskLike = str_replace(dol_string_nospecial('{'.$masktri.'}'), str_pad("", dol_strlen($maskcounter), "_"), $maskrefclient_maskLike);
1289 // @phan-suppress-next-line PhanParamSuspiciousOrder
1290 $maskrefclient_maskLike = str_replace(dol_string_nospecial('{'.$maskrefclient.'}'), $maskrefclient_clientcode.str_pad("", dol_strlen($maskrefclient_maskcounter), "_"), $maskrefclient_maskLike);
1291
1292 // Get counter in database
1293 $maskrefclient_sql = "SELECT MAX(".$maskrefclient_sqlstring.") as val";
1294 $maskrefclient_sql .= " FROM ".MAIN_DB_PREFIX.$table;
1295 $maskrefclient_sql .= " WHERE ".$db->sanitize($field)." LIKE '".$db->escape($maskrefclient_maskLike) . (getDolGlobalString('SEARCH_FOR_NEXT_VAL_ON_START_ONLY') ? "%" : "") . "'";
1296 if ($bentityon) { // only if entity enable
1297 $maskrefclient_sql .= " AND entity IN (".getEntity($sharetable).")";
1298 } elseif (!empty($forceentity)) {
1299 $maskrefclient_sql .= " AND entity IN (".$db->sanitize($forceentity).")";
1300 }
1301 if ($where) {
1302 $maskrefclient_sql .= $where; //use the same optional where as general mask
1303 }
1304 if ($sqlwhere) {
1305 $maskrefclient_sql .= ' AND '.$sqlwhere; //use the same sqlwhere as general mask
1306 }
1307 $maskrefclient_sql .= " AND (SUBSTRING(".$field.", ".(strpos($maskwithnocode, $maskrefclient) + 1).", ".dol_strlen($maskrefclient_maskclientcode).") = '".$db->escape($maskrefclient_clientcode)."')";
1308
1309 dol_syslog("functions2::get_next_value maskrefclient", LOG_DEBUG);
1310 $maskrefclient_resql = $db->query($maskrefclient_sql);
1311 if ($maskrefclient_resql) {
1312 $maskrefclient_obj = $db->fetch_object($maskrefclient_resql);
1313 $maskrefclient_counter = $maskrefclient_obj->val;
1314 } else {
1315 dol_print_error($db);
1316 }
1317
1318 if (empty($maskrefclient_counter) || preg_match('/[^0-9]/i', $maskrefclient_counter)) {
1319 $maskrefclient_counter = $maskrefclient_maskoffset;
1320 }
1321 $maskrefclient_counter++;
1322 }
1323
1324 // Build numFinal
1325 $numFinal = $mask;
1326
1327 // We replace special codes except refclient
1328 if (!empty($yearoffsettype) && !is_numeric($yearoffsettype) && $yearoffsettype != '=') { // yearoffsettype is - or +, so we don't want current year
1329 $numFinal = preg_replace('/\{yyyy\}/i', (string) ((int) date("Y", $date) + $yearoffset), $numFinal);
1330 $numFinal = preg_replace('/\{yy\}/i', (string) ((int) date("y", $date) + $yearoffset), $numFinal);
1331 $numFinal = preg_replace('/\{y\}/i', (string) ((int) substr((string) date("y", $date), 1, 1) + $yearoffset), $numFinal);
1332 } else { // we want yyyy to be current year
1333 $numFinal = preg_replace('/\{yyyy\}/i', date("Y", $date), $numFinal);
1334 $numFinal = preg_replace('/\{yy\}/i', date("y", $date), $numFinal);
1335 $numFinal = preg_replace('/\{y\}/i', substr(date("y", $date), 1, 1), $numFinal);
1336 }
1337 $numFinal = preg_replace('/\{mm\}/i', date("m", $date), $numFinal);
1338 $numFinal = preg_replace('/\{dd\}/i', date("d", $date), $numFinal);
1339
1340 // Now we replace the counter
1341 $maskbefore = '{'.$masktri.'}';
1342 $maskafter = str_pad($counter, dol_strlen($maskcounter), "0", STR_PAD_LEFT);
1343 //print 'x'.$numFinal.' - '.$maskbefore.' - '.$maskafter.'y';exit;
1344 $numFinal = str_replace($maskbefore, $maskafter, $numFinal);
1345
1346 // Now we replace the refclient
1347 if ($maskrefclient) {
1348 //print "maskrefclient=".$maskrefclient." maskrefclient_counter=".$maskrefclient_counter." maskwithonlyymcode=".$maskwithonlyymcode." maskwithnocode=".$maskwithnocode." maskrefclient_clientcode=".$maskrefclient_clientcode." maskrefclient_maskcounter=".$maskrefclient_maskcounter."\n<br>";exit;
1349 $maskrefclient_maskbefore = '{'.$maskrefclient.'}';
1350 $maskrefclient_maskafter = $maskrefclient_clientcode;
1351 if (dol_strlen($maskrefclient_maskcounter) > 0) {
1352 $maskrefclient_maskafter .= str_pad((string) $maskrefclient_counter, dol_strlen($maskrefclient_maskcounter), "0", STR_PAD_LEFT);
1353 }
1354 $numFinal = str_replace($maskrefclient_maskbefore, (string) $maskrefclient_maskafter, $numFinal);
1355 }
1356
1357 // Now we replace the type
1358 if ($masktype) {
1359 $masktype_maskbefore = '{'.$masktype.'}';
1360 $masktype_maskafter = $masktype_value;
1361 $numFinal = str_replace($masktype_maskbefore, $masktype_maskafter, $numFinal);
1362 }
1363
1364 // Now we replace the user
1365 if ($maskuser) {
1366 $maskuser_maskbefore = '{'.$maskuser.'}';
1367 $maskuser_maskafter = $maskuser_value;
1368 $numFinal = str_replace($maskuser_maskbefore, $maskuser_maskafter, $numFinal);
1369 }
1370
1371 // Now we replace the journal code
1372 if ($maskjournal) {
1373 $maskjournal_maskbefore = '{'.$maskjournal.'}';
1374 $maskjournal_maskafter = $maskjournal_value;
1375 $numFinal = str_replace($maskjournal_maskbefore, $maskjournal_maskafter, $numFinal);
1376 }
1377 } else {
1378 $numFinal = "ErrorBadMode";
1379 dol_syslog("functions2::get_next_value ErrorBadMode '$mode'", LOG_ERR);
1380 }
1381
1382 dol_syslog("functions2::get_next_value return ".$numFinal, LOG_DEBUG);
1383 return $numFinal;
1384}
1385
1397function get_string_between($string, $start, $end)
1398{
1399 $ini = strpos($string, $start);
1400 if ($ini === false) {
1401 return '';
1402 }
1403 $ini += strlen($start);
1404 $endpos = strpos($string, $end, $ini);
1405 if ($endpos === false) {
1406 return '';
1407 }
1408 return substr($string, $ini, $endpos - $ini);
1409}
1410
1418function check_value($mask, $value)
1419{
1420 $result = 0;
1421
1422 $hasglobalcounter = false;
1423 $maskrefclient_maskcounter = '';
1424
1425 // Extract value for mask counter, mask raz and mask offset
1426 $reg = array();
1427 if (preg_match('/\{(0+)([@\+][0-9]+)?([@\+][0-9]+)?\}/i', $mask, $reg)) {
1428 $masktri = $reg[1].(isset($reg[2]) ? $reg[2] : '').(isset($reg[3]) ? $reg[3] : '');
1429 $maskcounter = $reg[1];
1430 $hasglobalcounter = true;
1431 } else {
1432 // setting some defaults so the rest of the code won't fail if there is a third party counter
1433 $masktri = '00000';
1434 $maskcounter = '00000';
1435 }
1436 $maskraz = -1;
1437 $maskoffset = 0;
1438 if (dol_strlen($maskcounter) < 3) {
1439 return 'ErrorCounterMustHaveMoreThan3Digits';
1440 }
1441
1442 // Extract value for third party mask counter
1443 $regClientRef = array();
1444 if (preg_match('/\{(c+)(0*)\}/i', $mask, $regClientRef)) {
1445 $maskrefclient = $regClientRef[1].$regClientRef[2];
1446 $maskrefclient_maskclientcode = $regClientRef[1];
1447 $maskrefclient_maskcounter = $regClientRef[2];
1448 $maskrefclient_maskoffset = 0; //default value of maskrefclient_counter offset
1449 $maskrefclient_clientcode = substr('', 0, dol_strlen($maskrefclient_maskclientcode)); //get n first characters of client code to form maskrefclient_clientcode
1450 $maskrefclient_clientcode = str_pad($maskrefclient_clientcode, dol_strlen($maskrefclient_maskclientcode), "#", STR_PAD_RIGHT); //padding maskrefclient_clientcode for having exactly n characters in maskrefclient_clientcode
1451 $maskrefclient_clientcode = dol_string_nospecial($maskrefclient_clientcode); //sanitize maskrefclient_clientcode for sql insert and sql select like
1452 if (dol_strlen($maskrefclient_maskcounter) > 0 && dol_strlen($maskrefclient_maskcounter) < 3) {
1453 return 'ErrorCounterMustHaveMoreThan3Digits';
1454 }
1455 } else {
1456 $maskrefclient = '';
1457 }
1458
1459 // fail if there is neither a global nor a third party counter
1460 if (!$hasglobalcounter && ($maskrefclient_maskcounter == '')) {
1461 return 'ErrorBadMask';
1462 }
1463
1464 $maskwithonlyymcode = $mask;
1465 $maskwithonlyymcode = preg_replace('/\{(0+)([@\+][0-9]+)?([@\+][0-9]+)?\}/i', $maskcounter, $maskwithonlyymcode);
1466 $maskwithonlyymcode = preg_replace('/\{dd\}/i', 'dd', $maskwithonlyymcode);
1467 $maskwithonlyymcode = preg_replace('/\{(c+)(0*)\}/i', $maskrefclient, $maskwithonlyymcode);
1468 $maskwithnocode = $maskwithonlyymcode;
1469 $maskwithnocode = preg_replace('/\{yyyy\}/i', 'yyyy', $maskwithnocode);
1470 $maskwithnocode = preg_replace('/\{yy\}/i', 'yy', $maskwithnocode);
1471 $maskwithnocode = preg_replace('/\{y\}/i', 'y', $maskwithnocode);
1472 $maskwithnocode = preg_replace('/\{mm\}/i', 'mm', $maskwithnocode);
1473 // Now maskwithnocode = 0000ddmmyyyyccc for example
1474 // and maskcounter = 0000 for example
1475 //print "maskwithonlyymcode=".$maskwithonlyymcode." maskwithnocode=".$maskwithnocode."\n<br>";
1476
1477 // If an offset is asked
1478 if (!empty($reg[2]) && preg_match('/^\+/', $reg[2])) {
1479 $maskoffset = preg_replace('/^\+/', '', $reg[2]);
1480 }
1481 if (!empty($reg[3]) && preg_match('/^\+/', $reg[3])) {
1482 $maskoffset = preg_replace('/^\+/', '', $reg[3]);
1483 }
1484
1485 // Define $sqlwhere
1486
1487 // If a restore to zero after a month is asked we check if there is already a value for this year.
1488 if (!empty($reg[2]) && preg_match('/^@/', $reg[2])) {
1489 $maskraz = preg_replace('/^@/', '', $reg[2]);
1490 }
1491 if (!empty($reg[3]) && preg_match('/^@/', $reg[3])) {
1492 $maskraz = preg_replace('/^@/', '', $reg[3]);
1493 }
1494 if ($maskraz >= 0) {
1495 if ($maskraz == 99) {
1496 $maskraz = (int) date('m');
1497 $resetEveryMonth = true;
1498 }
1499 if ($maskraz > 12) {
1500 return 'ErrorBadMaskBadRazMonth';
1501 }
1502
1503 // Define reg
1504 if ($maskraz > 1 && !preg_match('/^(.*)\{(y+)\}\{(m+)\}/i', $maskwithonlyymcode, $reg)) {
1505 return 'ErrorCantUseRazInStartedYearIfNoYearMonthInMask';
1506 }
1507 if ($maskraz <= 1 && !preg_match('/^(.*)\{(y+)\}/i', $maskwithonlyymcode, $reg)) {
1508 return 'ErrorCantUseRazIfNoYearInMask';
1509 }
1510 //print "x".$maskwithonlyymcode." ".$maskraz;
1511 }
1512 //print "masktri=".$masktri." maskcounter=".$maskcounter." maskwithonlyymcode=".$maskwithonlyymcode." maskwithnocode=".$maskwithnocode." maskraz=".$maskraz." maskoffset=".$maskoffset."<br>\n";
1513
1514 if (function_exists('mb_strrpos')) {
1515 $posnumstart = mb_strrpos($maskwithnocode, $maskcounter, 0, 'UTF-8');
1516 } else {
1517 $posnumstart = strrpos($maskwithnocode, $maskcounter);
1518 } // Pos of counter in final string (from 0 to ...)
1519 if ($posnumstart < 0) {
1520 return 'ErrorBadMaskFailedToLocatePosOfSequence';
1521 }
1522
1523 // Check we have a number in $value at position ($posnumstart+1).', '.dol_strlen($maskcounter)
1524 // TODO
1525
1526 // Check length
1527 $len = dol_strlen($maskwithnocode);
1528 if (dol_strlen($value) != $len) {
1529 $result = -1;
1530 }
1531
1532 dol_syslog("functions2::check_value result=".$result, LOG_DEBUG);
1533 return $result;
1534}
1535
1544function binhex($bin, $pad = false, $upper = false)
1545{
1546 $last = dol_strlen($bin) - 1;
1547 $x = 0;
1548 for ($i = 0; $i <= $last; $i++) {
1549 $x += ($bin[$last - $i] ? 1 : 0) << $i;
1550 }
1551 $x = dechex($x);
1552 if ($pad) {
1553 while (dol_strlen($x) < intval(dol_strlen($bin)) / 4) {
1554 $x = "0$x";
1555 }
1556 }
1557 if ($upper) {
1558 $x = strtoupper($x);
1559 }
1560 return $x;
1561}
1562
1569function hexbin($hexa)
1570{
1571 $bin = '';
1572 $strLength = dol_strlen($hexa);
1573 for ($i = 0; $i < $strLength; $i++) {
1574 $bin .= str_pad(decbin(hexdec($hexa[$i])), 4, '0', STR_PAD_LEFT);
1575 }
1576 return $bin;
1577}
1578
1585function numero_semaine($time)
1586{
1587 $stime = dol_print_date($time, '%Y-%m-%d');
1588
1589 $reg = array();
1590 if (preg_match('/^([0-9]+)\-([0-9]+)\-([0-9]+)\s?([0-9]+)?:?([0-9]+)?/i', $stime, $reg)) {
1591 // Date est au format 'YYYY-MM-DD' ou 'YYYY-MM-DD HH:MM:SS'
1592 $annee = (int) $reg[1];
1593 $mois = (int) $reg[2];
1594 $jour = (int) $reg[3];
1595 } else {
1596 $annee = 0;
1597 $mois = 0;
1598 $jour = 0;
1599 }
1600
1601 /*
1602 * Norme ISO-8601:
1603 * - Week 1 of the year contains Jan 4th, or contains the first Thursday of January.
1604 * - Most years have 52 weeks, but 53 weeks for years starting on a Thursday and bisectile years that start on a Wednesday.
1605 * - The first day of a week is Monday
1606 */
1607
1608 // Definition du Jeudi de la semaine
1609 if ((int) date("w", mktime(12, 0, 0, $mois, $jour, $annee)) == 0) { // Dimanche
1610 $jeudiSemaine = mktime(12, 0, 0, $mois, $jour, $annee) - 3 * 24 * 60 * 60;
1611 } elseif (date("w", mktime(12, 0, 0, $mois, $jour, $annee)) < 4) { // du Lundi au Mercredi
1612 $jeudiSemaine = mktime(12, 0, 0, $mois, $jour, $annee) + (4 - (int) date("w", mktime(12, 0, 0, $mois, $jour, $annee))) * 24 * 60 * 60;
1613 } elseif ((int) date("w", mktime(12, 0, 0, $mois, $jour, $annee)) > 4) { // du Vendredi au Samedi
1614 $jeudiSemaine = mktime(12, 0, 0, $mois, $jour, $annee) - ((int) date("w", mktime(12, 0, 0, $mois, $jour, $annee)) - 4) * 24 * 60 * 60;
1615 } else { // Jeudi
1616 $jeudiSemaine = mktime(12, 0, 0, $mois, $jour, $annee);
1617 }
1618
1619 // Definition du premier Jeudi de l'annee
1620 if ((int) date("w", mktime(12, 0, 0, 1, 1, (int) date("Y", $jeudiSemaine))) == 0) { // Dimanche
1621 $premierJeudiAnnee = mktime(12, 0, 0, 1, 1, (int) date("Y", $jeudiSemaine)) + 4 * 24 * 60 * 60;
1622 } elseif ((int) date("w", mktime(12, 0, 0, 1, 1, (int) date("Y", $jeudiSemaine))) < 4) { // du Lundi au Mercredi
1623 $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;
1624 } elseif ((int) date("w", mktime(12, 0, 0, 1, 1, (int) date("Y", $jeudiSemaine))) > 4) { // du Vendredi au Samedi
1625 $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;
1626 } else { // Jeudi
1627 $premierJeudiAnnee = mktime(12, 0, 0, 1, 1, (int) date("Y", $jeudiSemaine));
1628 }
1629
1630 // Definition du numero de semaine: nb de jours entre "premier Jeudi de l'annee" et "Jeudi de la semaine";
1631 $numeroSemaine = (
1632 (
1633 (int) date("z", mktime(12, 0, 0, (int) date("m", $jeudiSemaine), (int) date("d", $jeudiSemaine), (int) date("Y", $jeudiSemaine)))
1634 -
1635 (int) date("z", mktime(12, 0, 0, (int) date("m", $premierJeudiAnnee), (int) date("d", $premierJeudiAnnee), (int) date("Y", $premierJeudiAnnee)))
1636 ) / 7
1637 ) + 1;
1638
1639 // Cas particulier de la semaine 53
1640 if ($numeroSemaine == 53) {
1641 // Les annees qui commencent un Jeudi et les annees bissextiles commencant un Mercredi en possedent 53
1642 if (
1643 ((int) date("w", mktime(12, 0, 0, 1, 1, (int) date("Y", $jeudiSemaine))) == 4)
1644 || (
1645 ((int) date("w", mktime(12, 0, 0, 1, 1, (int) date("Y", $jeudiSemaine))) == 3)
1646 && ((int) date("z", mktime(12, 0, 0, 12, 31, (int) date("Y", $jeudiSemaine))) == 365)
1647 )
1648 ) {
1649 $numeroSemaine = 53;
1650 } else {
1651 $numeroSemaine = 1;
1652 }
1653 }
1654
1655 //echo $jour."-".$mois."-".$annee." (".date("d-m-Y",$premierJeudiAnnee)." - ".date("d-m-Y",$jeudiSemaine).") -> ".$numeroSemaine."<BR>";
1656
1657 return sprintf("%02d", $numeroSemaine);
1658}
1659
1668function weight_convert($weight, &$from_unit, $to_unit)
1669{
1670 /* Pour convertire 320 gr en Kg appeler
1671 * $f = -3
1672 * weigh_convert(320, $f, 0) retournera 0.32
1673 *
1674 */
1675 $weight = is_numeric($weight) ? $weight : 0;
1676 while ($from_unit != $to_unit) {
1677 if ($from_unit > $to_unit) {
1678 $weight *= 10;
1679 $from_unit -= 1;
1680 $weight = weight_convert($weight, $from_unit, $to_unit);
1681 }
1682 if ($from_unit < $to_unit) {
1683 $weight /= 10;
1684 $from_unit += 1;
1685 $weight = weight_convert($weight, $from_unit, $to_unit);
1686 }
1687 }
1688
1689 return $weight;
1690}
1691
1704function dol_set_user_param($db, $conf, &$user, $tab, $entity = -1)
1705{
1706 // Verification parameters
1707 if (count($tab) < 1) {
1708 return -1;
1709 }
1710
1711 $entity = ($entity == -1 ? ((int) $conf->entity) : ((int) $entity));
1712
1713 $db->begin();
1714
1715 // We remove old parameters for all keys in $tab
1716 $sql = "DELETE FROM ".MAIN_DB_PREFIX."user_param";
1717 $sql .= " WHERE fk_user = ".((int) $user->id);
1718 $sql .= " AND entity = ".((int) $entity);
1719 $sql .= " AND param IN (";
1720 $i = 0;
1721 foreach ($tab as $key => $value) {
1722 if ($i > 0) {
1723 $sql .= ',';
1724 }
1725 $sql .= "'".$db->escape($key)."'";
1726 $i++;
1727 }
1728 $sql .= ")";
1729 dol_syslog("functions2.lib::dol_set_user_param", LOG_DEBUG);
1730
1731 $resql = $db->query($sql);
1732 if (!$resql) {
1733 dol_print_error($db);
1734 $db->rollback();
1735 return -1;
1736 }
1737
1738 foreach ($tab as $key => $value) {
1739 // Set new parameters
1740 $forcevalue = 0;
1741 if (is_array($value)) {
1742 if ($value["forcevalue"] == 1) {
1743 $forcevalue = 1;
1744 }
1745 $value = $value["value"];
1746 }
1747 if ($forcevalue == 1 || $value) {
1748 $sql = "INSERT INTO ".MAIN_DB_PREFIX."user_param (fk_user, entity, param, value)";
1749 $sql .= " VALUES (".((int) $user->id).",".((int) $entity).",";
1750 $sql .= " '".$db->escape($key)."','".$db->escape($value)."')";
1751
1752 dol_syslog("functions2.lib::dol_set_user_param", LOG_DEBUG);
1753 $result = $db->query($sql);
1754 if (!$result) {
1755 dol_print_error($db);
1756 $db->rollback();
1757 return -1;
1758 }
1759 $user->conf->$key = $value;
1760 //print "key=".$key." user->conf->key=".$user->conf->$key;
1761 } else {
1762 unset($user->conf->$key);
1763 }
1764 }
1765
1766 $db->commit();
1767 return 1;
1768}
1769
1777function dol_print_reduction($reduction, $langs)
1778{
1779 $string = '';
1780 if ($reduction == 100) {
1781 $string = $langs->transnoentities("Offered");
1782 } else {
1783 $string = vatrate((string) $reduction, true);
1784 }
1785
1786 return $string;
1787}
1788
1796function version_os($option = '')
1797{
1798 if ($option == 'smr') {
1799 $osversion = php_uname('s').' '.php_uname('m').' '.php_uname('r');
1800 } else {
1801 $osversion = php_uname();
1802 }
1803 return $osversion;
1804}
1805
1812function version_php()
1813{
1814 return phpversion();
1815}
1816
1822function version_db()
1823{
1824 global $db;
1825 if (is_object($db) && method_exists($db, 'getVersion')) {
1826 return $db->getVersion();
1827 }
1828 return '';
1829}
1830
1838{
1839 return DOL_VERSION;
1840}
1841
1848{
1849 return $_SERVER["SERVER_SOFTWARE"];
1850}
1851
1861function getListOfModels($db, $type, $maxfilenamelength = 0, $showempty = 0)
1862{
1863 global $conf, $hookmanager, $langs;
1864
1865 $docmodels = array();
1866 $found = 0;
1867 $dirtoscan = '';
1868
1869 $sql = "SELECT nom as id, nom as doc_template_name, libelle as label, description as description";
1870 $sql .= " FROM ".MAIN_DB_PREFIX."document_model";
1871 $sql .= " WHERE type = '".$db->escape($type)."'";
1872 $sql .= " AND entity IN (0,".((int) $conf->entity).")";
1873 $sql .= " ORDER BY description DESC";
1874
1875 dol_syslog('/core/lib/function2.lib.php::getListOfModels', LOG_DEBUG);
1876
1877 $resql_models = $db->query($sql);
1878 if ($resql_models) {
1879 $num = $db->num_rows($resql_models);
1880
1881 if ($showempty) {
1882 $docmodels[0] = '&nbsp;';
1883 }
1884
1885 $i = 0;
1886 while ($i < $num) {
1887 $found = 1;
1888
1889 $obj = $db->fetch_object($resql_models);
1890
1891 if ($obj->id == '0') { // We discard bad record (should not happen)
1892 $i++;
1893 continue;
1894 }
1895
1896 // If this generation module needs to scan a directory, then description field is filled
1897 // with the constant that contains list of directories to scan (COMPANY_ADDON_PDF_ODT_PATH, ...).
1898 if (!empty($obj->description)) { // A list of directories to scan is defined
1899 include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1900
1901 $const = $obj->description;
1902 $dirtoscan = preg_replace('/[\r\n]+/', ',', trim(getDolGlobalString($const)));
1903
1904 $listoffiles = array();
1905
1906 // Now we add models found in directories scanned
1907 $listofdir = explode(',', $dirtoscan);
1908 foreach ($listofdir as $key => $tmpdir) {
1909 $tmpdir = trim($tmpdir);
1910 $tmpdir = preg_replace('/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir);
1911 if (!$tmpdir) {
1912 unset($listofdir[$key]);
1913 continue;
1914 }
1915 if (is_dir($tmpdir)) {
1916 // all type of template is allowed
1917 $tmpfiles = dol_dir_list($tmpdir, 'files', 0, '', array(), 'name', SORT_ASC, 0);
1918 if (count($tmpfiles)) {
1919 $listoffiles = array_merge($listoffiles, $tmpfiles);
1920 }
1921 }
1922 }
1923
1924 if (count($listoffiles)) {
1925 foreach ($listoffiles as $record) {
1926 $max = ($maxfilenamelength ? $maxfilenamelength : 28);
1927 $docmodels[$obj->id.':'.$record['fullname']] = dol_trunc($record['name'], $max, 'middle');
1928 }
1929 } else {
1930 $docmodels[0] = $obj->label.': '.$langs->trans("None");
1931 }
1932 } else {
1933 if ($type == 'member' && $obj->doc_template_name == 'standard_member') { // Special case, if member template, we add variant per format
1934 global $_Avery_Labels;
1935 include_once DOL_DOCUMENT_ROOT.'/core/lib/format_cards.lib.php';
1936 foreach ($_Avery_Labels as $key => $val) {
1937 $docmodels[$obj->id.':'.$key] = ($obj->label ? $obj->label : $obj->doc_template_name).' '.$val['name'];
1938 }
1939 } else {
1940 // Common usage
1941 $docmodels[$obj->id] = $obj->label ? $obj->label : $obj->doc_template_name;
1942 }
1943 }
1944
1945 $i++;
1946 }
1947 } else {
1948 dol_print_error($db);
1949 return -1;
1950 }
1951 $parameters = array(
1952 'list' => &$docmodels,
1953 'found' => &$found,
1954 'type' => $type,
1955 'maxfilenamelength' => $maxfilenamelength,
1956 );
1957 $reshook = $hookmanager->executeHooks('getListOfModels', $parameters);
1958 if ($reshook < 0) {
1959 setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
1960 }
1961 if ($found) {
1962 return $docmodels;
1963 } else {
1964 return 0;
1965 }
1966}
1967
1975function is_ip($ip)
1976{
1977 // First we test if it is a valid IPv4
1978 if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
1979 // Then we test if it is a private range
1980 if (!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE)) {
1981 return 2;
1982 }
1983
1984 // Then we test if it is a reserved range
1985 if (!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_RES_RANGE)) {
1986 return 0;
1987 }
1988
1989 return 1;
1990 }
1991
1992 return 0; // If not valid
1993}
1994
2002function dol_buildlogin($lastname, $firstname)
2003{
2004 //$conf->global->MAIN_BUILD_LOGIN_RULE = 'f.lastname';
2005 $charforseparator = getDolGlobalString("MAIN_USER_SEPARATOR_CHAR_FOR_GENERATED_LOGIN", '.');
2006 if ($charforseparator == 'none') {
2007 $charforseparator = '';
2008 }
2009
2010 if (getDolGlobalString('MAIN_BUILD_LOGIN_RULE') == 'f.lastname') { // f.lastname
2011 $login = strtolower(dol_string_unaccent(dol_trunc($firstname, 1, 'right', 'UTF-8', 1)));
2012 $login .= ($login ? $charforseparator : '');
2013 $login .= strtolower(dol_string_unaccent($lastname));
2014 $login = dol_string_nospecial($login, ''); // For special names
2015 } else { // firstname.lastname
2016 $login = strtolower(dol_string_unaccent($firstname));
2017 $login .= ($login ? $charforseparator : '');
2018 $login .= strtolower(dol_string_unaccent($lastname));
2019 $login = dol_string_nospecial($login, ''); // For special names
2020 }
2021
2022 // TODO Add a hook to allow external modules to suggest new rules
2023
2024 return $login;
2025}
2026
2033{
2034 global $conf;
2035
2036 $params = array();
2037 $proxyuse = getDolGlobalString('MAIN_PROXY_USE');
2038 $proxyhost = (!$proxyuse ? false : $conf->global->MAIN_PROXY_HOST);
2039 $proxyport = (!$proxyuse ? false : $conf->global->MAIN_PROXY_PORT);
2040 $proxyuser = (!$proxyuse ? false : $conf->global->MAIN_PROXY_USER);
2041 $proxypass = (!$proxyuse ? false : $conf->global->MAIN_PROXY_PASS);
2042 $timeout = getDolGlobalInt('MAIN_USE_CONNECT_TIMEOUT', 10); // Connection timeout
2043 $response_timeout = getDolGlobalInt('MAIN_USE_RESPONSE_TIMEOUT', 30); // Response timeout
2044 //print extension_loaded('soap');
2045 if ($proxyuse) {
2046 $params = array('connection_timeout' => $timeout,
2047 'response_timeout' => $response_timeout,
2048 'proxy_use' => 1,
2049 'proxy_host' => $proxyhost,
2050 'proxy_port' => $proxyport,
2051 'proxy_login' => $proxyuser,
2052 'proxy_password' => $proxypass,
2053 'trace' => 1
2054 );
2055 } else {
2056 $params = array('connection_timeout' => $timeout,
2057 'response_timeout' => $response_timeout,
2058 'proxy_use' => 0,
2059 'proxy_host' => false,
2060 'proxy_port' => false,
2061 'proxy_login' => false,
2062 'proxy_password' => false,
2063 'trace' => 1
2064 );
2065 }
2066 return $params;
2067}
2068
2069
2079function dolGetElementUrl($objectid, $objecttype, $withpicto = 0, $option = '')
2080{
2081 global $db, $langs;
2082
2083 $ret = '';
2084 $regs = array();
2085
2086 // If we ask a resource form external module (instead of default path)
2087 if (preg_match('/^([^@]+)@([^@]+)$/i', $objecttype, $regs)) {
2088 $myobject = $regs[1];
2089 $module = $regs[2];
2090 } else {
2091 // Parse $objecttype (ex: project_task)
2092 $module = $myobject = $objecttype;
2093 if (preg_match('/^([^_]+)_([^_]+)/i', $objecttype, $regs)) {
2094 $module = $regs[1];
2095 $myobject = $regs[2];
2096 }
2097 }
2098
2099 // Generic case for $classpath
2100 $classpath = $module.'/class';
2101
2102 // Special cases, to work with non standard path
2103 if ($objecttype == 'facture' || $objecttype == 'invoice') {
2104 $langs->load('bills');
2105 $classpath = 'compta/facture/class';
2106 $module = 'facture';
2107 $myobject = 'facture';
2108 } elseif ($objecttype == 'commande' || $objecttype == 'order') {
2109 $langs->load('orders');
2110 $classpath = 'commande/class';
2111 $module = 'commande';
2112 $myobject = 'commande';
2113 } elseif ($objecttype == 'mailing') {
2114 $langs->load('mailing');
2115 $classpath = 'comm/mailing/class';
2116 } elseif ($objecttype == 'propal') {
2117 $langs->load('propal');
2118 $classpath = 'comm/propal/class';
2119 } elseif ($objecttype == 'supplier_proposal') {
2120 $langs->load('supplier_proposal');
2121 $classpath = 'supplier_proposal/class';
2122 } elseif ($objecttype == 'shipping') {
2123 $langs->load('sendings');
2124 $classpath = 'expedition/class';
2125 $myobject = 'expedition';
2126 $module = 'expedition';
2127 } elseif ($objecttype == 'delivery') {
2128 $langs->load('sendings');
2129 $classpath = 'delivery/class';
2130 $myobject = 'delivery';
2131 $module = 'delivery_note';
2132 } elseif ($objecttype == 'contract') {
2133 $langs->load('contracts');
2134 $classpath = 'contrat/class';
2135 $module = 'contrat';
2136 $myobject = 'contrat';
2137 } elseif ($objecttype == 'member') {
2138 $langs->load('members');
2139 $classpath = 'adherents/class';
2140 $module = 'adherent';
2141 $myobject = 'adherent';
2142 } elseif ($objecttype == 'cabinetmed_cons') {
2143 $classpath = 'cabinetmed/class';
2144 $module = 'cabinetmed';
2145 $myobject = 'cabinetmedcons';
2146 } elseif ($objecttype == 'fichinter') {
2147 $langs->load('interventions');
2148 $classpath = 'fichinter/class';
2149 $module = 'ficheinter';
2150 $myobject = 'fichinter';
2151 } elseif ($objecttype == 'project') {
2152 $langs->load('projects');
2153 $classpath = 'projet/class';
2154 $module = 'projet';
2155 } elseif ($objecttype == 'project_task') {
2156 $langs->load('projects');
2157 $classpath = 'projet/class';
2158 $module = 'projet';
2159 $myobject = 'task';
2160 } elseif ($objecttype == 'stock') {
2161 $classpath = 'product/stock/class';
2162 $module = 'stock';
2163 $myobject = 'stock';
2164 } elseif ($objecttype == 'inventory') {
2165 $classpath = 'product/inventory/class';
2166 $module = 'stock';
2167 $myobject = 'inventory';
2168 } elseif ($objecttype == 'mo') {
2169 $classpath = 'mrp/class';
2170 $module = 'mrp';
2171 $myobject = 'mo';
2172 } elseif ($objecttype == 'productlot') {
2173 $classpath = 'product/stock/class';
2174 $module = 'stock';
2175 $myobject = 'productlot';
2176 }
2177
2178 // Generic case for $classfile and $classname
2179 $classfile = strtolower($myobject);
2180 $classname = ucfirst($myobject);
2181 //print "objecttype=".$objecttype." module=".$module." subelement=".$subelement." classfile=".$classfile." classname=".$classname." classpath=".$classpath;
2182
2183 if ($objecttype == 'invoice_supplier') {
2184 $classfile = 'fournisseur.facture';
2185 $classname = 'FactureFournisseur';
2186 $classpath = 'fourn/class';
2187 $module = 'fournisseur';
2188 } elseif ($objecttype == 'order_supplier') {
2189 $classfile = 'fournisseur.commande';
2190 $classname = 'CommandeFournisseur';
2191 $classpath = 'fourn/class';
2192 $module = 'fournisseur';
2193 } elseif ($objecttype == 'supplier_proposal') {
2194 $classfile = 'supplier_proposal';
2195 $classname = 'SupplierProposal';
2196 $classpath = 'supplier_proposal/class';
2197 $module = 'supplier_proposal';
2198 } elseif ($objecttype == 'stock') {
2199 $classpath = 'product/stock/class';
2200 $classfile = 'entrepot';
2201 $classname = 'Entrepot';
2202 } elseif ($objecttype == 'facturerec') {
2203 $classpath = 'compta/facture/class';
2204 $classfile = 'facture-rec';
2205 $classname = 'FactureRec';
2206 $module = 'facture';
2207 } elseif ($objecttype == 'mailing') {
2208 $classpath = 'comm/mailing/class';
2209 $classfile = 'mailing';
2210 $classname = 'Mailing';
2211 }
2212
2213 if (isModEnabled($module)) {
2214 $res = dol_include_once('/'.$classpath.'/'.$classfile.'.class.php');
2215 if ($res) {
2216 if (class_exists($classname)) {
2217 $object = new $classname($db);
2218 $res = $object->fetch($objectid);
2219 if ($res > 0) {
2220 $ret = $object->getNomUrl($withpicto, $option);
2221 } elseif ($res == 0) {
2222 $ret = $langs->trans('Deleted');
2223 }
2224 unset($object);
2225 } else {
2226 dol_syslog("Class with classname ".$classname." is unknown even after the include", LOG_ERR);
2227 }
2228 }
2229 }
2230 return $ret;
2231}
2232
2233
2242function cleanCorruptedTree($db, $tabletocleantree, $fieldfkparent)
2243{
2244 $totalnb = 0;
2245 $listofid = array();
2246 $listofparentid = array();
2247
2248 // Get list of all id in array listofid and all parents in array listofparentid
2249 $sql = "SELECT rowid, ".$fieldfkparent." as parent_id FROM ".MAIN_DB_PREFIX.$tabletocleantree;
2250 $resql = $db->query($sql);
2251 if ($resql) {
2252 $num = $db->num_rows($resql);
2253 $i = 0;
2254 while ($i < $num) {
2255 $obj = $db->fetch_object($resql);
2256 $listofid[] = $obj->rowid;
2257 if ($obj->parent_id > 0) {
2258 $listofparentid[$obj->rowid] = $obj->parent_id;
2259 }
2260 $i++;
2261 }
2262 } else {
2263 dol_print_error($db);
2264 }
2265
2266 if (count($listofid)) {
2267 print 'Code requested to clean tree (may be to solve data corruption), so we check/clean orphelins and loops.'."<br>\n";
2268
2269 // Check loops on each other
2270 $sql = "UPDATE ".MAIN_DB_PREFIX.$tabletocleantree." SET ".$fieldfkparent." = 0 WHERE ".$fieldfkparent." = rowid"; // So we update only records linked to themself
2271 $resql = $db->query($sql);
2272 if ($resql) {
2273 $nb = $db->affected_rows($resql);
2274 if ($nb > 0) {
2275 print '<br>Some record that were parent of themself were cleaned.';
2276 }
2277
2278 $totalnb += $nb;
2279 }
2280 //else dol_print_error($db);
2281
2282 // Check other loops
2283 $listofidtoclean = array();
2284 foreach ($listofparentid as $id => $pid) {
2285 // Check depth
2286 //print 'Analyse record id='.$id.' with parent '.$pid.'<br>';
2287
2288 $cursor = $id;
2289 $arrayidparsed = array(); // We start from child $id
2290 while ($cursor > 0) {
2291 $arrayidparsed[$cursor] = 1;
2292 if ($arrayidparsed[$listofparentid[$cursor]]) { // We detect a loop. A record with a parent that was already into child
2293 print 'Found a loop between id '.$id.' - '.$cursor.'<br>';
2294 unset($arrayidparsed);
2295 $listofidtoclean[$cursor] = $id;
2296 break;
2297 }
2298 // @phpstan-ignore-next-line PHPStan thinks this line is never reached
2299 $cursor = $listofparentid[$cursor];
2300 }
2301
2302 if (count($listofidtoclean)) {
2303 break;
2304 }
2305 }
2306
2307 $sql = "UPDATE ".MAIN_DB_PREFIX.$db->sanitize($tabletocleantree);
2308 $sql .= " SET ".$db->sanitize($fieldfkparent)." = 0";
2309 $sql .= " WHERE rowid IN (".$db->sanitize(implode(',', $listofidtoclean)).")"; // So we update only records detected wrong
2310 $resql = $db->query($sql);
2311 if ($resql) {
2312 $nb = $db->affected_rows($resql);
2313 if ($nb > 0) {
2314 // Removed orphelins records
2315 print '<br>Some records were detected to have parent that is a child, we set them as root record for id: ';
2316 print implode(',', $listofidtoclean);
2317 }
2318
2319 $totalnb += $nb;
2320 }
2321 //else dol_print_error($db);
2322
2323 // Check and clean orphelins
2324 $sql = "UPDATE ".MAIN_DB_PREFIX.$db->sanitize($tabletocleantree);
2325 $sql .= " SET ".$db->sanitize($fieldfkparent)." = 0";
2326 $sql .= " WHERE ".$db->sanitize($fieldfkparent)." NOT IN (".$db->sanitize(implode(',', $listofid), 1).")"; // So we update only records linked to a non existing parent
2327 $resql = $db->query($sql);
2328 if ($resql) {
2329 $nb = $db->affected_rows($resql);
2330 if ($nb > 0) {
2331 // Removed orphelins records
2332 print '<br>Some orphelins were found and modified to be parent so records are visible again for id: ';
2333 print implode(',', $listofid);
2334 }
2335
2336 $totalnb += $nb;
2337 }
2338 //else dol_print_error($db);
2339
2340 print '<br>We fixed '.$totalnb.' record(s). Some records may still be corrupted. New check may be required.';
2341 return $totalnb;
2342 }
2343 return -1;
2344}
2345
2346
2356function colorArrayToHex($arraycolor, $colorifnotfound = '888888')
2357{
2358 if (!is_array($arraycolor)) {
2359 return $colorifnotfound;
2360 }
2361 if (empty($arraycolor)) {
2362 return $colorifnotfound;
2363 }
2364 return sprintf("%02s", dechex($arraycolor[0])).sprintf("%02s", dechex($arraycolor[1])).sprintf("%02s", dechex($arraycolor[2]));
2365}
2366
2377function colorStringToArray($stringcolor, $colorifnotfound = array(88, 88, 88))
2378{
2379 if (is_array($stringcolor)) {
2380 return $stringcolor; // If already in the correct output format, we return as is
2381 }
2382 $reg = array();
2383 $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);
2384 if (!$tmp) {
2385 $tmp = array_map('intval', explode(',', $stringcolor));
2386 '@phan-var-force int[] $tmp';
2387 if (count($tmp) < 3) {
2388 return $colorifnotfound;
2389 }
2390 return $tmp;
2391 }
2392 return array(hexdec($reg[1]), hexdec($reg[2]), hexdec($reg[3]));
2393}
2394
2400function colorValidateHex($color, $allow_white = true)
2401{
2402 if (!$allow_white && ($color === '#fff' || $color === '#ffffff')) {
2403 return false;
2404 }
2405
2406 if (preg_match('/^#[a-f0-9]{6}$/i', $color)) { //hex color is valid
2407 return true;
2408 }
2409 return false;
2410}
2411
2421function colorAgressiveness($hex, $ratio = -50, $brightness = 0)
2422{
2423 if (empty($ratio)) {
2424 $ratio = 0; // To avoid null
2425 }
2426
2427 // Steps should be between -255 and 255. Negative = darker, positive = lighter
2428 $ratio = max(-100, min(100, $ratio));
2429
2430 // Normalize into a six character long hex string
2431 $hex = str_replace('#', '', $hex);
2432 if (strlen($hex) == 3) {
2433 $hex = str_repeat(substr($hex, 0, 1), 2).str_repeat(substr($hex, 1, 1), 2).str_repeat(substr($hex, 2, 1), 2);
2434 }
2435
2436 // Split into three parts: R, G and B
2437 $color_parts = str_split($hex, 2);
2438 $return = '#';
2439
2440 foreach ($color_parts as $color) {
2441 $color = hexdec($color); // Convert to decimal
2442 if ($ratio > 0) { // We increase aggressivity
2443 if ($color > 127) {
2444 $color += ((255 - $color) * ($ratio / 100));
2445 }
2446 if ($color < 128) {
2447 $color -= ($color * ($ratio / 100));
2448 }
2449 } else { // We decrease aggressiveness
2450 if ($color > 128) {
2451 $color -= (($color - 128) * (abs($ratio) / 100));
2452 }
2453 if ($color < 127) {
2454 $color += ((128 - $color) * (abs($ratio) / 100));
2455 }
2456 }
2457 if ($brightness > 0) {
2458 $color = (int) ($color * (100 + abs($brightness)) / 100);
2459 } else {
2460 $color = (int) ($color * (100 - abs($brightness)) / 100);
2461 }
2462
2463 $color = max(0, min(255, (int) $color)); // Adjust color to stay into valid range
2464 $return .= str_pad(dechex($color), 2, '0', STR_PAD_LEFT); // Make two char hex code
2465 }
2466
2467 //var_dump($hex.' '.$ratio.' -> '.$return);
2468 return $return;
2469}
2470
2477function colorAdjustBrightness($hex, $steps)
2478{
2479 // Steps should be between -255 and 255. Negative = darker, positive = lighter
2480 $steps = max(-255, min(255, $steps));
2481
2482 // Normalize into a six character long hex string
2483 $hex = str_replace('#', '', $hex);
2484 if (strlen($hex) == 3) {
2485 $hex = str_repeat(substr($hex, 0, 1), 2).str_repeat(substr($hex, 1, 1), 2).str_repeat(substr($hex, 2, 1), 2);
2486 }
2487
2488 // Split into three parts: R, G and B
2489 $color_parts = str_split($hex, 2);
2490 $return = '#';
2491
2492 foreach ($color_parts as $color) {
2493 $color = hexdec($color); // Convert to decimal
2494 $color = max(0, min(255, $color + $steps)); // Adjust color
2495 $return .= str_pad(dechex($color), 2, '0', STR_PAD_LEFT); // Make two char hex code
2496 }
2497
2498 return $return;
2499}
2500
2506function colorDarker($hex, $percent)
2507{
2508 $steps = intval(255 * $percent / 100) * -1;
2509 return colorAdjustBrightness($hex, $steps);
2510}
2511
2517function colorLighten($hex, $percent)
2518{
2519 $steps = intval(255 * $percent / 100);
2520 return colorAdjustBrightness($hex, $steps);
2521}
2522
2523
2530function colorHexToRgb($hex, $alpha = false, $returnArray = false)
2531{
2532 $string = '';
2533 $hex = str_replace('#', '', $hex);
2534 $length = strlen($hex);
2535 $rgb = array();
2536 $rgb['r'] = hexdec($length == 6 ? substr($hex, 0, 2) : ($length == 3 ? str_repeat(substr($hex, 0, 1), 2) : 0));
2537 $rgb['g'] = hexdec($length == 6 ? substr($hex, 2, 2) : ($length == 3 ? str_repeat(substr($hex, 1, 1), 2) : 0));
2538 $rgb['b'] = hexdec($length == 6 ? substr($hex, 4, 2) : ($length == 3 ? str_repeat(substr($hex, 2, 1), 2) : 0));
2539 if ($alpha !== false) {
2540 $rgb['a'] = (float) $alpha;
2541 $string = 'rgba('.implode(',', array_map('strval', $rgb)).')';
2542 } else {
2543 $string = 'rgb('.implode(',', array_map('strval', $rgb)).')';
2544 }
2545
2546 if ($returnArray) {
2547 return $rgb;
2548 } else {
2549 return $string;
2550 }
2551}
2552
2561function colorHexToHsl($hex, $alpha = false, $returnArray = false)
2562{
2563 $hex = colorArrayToHex(colorStringToArray($hex));
2564 $hex = str_replace('#', '', $hex);
2565 $red = hexdec(substr($hex, 0, 2)) / 255;
2566 $green = hexdec(substr($hex, 2, 2)) / 255;
2567 $blue = hexdec(substr($hex, 4, 2)) / 255;
2568
2569 $cmin = min($red, $green, $blue);
2570 $cmax = max($red, $green, $blue);
2571 $delta = $cmax - $cmin;
2572
2573 if ($delta == 0) {
2574 $hue = 0;
2575 } elseif ($cmax === $red) {
2576 $hue = (($green - $blue) / $delta);
2577 } elseif ($cmax === $green) {
2578 $hue = ($blue - $red) / $delta + 2;
2579 } else {
2580 $hue = ($red - $green) / $delta + 4;
2581 }
2582
2583 $hue = round($hue * 60);
2584 if ($hue < 0) {
2585 $hue += 360;
2586 }
2587
2588 $lightness = (($cmax + $cmin) / 2);
2589 $saturation = $delta === 0 ? 0 : ($delta / (1 - abs(2 * $lightness - 1)));
2590 if ($saturation < 0) {
2591 $saturation += 1;
2592 }
2593
2594 $lightness = round($lightness * 100);
2595 $saturation = round($saturation * 100);
2596
2597 if ($returnArray) {
2598 return array(
2599 'h' => $hue,
2600 'l' => $lightness,
2601 's' => $saturation,
2602 'a' => $alpha === false ? 1 : $alpha
2603 );
2604 } elseif ($alpha) {
2605 return 'hsla('.$hue.', '.$saturation.', '.$lightness.' / '.$alpha.')';
2606 } else {
2607 return 'hsl('.$hue.', '.$saturation.', '.$lightness.')';
2608 }
2609}
2610
2618function cartesianArray(array $input)
2619{
2620 // filter out empty values
2621 $input = array_filter($input);
2622
2623 $result = array(array());
2624
2625 foreach ($input as $key => $values) {
2626 $append = array();
2627
2628 foreach ($result as $product) {
2629 foreach ($values as $item) {
2630 $product[$key] = $item;
2631 $append[] = $product;
2632 }
2633 }
2634
2635 $result = $append;
2636 }
2637
2638 return $result;
2639}
2640
2641
2648function getModuleDirForApiClass($moduleobject)
2649{
2650 $moduledirforclass = $moduleobject;
2651 if ($moduledirforclass != 'api') {
2652 $moduledirforclass = preg_replace('/api$/i', '', $moduledirforclass);
2653 }
2654
2655 if ($moduleobject == 'contracts') {
2656 $moduledirforclass = 'contrat';
2657 } elseif (in_array($moduleobject, array('admin', 'login', 'setup', 'access', 'status', 'tools', 'documents', 'objectlinks', 'emailtemplates'))) {
2658 $moduledirforclass = 'api';
2659 } elseif (in_array($moduleobject, ['contact', 'contacts', 'customer', 'thirdparty', 'thirdparties'])) {
2660 $moduledirforclass = 'societe';
2661 } elseif ($moduleobject == 'propal' || $moduleobject == 'propale' || $moduleobject == 'proposals') {
2662 $moduledirforclass = 'comm/propal';
2663 } elseif ($moduleobject == 'agenda' || $moduleobject == 'agendaevents') {
2664 $moduledirforclass = 'comm/action';
2665 } elseif ($moduleobject == 'mailing' || $moduleobject == 'mailings') {
2666 $moduledirforclass = 'comm/mailing';
2667 } elseif (in_array($moduleobject, ['adherent', 'members', 'memberstypes', 'subscriptions'])) {
2668 $moduledirforclass = 'adherents';
2669 } elseif ($moduleobject == 'don' || $moduleobject == 'donations') {
2670 $moduledirforclass = 'don';
2671 } elseif ($moduleobject == 'banque' || $moduleobject == 'bankaccounts') {
2672 $moduledirforclass = 'compta/bank';
2673 } elseif ($moduleobject == 'category' || $moduleobject == 'categorie') {
2674 $moduledirforclass = 'categories';
2675 } elseif ($moduleobject == 'order' || $moduleobject == 'orders') {
2676 $moduledirforclass = 'commande';
2677 } elseif ($moduleobject == 'shipments') {
2678 $moduledirforclass = 'expedition';
2679 } elseif ($moduleobject == 'multicurrencies') {
2680 $moduledirforclass = 'multicurrency';
2681 } elseif ($moduleobject == 'facture' || $moduleobject == 'invoice' || $moduleobject == 'invoices') {
2682 $moduledirforclass = 'compta/facture';
2683 } elseif ($moduleobject == 'project' || $moduleobject == 'projects' || $moduleobject == 'task' || $moduleobject == 'tasks') {
2684 $moduledirforclass = 'projet';
2685 } elseif ($moduleobject == 'stock' || $moduleobject == 'stockmovements' || $moduleobject == 'warehouses' || $moduleobject == 'productlots') {
2686 $moduledirforclass = 'product/stock';
2687 } elseif ($moduleobject == 'supplierproposals' || $moduleobject == 'supplierproposal' || $moduleobject == 'supplier_proposal') {
2688 $moduledirforclass = 'supplier_proposal';
2689 } elseif ($moduleobject == 'fournisseur' || $moduleobject == 'supplierinvoices' || $moduleobject == 'supplierorders') {
2690 $moduledirforclass = 'fourn';
2691 } elseif ($moduleobject == 'ficheinter' || $moduleobject == 'interventions') {
2692 $moduledirforclass = 'fichinter';
2693 } elseif ($moduleobject == 'mos') {
2694 $moduledirforclass = 'mrp';
2695 } elseif ($moduleobject == 'workstations') {
2696 $moduledirforclass = 'workstation';
2697 } elseif ($moduleobject == 'accounting') {
2698 $moduledirforclass = 'accountancy';
2699 } elseif ($moduleobject == 'paiements') {
2700 $moduledirforclass = 'compta/facture';
2701 } elseif (in_array($moduleobject, array('products', 'expensereports', 'users', 'tickets', 'boms', 'receptions', 'partnerships', 'recruitments'))) {
2702 $moduledirforclass = preg_replace('/s$/', '', $moduleobject);
2703 } elseif ($moduleobject == 'paymentsalaries') {
2704 $moduledirforclass = 'salaries';
2705 } elseif ($moduleobject == 'paymentexpensereports') {
2706 $moduledirforclass = 'expensereport';
2707 } elseif ($moduleobject == 'eventattendees') {
2708 $moduledirforclass = 'eventorganization';
2709 } elseif ($moduleobject == 'holidays') {
2710 $moduledirforclass = 'holiday';
2711 }
2712
2713 return $moduledirforclass;
2714}
2715
2723function randomColorPart($min = 0, $max = 255)
2724{
2725 return str_pad(dechex(mt_rand($min, $max)), 2, '0', STR_PAD_LEFT);
2726}
2727
2735function randomColor($min = 0, $max = 255)
2736{
2737 return randomColorPart($min, $max).randomColorPart($min, $max).randomColorPart($min, $max);
2738}
2739
2740
2741if (!function_exists('dolEscapeXML')) {
2748 function dolEscapeXML($string)
2749 {
2750 return strtr($string, array('\'' => '&apos;', '"' => '&quot;', '&' => '&amp;', '<' => '&lt;', '>' => '&gt;'));
2751 }
2752}
2753
2754
2762{
2764 // Define $urlwithroot
2765 $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
2766 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
2767 //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
2768 $notetoshow = preg_replace('/src="[a-zA-Z0-9_\/\-\.]*(viewimage\.php\?modulepart=medias[^"]*)"/', 'src="'.$urlwithroot.'/\1"', $notetoshow);
2769 return $notetoshow;
2770}
2771
2780function price2fec($amount)
2781{
2782 global $conf;
2783
2784 // Clean parameters
2785 if (empty($amount)) {
2786 $amount = 0; // To have a numeric value if amount not defined or = ''
2787 }
2788 $amount = (is_numeric($amount) ? $amount : 0); // Check if amount is numeric, for example, an error occurred when amount value = o (letter) instead 0 (number)
2789
2790 // Output decimal number by default
2791 $nbdecimal = (!getDolGlobalString('ACCOUNTING_FEC_DECIMAL_LENGTH') ? 2 : $conf->global->ACCOUNTING_FEC_DECIMAL_LENGTH);
2792
2793 // Output separators by default
2794 $dec = (!getDolGlobalString('ACCOUNTING_FEC_DECIMAL_SEPARATOR') ? ',' : $conf->global->ACCOUNTING_FEC_DECIMAL_SEPARATOR);
2795 $thousand = (!getDolGlobalString('ACCOUNTING_FEC_THOUSAND_SEPARATOR') ? '' : $conf->global->ACCOUNTING_FEC_THOUSAND_SEPARATOR);
2796
2797 // Format number
2798 $output = number_format($amount, $nbdecimal, $dec, $thousand);
2799
2800 return $output;
2801}
2802
2809function phpSyntaxError($code)
2810{
2811 if (!defined("CR")) {
2812 define("CR", "\r");
2813 }
2814 if (!defined("LF")) {
2815 define("LF", "\n");
2816 }
2817 if (!defined("CRLF")) {
2818 define("CRLF", "\r\n");
2819 }
2820
2821 $braces = 0;
2822 $inString = 0;
2823 foreach (token_get_all('<?php '.$code) as $token) {
2824 if (is_array($token)) {
2825 switch ($token[0]) {
2826 case T_CURLY_OPEN:
2827 case T_DOLLAR_OPEN_CURLY_BRACES:
2828 case T_START_HEREDOC:
2829 ++$inString;
2830 break;
2831 case T_END_HEREDOC:
2832 --$inString;
2833 break;
2834 }
2835 } elseif ($inString & 1) {
2836 switch ($token) {
2837 case '`':
2838 case '\'':
2839 case '"':
2840 --$inString;
2841 break;
2842 }
2843 } else {
2844 switch ($token) {
2845 case '`':
2846 case '\'':
2847 case '"':
2848 ++$inString;
2849 break;
2850 case '{':
2851 ++$braces;
2852 break;
2853 case '}':
2854 if ($inString) {
2855 --$inString;
2856 } else {
2857 --$braces;
2858 if ($braces < 0) {
2859 break 2;
2860 }
2861 }
2862 break;
2863 }
2864 }
2865 }
2866 $inString = @ini_set('log_errors', false);
2867 $token = @ini_set('display_errors', true);
2868 ob_start();
2869 $code = substr($code, strlen('<?php '));
2870 $braces || $code = "if(0){{$code}\n}";
2871 // @phan-suppress-next-line PhanPluginUnsafeEval
2872 if (eval($code) === false) {
2873 if ($braces) {
2874 $braces = PHP_INT_MAX;
2875 } else {
2876 false !== strpos($code, CR) && $code = strtr(str_replace(CRLF, LF, $code), CR, LF);
2877 $braces = substr_count($code, LF);
2878 }
2879 $code = ob_get_clean();
2880 $code = strip_tags($code);
2881 if (preg_match("'syntax error, (.+) in .+ on line (\d+)$'s", $code, $code)) {
2882 $code[2] = (int) $code[2];
2883 $code = $code[2] <= $braces
2884 ? array($code[1], $code[2])
2885 : array('unexpected $end'.substr($code[1], 14), $braces);
2886 } else {
2887 $code = array('syntax error', 0);
2888 }
2889 } else {
2890 ob_end_clean();
2891 $code = false;
2892 }
2893 @ini_set('display_errors', $token);
2894 @ini_set('log_errors', $inString);
2895 return $code;
2896}
2897
2898
2905{
2906 global $user;
2907
2908 // If $acceptlocallinktomedia is true, we can add link media files int email templates (we already can do this into HTML editor of an email).
2909 // 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:
2910 // $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
2911 // $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
2912
2913 $acceptlocallinktomedia = getDolGlobalInt('MAIN_DISALLOW_MEDIAS_IN_EMAIL_TEMPLATES') ? 0 : 1;
2914
2915 // By default we accept to add medias from emails templates but this may be refused in the future
2916 // we detect we are not on a public url that we can access remotely (if we are on a private network, such files can't be reached),
2917 // except if MAIN_ALLOW_WYSIWYG_LOCAL_MEDIAS_ON_PRIVATE_NETWORK is net, in which case we accept also if instance has a local or private network URL.
2918
2919 if ($acceptlocallinktomedia) {
2921 $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
2922
2923 // Parse $newUrl to get the IP of the server
2924 $newUrlArray = parse_url($urlwithouturlroot);
2925 $hosttocheck = $newUrlArray['host'];
2926 $hosttocheck = str_replace(array('[', ']'), '', $hosttocheck); // Remove brackets of IPv6
2927
2928 if (function_exists('gethostbyname')) {
2929 $iptocheck = gethostbyname($hosttocheck);
2930 } else {
2931 $iptocheck = $hosttocheck;
2932 }
2933
2934 //var_dump($iptocheck.' '.$acceptlocallinktomedia);
2935 $allowPrivateNetworkIP = getDolGlobalInt('MAIN_ALLOW_WYSIWYG_LOCAL_MEDIAS_ON_PRIVATE_NETWORK');
2936 if (!$allowPrivateNetworkIP && !filter_var($iptocheck, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
2937 // If ip of public url ($iptocheck) is a private network IP (192.168.0.1; 127.0.0.1...), we do not allow to upload files on media (they are unreachable publicly).
2938 $acceptlocallinktomedia = 0;
2939 //dol_syslog("WYSIWYG Editor : local media not allowed (checked IP: {$iptocheck}). Use MAIN_ALLOW_WYSIWYG_LOCAL_MEDIAS_ON_PRIVATE_NETWORK = 1 to allow local URL into WYSIWYG html content");
2940 }
2941
2942 $allowUrlInHTTP = getDolGlobalInt('MAIN_ALLOW_WYSIWYG_EVEN_ON_UNSECURED_EXTERNAL_HTTP_URL');
2943 if (!$allowUrlInHTTP && preg_match('/http:/i', $urlwithouturlroot)) {
2944 // 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.
2945 $acceptlocallinktomedia = 0;
2946 // TODO Show a warning
2947 }
2948
2949 if (!empty($user->socid)) {
2950 $acceptlocallinktomedia = 0;
2951 }
2952 }
2953
2954 //return 1;
2955 return $acceptlocallinktomedia;
2956}
2957
2958
2966{
2967 $string = trim($string);
2968
2969 // If string does not start and end with parenthesis, we return $string as is.
2970 if (! preg_match('/^\‍(.*\‍)$/', $string)) {
2971 return $string;
2972 }
2973
2974 $nbofchars = dol_strlen($string);
2975 $i = 0;
2976 $g = 0;
2977 $countparenthesis = 0;
2978 while ($i < $nbofchars) {
2979 $char = dol_substr($string, $i, 1);
2980 if ($char == '(') {
2981 $countparenthesis++;
2982 } elseif ($char == ')') {
2983 $countparenthesis--;
2984 if ($countparenthesis <= 0) { // We reach the end of an independent group of parenthesis
2985 $g++;
2986 }
2987 }
2988 $i++;
2989 }
2990
2991 if ($g <= 1) {
2992 return preg_replace('/^\‍(/', '', preg_replace('/\‍)$/', '', $string));
2993 }
2994
2995 return $string;
2996}
2997
2998
3006{
3007 $arrayofcommonemoji = array(
3008 'misc' => array('2600', '26FF'), // Miscellaneous Symbols
3009 'ding' => array('2700', '27BF'), // Dingbats
3010 '????' => array('9989', '9989'), // Variation Selectors
3011 'vars' => array('FE00', 'FE0F'), // Variation Selectors
3012 'pict' => array('1F300', '1F5FF'), // Miscellaneous Symbols and Pictographs
3013 'emot' => array('1F600', '1F64F'), // Emoticons
3014 'tran' => array('1F680', '1F6FF'), // Transport and Map Symbols
3015 'flag' => array('1F1E0', '1F1FF'), // Flags (note: may be 1F1E6 instead of 1F1E0)
3016 'supp' => array('1F900', '1F9FF'), // Supplemental Symbols and Pictographs
3017 );
3018
3019 return $arrayofcommonemoji;
3020}
3021
3029function removeEmoji($text, $allowedemoji = 1)
3030{
3031 // $allowedemoji can be
3032 // 0=no emoji, 1=exclude the main known emojis (default), 2=keep only the main known (not implemented), 3=accept all
3033 // Note that to accept emoji in database, you must use utf8mb4, utf8mb3 is not enough.
3034
3035 if ($allowedemoji == 0) {
3036 // For a large removal:
3037 $text = preg_replace('/[\x{2600}-\x{FFFF}]/u', '', $text);
3038 $text = preg_replace('/[\x{10000}-\x{10FFFF}]/u', '', $text);
3039 }
3040
3041 // Delete emoji chars with a regex
3042 // See https://www.unicode.org/emoji/charts/full-emoji-list.html
3043 if ($allowedemoji == 1) {
3044 $arrayofcommonemoji = getArrayOfEmojiBis();
3045
3046 foreach ($arrayofcommonemoji as $key => $valarray) {
3047 $text = preg_replace('/[\x{'.$valarray[0].'}-\x{'.$valarray[1].'}]/u', '', $text);
3048 }
3049 }
3050
3051 if ($allowedemoji == 2) {
3052 // TODO Not yet implemented
3053 }
3054
3055 return $text;
3056}
3057
3058
3067function csvClean($newvalue, $charset = '', $separator = '')
3068{
3069 global $langs;
3070
3071 $addquote = 0;
3072
3073 if (empty($charset)) {
3074 $charset = getDolGlobalString('EXPORT_CSV_FORCE_CHARSET');
3075 }
3076 if (empty($separator)) {
3077 $separator = getDolGlobalString('EXPORT_CSV_SEPARATOR_TO_USE');
3078 }
3079
3080
3081 $newvalue = $langs->convToOutputCharset((string) $newvalue, 'UTF-8', $charset); // newvalue is now encoded into $charset
3082
3083
3084 // Rule Dolibarr: No HTML
3085 //print $charset.' '.$newvalue."\n";
3086 //$newvalue=dol_string_nohtmltag($newvalue,0,$charset);
3087 $newvalue = dol_htmlcleanlastbr($newvalue);
3088 //print $charset.' '.$newvalue."\n";
3089
3090 // 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)
3091 $oldvalue = $newvalue;
3092 $newvalue = str_replace("\r", '', $newvalue);
3093 $newvalue = str_replace("\n", '\n', $newvalue);
3094 if (getDolGlobalString('USE_STRICT_CSV_RULES') && $oldvalue != $newvalue) {
3095 // If we must use enclusure on text with CR/LF)
3096 if (getDolGlobalInt('USE_STRICT_CSV_RULES') == 1) {
3097 // If we use strict CSV rules (original value must remain but we add quote)
3098 $newvalue = $oldvalue;
3099 }
3100 $addquote = 1;
3101 }
3102
3103 // Rule 2 CSV: If value contains ", we must escape with ", and add "
3104 if (preg_match('/"/', $newvalue)) {
3105 $addquote = 1;
3106 $newvalue = str_replace('"', '""', $newvalue);
3107 }
3108
3109 // Rule 3 CSV: If value contains separator, we must add "
3110 if (preg_match('/'.$separator.'/', $newvalue)) {
3111 $addquote = 1;
3112 }
3113
3114 return ($addquote ? '"' : '').$newvalue.($addquote ? '"' : '');
3115}
3116
3117
3127function printCodeForPing($constanttosavelastko, $constanttosavefirstok, $arrayofdata = array(), $forceping = 0)
3128{
3129 global $dolibarr_distrib;
3130 global $db, $conf;
3131
3132 $hash_unique_id = dol_hash('dolibarr'.$conf->file->instance_unique_id, 'sha256'); // Note: if the global salt changes, this hash changes too so ping may be counted twice. We don't mind. It is for statistics and inventory purpose only.
3133
3134 // Disable ping if $constanttosavelastpingko is set and is recent (this month)
3135 if (getDolGlobalString($constanttosavelastko) && substr(getDolGlobalString($constanttosavelastko), 0, 6) == dol_print_date(dol_now(), '%Y%m') && !$forceping) {
3136 print "\n<!-- NO JS CODE TO ENABLE the call for ".$constanttosavefirstok.". An error already occurred this month (".$constanttosavelastko." is set), we will re-try next month. -->\n";
3137 } else {
3138 print "\n".'<!-- Includes JS to make ajax call for '.$constanttosavefirstok.'. forceping='.$forceping.' '.$constanttosavefirstok.'='.getDolGlobalString($constanttosavefirstok).' '.$constanttosavelastko.'='.getDolGlobalString($constanttosavelastko).' -->'."\n";
3139 print "<!-- JS CODE TO ENABLE the call -->\n";
3140 $url_for_ping = getDolGlobalString('MAIN_URL_FOR_PING', "https://ping.dolibarr.org/");
3141 // Try to guess the distrib used
3142 $distrib = 'standard';
3143 if (isset($_SERVER["SERVER_ADMIN"]) && $_SERVER["SERVER_ADMIN"] == 'doliwamp@localhost') {
3144 $distrib = 'doliwamp';
3145 }
3146 if (!empty($dolibarr_distrib)) {
3147 $distrib = $dolibarr_distrib;
3148 }
3149 ?>
3150 <script>
3151 jQuery(document).ready(function (tmp) {
3152 console.log("Try remote call with hash_unique_id is dol_hash('dolibarr'+instance_unique_id, 'sha256')");
3153 $.ajax({
3154 method: "POST",
3155 url: "<?php echo $url_for_ping ?>",
3156 timeout: 500, // timeout milliseconds
3157 cache: false,
3158 data: {
3159 <?php
3160 foreach ($arrayofdata as $datakey => $dataval) {
3161 print $datakey.": '".dol_escape_js($dataval)."',\n";
3162 }
3163 ?>
3164 hash_algo: 'dol_hash-sha256',
3165 hash_unique_id: '<?php echo dol_escape_js($hash_unique_id); ?>',
3166 version: '<?php echo (float) DOL_VERSION; ?>',
3167 version_full: '<?php echo DOL_VERSION; ?>',
3168 entity: '<?php echo (int) $conf->entity; ?>',
3169 dbtype: '<?php echo dol_escape_js($db->type); ?>',
3170 php_version: '<?php echo dol_escape_js(phpversion()); ?>',
3171 os_version: '<?php echo dol_escape_js(version_os('smr')); ?>',
3172 db_version: '<?php echo dol_escape_js(version_db()); ?>',
3173 distrib: '<?php echo dol_escape_js($distrib); ?>',
3174 token: 'notrequired'
3175 },
3176 success: function (data, status, xhr) { // success callback function (data contains body of response)
3177 console.log("Ping ok");
3178 $.ajax({
3179 method: 'GET',
3180 url: '<?php echo DOL_URL_ROOT.'/core/ajax/pingresult.php'; ?>',
3181 timeout: 500, // timeout milliseconds
3182 cache: false,
3183 data: { hash_algo: 'dol_hash-sha256', hash_unique_id: '<?php echo dol_escape_js($hash_unique_id); ?>', action: '<?php echo $constanttosavefirstok ?>', token: '<?php echo currentToken(); ?>' }, // for update
3184 });
3185 },
3186 error: function (data,status,xhr) { // error callback function
3187 console.log("Ping ko: " + data);
3188 $.ajax({
3189 method: 'GET',
3190 url: '<?php echo DOL_URL_ROOT.'/core/ajax/pingresult.php'; ?>',
3191 timeout: 500, // timeout milliseconds
3192 cache: false,
3193 data: { hash_algo: 'dol_hash-sha256', hash_unique_id: '<?php echo dol_escape_js($hash_unique_id); ?>', action: '<?php echo $constanttosavelastko ?>', token: '<?php echo currentToken(); ?>' },
3194 });
3195 }
3196 });
3197 });
3198 </script>
3199 <?php
3200 }
3201}
$id
Support class for third parties, contacts, members, users or resources.
Definition account.php:47
if(! $sortfield) if(! $sortorder) $object
Definition account.php:100
global $dolibarr_main_url_root
Class to manage Dolibarr users.
print $langs trans("Ref").' m titre as m m statut as status
Or an array listing all the potential status of the object: array: int of the status => translated la...
Definition index.php:171
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:64
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.
getListOfModels($db, $type, $maxfilenamelength=0, $showempty=0)
Return list of activated modules usable for document generation.
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.
printCodeForPing($constanttosavelastko, $constanttosavefirstok, $arrayofdata=array(), $forceping=0)
Function to output HTML to make an ajax call to make registration.
hexbin($hexa)
Convert an hexadecimal string into a binary string.
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.
dol_set_user_param($db, $conf, &$user, $tab, $entity=-1)
Save personal parameter.
dol_print_object_info($object, $usetable=0)
Show information on an object TODO Move this into html.formother.
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...
get_next_value($db, $mask, $table, $field, $where='', $objsoc='', $date='', $mode='next', $bentityon=true, $objuser=null, $forceentity=null, $objbookkeeping=null)
Return last or next value for a mask (according to area we should not reset)
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_now($mode='gmt')
Return date for now.
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...
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0, $attop=0)
Set event messages in dol_events session object.
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.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
dol_escape_js($stringtoescape, $mode=0, $noescapebackslashn=0)
Returns text escaped for inclusion into javascript code.
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_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false, $decorate=0)
Output date in a string format according to outputlangs (or langs if not defined).
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.
isModEnabled($module)
Is Dolibarr module enabled.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
if(getDolGlobalString( 'TAKEPOS_SHOW_CUSTOMER')) print $langs trans('Date')." left Label right Qty right Price right TotalHT right TotalTTC right right right right right right right right right centpercent right TotalHT right n right VAT right n right TotalVAT right n No sujeto a RE IRPF right TotalLT1 right n right TotalLT2 right n right TotalTTC right n takeposcustomercurrency takeposcustomercurrency takeposcustomercurrency takeposcustomercurrency right TotalTTC takeposcustomercurrency right takeposcustomercurrency n right PaymentTypeShortLIQ right SELECT p pos_change as p datep as date
Definition receipt.php:464
dol_hash($chain, $type='0', $nosalt=0, $mode=0)
Returns a hash (non reversible encryption) of a string.