/
functions2.lib.php
1953 lines (1749 loc) · 71 KB
/
functions2.lib.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/* Copyright (C) 2008-2014 Laurent Destailleur <eldy@users.sourceforge.net>
* Copyright (C) 2008-2012 Regis Houssin <regis.houssin@capnetworks.com>
* Copyright (C) 2008 Raphael Bertrand (Resultic) <raphael.bertrand@resultic.fr>
* Copyright (C) 2014 Marcos García <marcosgdf@gmail.com>
* Copyright (C) 2015 Ferran Marcet <fmarcet@2byte.es>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* or see http://www.gnu.org/
*/
/**
* \file htdocs/core/lib/functions2.lib.php
* \brief A set of functions for Dolibarr
* This file contains all rare functions.
*/
// Enable this line to trace path when function is called.
//print xdebug_print_function_stack('Functions2.lib was called');exit;
/**
* Return first line of text. Cut will depends if content is HTML or not.
*
* @param string $text Input text
* @return string Output text
* @see dol_nboflines_bis
*/
function dolGetFirstLineOfText($text)
{
if (dol_textishtml($text))
{
$firstline=preg_replace('/<br[^>]*>.*$/s','',$text); // The s pattern modifier means the . can match newline characters
}
else
{
$firstline=preg_replace('/[\n\r].*/','',$text);
}
return $firstline.((strlen($firstline) != strlen($text))?'...':'');
}
/**
* Same function than javascript unescape() function but in PHP.
*
* @param string $source String to decode
* @return string Unescaped string
*/
function jsUnEscape($source)
{
$decodedStr = "";
$pos = 0;
$len = strlen($source);
while ($pos < $len) {
$charAt = substr($source, $pos, 1);
if ($charAt == '%') {
$pos++;
$charAt = substr($source, $pos, 1);
if ($charAt == 'u') {
// we got a unicode character
$pos++;
$unicodeHexVal = substr($source, $pos, 4);
$unicode = hexdec($unicodeHexVal);
$entity = "&#". $unicode . ';';
$decodedStr .= utf8_encode($entity);
$pos += 4;
}
else {
// we have an escaped ascii character
$hexVal = substr($source, $pos, 2);
$decodedStr .= chr(hexdec($hexVal));
$pos += 2;
}
} else {
$decodedStr .= $charAt;
$pos++;
}
}
return dol_html_entity_decode($decodedStr, ENT_COMPAT);
}
/**
* Return list of modules directories
*
* @param string $subdir Sub directory (Example: '/mailings')
* @return array Array of directories that can contains module descriptors
*/
function dolGetModulesDirs($subdir='')
{
global $conf;
$modulesdir=array();
foreach ($conf->file->dol_document_root as $type => $dirroot)
{
// Default core/modules dir
$modulesdir[$dirroot . '/core/modules'.$subdir.'/'] = $dirroot . '/core/modules'.$subdir.'/';
// Scan dir from external modules
$handle=@opendir($dirroot);
if (is_resource($handle))
{
while (($file = readdir($handle))!==false)
{
if (is_dir($dirroot.'/'.$file) && substr($file, 0, 1) <> '.' && substr($file, 0, 3) <> 'CVS' && $file != 'includes')
{
if (is_dir($dirroot . '/' . $file . '/core/modules'.$subdir.'/'))
{
$modulesdir[$dirroot . '/' . $file . '/core/modules'.$subdir.'/'] = $dirroot . '/' . $file . '/core/modules'.$subdir.'/';
}
}
}
closedir($handle);
}
}
return $modulesdir;
}
/**
* Try to guess default paper format according to language into $langs
*
* @param Translate $outputlangs Output lang to use to autodetect output format if setup not done
* @return string Default paper format code
*/
function dol_getDefaultFormat($outputlangs='')
{
global $langs;
$selected='EUA4';
if (empty($outputlangs) || ! is_object($outputlangs)) $outputlangs=$langs;
if ($outputlangs->defaultlang == 'ca_CA') $selected='CAP4'; // Canada
if ($outputlangs->defaultlang == 'en_US') $selected='USLetter'; // US
return $selected;
}
/**
* Output content of a file $filename in version of current language (otherwise may use an alternate language)
*
* @param Translate $langs Object language to use for output
* @param string $filename Relative filename to output
* @param int $searchalt 1=Search also in alternative languages
* @return boolean true if OK, false if KO
*/
function dol_print_file($langs,$filename,$searchalt=0)
{
global $conf;
// Test if file is in lang directory
foreach($langs->dir as $searchdir)
{
$formfile=($searchdir."/langs/".$langs->defaultlang."/".$filename);
dol_syslog('functions2::dol_print_file search file '.$formfile, LOG_DEBUG);
if (is_readable($formfile))
{
$content=file_get_contents($formfile);
$isutf8=utf8_check($content);
if (! $isutf8 && $conf->file->character_set_client == 'UTF-8') print utf8_encode($content);
elseif ($isutf8 && $conf->file->character_set_client == 'ISO-8859-1') print utf8_decode($content);
else print $content;
return true;
}
else dol_syslog('functions2::dol_print_file not found', LOG_DEBUG);
if ($searchalt) {
// Test si fichier dans repertoire de la langue alternative
if ($langs->defaultlang != "en_US") $formfilealt = $searchdir."/langs/en_US/".$filename;
else $formfilealt = $searchdir."/langs/fr_FR/".$filename;
dol_syslog('functions2::dol_print_file search alt file '.$formfilealt, LOG_DEBUG);
//print 'getcwd='.getcwd().' htmlfilealt='.$formfilealt.' X '.file_exists(getcwd().'/'.$formfilealt);
if (is_readable($formfilealt))
{
$content=file_get_contents($formfilealt);
$isutf8=utf8_check($content);
if (! $isutf8 && $conf->file->character_set_client == 'UTF-8') print utf8_encode($content);
elseif ($isutf8 && $conf->file->character_set_client == 'ISO-8859-1') print utf8_decode($content);
else print $content;
return true;
}
else dol_syslog('functions2::dol_print_file not found', LOG_DEBUG);
}
}
return false;
}
/**
* Show informations on an object
* TODO Move this into html.formother
*
* @param object $object Objet to show
* @return void
*/
function dol_print_object_info($object)
{
global $langs,$db;
$langs->load("other");
$langs->load("admin");
include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
$deltadateforserver=getServerTimeZoneInt('now');
$deltadateforclient=((int) $_SESSION['dol_tz'] + (int) $_SESSION['dol_dst']);
//$deltadateforcompany=((int) $_SESSION['dol_tz'] + (int) $_SESSION['dol_dst']);
$deltadateforuser=round($deltadateforclient-$deltadateforserver);
//print "x".$deltadateforserver." - ".$deltadateforclient." - ".$deltadateforuser;
// Import key
if (! empty($object->import_key))
print $langs->trans("ImportedWithSet").': '.$object->import_key.'<br>';
// User creation
if (! empty($object->user_creation))
{
print $langs->trans("CreatedBy").': ';
if (is_object($object->user_creation))
{
if ($object->user_creation->id) print $object->user_creation->getNomUrl(1);
else print $langs->trans("Unknown");
}
else
{
$userstatic=new User($db);
$userstatic->fetch($object->user_creation);
if ($userstatic->id) print $userstatic->getNomUrl(1);
else print $langs->trans("Unknown");
}
print '<br>';
}
// Date creation
if (! empty($object->date_creation))
{
print $langs->trans("DateCreation").': '.dol_print_date($object->date_creation, 'dayhour');
if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' / '.dol_print_date($object->date_creation+($deltadateforuser*3600),"dayhour").' '.$langs->trans("ClientHour");
print '<br>';
}
// User change
if (! empty($object->user_modification))
{
print $langs->trans("ModifiedBy").': ';
if (is_object($object->user_modification))
{
if ($object->user_modification->id) print $object->user_modification->getNomUrl(1);
else print $langs->trans("Unknown");
}
else
{
$userstatic=new User($db);
$userstatic->fetch($object->user_modification);
if ($userstatic->id) print $userstatic->getNomUrl(1);
else print $langs->trans("Unknown");
}
print '<br>';
}
// Date change
if (! empty($object->date_modification))
{
print $langs->trans("DateLastModification").': '.dol_print_date($object->date_modification, 'dayhour');
if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' / '.dol_print_date($object->date_modification+($deltadateforuser*3600),"dayhour").' '.$langs->trans("ClientHour");
print '<br>';
}
// User validation
if (! empty($object->user_validation))
{
print $langs->trans("ValidatedBy").': ';
if (is_object($object->user_validation))
{
if ($object->user_validation->id) print $object->user_validation->getNomUrl(1);
else print $langs->trans("Unknown");
}
else
{
$userstatic=new User($db);
$userstatic->fetch($object->user_validation);
if ($userstatic->id) print $userstatic->getNomUrl(1);
else print $langs->trans("Unknown");
}
print '<br>';
}
// Date validation
if (! empty($object->date_validation))
{
print $langs->trans("DateValidation").': '.dol_print_date($object->date_validation, 'dayhour');
if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' / '.dol_print_date($object->date_validation+($deltadateforuser*3600),"dayhour").' '.$langs->trans("ClientHour");
print '<br>';
}
// User approve
if (! empty($object->user_approve))
{
print $langs->trans("ApprovedBy").': ';
if (is_object($object->user_approve))
{
if ($object->user_approve->id) print $object->user_approve->getNomUrl(1);
else print $langs->trans("Unknown");
}
else
{
$userstatic=new User($db);
$userstatic->fetch($object->user_approve);
if ($userstatic->id) print $userstatic->getNomUrl(1);
else print $langs->trans("Unknown");
}
print '<br>';
}
// Date approve
if (! empty($object->date_approve))
{
print $langs->trans("DateApprove").': '.dol_print_date($object->date_approve, 'dayhour');
if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' / '.dol_print_date($object->date_approve+($deltadateforuser*3600),"dayhour").' '.$langs->trans("ClientHour");
print '<br>';
}
// User close
if (! empty($object->user_cloture))
{
print $langs->trans("ClosedBy").': ';
if (is_object($object->user_cloture))
{
if ($object->user_cloture->id) print $object->user_cloture->getNomUrl(1);
else print $langs->trans("Unknown");
}
else
{
$userstatic=new User($db);
$userstatic->fetch($object->user_cloture);
if ($userstatic->id) print $userstatic->getNomUrl(1);
else print $langs->trans("Unknown");
}
print '<br>';
}
// Date close
if (! empty($object->date_cloture))
{
print $langs->trans("DateClosing").': '.dol_print_date($object->date_cloture, 'dayhour');
if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' / '.dol_print_date($object->date_cloture+($deltadateforuser*3600),"dayhour").' '.$langs->trans("ClientHour");
print '<br>';
}
// User conciliate
if (! empty($object->user_rappro))
{
print $langs->trans("ConciliatedBy").': ';
if (is_object($object->user_rappro))
{
if ($object->user_rappro->id) print $object->user_rappro->getNomUrl(1);
else print $langs->trans("Unknown");
}
else
{
$userstatic=new User($db);
$userstatic->fetch($object->user_rappro);
if ($userstatic->id) print $userstatic->getNomUrl(1);
else print $langs->trans("Unknown");
}
print '<br>';
}
// Date conciliate
if (! empty($object->date_rappro))
{
print $langs->trans("DateConciliating").': '.dol_print_date($object->date_rappro, 'dayhour');
if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' / '.dol_print_date($object->date_rappro+($deltadateforuser*3600),"dayhour").' '.$langs->trans("ClientHour");
print '<br>';
}
// Date send
if (! empty($object->date_envoi))
{
print $langs->trans("DateLastSend").': '.dol_print_date($object->date_envoi, 'dayhour');
if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' / '.dol_print_date($object->date_envoi+($deltadateforuser*3600),"dayhour").' '.$langs->trans("ClientHour");
print '<br>';
}
}
/**
* Return an email formatted to include a tracking id
* For example myemail@mydomain.com becom myemail+trackingid@mydomain.com
*
* @param string $email Email address (Ex: "toto@titi.com", "John Do <johndo@titi.com>")
* @param string $trackingid Tracking id (Ex: thi123 for thirdparty with id 123)
* @return boolean True if domain email is OK, False if KO
*/
function dolAddEmailTrackId($email, $trackingid)
{
$tmp=explode('@',$email);
return $tmp[0].'+'.$trackingid.'@'.(isset($tmp[1])?$tmp[1]:'');
}
/**
* Return true if email has a domain name that can't be resolved
*
* @param string $mail Email address (Ex: "toto@titi.com", "John Do <johndo@titi.com>")
* @return boolean True if domain email is OK, False if KO
*/
function isValidMailDomain($mail)
{
list($user, $domain) = explode("@", $mail, 2);
if (checkdnsrr($domain, "MX"))
{
return true;
}
else
{
return false;
}
}
/**
* Url string validation
* <http[s]> :// [user[:pass]@] hostname [port] [/path] [?getquery] [anchor]
*
* @param string $url Url
* @param int $http 1: verify http is provided, 0: not verify http
* @param int $pass 1: verify user and pass is provided, 0: not verify user and pass
* @param int $port 1: verify port is provided, 0: not verify port
* @param int $path 1: verify a path is provided "/" or "/..." or "/.../", 0: not verify path
* @param int $query 1: verify query is provided, 0: not verify query
* @param int $anchor 1: verify anchor is provided, 0: not verify anchor
* @return int 1=Check is OK, 0=Check is KO
*/
function isValidUrl($url,$http=0,$pass=0,$port=0,$path=0,$query=0,$anchor=0)
{
$ValidUrl = 0;
$urlregex = '';
// SCHEME
if ($http) $urlregex .= "^(http:\/\/|https:\/\/)";
// USER AND PASS
if ($pass) $urlregex .= "([a-z0-9+!*(),;?&=\$_.-]+(\:[a-z0-9+!*(),;?&=\$_.-]+)?@)";
// HOSTNAME OR IP
//$urlregex .= "[a-z0-9+\$_-]+(\.[a-z0-9+\$_-]+)*"; // x allowed (ex. http://localhost, http://routerlogin)
//$urlregex .= "[a-z0-9+\$_-]+(\.[a-z0-9+\$_-]+)+"; // x.x
$urlregex .= "([a-z0-9+\$_\\\:-])+(\.[a-z0-9+\$_-][a-z0-9+\$_-]+)*"; // x ou x.xx (2 x ou plus)
//use only one of the above
// PORT
if ($port) $urlregex .= "(\:[0-9]{2,5})";
// PATH
if ($path) $urlregex .= "(\/([a-z0-9+\$_-]\.?)+)*\/";
// GET Query
if ($query) $urlregex .= "(\?[a-z+&\$_.-][a-z0-9;:@\/&%=+\$_.-]*)";
// ANCHOR
if ($anchor) $urlregex .= "(#[a-z_.-][a-z0-9+\$_.-]*)$";
// check
if (preg_match('/'.$urlregex.'/i', $url))
{
$ValidUrl = 1;
}
//print $urlregex.' - '.$url.' - '.$ValidUrl;
return $ValidUrl;
}
/**
* Clean an url string
*
* @param string $url Url
* @param string $http 1 = keep both http:// and https://, 0: remove http:// but not https://
* @return string Cleaned url
*/
function clean_url($url,$http=1)
{
// Fixed by Matelli (see http://matelli.fr/showcases/patchs-dolibarr/fix-cleaning-url.html)
// To include the minus sign in a char class, we must not escape it but put it at the end of the class
// Also, there's no need of escape a dot sign in a class
if (preg_match('/^(https?:[\\/]+)?([0-9A-Z.-]+\.[A-Z]{2,4})(:[0-9]+)?/i',$url,$regs))
{
$proto=$regs[1];
$domain=$regs[2];
$port=isset($regs[3])?$regs[3]:'';
//print $url." -> ".$proto." - ".$domain." - ".$port;
//$url = dol_string_nospecial(trim($url));
$url = trim($url);
// Si http: defini on supprime le http (Si https on ne supprime pas)
$newproto=$proto;
if ($http==0)
{
if (preg_match('/^http:[\\/]+/i',$url))
{
$url = preg_replace('/^http:[\\/]+/i','',$url);
$newproto = '';
}
}
// On passe le nom de domaine en minuscule
$CleanUrl = preg_replace('/^'.preg_quote($proto.$domain,'/').'/i', $newproto.strtolower($domain), $url);
return $CleanUrl;
}
else return $url;
}
/**
* Returns an email value with obfuscated parts.
*
* @param string $mail Email
* @param string $replace Replacement character (defaul : *)
* @param int $nbreplace Number of replacement character (default : 8)
* @param int $nbdisplaymail Number of character unchanged (default: 4)
* @param int $nbdisplaydomain Number of character unchanged of domain (default: 3)
* @param bool $displaytld Display tld (default: true)
* @return string Return email with hidden parts or '';
*/
function dolObfuscateEmail($mail, $replace="*", $nbreplace=8, $nbdisplaymail=4, $nbdisplaydomain=3, $displaytld=true)
{
if(!isValidEmail($mail))return '';
$tab = explode('@', $mail);
$tab2 = explode('.',$tab[1]);
$string_replace = '';
$mail_name = $tab[0];
$mail_domaine = $tab2[0];
$mail_tld = '';
for($i=1; $i < count($tab2) && $displaytld ;$i++)
{
$mail_tld .= '.'.$tab2[$i];
}
for($i=0; $i < $nbreplace; $i++){
$string_replace .= $replace;
}
if(strlen($mail_name) > $nbdisplaymail){
$mail_name = substr($mail_name, 0, $nbdisplaymail);
}
if(strlen($mail_domaine) > $nbdisplaydomain){
$mail_domaine = substr($mail_domaine, strlen($mail_domaine)-$nbdisplaydomain);
}
return $mail_name . $string_replace . $mail_domaine . $mail_tld;
}
/**
* Return lines of an html table from an array
* Used by array2table function only
*
* @param array $data Array of data
* @param string $troptions Options for tr
* @param string $tdoptions Options for td
* @return string
*/
function array2tr($data,$troptions='',$tdoptions='')
{
$text = '<tr '.$troptions.'>' ;
foreach($data as $key => $item){
$text.= '<td '.$tdoptions.'>'.$item.'</td>' ;
}
$text.= '</tr>' ;
return $text ;
}
/**
* Return an html table from an array
*
* @param array $data Array of data
* @param int $tableMarkup Table markup
* @param string $tableoptions Options for table
* @param string $troptions Options for tr
* @param string $tdoptions Options for td
* @return string
*/
function array2table($data,$tableMarkup=1,$tableoptions='',$troptions='',$tdoptions='')
{
$text='' ;
if($tableMarkup) $text = '<table '.$tableoptions.'>' ;
foreach($data as $key => $item){
if(is_array($item)){
$text.=array2tr($item,$troptions,$tdoptions);
} else {
$text.= '<tr '.$troptions.'>' ;
$text.= '<td '.$tdoptions.'>'.$key.'</td>' ;
$text.= '<td '.$tdoptions.'>'.$item.'</td>' ;
$text.= '</tr>' ;
}
}
if($tableMarkup) $text.= '</table>' ;
return $text ;
}
/**
* Return last or next value for a mask (according to area we should not reset)
*
* @param DoliDB $db Database handler
* @param string $mask Mask to use
* @param string $table Table containing field with counter
* @param string $field Field containing already used values of counter
* @param string $where To add a filter on selection (for exemple to filter on invoice types)
* @param Societe $objsoc The company that own the object we need a counter for
* @param string $date Date to use for the {y},{m},{d} tags.
* @param string $mode 'next' for next value or 'last' for last value
* @param bool $bentityon Activate the entity filter. Default is true (for modules not compatible with multicompany)
* @return string New value (numeric) or error message
*/
function get_next_value($db,$mask,$table,$field,$where='',$objsoc='',$date='',$mode='next', $bentityon=true)
{
global $conf;
if (! is_object($objsoc)) $valueforccc=$objsoc;
else if($table == "commande_fournisseur" || $table == "facture_fourn" ) $valueforccc=$objsoc->code_fournisseur;
else $valueforccc=$objsoc->code_client;
// Clean parameters
if ($date == '') $date=dol_now(); // We use local year and month of PHP server to search numbers
// but we should use local year and month of user
// For debugging
//include_once(DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php');
//$mask='FA{yy}{mm}-{0000@99}';
//$date=dol_mktime(12, 0, 0, 1, 1, 1900);
//$date=dol_stringtotime('20130101');
$hasglobalcounter=false;
// Extract value for mask counter, mask raz and mask offset
if (preg_match('/\{(0+)([@\+][0-9\-\+\=]+)?([@\+][0-9\-\+\=]+)?\}/i',$mask,$reg))
{
$masktri=$reg[1].(! empty($reg[2])?$reg[2]:'').(! empty($reg[3])?$reg[3]:'');
$maskcounter=$reg[1];
$hasglobalcounter=true;
}
else
{
// setting some defaults so the rest of the code won't fail if there is a third party counter
$masktri='00000';
$maskcounter='00000';
}
$maskraz=-1;
$maskoffset=0;
$resetEveryMonth=false;
if (dol_strlen($maskcounter) < 3 && empty($conf->global->MAIN_COUNTER_WITH_LESS_3_DIGITS)) return 'ErrorCounterMustHaveMoreThan3Digits';
// Extract value for third party mask counter
if (preg_match('/\{(c+)(0*)\}/i',$mask,$regClientRef))
{
$maskrefclient=$regClientRef[1].$regClientRef[2];
$maskrefclient_maskclientcode=$regClientRef[1];
$maskrefclient_maskcounter=$regClientRef[2];
$maskrefclient_maskoffset=0; //default value of maskrefclient_counter offset
$maskrefclient_clientcode=substr($valueforccc,0,dol_strlen($maskrefclient_maskclientcode));//get n first characters of client code where n is length in mask
$maskrefclient_clientcode=str_pad($maskrefclient_clientcode,dol_strlen($maskrefclient_maskclientcode),"#",STR_PAD_RIGHT);//padding maskrefclient_clientcode for having exactly n characters in maskrefclient_clientcode
$maskrefclient_clientcode=dol_string_nospecial($maskrefclient_clientcode);//sanitize maskrefclient_clientcode for sql insert and sql select like
if (dol_strlen($maskrefclient_maskcounter) > 0 && dol_strlen($maskrefclient_maskcounter) < 3) return 'ErrorCounterMustHaveMoreThan3Digits';
}
else $maskrefclient='';
// fail if there is neither a global nor a third party counter
if (! $hasglobalcounter && ($maskrefclient_maskcounter == ''))
{
return 'ErrorBadMask';
}
// Extract value for third party type
if (preg_match('/\{(t+)\}/i',$mask,$regType))
{
$masktype=$regType[1];
$masktype_value=substr(preg_replace('/^TE_/','',$objsoc->typent_code),0,dol_strlen($regType[1]));// get n first characters of thirdpaty typent_code (where n is length in mask)
$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
}
else
{
$masktype='';
$masktype_value='';
}
$maskwithonlyymcode=$mask;
$maskwithonlyymcode=preg_replace('/\{(0+)([@\+][0-9\-\+\=]+)?([@\+][0-9\-\+\=]+)?\}/i',$maskcounter,$maskwithonlyymcode);
$maskwithonlyymcode=preg_replace('/\{dd\}/i','dd',$maskwithonlyymcode);
$maskwithonlyymcode=preg_replace('/\{(c+)(0*)\}/i',$maskrefclient,$maskwithonlyymcode);
$maskwithonlyymcode=preg_replace('/\{(t+)\}/i',$masktype_value,$maskwithonlyymcode);
$maskwithnocode=$maskwithonlyymcode;
$maskwithnocode=preg_replace('/\{yyyy\}/i','yyyy',$maskwithnocode);
$maskwithnocode=preg_replace('/\{yy\}/i','yy',$maskwithnocode);
$maskwithnocode=preg_replace('/\{y\}/i','y',$maskwithnocode);
$maskwithnocode=preg_replace('/\{mm\}/i','mm',$maskwithnocode);
// Now maskwithnocode = 0000ddmmyyyyccc for example
// and maskcounter = 0000 for example
//print "maskwithonlyymcode=".$maskwithonlyymcode." maskwithnocode=".$maskwithnocode."\n<br>";
//var_dump($reg);
// If an offset is asked
if (! empty($reg[2]) && preg_match('/^\+/',$reg[2])) $maskoffset=preg_replace('/^\+/','',$reg[2]);
if (! empty($reg[3]) && preg_match('/^\+/',$reg[3])) $maskoffset=preg_replace('/^\+/','',$reg[3]);
// Define $sqlwhere
$sqlwhere='';
$yearoffset=0; // Use year of current $date by default
$yearoffsettype=false; // false: no reset, 0,-,=,+: reset at offset SOCIETE_FISCAL_MONTH_START, x=reset at offset x
// If a restore to zero after a month is asked we check if there is already a value for this year.
if (! empty($reg[2]) && preg_match('/^@/',$reg[2])) $yearoffsettype = preg_replace('/^@/','',$reg[2]);
if (! empty($reg[3]) && preg_match('/^@/',$reg[3])) $yearoffsettype = preg_replace('/^@/','',$reg[3]);
//print "yearoffset=".$yearoffset." yearoffsettype=".$yearoffsettype;
if (is_numeric($yearoffsettype) && $yearoffsettype >= 1)
$maskraz=$yearoffsettype; // For backward compatibility
else if ($yearoffsettype === '0' || (! empty($yearoffsettype) && ! is_numeric($yearoffsettype) && $conf->global->SOCIETE_FISCAL_MONTH_START > 1))
$maskraz = $conf->global->SOCIETE_FISCAL_MONTH_START;
//print "maskraz=".$maskraz; // -1=no reset
if ($maskraz > 0) { // A reset is required
if ($maskraz == 99) {
$maskraz = date('m', $date);
$resetEveryMonth = true;
}
if ($maskraz > 12) return 'ErrorBadMaskBadRazMonth';
// Define posy, posm and reg
if ($maskraz > 1) // if reset is not first month, we need month and year into mask
{
if (preg_match('/^(.*)\{(y+)\}\{(m+)\}/i',$maskwithonlyymcode,$reg)) { $posy=2; $posm=3; }
elseif (preg_match('/^(.*)\{(m+)\}\{(y+)\}/i',$maskwithonlyymcode,$reg)) { $posy=3; $posm=2; }
else return 'ErrorCantUseRazInStartedYearIfNoYearMonthInMask';
if (dol_strlen($reg[$posy]) < 2) return 'ErrorCantUseRazWithYearOnOneDigit';
}
else // if reset is for a specific month in year, we need year
{
if (preg_match('/^(.*)\{(m+)\}\{(y+)\}/i',$maskwithonlyymcode,$reg)) { $posy=3; $posm=2; }
else if (preg_match('/^(.*)\{(y+)\}\{(m+)\}/i',$maskwithonlyymcode,$reg)) { $posy=2; $posm=3; }
else if (preg_match('/^(.*)\{(y+)\}/i',$maskwithonlyymcode,$reg)) { $posy=2; $posm=0; }
else return 'ErrorCantUseRazIfNoYearInMask';
}
// Define length
$yearlen = $posy?dol_strlen($reg[$posy]):0;
$monthlen = $posm?dol_strlen($reg[$posm]):0;
// Define pos
$yearpos = (dol_strlen($reg[1])+1);
$monthpos = ($yearpos+$yearlen);
if ($posy == 3 && $posm == 2) { // if month is before year
$monthpos = (dol_strlen($reg[1])+1);
$yearpos = ($monthpos+$monthlen);
}
//print "xxx ".$maskwithonlyymcode." maskraz=".$maskraz." posy=".$posy." yearlen=".$yearlen." yearpos=".$yearpos." posm=".$posm." monthlen=".$monthlen." monthpos=".$monthpos." yearoffsettype=".$yearoffsettype." resetEveryMonth=".$resetEveryMonth."\n";
// Define $yearcomp and $monthcomp (that will be use in the select where to search max number)
$monthcomp=$maskraz;
$yearcomp=0;
if (! empty($yearoffsettype) && ! is_numeric($yearoffsettype) && $yearoffsettype != '=') // $yearoffsettype is - or +
{
$currentyear=date("Y", $date);
$fiscaldate=dol_mktime('0','0','0',$maskraz,'1',$currentyear);
$newyeardate=dol_mktime('0','0','0','1','1',$currentyear);
$nextnewyeardate=dol_mktime('0','0','0','1','1',$currentyear+1);
//echo 'currentyear='.$currentyear.' date='.dol_print_date($date, 'day').' fiscaldate='.dol_print_date($fiscaldate, 'day').'<br>';
// If after or equal of current fiscal date
if ($date >= $fiscaldate)
{
// If before of next new year date
if ($date < $nextnewyeardate && $yearoffsettype == '+') $yearoffset=1;
}
// If after or equal of current new year date
else if ($date >= $newyeardate && $yearoffsettype == '-') $yearoffset=-1;
}
// For backward compatibility
else if (date("m",$date) < $maskraz && empty($resetEveryMonth)) { $yearoffset=-1; } // If current month lower that month of return to zero, year is previous year
if ($yearlen == 4) $yearcomp=sprintf("%04d",date("Y",$date)+$yearoffset);
elseif ($yearlen == 2) $yearcomp=sprintf("%02d",date("y",$date)+$yearoffset);
elseif ($yearlen == 1) $yearcomp=substr(date("y",$date),2,1)+$yearoffset;
if ($monthcomp > 1 && empty($resetEveryMonth)) // Test with month is useless if monthcomp = 0 or 1 (0 is same as 1) (regis: $monthcomp can't equal 0)
{
if ($yearlen == 4) $yearcomp1=sprintf("%04d",date("Y",$date)+$yearoffset+1);
elseif ($yearlen == 2) $yearcomp1=sprintf("%02d",date("y",$date)+$yearoffset+1);
$sqlwhere.="(";
$sqlwhere.=" (SUBSTRING(".$field.", ".$yearpos.", ".$yearlen.") = '".$yearcomp."'";
$sqlwhere.=" AND SUBSTRING(".$field.", ".$monthpos.", ".$monthlen.") >= '".str_pad($monthcomp, $monthlen, '0', STR_PAD_LEFT)."')";
$sqlwhere.=" OR";
$sqlwhere.=" (SUBSTRING(".$field.", ".$yearpos.", ".$yearlen.") = '".$yearcomp1."'";
$sqlwhere.=" AND SUBSTRING(".$field.", ".$monthpos.", ".$monthlen.") < '".str_pad($monthcomp, $monthlen, '0', STR_PAD_LEFT)."') ";
$sqlwhere.=')';
}
else if ($resetEveryMonth)
{
$sqlwhere.="(SUBSTRING(".$field.", ".$yearpos.", ".$yearlen.") = '".$yearcomp."'";
$sqlwhere.=" AND SUBSTRING(".$field.", ".$monthpos.", ".$monthlen.") = '".str_pad($monthcomp, $monthlen, '0', STR_PAD_LEFT)."')";
}
else // reset is done on january
{
$sqlwhere.='(SUBSTRING('.$field.', '.$yearpos.', '.$yearlen.") = '".$yearcomp."')";
}
}
//print "sqlwhere=".$sqlwhere." yearcomp=".$yearcomp."<br>\n"; // sqlwhere and yearcomp defined only if we ask a reset
//print "masktri=".$masktri." maskcounter=".$maskcounter." maskraz=".$maskraz." maskoffset=".$maskoffset."<br>\n";
// Define $sqlstring
$posnumstart=strrpos($maskwithnocode,$maskcounter); // Pos of counter in final string (from 0 to ...)
if ($posnumstart < 0) return 'ErrorBadMaskFailedToLocatePosOfSequence';
$sqlstring='SUBSTRING('.$field.', '.($posnumstart+1).', '.dol_strlen($maskcounter).')';
// Define $maskLike
$maskLike = dol_string_nospecial($mask);
$maskLike = str_replace("%","_",$maskLike);
// Replace protected special codes with matching number of _ as wild card caracter
$maskLike = preg_replace('/\{yyyy\}/i','____',$maskLike);
$maskLike = preg_replace('/\{yy\}/i','__',$maskLike);
$maskLike = preg_replace('/\{y\}/i','_',$maskLike);
$maskLike = preg_replace('/\{mm\}/i','__',$maskLike);
$maskLike = preg_replace('/\{dd\}/i','__',$maskLike);
$maskLike = str_replace(dol_string_nospecial('{'.$masktri.'}'),str_pad("",dol_strlen($maskcounter),"_"),$maskLike);
if ($maskrefclient) $maskLike = str_replace(dol_string_nospecial('{'.$maskrefclient.'}'),str_pad("",dol_strlen($maskrefclient),"_"),$maskLike);
if ($masktype) $maskLike = str_replace(dol_string_nospecial('{'.$masktype.'}'),$masktype_value,$maskLike);
// Get counter in database
$counter=0;
$sql = "SELECT MAX(".$sqlstring.") as val";
$sql.= " FROM ".MAIN_DB_PREFIX.$table;
$sql.= " WHERE ".$field." LIKE '".$maskLike."'";
$sql.= " AND ".$field." NOT LIKE '(PROV%)'";
if ($bentityon) // only if entity enable
$sql.= " AND entity IN (".getEntity($table, 1).")";
if ($where) $sql.=$where;
if ($sqlwhere) $sql.=' AND '.$sqlwhere;
//print $sql.'<br>';
dol_syslog("functions2::get_next_value mode=".$mode."", LOG_DEBUG);
$resql=$db->query($sql);
if ($resql)
{
$obj = $db->fetch_object($resql);
$counter = $obj->val;
}
else dol_print_error($db);
// Check if we must force counter to maskoffset
if (empty($counter) || preg_match('/[^0-9]/i',$counter)) $counter=$maskoffset;
else if ($counter < $maskoffset && empty($conf->global->MAIN_NUMBERING_OFFSET_ONLY_FOR_FIRST)) $counter=$maskoffset;
if ($mode == 'last') // We found value for counter = last counter value. Now need to get corresponding ref of invoice.
{
$counterpadded=str_pad($counter,dol_strlen($maskcounter),"0",STR_PAD_LEFT);
// Define $maskLike
$maskLike = dol_string_nospecial($mask);
$maskLike = str_replace("%","_",$maskLike);
// Replace protected special codes with matching number of _ as wild card caracter
$maskLike = preg_replace('/\{yyyy\}/i','____',$maskLike);
$maskLike = preg_replace('/\{yy\}/i','__',$maskLike);
$maskLike = preg_replace('/\{y\}/i','_',$maskLike);
$maskLike = preg_replace('/\{mm\}/i','__',$maskLike);
$maskLike = preg_replace('/\{dd\}/i','__',$maskLike);
$maskLike = str_replace(dol_string_nospecial('{'.$masktri.'}'),$counterpadded,$maskLike);
if ($maskrefclient) $maskLike = str_replace(dol_string_nospecial('{'.$maskrefclient.'}'),str_pad("",dol_strlen($maskrefclient),"_"),$maskLike);
if ($masktype) $maskLike = str_replace(dol_string_nospecial('{'.$masktype.'}'),$masktype_value,$maskLike);
$ref='';
$sql = "SELECT ".$field." as ref";
$sql.= " FROM ".MAIN_DB_PREFIX.$table;
$sql.= " WHERE ".$field." LIKE '".$maskLike."'";
$sql.= " AND ".$field." NOT LIKE '%PROV%'";
if ($bentityon) // only if entity enable
$sql.= " AND entity IN (".getEntity($table, 1).")";
if ($where) $sql.=$where;
if ($sqlwhere) $sql.=' AND '.$sqlwhere;
dol_syslog("functions2::get_next_value", LOG_DEBUG);
$resql=$db->query($sql);
if ($resql)
{
$obj = $db->fetch_object($resql);
if ($obj) $ref = $obj->ref;
}
else dol_print_error($db);
$numFinal=$ref;
}
else if ($mode == 'next')
{
$counter++;
// If value for $counter has a length higher than $maskcounter chars
if ($counter >= pow(10, dol_strlen($maskcounter)))
{
$counter='ErrorMaxNumberReachForThisMask';
}
if (! empty($maskrefclient_maskcounter))
{
//print "maskrefclient_maskcounter=".$maskrefclient_maskcounter." maskwithnocode=".$maskwithnocode." maskrefclient=".$maskrefclient."\n<br>";
// Define $sqlstring
$maskrefclient_posnumstart=strpos($maskwithnocode,$maskrefclient_maskcounter,strpos($maskwithnocode,$maskrefclient)); // Pos of counter in final string (from 0 to ...)
if ($maskrefclient_posnumstart <= 0) return 'ErrorBadMask';
$maskrefclient_sqlstring='SUBSTRING('.$field.', '.($maskrefclient_posnumstart+1).', '.dol_strlen($maskrefclient_maskcounter).')';
//print "x".$sqlstring;
// Define $maskrefclient_maskLike
$maskrefclient_maskLike = dol_string_nospecial($mask);
$maskrefclient_maskLike = str_replace("%","_",$maskrefclient_maskLike);
// Replace protected special codes with matching number of _ as wild card caracter
$maskrefclient_maskLike = str_replace(dol_string_nospecial('{yyyy}'),'____',$maskrefclient_maskLike);
$maskrefclient_maskLike = str_replace(dol_string_nospecial('{yy}'),'__',$maskrefclient_maskLike);
$maskrefclient_maskLike = str_replace(dol_string_nospecial('{y}'),'_',$maskrefclient_maskLike);
$maskrefclient_maskLike = str_replace(dol_string_nospecial('{mm}'),'__',$maskrefclient_maskLike);
$maskrefclient_maskLike = str_replace(dol_string_nospecial('{dd}'),'__',$maskrefclient_maskLike);
$maskrefclient_maskLike = str_replace(dol_string_nospecial('{'.$masktri.'}'),str_pad("",dol_strlen($maskcounter),"_"),$maskrefclient_maskLike);
$maskrefclient_maskLike = str_replace(dol_string_nospecial('{'.$maskrefclient.'}'),$maskrefclient_clientcode.str_pad("",dol_strlen($maskrefclient_maskcounter),"_"),$maskrefclient_maskLike);
// Get counter in database
$maskrefclient_counter=0;
$maskrefclient_sql = "SELECT MAX(".$maskrefclient_sqlstring.") as val";
$maskrefclient_sql.= " FROM ".MAIN_DB_PREFIX.$table;
//$sql.= " WHERE ".$field." not like '(%'";
$maskrefclient_sql.= " WHERE ".$field." LIKE '".$maskrefclient_maskLike."'";
if ($bentityon) // only if entity enable
$maskrefclient_sql.= " AND entity IN (".getEntity($table, 1).")";
if ($where) $maskrefclient_sql.=$where; //use the same optional where as general mask
if ($sqlwhere) $maskrefclient_sql.=' AND '.$sqlwhere; //use the same sqlwhere as general mask
$maskrefclient_sql.=' AND (SUBSTRING('.$field.', '.(strpos($maskwithnocode,$maskrefclient)+1).', '.dol_strlen($maskrefclient_maskclientcode).")='".$maskrefclient_clientcode."')";
dol_syslog("functions2::get_next_value maskrefclient", LOG_DEBUG);
$maskrefclient_resql=$db->query($maskrefclient_sql);
if ($maskrefclient_resql)
{
$maskrefclient_obj = $db->fetch_object($maskrefclient_resql);
$maskrefclient_counter = $maskrefclient_obj->val;
}
else dol_print_error($db);
if (empty($maskrefclient_counter) || preg_match('/[^0-9]/i',$maskrefclient_counter)) $maskrefclient_counter=$maskrefclient_maskoffset;
$maskrefclient_counter++;
}
// Build numFinal
$numFinal = $mask;
// We replace special codes except refclient
if (! empty($yearoffsettype) && ! is_numeric($yearoffsettype) && $yearoffsettype != '=') // yearoffsettype is - or +, so we don't want current year
{
$numFinal = preg_replace('/\{yyyy\}/i',date("Y",$date)+$yearoffset, $numFinal);
$numFinal = preg_replace('/\{yy\}/i', date("y",$date)+$yearoffset, $numFinal);
$numFinal = preg_replace('/\{y\}/i', substr(date("y",$date),2,1)+$yearoffset, $numFinal);
}
else // we want yyyy to be current year
{
$numFinal = preg_replace('/\{yyyy\}/i',date("Y",$date), $numFinal);
$numFinal = preg_replace('/\{yy\}/i', date("y",$date), $numFinal);
$numFinal = preg_replace('/\{y\}/i', substr(date("y",$date),2,1), $numFinal);
}
$numFinal = preg_replace('/\{mm\}/i', date("m",$date), $numFinal);
$numFinal = preg_replace('/\{dd\}/i', date("d",$date), $numFinal);
// Now we replace the counter
$maskbefore='{'.$masktri.'}';
$maskafter=str_pad($counter,dol_strlen($maskcounter),"0",STR_PAD_LEFT);
//print 'x'.$maskbefore.'-'.$maskafter.'y';
$numFinal = str_replace($maskbefore,$maskafter,$numFinal);
// Now we replace the refclient
if ($maskrefclient)
{
//print "maskrefclient=".$maskrefclient." maskwithonlyymcode=".$maskwithonlyymcode." maskwithnocode=".$maskwithnocode."\n<br>";
$maskrefclient_maskbefore='{'.$maskrefclient.'}';
$maskrefclient_maskafter=$maskrefclient_clientcode.str_pad($maskrefclient_counter,dol_strlen($maskrefclient_maskcounter),"0",STR_PAD_LEFT);
$numFinal = str_replace($maskrefclient_maskbefore,$maskrefclient_maskafter,$numFinal);
}
// Now we replace the type
if ($masktype)
{
$masktype_maskbefore='{'.$masktype.'}';
$masktype_maskafter=$masktype_value;
$numFinal = str_replace($masktype_maskbefore,$masktype_maskafter,$numFinal);
}
}
dol_syslog("functions2::get_next_value return ".$numFinal,LOG_DEBUG);
return $numFinal;
}