dolibarr /htdocs/core/lib/functions.lib.php

Language PHP Lines 4481
MD5 Hash 1cdd3126dd381b0536d2d331e41c8c37 Estimated Cost $76,452 (why?)
Repository https://github.com/asterix14/dolibarr.git View Raw File
   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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
<?php
/* Copyright (C) 2000-2007 Rodolphe Quiedeville <rodolphe@quiedeville.org>
 * Copyright (C) 2003      Jean-Louis Bergamo   <jlb@j1b.org>
 * Copyright (C) 2004-2011 Laurent Destailleur  <eldy@users.sourceforge.net>
 * Copyright (C) 2004      Sebastien Di Cintio  <sdicintio@ressource-toi.org>
 * Copyright (C) 2004      Benoit Mortier       <benoit.mortier@opensides.be>
 * Copyright (C) 2004      Christophe Combelles <ccomb@free.fr>
 * Copyright (C) 2005-2010 Regis Houssin        <regis@dolibarr.fr>
 * Copyright (C) 2008      Raphael Bertrand (Resultic)       <raphael.bertrand@resultic.fr>
 * Copyright (C) 2010-2011 Juanjo Menent        <jmenent@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 2 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/functions.lib.php
 *	\brief			A set of functions for Dolibarr
 *					This file contains all frequently used functions.
 */


if (! function_exists('json_encode'))
{
    /**
     * Implement json_encode for PHP that does not support it
     *
     * @param	mixed	$elements		PHP Object to json encode
     * @return 	string					Json encoded string
     */
    function json_encode($elements)
    {
    	$num = count($elements);

    	// determine type
    	if (is_numeric(key($elements)))
    	{
    		// indexed (list)
    		$output = '[';
    		for ($i = 0, $last = ($num - 1); isset($elements[$i]); ++$i)
    		{
    			if (is_array($elements[$i])) $output.= json_encode($elements[$i]);
    			else $output .= _val($elements[$i]);
    			if($i !== $last) $output.= ',';
    		}
    		$output.= ']';
    	}
    	else
    	{
    		// associative (object)
    		$output = '{';
    		$last = $num - 1;
    		$i = 0;
    		foreach($elements as $key => $value)
    		{
    			$output .= '"'.$key.'":';
    			if (is_array($value)) $output.= json_encode($value);
    			else $output .= _val($value);
    			if ($i !== $last) $output.= ',';
    			++$i;
    		}
    		$output.= '}';
    	}

    	// return
    	return $output;
    }

    function _val($val)
    {
    	if (is_string($val)) return '"'.rawurlencode($val).'"';
    	elseif (is_int($val)) return sprintf('%d', $val);
    	elseif (is_float($val)) return sprintf('%F', $val);
    	elseif (is_bool($val)) return ($val ? 'true' : 'false');
    	else  return 'null';
    }
}

if (! function_exists('json_decode'))
{
	/**
	 * Implement json_decode for PHP that does not support it
	 *
	 * @param	string	$json		Json encoded to PHP Object or Array
	 * @param	bool	$assoc		False return an object, true return an array
	 * @return 	mixed				Object or Array
	 */
	function json_decode($json, $assoc=false)
	{
		$comment = false;

		$strLength = dol_strlen($json);
		for ($i=0; $i<$strLength; $i++)
		{
			if (! $comment)
			{
				if (($json[$i] == '{') || ($json[$i] == '[')) $out.= 'array(';
				else if (($json[$i] == '}') || ($json[$i] == ']')) $out.= ')';
				else if ($json[$i] == ':') $out.= ' => ';
				else $out.= $json[$i];
			}
			else $out.= $json[$i];
			if ($json[$i] == '"' && $json[($i-1)]!="\\") $comment = !$comment;
		}

		// Return an array
		eval('$array = '.$out.';');

		// Return an object
		if (! $assoc)
		{
			if (! empty($array))
			{
				$object = false;

				foreach ($array as $key => $value)
				{
					$object->{$key} = $value;
				}

				return $object;
			}

			return false;
		}

		return $array;
	}
}


/**
 * Return a DoliDB instance (database handler).
 *
 * @param   string	$type		Type of database (mysql, pgsql...)
 * @param	string	$host		Address of database server
 * @param	string	$user		Nom de l'utilisateur autorise
 * @param	string	$pass		Mot de passe
 * @param	string	$name		Nom de la database
 * @param	int		$port		Port of database server
 * @return	DoliDB				A DoliDB instance
 */
function getDoliDBInstance($type, $host, $user, $pass, $name, $port)
{
    require_once(DOL_DOCUMENT_ROOT ."/core/db/".$type.".class.php");

    $class='DoliDB'.ucfirst($type);
    $dolidb=new $class($type, $host, $user, $pass, $name, $port);
    return $dolidb;
}


/**
 *  Function called at end of web php process
 *
 *  @return	void
 */
function dol_shutdown()
{
    global $conf,$user,$langs,$db;
    $disconnectdone=false;
    if (is_object($db) && ! empty($db->connected)) $disconnectdone=$db->close();
    dol_syslog("--- End access to ".$_SERVER["PHP_SELF"].($disconnectdone?' (Warn: db disconnection forced)':''), ($disconnectdone?LOG_WARNING:LOG_DEBUG));
}


/**
 *  Return value of a param into GET or POST supervariable
 *
 *  @param	string	$paramname   Name of parameter to found
 *  @param	string	$check	     Type of check (''=no check,  'int'=check it's numeric, 'alpha'=check it's alpha only)
 *  @param	int		$method	     Type of method (0 = get then post, 1 = only get, 2 = only post, 3 = post then get)
 *  @return string      		 Value found or '' if check fails
 */
function GETPOST($paramname,$check='',$method=0)
{
    if (empty($method)) $out = isset($_GET[$paramname])?$_GET[$paramname]:(isset($_POST[$paramname])?$_POST[$paramname]:'');
    elseif ($method==1) $out = isset($_GET[$paramname])?$_GET[$paramname]:'';
    elseif ($method==2) $out = isset($_POST[$paramname])?$_POST[$paramname]:'';
    elseif ($method==3) $out = isset($_POST[$paramname])?$_POST[$paramname]:(isset($_GET[$paramname])?$_GET[$paramname]:'');

    if (!empty($check))
    {
        // Check if numeric
        if ($check == 'int' && ! preg_match('/^[\.,0-9]+$/i',trim($out))) $out='';
        // Check if alpha
        //if ($check == 'alpha' && ! preg_match('/^[ =:@#\/\\\(\)\-\._a-z0-9]+$/i',trim($out))) $out='';
        // '"' is dangerous because param in url can close the href= or src= and add javascript functions.
        if ($check == 'alpha' && preg_match('/"/',trim($out))) $out='';
    }

    return $out;
}


/**
 *  Return a prefix to use for this Dolibarr instance for session or cookie names.
 *  This prefix is unique for instance and avoid conflict between multi-instances,
 *  even when having two instances with one root dir or two instances in virtual servers
 *
 *  @return	string      		A calculated prefix
 */
function dol_getprefix()
{
    return dol_hash($_SERVER["SERVER_NAME"].$_SERVER["DOCUMENT_ROOT"].DOL_DOCUMENT_ROOT.DOL_URL_ROOT);
}

/**
 *	Make an include_once using default root and alternate root if it fails.
 *	WARNING: In most cases, you should not use this function:
 *  To link to a core file, use include(DOL_DOCUMENT_ROOT.'/pathtofile')
 *  To link to a module file from a module file, use include('./mymodulefile');
 *  To link to a module file from a core file, then this function can be used
 *
 * 	@param	string	$relpath	Relative path to file (Ie: mydir/myfile, ../myfile, ...)
 *  @return int					false if include fails.
 */
function dol_include_once($relpath)
{
    global $conf,$langs,$user,$mysoc;   // Other global var must be retreived with $GLOBALS['var']
    return @include_once(dol_buildpath($relpath));
}


/**
 *	Return path of url or filesystem. Return default_root or alternate root if file_exist fails
 *
 * 	@param	string	$path		Relative path to file (if mode=0, ie: mydir/myfile, ../myfile, ...) or relative url (if mode=1).
 *  @param	int		$type		0=Used for a Filesystem path, 1=Used for an URL path (output relative), 2=Used for an URL path (output full path)
 *  @return string				Full filsystem path (if mode=0), Full url path (if mode=1)
 */
function dol_buildpath($path,$type=0)
{
    if (empty($type))	// For a filesystem path
    {
        $res = DOL_DOCUMENT_ROOT.$path;	// Standard value
        if (defined('DOL_DOCUMENT_ROOT_ALT') && DOL_DOCUMENT_ROOT_ALT)	// We check only if alternate feature is used
        {
            if (! file_exists(DOL_DOCUMENT_ROOT.$path)) $res = DOL_DOCUMENT_ROOT_ALT.$path;
        }
    }
    else				// For an url path
    {
        // We try to get local path of file on filesystem from url
        // Note that trying to know if a file on disk exist by forging path on disk from url
        // works only for some web server and some setup. This is bugged when
        // using proxy, rewriting, virtual path, etc...
        if ($type == 1)
        {
            $res = DOL_URL_ROOT.$path;		// Standard value
            if (defined('DOL_URL_ROOT_ALT') && DOL_URL_ROOT_ALT)			// We check only if alternate feature is used
            {
                preg_match('/^([^\?]+(\.css\.php|\.css|\.js\.php|\.js|\.png|\.jpg|\.php)?)/i',$path,$regs);    // Take part before '?'
                if (! empty($regs[1]))
                {
                    if (! file_exists(DOL_DOCUMENT_ROOT.$regs[1])) $res = DOL_URL_ROOT_ALT.$path;
                }
            }
        }
        if ($type == 2)
        {
            $res = DOL_MAIN_URL_ROOT.$path;      // Standard value
            if (defined('DOL_URL_ROOT_ALT') && DOL_URL_ROOT_ALT)            // We check only if alternate feature is used
            {
                preg_match('/^([^\?]+(\.css\.php|\.css|\.js\.php|\.js|\.png|\.jpg|\.php)?)/i',$path,$regs);    // Take part before '?'
                if (! empty($regs[1]))
                {
                    if (! file_exists(DOL_DOCUMENT_ROOT.$regs[1])) $res = DOL_MAIN_URL_ROOT_ALT.$path;
                }
            }
        }
    }

    return $res;
}

/**
 *	Create a clone of instance of object (new instance with same properties)
 * 	This function works for both PHP4 and PHP5
 *
 * 	@param	object	$object		Object to clone
 *	@return object				Object clone
 */
function dol_clone($object)
{
    dol_syslog("Functions.lib::dol_clone Clone object");

    // We create dynamically a clone function, making a =
    if (version_compare(phpversion(), '5.0') < 0 && ! function_exists('clone'))
    {
        eval('function clone($object){return($object);}');
    }
    $myclone=clone($object);
    return $myclone;
}

/**
 *	Optimize a size for some browsers (phone, smarphone, ...)
 *
 * 	@param	int		$size		Size we want
 * 	@param	string	$type		Type of optimizing:
 * 										'' = function used to define a size for truncation
 * 										'width' = function is used to define a width
 *	@return int					New size after optimizing
 */
function dol_size($size,$type='')
{
    global $conf;
    if (empty($conf->browser->phone)) return $size;
    if ($type == 'width' && $size > 250) return 250;
    else return 10;
}


/**
 *	Return date for now. We should always use this function without parameters (that means GMT time)
 *
 * 	@param	string		$mode	'gmt' => we return GMT timestamp,
 * 								'tzserver' => we add the PHP server timezone
 *  							'tzref' => we add the company timezone
 * 								'tzuser' => we add the user timezone
 *	@return timestamp   $date	Timestamp
 */
function dol_now($mode='gmt')
{
    // Note that gmmktime and mktime return same value (GMT) whithout parameters
    if ($mode == 'gmt') $ret=gmmktime();	// Time for now at greenwich.
    else if ($mode == 'tzserver')			// Time for now with PHP server timezone added
    {
        $tzsecond=-dol_mktime(0,0,0,1,1,1970);
        $ret=gmmktime()+$tzsecond;
    }
    else if ($mode == 'tzref')				// Time for now where parent company timezone is added
    {
        // TODO Should add the company timezone
        $ret=gmmktime();
    }
    else if ($mode == 'tzuser')				// Time for now where user timezone is added
    {
        //print 'eeee'.time().'-'.mktime().'-'.gmmktime();
        $tzhour=isset($_SESSION['dol_tz'])?$_SESSION['dol_tz']:0;
        $ret=gmmktime()+($tzhour*60*60);
    }
    return $ret;
}


/**
 *	Clean a string to use it as a file name
 *
 *	@param	string	$str            String to clean
 * 	@param	string	$newstr			String to replace bad chars with
 *	@return string          		String cleaned (a-zA-Z_)
 *
 * 	@see        	dol_string_nospecial, dol_string_unaccent
 */
function dol_sanitizeFileName($str,$newstr='_')
{
    global $conf;
    return dol_string_nospecial(dol_string_unaccent($str),$newstr,$conf->filesystem_forbidden_chars);
}

/**
 *	Clean a string from all accent characters to be used as ref, login or by dol_sanitizeFileName
 *
 *	@param	string	$str			String to clean
 *	@return string   	       		Cleaned string
 *
 * 	@see    		dol_sanitizeFilename, dol_string_nospecial
 */
function dol_string_unaccent($str)
{
    if (utf8_check($str))
    {
        $string = rawurlencode($str);
        $replacements = array(
		'%C3%80' => 'A','%C3%81' => 'A',
		'%C3%88' => 'E','%C3%89' => 'E',
		'%C3%8C' => 'I','%C3%8D' => 'I',
		'%C3%92' => 'O','%C3%93' => 'O',
		'%C3%99' => 'U','%C3%9A' => 'U',
		'%C3%A0' => 'a','%C3%A1' => 'a','%C3%A2' => 'a',
		'%C3%A8' => 'e','%C3%A9' => 'e','%C3%AA' => 'e','%C3%AB' => 'e',
		'%C3%AC' => 'i','%C3%AD' => 'i','%C3%AE' => 'i',
		'%C3%B2' => 'o','%C3%B3' => 'o',
		'%C3%B9' => 'u','%C3%BA' => 'u'
		);
		$string=strtr($string, $replacements);
		return rawurldecode($string);
    }
    else
    {
        $string = strtr($str,
		"\xC0\xC1\xC2\xC3\xC5\xC7
	        \xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1
	        \xD2\xD3\xD4\xD5\xD8\xD9\xDA\xDB\xDD
	        \xE0\xE1\xE2\xE3\xE5\xE7\xE8\xE9\xEA\xEB
	        \xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF8
	        \xF9\xFA\xFB\xFD\xFF",
		"AAAAAC
	        EEEEIIIIDN
	        OOOOOUUUY
	        aaaaaceeee
	        iiiidnooooo
	        uuuyy");
        $string = strtr($string, array("\xC4"=>"Ae", "\xC6"=>"AE", "\xD6"=>"Oe", "\xDC"=>"Ue", "\xDE"=>"TH", "\xDF"=>"ss", "\xE4"=>"ae", "\xE6"=>"ae", "\xF6"=>"oe", "\xFC"=>"ue", "\xFE"=>"th"));
        return $string;
    }
}

/**
 *	Clean a string from all punctuation characters to use it as a ref or login
 *
 *	@param	string	$str            String to clean
 * 	@param	string	$newstr			String to replace forbidden chars with
 *  @param  array	$badchars       List of forbidden characters
 * 	@return string          		Cleaned string
 *
 * 	@see    		dol_sanitizeFilename, dol_string_unaccent
 */
function dol_string_nospecial($str,$newstr='_',$badchars='')
{
    $forbidden_chars_to_replace=array(" ","'","/","\\",":","*","?","\"","<",">","|","[","]",",",";","=");
    $forbidden_chars_to_remove=array();
    if (is_array($badchars)) $forbidden_chars_to_replace=$badchars;
    //$forbidden_chars_to_remove=array("(",")");

    return str_replace($forbidden_chars_to_replace,$newstr,str_replace($forbidden_chars_to_remove,"",$str));
}

/**
 *  Returns text escaped for inclusion into javascript code
 *
 *  @param       string		$stringtoescape		String to escape
 *  @return      string     		 			Escaped string
 */
function dol_escape_js($stringtoescape)
{
    // escape quotes and backslashes, newlines, etc.
    $substitjs=array("&#039;"=>"\\'",'\\'=>'\\\\',"'"=>"\\'",'"'=>"\\'","\r"=>'\\r',"\n"=>'\\n','</'=>'<\/');
    return strtr($stringtoescape, $substitjs);
}


/**
 *  Returns text escaped for inclusion in HTML alt or title tags
 *
 *  @param      string		$stringtoescape		String to escape
 *  @param		int			$keepb				Do not clean b tags
 *  @return     string     				 		Escaped string
 */
function dol_escape_htmltag($stringtoescape,$keepb=0)
{
    // escape quotes and backslashes, newlines, etc.
    $tmp=dol_html_entity_decode($stringtoescape,ENT_COMPAT,'UTF-8');
    if ($keepb) $tmp=strtr($tmp, array('"'=>'',"\r"=>'\\r',"\n"=>'\\n'));
    else $tmp=strtr($tmp, array('"'=>'',"\r"=>'\\r',"\n"=>'\\n',"<b>"=>'','</b>'=>''));
    return dol_htmlentities($tmp,ENT_COMPAT,'UTF-8');
}

/**
 *	Write log message into outputs. Possible outputs can be:
 *	A file if SYSLOG_FILE_ON defined:   	file name is then defined by SYSLOG_FILE
 *	Syslog if SYSLOG_SYSLOG_ON defined:    	facility is then defined by SYSLOG_FACILITY
 * 	Warning, les fonctions syslog sont buggues sous Windows et generent des
 *	fautes de protection memoire. Pour resoudre, utiliser le loggage fichier,
 *	au lieu du loggage syslog (configuration du module).
 *	Note: If SYSLOG_FILE_NO_ERROR defined, we never output error message when writing to log fails.
 *
 *	This function works only if syslog module is enabled.
 * 	This must not use any call to other function calling dol_syslog (avoid infinite loop).
 *
 * 	@param  string		$message	Line to log. Ne doit pas etre traduit si level = LOG_ERR
 *	@param  int			$level		Log level
 *									On Windows LOG_ERR=4, LOG_WARNING=5, LOG_NOTICE=LOG_INFO=6, LOG_DEBUG=6 si define_syslog_variables ou PHP 5.3+, 7 si dolibarr
 *									On Linux   LOG_ERR=3, LOG_WARNING=4, LOG_INFO=6, LOG_DEBUG=7
 *	@return	void
 */
function dol_syslog($message, $level=LOG_INFO)
{
    global $conf,$user,$langs,$_REQUEST;

    // If adding log inside HTML page is required
    if (! empty($_REQUEST['logtohtml']) && ! empty($conf->global->MAIN_LOGTOHTML))
    {
        $conf->logbuffer[]=dol_print_date(time(),"%Y-%m-%d %H:%M:%S")." ".$message;
    }

    // If syslog module enabled
    if (! empty($conf->syslog->enabled))
    {
        //print $level.' - '.$conf->global->SYSLOG_LEVEL.' - '.$conf->syslog->enabled." \n";
        if ($level > $conf->global->SYSLOG_LEVEL) return;

        // Translate error message if this is an error message (rare) and langs is loaded
        if ($level == LOG_ERR)
        {
            if (is_object($langs))
            {
                $langs->load("errors");
                if ($message != $langs->trans($message)) $message = $langs->trans($message);
            }
        }

        // Add page/script name to log message
        $script=isset($_SERVER['PHP_SELF'])?basename($_SERVER['PHP_SELF'],'.php').' ':'';
        $message=$script.$message;

        // Add user to log message
        $login='nologin';
        if (is_object($user) && $user->id) $login=$user->login;
        $message=sprintf("%-8s",$login)." ".$message;

        // Check if log is to a file (SYSLOG_FILE_ON defined)
        if (defined("SYSLOG_FILE_ON") && constant("SYSLOG_FILE_ON"))
        {
            $filelog=SYSLOG_FILE;
            $filelog=preg_replace('/DOL_DATA_ROOT/i',DOL_DATA_ROOT,$filelog);
            //print "filelog=".$filelog."\n";
            if (defined("SYSLOG_FILE_NO_ERROR")) $file=@fopen($filelog,"a+");
            else $file=fopen($filelog,"a+");

            if ($file)
            {
                $ip='???';	// $ip contains information to identify computer that run the code
                if (! empty($_SERVER["REMOTE_ADDR"])) $ip=$_SERVER["REMOTE_ADDR"];			// In most cases.
                else if (! empty($_SERVER['SERVER_ADDR'])) $ip=$_SERVER['SERVER_ADDR'];		// This is when PHP session is ran inside a web server but not inside a client request (example: init code of apache)
                else if (! empty($_SERVER['COMPUTERNAME'])) $ip=$_SERVER['COMPUTERNAME'].(empty($_SERVER['USERNAME'])?'':'@'.$_SERVER['USERNAME']);	// This is when PHP session is ran outside a web server, like from Windows command line (Not always defined, but usefull if OS defined it).
                else if (! empty($_SERVER['LOGNAME'])) $ip='???@'.$_SERVER['LOGNAME'];	// This is when PHP session is ran outside a web server, like from Linux command line (Not always defined, but usefull if OS defined it).

                $liblevelarray=array(LOG_ERR=>'ERROR',LOG_WARNING=>'WARN',LOG_INFO=>'INFO',LOG_DEBUG=>'DEBUG');
                $liblevel=$liblevelarray[$level];
                if (! $liblevel) $liblevel='UNDEF';

                $message=dol_print_date(time(),"%Y-%m-%d %H:%M:%S")." ".sprintf("%-5s",$liblevel)." ".sprintf("%-15s",$ip)." ".$message;

                fwrite($file,$message."\n");
                fclose($file);
                // This is for log file, we do not change permissions

                // If enable html log tag enabled and url parameter log defined, we show output log on HTML comments
                if (! empty($conf->global->MAIN_ENABLE_LOG_HTML) && ! empty($_GET["log"]))
                {
                    print "\n\n<!-- Log start\n";
                    print $message."\n";
                    print "Log end -->\n";
                }
            }
            elseif (! defined("SYSLOG_FILE_NO_ERROR"))
            {
                // Do not use here a call to functions that make call to dol_syslog so making call to langs. A simple print is enough.
                print "Error, failed to open file ".$filelog."\n";
            }
        }

        // Check if log is to syslog (SYSLOG_SYSLOG_ON defined)
        if (defined("SYSLOG_SYSLOG_ON") && constant("SYSLOG_SYSLOG_ON"))
        {
            if (function_exists('openlog'))	// This function does not exists on some ISP (Ex: Free in France)
            {
                $facility = LOG_USER;
                if (defined("SYSLOG_FACILITY") && constant("SYSLOG_FACILITY"))
                {
                    // Exemple: SYSLOG_FACILITY vaut LOG_USER qui vaut 8. On a besoin de 8 dans $facility.
                    $facility = constant("SYSLOG_FACILITY");
                }

                openlog("dolibarr", LOG_PID | LOG_PERROR, (int) $facility);		// (int) is required to avoid error parameter 3 expected to be long
                if (! $level) syslog(LOG_ERR, $message);
                else          syslog($level, $message);
                closelog();
            }
        }

        // Check if log is to syslog (SYSLOG_FIREPHP_ON defined)
        if (defined("SYSLOG_FIREPHP_ON") && constant("SYSLOG_FIREPHP_ON") && ! empty($_SERVER["SERVER_NAME"]))     //! empty($_SERVER["SERVER_NAME"]) to be sure to enable this in Web mode only
        {
            try
            {
                // Warning FirePHPCore must be into PHP include path. It is not possible to use into require_once() a constant from
                // database or config file because we must be able to log data before database or config file read.
			    $oldinclude=get_include_path();
                set_include_path('/usr/share/php/');
                require_once('FirePHPCore/FirePHP.class.php');
                set_include_path($oldinclude);
                ob_start();
                $firephp = FirePHP::getInstance(true);
                if ($level == LOG_ERR) $firephp->error($message);
                elseif ($level == LOG_WARNING) $firephp->warn($message);
                elseif ($level == LOG_INFO) $firephp->log($message);
                else $firephp->log($message);
            }
            catch(Exception $e)
            {
            }
        }
    }
}


/**
 *	Show tab header of a card
 *
 *	@param	array	$links		Array of tabs
 *	@param	int		$active     Active tab name
 *	@param  string	$title      Title
 *	@param  int		$notab		0=Add tab header, 1=no tab header
 * 	@param	string	$picto		Add a picto on tab title
 * 	@return	void
 */
function dol_fiche_head($links=array(), $active='0', $title='', $notab=0, $picto='')
{
    print dol_get_fiche_head($links, $active, $title, $notab, $picto);
}

/**
 *  Show tab header of a card
 *
 *	@param	array	$links		Array of tabs
 *	@param	int		$active     Active tab name
 *	@param  string	$title      Title
 *	@param  int		$notab		0=Add tab header, 1=no tab header
 * 	@param	string	$picto		Add a picto on tab title
 * 	@return	void
 */
function dol_get_fiche_head($links=array(), $active='0', $title='', $notab=0, $picto='')
{
    $out="\n".'<div class="tabs">'."\n";

    // Affichage titre
    if ($title)
    {
        $limittitle=30;
        $out.='<a class="tabTitle">';
        if ($picto) $out.=img_object('',$picto).' ';
        $out.=dol_trunc($title,$limittitle);
        $out.='</a>';
    }

    // Define max of key (max may be higher than sizeof because of hole due to module disabling some tabs).
    $maxkey=-1;
    if (is_array($links))
    {
        $keys=array_keys($links);
        if (count($keys)) $maxkey=max($keys);
    }

    // Show tabs
    for ($i = 0 ; $i <= $maxkey ; $i++)
    {
        if (isset($links[$i][2]) && $links[$i][2] == 'image')
        {
            if (!empty($links[$i][0]))
            {
                $out.='<a class="tabimage" href="'.$links[$i][0].'">'.$links[$i][1].'</a>'."\n";
            }
            else
            {
                $out.='<span class="tabspan">'.$links[$i][1].'</span>'."\n";
            }
        }
        else if (! empty($links[$i][1]))
        {
            //print "x $i $active ".$links[$i][2]." z";
            if ((is_numeric($active) && $i == $active)
            || (! is_numeric($active) && $active == $links[$i][2]))
            {
                $out.='<a id="active" class="tab" href="'.$links[$i][0].'">'.$links[$i][1].'</a>'."\n";
            }
            else
            {
                $out.='<a id="'.$links[$i][2].'" class="tab" href="'.$links[$i][0].'">'.$links[$i][1].'</a>'."\n";
            }
        }
    }

    $out.="</div>\n";

    if (! $notab) $out.="\n".'<div class="tabBar">'."\n";

    return $out;
}

/**
 *  Show tab footer of a card
 *
 *  @param	int		$notab       0=Add tab footer, 1=no tab footer
 *  @return	void
 */
function dol_fiche_end($notab=0)
{
    print dol_get_fiche_end($notab);
}

/**
 *	Return tab footer of a card
 *
 *	@param  int		$notab		0=Add tab footer, 1=no tab footer
 *  @return	void
 */
function dol_get_fiche_end($notab=0)
{
    if (! $notab) return "\n</div>\n";
    else return '';
}


/* For backward compatibility */
function dolibarr_print_date($time,$format='',$to_gmt=false,$outputlangs='',$encodetooutput=false)
{
    return dol_print_date($time,$format,$to_gmt,$outputlangs,$encodetooutput);
}


/**
 *      Return a formated address (part address/zip/town/state) according to country rules
 *
 *      @param      outputlangs     Output langs object
 *      @param      object          A company or contact object
 *      @return     string          Formated string
 */
function dol_format_address($outputlangs,$object)
{
	$ret='';
	$countriesusingstate=array('US','IN');

	// Address
	$ret .= $outputlangs->convToOutputCharset($object->address);
	// Zip/Town/State
	if (in_array($object->country_code,array('US')))   // US: town, state, zip
	{
		$ret .= ($ret ? "\n" : '' ).$outputlangs->convToOutputCharset($object->town);
		if ($object->state && in_array($object->country_code,$countriesusingstate))
		{
			$ret.=", ".$outputlangs->convToOutputCharset($object->departement);
		}
		if ($object->zip) $ret .= ', '.$outputlangs->convToOutputCharset($object->zip);
	}
	else                                        // Other: zip town, state
	{
		$ret .= ($ret ? "\n" : '' ).$outputlangs->convToOutputCharset($object->zip);
		$ret .= ' '.$outputlangs->convToOutputCharset($object->town);
		if ($object->state && in_array($object->country_code,$countriesusingstate))
		{
			$ret.=", ".$outputlangs->convToOutputCharset($object->state);
		}
	}

	return $ret;
}


/**
 *	Output date in a string format according to outputlangs (or langs if not defined).
 * 	Return charset is always UTF-8, except if encodetoouput is defined. In this cas charset is output charset
 *
 *	@param	timestamp	$time        	GM Timestamps date (or deprecated strings 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS')
 *	@param	string		$format      	Output date format
 *										"%d %b %Y",
 *										"%d/%m/%Y %H:%M",
 *										"%d/%m/%Y %H:%M:%S",
 *										"day", "daytext", "dayhour", "dayhourldap", "dayhourtext"
 * 	@param	string		$tzoutput		true=output or 'gmt' => string is for Greenwich location
 * 										false or 'tzserver' => output string is for local PHP server TZ usage
 * 										'tzuser' => output string is for local browser TZ usage
 *	@param	Tranlsate	$outputlangs	Object lang that contains language for text translation.
 *  @param  boolean		$encodetooutput false=no convert into output pagecode
 * 	@return string      				Formated date or '' if time is null
 *
 *  @see        dol_mktime, dol_stringtotime, dol_getdate
 */
function dol_print_date($time,$format='',$tzoutput='tzserver',$outputlangs='',$encodetooutput=false)
{
    global $conf,$langs;

    $to_gmt=false;
    $offsettz=$offsetdst=0;
    if ($tzoutput)
    {
        $to_gmt=true;	// For backward compatibility
        if (is_string($tzoutput))
        {
            if ($tzoutput == 'tzserver')
            {
                $to_gmt=false;
                $offsettz=$offsetdst=0;
            }
            if ($tzoutput == 'tzuser')
            {
                $to_gmt=true;
                $offsettz=(empty($_SESSION['dol_tz'])?0:$_SESSION['dol_tz'])*60*60;
                $offsetdst=(empty($_SESSION['dol_dst'])?0:$_SESSION['dol_dst'])*60*60;
            }
            if ($tzoutput == 'tzcompany')
            {
                $to_gmt=false;
                $offsettz=$offsetdst=0;	// TODO Define this and use it later
            }
        }
    }

    if (! is_object($outputlangs)) $outputlangs=$langs;

    // Si format non defini, on prend $conf->format_date_text_short sinon %Y-%m-%d %H:%M:%S
    if (! $format) $format=(isset($conf->format_date_text_short) ? $conf->format_date_text_short : '%Y-%m-%d %H:%M:%S');

    // Change predefined format into computer format. If found translation in lang file we use it, otherwise we use default.
    if ($format == 'day')               $format=($outputlangs->trans("FormatDateShort")!="FormatDateShort"?$outputlangs->trans("FormatDateShort"):$conf->format_date_short);
    if ($format == 'hour')              $format=($outputlangs->trans("FormatHourShort")!="FormatHourShort"?$outputlangs->trans("FormatHourShort"):$conf->format_hour_short);
    if ($format == 'hourduration')      $format=($outputlangs->trans("FormatHourShortDuration")!="FormatHourShortDuration"?$outputlangs->trans("FormatHourShortDuration"):$conf->format_hour_short_duration);
    if ($format == 'daytext')           $format=($outputlangs->trans("FormatDateText")!="FormatDateText"?$outputlangs->trans("FormatDateText"):$conf->format_date_text);
    if ($format == 'daytextshort')      $format=($outputlangs->trans("FormatDateTextShort")!="FormatDateTextShort"?$outputlangs->trans("FormatDateTextShort"):$conf->format_date_text_short);
    if ($format == 'dayhour')           $format=($outputlangs->trans("FormatDateHourShort")!="FormatDateHourShort"?$outputlangs->trans("FormatDateHourShort"):$conf->format_date_hour_short);
    if ($format == 'dayhourtext')       $format=($outputlangs->trans("FormatDateHourText")!="FormatDateHourText"?$outputlangs->trans("FormatDateHourText"):$conf->format_date_hour_text);
    if ($format == 'dayhourtextshort')  $format=($outputlangs->trans("FormatDateHourTextShort")!="FormatDateHourTextShort"?$outputlangs->trans("FormatDateHourTextShort"):$conf->format_date_hour_text_short);

    // Format not sensitive to language
    if ($format == 'dayhourlog')        $format='%Y%m%d%H%M%S';
    if ($format == 'dayhourldap')       $format='%Y%m%d%H%M%SZ';
    if ($format == 'dayhourxcard')      $format='%Y%m%dT%H%M%SZ';
    if ($format == 'dayxcard')          $format='%Y%m%d';
    if ($format == 'dayrfc')            $format='%Y-%m-%d';             // DATE_RFC3339
    if ($format == 'dayhourrfc')        $format='%Y-%m-%dT%H:%M:%SZ';   // DATETIME RFC3339

    // If date undefined or "", we return ""
    if (dol_strlen($time) == 0) return '';		// $time=0 allowed (it means 01/01/1970 00:00:00)

    //print 'x'.$time;

    if (preg_match('/%b/i',$format))		// There is some text to translate
    {
        // We inhibate translation to text made by strftime functions. We will use trans instead later.
        $format=str_replace('%b','__b__',$format);
        $format=str_replace('%B','__B__',$format);
    }
    if (preg_match('/%a/i',$format))		// There is some text to translate
    {
        // We inhibate translation to text made by strftime functions. We will use trans instead later.
        $format=str_replace('%a','__a__',$format);
        $format=str_replace('%A','__A__',$format);
    }

    // Analyze date (deprecated)   Ex: 1970-01-01, 1970-01-01 01:00:00, 19700101010000
    if (preg_match('/^([0-9]+)\-([0-9]+)\-([0-9]+) ?([0-9]+)?:?([0-9]+)?:?([0-9]+)?/i',$time,$reg)
    || preg_match('/^([0-9][0-9][0-9][0-9])([0-9][0-9])([0-9][0-9])([0-9][0-9])([0-9][0-9])([0-9][0-9])$/i',$time,$reg))
    {
        // This part of code should not be used.
        dol_syslog("Functions.lib::dol_print_date function call with deprecated value of time in page ".$_SERVER["PHP_SELF"], LOG_WARNING);
        // Date has format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS' or 'YYYYMMDDHHMMSS'
        $syear = $reg[1];
        $smonth = $reg[2];
        $sday = $reg[3];
        $shour = $reg[4];
        $smin = $reg[5];
        $ssec = $reg[6];

        $time=dol_mktime($shour,$smin,$ssec,$smonth,$sday,$syear,true);
        $ret=adodb_strftime($format,$time+$offsettz+$offsetdst,$to_gmt);
    }
    else
    {
        // Date is a timestamps
        if ($time < 100000000000)	// Protection against bad date values
        {
            $ret=adodb_strftime($format,$time+$offsettz+$offsetdst,$to_gmt);
        }
        else $ret='Bad value '.$time.' for date';
    }

    if (preg_match('/__b__/i',$format))
    {
        // Here ret is string in PHP setup language (strftime was used). Now we convert to $outputlangs.
        $month=adodb_strftime('%m',$time+$offsettz+$offsetdst);
        if ($encodetooutput)
        {
            $monthtext=$outputlangs->transnoentities('Month'.$month);
            $monthtextshort=$outputlangs->transnoentities('MonthShort'.$month);
        }
        else
        {
            $monthtext=$outputlangs->transnoentitiesnoconv('Month'.$month);
            $monthtextshort=$outputlangs->transnoentitiesnoconv('MonthShort'.$month);
        }
        //print 'monthtext='.$monthtext.' monthtextshort='.$monthtextshort;
        $ret=str_replace('__b__',$monthtextshort,$ret);
        $ret=str_replace('__B__',$monthtext,$ret);
        //print 'x'.$outputlangs->charset_output.'-'.$ret.'x';
        //return $ret;
    }
    if (preg_match('/__a__/i',$format))
    {
        $w=adodb_strftime('%w',$time+$offsettz+$offsetdst);
        $dayweek=$outputlangs->transnoentitiesnoconv('Day'.$w);
        $ret=str_replace('__A__',$dayweek,$ret);
        $ret=str_replace('__a__',dol_substr($dayweek,0,3),$ret);
    }

    return $ret;
}


/**
 *	Convert a string date into a GM Timestamps date
 *
 *	@param	string	$string		Date in a string
 *				     	        YYYYMMDD
 *	                 			YYYYMMDDHHMMSS
 *								YYYY-MM-DDTHH:MM:SSZ (RFC3339)
 *		                		DD/MM/YY or DD/MM/YYYY (this format should not be used anymore)
 *		                		DD/MM/YY HH:MM:SS or DD/MM/YYYY HH:MM:SS (this format should not be used anymore)
 *  @param	int		$gm         1=Input date is GM date, 0=Input date is local date
 *		                		19700101020000 -> 7200 with gm=1
 *  @return	date				Date
 *
 *  @see    dol_print_date, dol_mktime, dol_getdate
 */
function dol_stringtotime($string, $gm=1)
{
    if (preg_match('/^([0-9]+)\/([0-9]+)\/([0-9]+)\s?([0-9]+)?:?([0-9]+)?:?([0-9]+)?/i',$string,$reg))
    {
        // This part of code should not be used.
        dol_syslog("Functions.lib::dol_stringtotime call to function with deprecated parameter", LOG_WARNING);
        // Date est au format 'DD/MM/YY' ou 'DD/MM/YY HH:MM:SS'
        // Date est au format 'DD/MM/YYYY' ou 'DD/MM/YYYY HH:MM:SS'
        $sday = $reg[1];
        $smonth = $reg[2];
        $syear = $reg[3];
        $shour = $reg[4];
        $smin = $reg[5];
        $ssec = $reg[6];
        if ($syear < 50) $syear+=1900;
        if ($syear >= 50 && $syear < 100) $syear+=2000;
        $string=sprintf("%04d%02d%02d%02d%02d%02d",$syear,$smonth,$sday,$shour,$smin,$ssec);
    }
    // Convert date RFC3339
    else if (preg_match('/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})Z$/i',$string,$reg))
    {
        $syear = $reg[1];
        $smonth = $reg[2];
        $sday = $reg[3];
        $shour = $reg[4];
        $smin = $reg[5];
        $ssec = $reg[6];
        $string=sprintf("%04d%02d%02d%02d%02d%02d",$syear,$smonth,$sday,$shour,$smin,$ssec);
    }

    $string=preg_replace('/([^0-9])/i','',$string);
    $tmp=$string.'000000';
    $date=dol_mktime(substr($tmp,8,2),substr($tmp,10,2),substr($tmp,12,2),substr($tmp,4,2),substr($tmp,6,2),substr($tmp,0,4),$gm);
    return $date;
}


/**
 *	Return an array with date info
 *  PHP getdate is restricted to the years 1901-2038 on Unix and 1970-2038 on Windows
 *
 *	@param	timestamp	$timestamp		Timestamp
 *	@param	boolean		$fast			Fast mode
 *	@return	array						Array of informations
 *										If no fast mode:
 *										'seconds' => $secs,
 *										'minutes' => $min,
 *										'hours' => $hour,
 *										'mday' => $day,
 *										'wday' => $dow,
 *										'mon' => $month,
 *										'year' => $year,
 *										'yday' => floor($secsInYear/$_day_power),
 *										'weekday' => gmdate('l',$_day_power*(3+$dow)),
 *										'month' => gmdate('F',mktime(0,0,0,$month,2,1971)),
 *										If fast mode:
 *										'seconds' => $secs,
 *										'minutes' => $min,
 *										'hours' => $hour,
 *										'mday' => $day,
 *										'mon' => $month,
 *										'year' => $year,
 *										'yday' => floor($secsInYear/$_day_power),
 *										'leap' => $leaf,
 *										'ndays' => $ndays
 */
function dol_getdate($timestamp,$fast=false)
{
    $usealternatemethod=false;
    if ($timestamp <= 0) $usealternatemethod=true;				// <= 1970
    if ($timestamp >= 2145913200) $usealternatemethod=true;		// >= 2038

    if ($usealternatemethod)
    {
        $arrayinfo=adodb_getdate($timestamp,$fast);
    }
    else
    {
        $arrayinfo=getdate($timestamp);
    }

    return $arrayinfo;
}

/* For backward compatibility */
function dolibarr_mktime($hour,$minute,$second,$month,$day,$year,$gm=false,$check=1)
{
    return dol_mktime($hour,$minute,$second,$month,$day,$year,$gm,$check);
}

/**
 *	Return a timestamp date built from detailed informations (by default a local PHP server timestamp)
 * 	Replace function mktime not available under Windows if year < 1970
 *	PHP mktime is restricted to the years 1901-2038 on Unix and 1970-2038 on Windows
 *
 * 	@param		hour			Hour	(can be -1 for undefined)
 *	@param		minute			Minute	(can be -1 for undefined)
 *	@param		second			Second	(can be -1 for undefined)
 *	@param		month			Month (1 to 12)
 *	@param		day				Day (1 to 31)
 *	@param		year			Year
 *	@param		gm				1=Input informations are GMT values, otherwise local to server TZ
 *	@param		check			0=No check on parameters (Can use day 32, etc...)
 *  @param		isdst			Dayling saving time
 *	@return		timestamp		Date as a timestamp, '' if error
 * 	@see 		dol_print_date, dol_stringtotime
 */
function dol_mktime($hour,$minute,$second,$month,$day,$year,$gm=false,$check=1,$isdst=true)
{
    //print "- ".$hour.",".$minute.",".$second.",".$month.",".$day.",".$year.",".$_SERVER["WINDIR"]." -";

    // Clean parameters
    if ($hour   == -1) $hour=0;
    if ($minute == -1) $minute=0;
    if ($second == -1) $second=0;

    // Check parameters
    if ($check)
    {
        if (! $month || ! $day)  return '';
        if ($day   > 31) return '';
        if ($month > 12) return '';
        if ($hour  < 0 || $hour   > 24) return '';
        if ($minute< 0 || $minute > 60) return '';
        if ($second< 0 || $second > 60) return '';
    }

    $usealternatemethod=false;
    if ($year <= 1970) $usealternatemethod=true;		// <= 1970
    if ($year >= 2038) $usealternatemethod=true;		// >= 2038

    if ($usealternatemethod || $gm)	// Si time gm, seule adodb peut convertir
    {
        /*
         // On peut utiliser strtotime pour obtenir la traduction.
         // strtotime is ok for range: Friday 13 December 1901 20:45:54 GMT to Tuesday 19 January 2038 03:14:07 GMT.
         $montharray=array(1=>'january',2=>'february',3=>'march',4=>'april',5=>'may',6=>'june',
         7=>'july',8=>'august',9=>'september',10=>'october',11=>'november',12=>'december');
         $string=$day." ".$montharray[0+$month]." ".$year." ".$hour.":".$minute.":".$second." GMT";
         $date=strtotime($string);
         print "- ".$string." ".$date." -";
         */
        $date=adodb_mktime($hour,$minute,$second,$month,$day,$year,$isdst,$gm);
    }
    else
    {
        $date=mktime($hour,$minute,$second,$month,$day,$year);
    }
    return $date;
}


/* For backward compatibility */
function dolibarr_date($fmt, $timestamp, $gm=false)
{
    return dol_date($fmt, $timestamp, $gm);
}

/**
 *	Returns formated date
 *
 *	@param		string		$fmt			Format (Exemple: 'Y-m-d H:i:s')
 *	@param		timestamp	$timestamp		Date. Example: If timestamp=0 and gm=1, return 01/01/1970 00:00:00
 *	@param		boolean		$gm				1 if timestamp was built with gmmktime, 0 if timestamp was build with mktime
 *	@return		string						Formated date
 *
 *  @deprecated Replaced by dol_print_date
 */
function dol_date($fmt, $timestamp, $gm=false)
{
    $usealternatemethod=false;
    if ($timestamp <= 0) $usealternatemethod=true;
    if ($timestamp >= 2145913200) $usealternatemethod=true;

    if ($usealternatemethod || $gm)	// Si time gm, seule adodb peut convertir
    {
        $string=adodb_date($fmt,$timestamp,$gm);
    }
    else
    {
        $string=date($fmt,$timestamp);
    }

    return $string;
}


/**
 * Return string with formated size
 *
 * @param	int		$size		Size to print
 * @param	int		$shortvalue	Tell if we want long value to use another unit (Ex: 1.5Kb instead of 1500b)
 * @param	int		$shortunit	Use short value of size unit
 * @return	string				Link
 */
function dol_print_size($size,$shortvalue=0,$shortunit=0)
{
    global $langs;
    $level=1024;

    // Set value text
    if (empty($shortvalue) || $size < ($level*10))
    {
        $ret=$size;
        $textunitshort=$langs->trans("b");
        $textunitlong=$langs->trans("Bytes");
    }
    else
    {
        $ret=round($size/$level,0);
        $textunitshort=$langs->trans("Kb");
        $textunitlong=$langs->trans("KiloBytes");
    }
    // Use long or short text unit
    if (empty($shortunit)) { $ret.=' '.$textunitlong; }
    else { $ret.=' '.$textunitshort; }

    return $ret;
}

/**
 * Show Url link
 *
 * @param	string		$url		Url to show
 * @param	string		$target		Target for link
 * @param	int			$max		Max number of characters to show
 * @return	string					HTML Link
 */
function dol_print_url($url,$target='_blank',$max=32)
{
    if (empty($url)) return '';

    $link='<a href="';
    if (! preg_match('/^http/i',$url)) $link.='http://';
    $link.=$url;
    if ($target) $link.='" target="'.$target.'">';
    if (! preg_match('/^http/i',$url)) $link.='http://';
    $link.=dol_trunc($url,$max);
    $link.='</a>';
    return $link;
}

/**
 * Show EMail link
 *
 * @param	string		$email			EMail to show (only email, without 'Name of recipient' before)
 * @param 	int			$cid 			Id of contact if known
 * @param 	int			$socid 			Id of third party if known
 * @param 	int			$addlink		0=no link to create action
 * @param	int			$max			Max number of characters to show
 * @param	int			$showinvalid	Show warning if syntax email is wrong
 * @return	string						HTML Link
 */
function dol_print_email($email,$cid=0,$socid=0,$addlink=0,$max=64,$showinvalid=1)
{
    global $conf,$user,$langs;

    $newemail=$email;

    if (empty($email)) return '&nbsp;';

    if (! empty($addlink))
    {
        $newemail='<a href="';
        if (! preg_match('/^mailto:/i',$email)) $newemail.='mailto:';
        $newemail.=$email;
        $newemail.='">';
        $newemail.=dol_trunc($email,$max);
        $newemail.='</a>';
        if ($showinvalid && ! isValidEmail($email))
        {
            $langs->load("errors");
            $newemail.=img_warning($langs->trans("ErrorBadEMail",$email));
        }

        if (($cid || $socid) && $conf->agenda->enabled && $user->rights->agenda->myactions->create)
        {
            $type='AC_EMAIL'; $link='';
            if (! empty($conf->global->AGENDA_ADDACTIONFOREMAIL)) $link='<a href="'.DOL_URL_ROOT.'/comm/action/fiche.php?action=create&amp;backtopage=1&amp;actioncode='.$type.'&amp;contactid='.$cid.'&amp;socid='.$socid.'">'.img_object($langs->trans("AddAction"),"calendar").'</a>';
            $newemail='<table class="nobordernopadding"><tr><td>'.$newemail.' </td><td>&nbsp;'.$link.'</td></tr></table>';
        }
    }
    else
    {
        if ($showinvalid && ! isValidEmail($email))
        {
            $langs->load("errors");
            $newemail.=img_warning($langs->trans("ErrorBadEMail",$email));
        }
    }
    return $newemail;
}

/* For backward compatibility */
function dolibarr_print_phone($phone,$country="FR",$cid=0,$socid=0,$addlink=0,$separ="&nbsp;")
{
    return dol_print_phone($phone,$country,$cid,$socid,$addlink,$separ);
}

/**
 * 	Format phone numbers according to country
 *
 * 	@param	string	$phone 		Phone number to format
 * 	@param 	string	$country 	Country code to use for formatting
 * 	@param 	int		$cid 		Id of contact if known
 * 	@param 	int		$socid 		Id of third party if known
 * 	@param 	int		$addlink	0=no link to create action
 * 	@param 	string	$separ 		separation between numbers for a better visibility example : xx.xx.xx.xx.xx
 * 	@return string 				Formated phone number
 */
function dol_print_phone($phone,$country="FR",$cid=0,$socid=0,$addlink=0,$separ="&nbsp;")
{
    global $conf,$user,$langs;

    // Clean phone parameter
    $phone = preg_replace("/[\s.-]/","",trim($phone));
    if (empty($phone)) { return ''; }

    $newphone=$phone;
    if (strtoupper($country) == "FR")
    {
        // France
        if (dol_strlen($phone) == 10) {
            $newphone=substr($newphone,0,2).$separ.substr($newphone,2,2).$separ.substr($newphone,4,2).$separ.substr($newphone,6,2).$separ.substr($newphone,8,2);
        }
        elseif (dol_strlen($newphone) == 7)
        {
            $newphone=substr($newphone,0,3).$separ.substr($newphone,3,2).$separ.substr($newphone,5,2);
        }
        elseif (dol_strlen($newphone) == 9)
        {
            $newphone=substr($newphone,0,2).$separ.substr($newphone,2,3).$separ.substr($newphone,5,2).$separ.substr($newphone,7,2);
        }
        elseif (dol_strlen($newphone) == 11)
        {
            $newphone=substr($newphone,0,3).$separ.substr($newphone,3,2).$separ.substr($newphone,5,2).$separ.substr($newphone,7,2).$separ.substr($newphone,9,2);
        }
        elseif (dol_strlen($newphone) == 12)
        {
            $newphone=substr($newphone,0,4).$separ.substr($newphone,4,2).$separ.substr($newphone,6,2).$separ.substr($newphone,8,2).$separ.substr($newphone,10,2);
        }
    }

    if (! empty($addlink))
    {
        if ($conf->clicktodial->enabled)
        {
            if (empty($user->clicktodial_loaded)) $user->fetch_clicktodial();

            if (empty($conf->global->CLICKTODIAL_URL)) $urlmask='ErrorClickToDialModuleNotConfigured';
            else $urlmask=$conf->global->CLICKTODIAL_URL;
            // This line is for backward compatibility
            $url = sprintf($urlmask, urlencode($phone), urlencode($user->clicktodial_poste), urlencode($user->clicktodial_login), urlencode($user->clicktodial_password));
            // Thoose lines are for substitution
            $substitarray=array('__PHONEFROM__'=>urlencode($user->clicktodial_poste),
			               		'__PHONETO__'=>urlencode($phone),
						   		'__LOGIN__'=>urlencode($user->clicktodial_login),
			               		'__PASS__'=>urlencode($user->clicktodial_password));
            $url = make_substitutions($url, $substitarray);
            $newphonesav=$newphone;
            $newphone ='<a href="'.$url.'"';
            if (! empty($conf->global->CLICKTODIAL_FORCENEWTARGET)) $newphone.=' target="_blank"';
            $newphone.='>'.$newphonesav.'</a>';
        }

        //if (($cid || $socid) && $conf->agenda->enabled && $user->rights->agenda->myactions->create)
        if ($conf->agenda->enabled && $user->rights->agenda->myactions->create)
        {
            $type='AC_TEL'; $link='';
            if ($addlink == 'AC_FAX') $type='AC_FAX';
            if (! empty($conf->global->AGENDA_ADDACTIONFORPHONE)) $link='<a href="'.DOL_URL_ROOT.'/comm/action/fiche.php?action=create&amp;backtopage=1&amp;actioncode='.$type.($cid?'&amp;contactid='.$cid:'').($socid?'&amp;socid='.$socid:'').'">'.img_object($langs->trans("AddAction"),"calendar").'</a>';
            $newphone='<table class="nobordernopadding"><tr><td>'.$newphone.' </td><td>&nbsp;'.$link.'</td></tr></table>';
        }
    }

    return $newphone;
}

/**
 * 	Return an IP formated to be shown on screen
 *
 * 	@param	string	$ip			IP
 * 	@param	int		$mode		1=return only country/flag,2=return only IP
 * 	@return string 				Formated IP, with country if GeoIP module is enabled
 */
function dol_print_ip($ip,$mode=0)
{
    global $conf,$langs;

    $ret='';

    if (empty($mode)) $ret.=$ip;

    if (! empty($conf->geoipmaxmind->enabled) && $mode != 2)
    {
        $datafile=$conf->global->GEOIPMAXMIND_COUNTRY_DATAFILE;
        //$ip='24.24.24.24';
        //$datafile='E:\Mes Sites\Web\Admin1\awstats\maxmind\GeoIP.dat';    Note that this must be downloaded datafile (not same than datafile provided with ubuntu packages)

        include_once(DOL_DOCUMENT_ROOT.'/core/class/dolgeoip.class.php');
        $geoip=new DolGeoIP('country',$datafile);
        //print 'ip='.$ip.' databaseType='.$geoip->gi->databaseType." GEOIP_CITY_EDITION_REV1=".GEOIP_CITY_EDITION_REV1."\n";
        //print "geoip_country_id_by_addr=".geoip_country_id_by_addr($geoip->gi,$ip)."\n";
        $countrycode=$geoip->getCountryCodeFromIP($ip);
        if ($countrycode)	// If success, countrycode is us, fr, ...
        {
            if (file_exists(DOL_DOCUMENT_ROOT.'/theme/common/flags/'.$countrycode.'.png'))
            {
                $ret.=' '.img_picto($countrycode.' '.$langs->trans("AccordingToGeoIPDatabase"),DOL_URL_ROOT.'/theme/common/flags/'.$countrycode.'.png','',1);
            }
            else $ret.=' ('.$countrycode.')';
        }
    }

    return $ret;
}

/**
 *  Return country code for current user.
 *  If software is used inside a local network, detection may fails (we need a public ip)
 *
 *  @return     string      Country code (fr, es, it, us, ...)
 */
function dol_user_country()
{
    global $conf,$langs,$user;

    //$ret=$user->xxx;
    $ret='';
    if (! empty($conf->geoipmaxmind->enabled))
    {
        $ip=$_SERVER["REMOTE_ADDR"];
        $datafile=$conf->global->GEOIPMAXMIND_COUNTRY_DATAFILE;
        //$ip='24.24.24.24';
        //$datafile='E:\Mes Sites\Web\Admin1\awstats\maxmind\GeoIP.dat';
        include_once(DOL_DOCUMENT_ROOT.'/core/class/dolgeoip.class.php');
        $geoip=new DolGeoIP('country',$datafile);
        $countrycode=$geoip->getCountryCodeFromIP($ip);
        $ret=$countrycode;
    }
    return $ret;
}

/**
 *  Format address string
 *
 *  @param	string	$address     Address
 *  @param  int		$htmlid      Html ID
 *  @param  int		$mode        thirdparty|contact|member|other
 *  @param  int		$id          Id of object
 *  @return void
 */
function dol_print_address($address, $htmlid='gmap', $mode, $id)
{
    global $conf,$user,$langs;

    if ($address)
    {
        print nl2br($address);
        $showmap=0;
        if ($mode=='thirdparty' && $conf->google->enabled && $conf->global->GOOGLE_ENABLE_GMAPS) $showmap=1;
        if ($mode=='contact' && $conf->google->enabled && $conf->global->GOOGLE_ENABLE_GMAPS_CONTACTS) $showmap=1;
        if ($mode=='member' && $conf->google->enabled && $conf->global->GOOGLE_ENABLE_GMAPS_MEMBERS) $showmap=1;

        if ($showmap)
        {
            $url=dol_buildpath('/google/gmaps.php?mode='.$mode.'&id='.$id,1);
            /*    print ' <img id="'.$htmlid.'" src="'.DOL_URL_ROOT.'/theme/common/gmap.png">';
             print '<script type="text/javascript">
             $(\'#gmap\').css(\'cursor\',\'pointer\');
             $(\'#gmap\').click(function() {
             $( \'<div>\').dialog({
             modal: true,
             open: function ()
             {
             $(this).load(\''.$url.'\');
             },
             height: 400,
             width: 600,
             title: \'GMap\'
             });
             });
             </script>
             '; */
            print ' <a href="'.$url.'" target="_gmaps"><img id="'.$htmlid.'" border="0" src="'.DOL_URL_ROOT.'/theme/common/gmap.png"></a>';
        }
    }
}


/**
 *	Return true if email syntax is ok
 *
 *	@param	    string		$address    email (Ex: "toto@titi.com", "John Do <johndo@titi.com>")
 *	@return     boolean     			true if email syntax is OK, false if KO or empty string
 */
function isValidEmail($address)
{
    if (preg_match("/.*<(.+)>/i", $address, $regs)) {
        $address = $regs[1];
    }
    // 2 letters domains extensions are for countries
    // 3 letters domains extensions: biz|com|edu|gov|int|mil|net|org|pro|...
    if (preg_match("/^[^@\s\t]+@([a-zA-Z0-9\-]+\.)+([a-zA-Z0-9\-]{2,3}|asso|aero|coop|info|name)\$/i",$address))
    {
        return true;
    }
    else
    {
        return false;
    }
}

/**
 *  Return true if phone number syntax is ok
 *
 *  @param      string		$address    phone (Ex: "0601010101")
 *  @return     boolean     			true if phone syntax is OK, false if KO or empty string
 */
function isValidPhone($address)
{
    return true;
}


/**
 * Make a strlen call. Works even if mbstring module not enabled
 *
 * @param   string		$string				String to calculate length
 * @param   string		$stringencoding		Encoding of string
 * @return  int								Length of string
 */
function dol_strlen($string,$stringencoding='UTF-8')
{
    if (function_exists('mb_strlen')) return mb_strlen($string,$stringencoding);
    else return strlen($string);
}

/**
 * Make a substring. Works even in mbstring module is not enabled.
 *
 * @param	string	$string				String to scan
 * @param	string	$start				Start position
 * @param	int		$length				Length
 * @param   string	$stringencoding		Page code used for input string encoding
 * @return  string						substring
 */
function dol_substr($string,$start,$length,$stringencoding='')
{
    global $langs;

    if (empty($stringencoding)) $stringencoding=$langs->charset_output;

    $ret='';
    if (function_exists('mb_substr'))
    {
        $ret=mb_substr($string,$start,$length,$stringencoding);
    }
    else
    {
        $ret=substr($string,$start,$length);
    }
    return $ret;
}


/* For backward compatibility */
function dolibarr_trunc($string,$size=40,$trunc='right',$stringencoding='')
{
    return dol_trunc($string,$size,$trunc,$stringencoding);
}


/**
 *  Show a javascript graph
 *  
 *  @param		string	$htmlid			Html id name
 *  @param		int		$width			Width in pixel
 *  @param		int		$height			Height in pixel
 *  @param		array	$data			Data array
 *  @param		int		$showlegend		1 to show legend, 0 otherwise
 *  @param		string	$type			Type of graph ('pie', 'barline')
 *  @param		int		$showpercent	Show percent (with type='pie' only)
 *  @param		string	$url			Param to add an url to click values
 *  @return		void
 */
function dol_print_graph($htmlid,$width,$height,$data,$showlegend=0,$type='pie',$showpercent=0,$url='')
{
	global $conf,$langs;
	global $theme_datacolor;    // To have var kept when function is called several times
	if (empty($conf->use_javascript_ajax)) return;
	$jsgraphlib='flot';
	$datacolor=array();
	
	// Load colors of theme into $datacolor array
	$color_file = DOL_DOCUMENT_ROOT."/theme/".$conf->theme."/graph-color.php";
	if (is_readable($color_file))
	{
		include_once($color_file);
		if (isset($theme_datacolor))
		{
			$datacolor=array();
			foreach($theme_datacolor as $val)
			{
				$datacolor[]="#".sprintf("%02x",$val[0]).sprintf("%02x",$val[1]).sprintf("%02x",$val[2]);
			}
		}
	}
	print '<div id="'.$htmlid.'" style="width:'.$width.'px;height:'.$height.'px;"></div>';
	
	// We use Flot js lib
	if ($jsgraphlib == 'flot')
	{
		if ($type == 'pie')
		{
			// data is   array('series'=>array(serie1,serie2,...),
			//                 'seriestype'=>array('bar','line',...),
			//                 'seriescolor'=>array(0=>'#999999',1=>'#999999',...)
			//                 'xlabel'=>array(0=>labelx1,1=>labelx2,...));
			// serieX is array('label'=>'label', data=>val)
			print '
			<script type="text/javascript">
			$(function () {
				var data = '.json_encode($data['series']).';
				
				function plotWithOptions() {
					$.plot($("#'.$htmlid.'"), data,
					{
						series: {
							pie: {
								show: true,
								radius: 3/4,
								label: {
									show: true,
									radius: 3/4,
									formatter: function(label, series) {
										var percent=Math.round(series.percent);
										var number=series.data[0][1];
										return \'';
										print '<div style="font-size:8pt;text-align:center;padding:2px;color:white;">';
										if ($url) print '<a style="color: #FFFFFF;" border="0" href="'.$url.'=">';
										print '\'+'.($showlegend?'number':'label+\'<br/>\'+number');
										if (! empty($showpercent)) print '+\'<br/>\'+percent+\'%\'';
										print '+\'';
										if ($url) print '</a>';
										print '</div>\';
									},
									background: {
										opacity: 0.5,
										color: \'#000000\'
									}
								}
							}
						},
						zoom: {
							interactive: true
						},
						pan: {
							interactive: true
						},';
						if (count($datacolor))
						{
							print 'colors: '.(! empty($data['seriescolor']) ? json_encode($data['seriescolor']) : json_encode($datacolor)).',';
						}
						print 'legend: {show: '.($showlegend?'true':'false').', position: \'ne\' }
					});
				}
				plotWithOptions();
			});
			</script>';
		}
		else if ($type == 'barline')
		{
			// data is   array('series'=>array(serie1,serie2,...),
			//                 'seriestype'=>array('bar','line',...),
			//                 'seriescolor'=>array(0=>'#999999',1=>'#999999',...)
			//                 'xlabel'=>array(0=>labelx1,1=>labelx2,...));
			// serieX is array('label'=>'label', data=>array(0=>y1,1=>y2,...)) with same nb of value than into xlabel
			print '
			<script type="text/javascript">
			$(function () {
				var data = [';
				$i=0; $outputserie=0;
				foreach($data['series'] as $serie)
				{
					if ($data['seriestype'][$i]=='line') { $i++; continue; };
					if ($outputserie > 0) print ',';
					print '{ bars: { stack: 0, show: true, barWidth: 0.9, align: \'center\' }, label: \''.dol_escape_js($serie['label']).'\', data: '.json_encode($serie['data']).'}'."\n";
					$outputserie++; $i++;
				}
				if ($outputserie) print ', ';
				//print '];
				//var datalines = [';
				$i=0; $outputserie=0;
				foreach($data['series'] as $serie)
				{
					if (empty($data['seriestype'][$i]) || $data['seriestype'][$i]=='bar') { $i++; continue; };
					if ($outputserie > 0) print ',';
					print '{ lines: { show: true }, label: \''.dol_escape_js($serie['label']).'\', data: '.json_encode($serie['data']).'}'."\n";
					$outputserie++; $i++;
				}
				print '];
				var dataticks = '.json_encode($data['xlabel']).'
				
				function plotWithOptions() {
					$.plot(jQuery("#'.$htmlid.'"), data,
					{
						series: {
							stack: 0
						},
						zoom: {
							interactive: true
						},
						pan: {
							interactive: true
						},';
						if (count($datacolor))
						{
							print 'colors: '.json_encode($datacolor).',';
						}
						print 'legend: {show: '.($showlegend?'true':'false').'},
						xaxis: {ticks: dataticks}
					});
				}
				plotWithOptions();
			});
			</script>';
		}
		else print 'BadValueForPArameterType';
	}
}

/**
 *	Truncate a string to a particular length adding '...' if string larger than length.
 * 	If length = max length+1, we do no truncate to avoid having just 1 char replaced with '...'.
 *  MAIN_DISABLE_TRUNC=1 can disable all truncings
 *
 *	@param      string				String to truncate
 *	@param      size				Max string size. 0 for no limit.
 *	@param		trunc				Where to trunc: right, left, middle, wrap
 * 	@param		stringencoding		Tell what is source string encoding
 *	@return     string				Truncated string
 */
function dol_trunc($string,$size=40,$trunc='right',$stringencoding='UTF-8')
{
    global $conf;

    if ($size==0) return $string;
    if (empty($conf->global->MAIN_DISABLE_TRUNC))
    {
        // We go always here
        if ($trunc == 'right')
        {
            $newstring=dol_textishtml($string)?dol_string_nohtmltag($string,1):$string;
            if (dol_strlen($newstring,$stringencoding) > ($size+1))
            return dol_substr($newstring,0,$size,$stringencoding).'...';
            else
            return $string;
        }
        if ($trunc == 'middle')
        {
            $newstring=dol_textishtml($string)?dol_string_nohtmltag($string,1):$string;
            if (dol_strlen($newstring,$stringencoding) > 2 && dol_strlen($newstring,$stringencoding) > ($size+1))
            {
                $size1=round($size/2);
                $size2=round($size/2);
                return dol_substr($newstring,0,$size1,$stringencoding).'...'.dol_substr($newstring,dol_strlen($newstring,$stringencoding) - $size2,$size2,$stringencoding);
            }
            else
            return $string;
        }
        if ($trunc == 'left')
        {
            $newstring=dol_textishtml($string)?dol_string_nohtmltag($string,1):$string;
            if (dol_strlen($newstring,$stringencoding) > ($size+1))
            return '...'.dol_substr($newstring,dol_strlen($newstring,$stringencoding) - $size,$size,$stringencoding);
            else
            return $string;
        }
        if ($trunc == 'wrap')
        {
            $newstring=dol_textishtml($string)?dol_string_nohtmltag($string,1):$string;
            if (dol_strlen($newstring,$stringencoding) > ($size+1))
            return dol_substr($newstring,0,$size,$stringencoding)."\n".dol_trunc(dol_substr($newstring,$size,dol_strlen($newstring,$stringencoding)-$size,$stringencoding),$size,$trunc);
            else
            return $string;
        }
    }
    else
    {
        return $string;
    }
}


/**
 *	Show a picto called object_picto (generic function)
 *
 *	@param      string		$alt           		Text of alt on image
 *	@param      string		$picto         		Name of image to show object_picto (example: user, group, action, bill, contract, propal, product, ...)
 *							 		       		For external modules use imagename@mymodule to search into directory "img" of module.
 *  @param      string		$options       		Add more attribute on img tag
 *  @param      int			$pictoisfullpath    If 1, image path is a full path
 *	@return     string      					Return img tag
 *  @see        #img_picto, #img_picto_common
 */
function img_object($alt, $picto, $options='', $pictoisfullpath=0)
{
    global $conf;

    // Clean parameters
    if (! preg_match('/(\.png|\.gif)$/i',$picto) && ! preg_match('/^([^@]+)@([^@]+)$/i',$picto)) $picto.='.png';

    // Define fullpathpicto to use into src
    if (! empty($pictoisfullpath)) $fullpathpicto=$picto;
    else
    {
        // By default, we search into theme directory
        $url = DOL_URL_ROOT;
        $path = 'theme/'.$conf->theme;
        if (! empty($conf->global->MAIN_FORCETHEMEDIR)) $path=preg_replace('/^\//','',$conf->global->MAIN_FORCETHEMEDIR).'/'.$path;
        // If we ask an image into module/img (not into a theme path)
        if (preg_match('/^([^@]+)@([^@]+)$/i',$picto,$regs)) { $picto = $regs[1]; $path=$regs[2]; }      // If image into a module/img path
        if (! preg_match('/(\.png|\.gif)$/i',$picto)) $picto.='.png';
        // If img file not into standard path, we use alternate path
        if (defined('DOL_URL_ROOT_ALT') && DOL_URL_ROOT_ALT && ! file_exists(DOL_DOCUMENT_ROOT.'/'.$path.'/img/object_'.$picto)) $url = DOL_URL_ROOT_ALT;

        $fullpathpicto=$url.'/'.$path.'/img/object_'.$picto;
    }

    return '<img src="'.$fullpathpicto.'" border="0" alt="'.dol_escape_htmltag($alt).'" title="'.dol_escape_htmltag($alt).'"'.($options?' '.$options:'').'>';
}

/**
 *	Show picto whatever it's its name (generic function)
 *
 *	@param      string		$alt         		Text on alt and title of image
 *	@param      string		$picto       		Name of image file to show ('filenew', ...)
 *												If no extension provided, we use '.png'. Image must be stored into theme/xxx/img directory.
 *                                  			Example: picto.png                  if picto.png is stored into htdocs/theme/mytheme/img
 *                                  			Example: picto.png@mymodule         if picto.png is stored into htdocs/mymodule/img
 *                                  			Example: /mydir/mysubdir/picto.png  if picto.png is stored into htdocs/mydir/mysubdir (pictoisfullpath must be set to 1)
 *	@param		string		$options			Add more attribute on img tag (For example 'style="float: right"')
 *	@param		int			$pictoisfullpath	If 1, image path is a full path
 *  @return     string       				    Return img tag
 *  @see        #img_object, #img_picto_common
 */
function img_picto($alt, $picto, $options='', $pictoisfullpath=0)
{
    global $conf;

    // Clean parameters
    if (! preg_match('/(\.png|\.gif)$/i',$picto) && ! preg_match('/^([^@]+)@([^@]+)$/i',$picto)) $picto.='.png';

    // Define fullpathpicto to use into src
    if (! empty($pictoisfullpath)) $fullpathpicto=$picto;
    else
    {
        // By default, we search into theme directory
        $url = DOL_URL_ROOT;
        $path = 'theme/'.$conf->theme;
        if (! empty($conf->global->MAIN_FORCETHEMEDIR)) $path=preg_replace('/^\//','',$conf->global->MAIN_FORCETHEMEDIR).'/'.$path;
        // If we ask an image into module/img (not into a theme path)
        if (preg_match('/^([^@]+)@([^@]+)$/i',$picto,$regs)) { $picto = $regs[1]; $path=$regs[2]; }      // If image into a module/img path
        if (! preg_match('/(\.png|\.gif)$/i',$picto)) $picto.='.png';
        // If img file not into standard path, we use alternate path
        if (defined('DOL_URL_ROOT_ALT') && DOL_URL_ROOT_ALT && ! file_exists(DOL_DOCUMENT_ROOT.'/'.$path.'/img/'.$picto)) $url = DOL_URL_ROOT_ALT;

        $fullpathpicto=$url.'/'.$path.'/img/'.$picto;
    }

    return '<img src="'.$fullpathpicto.'" border="0" alt="'.dol_escape_htmltag($alt).'" title="'.dol_escape_htmltag($alt).'"'.($options?' '.$options:'').'>';
}

/**
 *	Show picto (generic function)
 *
 *	@param      string		$alt         		Text on alt and title of image
 *	@param      string		$picto       		Name of image file to show (If no extension provided, we use '.png'). Image must be stored into htdocs/theme/common directory.
 *	@param		string		$options			Add more attribute on img tag
 *	@param		int			$pictoisfullpath	If 1, image path is a full path
 *	@return     string      					Return img tag
 *  @see        #img_object, #img_picto
 */
function img_picto_common($alt, $picto, $options='', $pictoisfullpath=0)
{
    global $conf;
    if (! preg_match('/(\.png|\.gif)$/i',$picto)) $picto.='.png';
    if ($pictoisfullpath) return '<img src="'.$picto.'" border="0" alt="'.dol_escape_htmltag($alt).'" title="'.dol_escape_htmltag($alt).'"'.($options?' '.$options:'').'>';
    if (! empty($conf->global->MAIN_MODULE_CAN_OVERWRITE_COMMONICONS) && file_exists(DOL_DOCUMENT_ROOT.'/theme/'.$conf->theme.'/'.$picto)) return '<img src="'.DOL_URL_ROOT.'/theme/'.$conf->theme.'/'.$picto.'" border="0" alt="'.dol_escape_htmltag($alt).'" title="'.dol_escape_htmltag($alt).'"'.($options?' '.$options:'').'>';
    return '<img src="'.DOL_URL_ROOT.'/theme/common/'.$picto.'" border="0" alt="'.dol_escape_htmltag($alt).'" title="'.dol_escape_htmltag($alt).'"'.($options?' '.$options:'').'>';
}

/**
 *	Show logo action
 *
 *	@param      alt         Text for image alt and title
 *	@param      numaction   Action to show
 *	@return     string      Return an img tag
 */
function img_action($alt = "default", $numaction)
{
    global $conf,$langs;
    if ($alt=="default") {
        if ($numaction == -1) $alt=$langs->trans("ChangeDoNotContact");
        if ($numaction == 0)  $alt=$langs->trans("ChangeNeverContacted");
        if ($numaction == 1)  $alt=$langs->trans("ChangeToContact");
        if ($numaction == 2)  $alt=$langs->trans("ChangeContactInProcess");
        if ($numaction == 3)  $alt=$langs->trans("ChangeContactDone");
    }
    return '<img src="'.DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/stcomm'.$numaction.'.png" border="0" alt="'.dol_escape_htmltag($alt).'" title="'.dol_escape_htmltag($alt).'">';
}

/**
 *  Show pdf logo
 *
 *  @param      alt         Texte sur le alt de l'image
 *  @param      $size       Taille de l'icone : 3 = 16x16px , 2 = 14x14px
 *  @return     string      Retourne tag img
 */
function img_pdf($alt = "default",$size=3)
{
    global $conf,$langs;
    if ($alt=="default") $alt=$langs->trans("Show");
    return '<img src="'.DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/pdf'.$size.'.png" border="0" alt="'.dol_escape_htmltag($alt).'" title="'.dol_escape_htmltag($alt).'">';
}

/**
 *	Show logo +
 *
 *	@param      alt         Texte sur le alt de l'image
 *	@return     string      Retourne tag img
 */
function img_edit_add($alt = "default")
{
    global $conf,$langs;
    if ($alt=="default") $alt=$langs->trans("Add");
    return img_picto($alt,'edit_add.png');
}
/**
 *	Show logo -
 *
 *	@param      alt         Texte sur le alt de l'image
 *	@return     string      Retourne tag img
 */
function img_edit_remove($alt = "default")
{
    global $conf,$langs;
    if ($alt=="default") $alt=$langs->trans("Remove");
    return img_picto($alt,'edit_remove.png');
}

/**
 *	Show logo editer/modifier fiche
 *
 *	@param      alt         Texte sur le alt de l'image
 *	@param      float       Si il faut y mettre le style "float: right"
 *	@param      other		Add more attributes on img
 *	@return     string      Retourne tag img
 */
function img_edit($alt = "default", $float=0, $other='')
{
    global $conf,$langs;
    if ($alt=="default") $alt=$langs->trans("Modify");
    $img='<img src="'.DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/edit.png" border="0" alt="'.dol_escape_htmltag($alt).'" title="'.dol_escape_htmltag($alt).'"';
    if ($float) $img.=' style="float: right"';
    if ($other) $img.=' '.$other;
    $img.='>';
    return $img;
}

/**
 *	Show logo view card
 *
 *	@param      alt         Texte sur le alt de l'image
 *	@param      float       Si il faut y mettre le style "float: right"
 *	@param      other		Add more attributes on img
 *	@return     string      Retourne tag img
 */
function img_view($alt = "default", $float=0, $other='')
{
    global $conf,$langs;
    if ($alt=="default") $alt=$langs->trans("View");
    $img='<img src="'.DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/view.png" border="0" alt="'.dol_escape_htmltag($alt).'" title="'.dol_escape_htmltag($alt).'"';
    if ($float) $img.=' style="float: right"';
    if ($other) $img.=' '.$other;
    $img.='>';
    return $img;
}

/**
 *  Show delete logo
 *
 *  @param      alt         Texte sur le alt de l'image
 *	@param     other      Add more attributes on img
 *  @return     string      Retourne tag img
 */
function img_delete($alt = "default", $other='')
{
    global $conf,$langs;
    if ($alt=="default") $alt=$langs->trans("Delete");
    return img_picto($alt,'delete.png',$other);
}


/**
 *	Show help logo with cursor "?"
 *
 * 	@param		usehelpcursor
 * 	@param		usealttitle		Texte to use as alt title
 * 	@return     string      	Retourne tag img
 */
function img_help($usehelpcursor=1,$usealttitle=1)
{
    global $conf,$langs;
    $s ='<img ';
    if ($usehelpcursor) $s.='style="cursor: help;" ';
    $s.='src="'.DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/info.png" border="0"';
    if ($usealttitle)
    {
        if (is_string($usealttitle)) $s.=' alt="'.dol_escape_htmltag($usealttitle).'" title="'.dol_escape_htmltag($usealttitle).'"';
        else $s.=' alt="'.$langs->trans("Info").'" title="'.$langs->trans("Info").'"';
    }
    else $s.=' alt=""';
    $s.='>';
    return $s;
}

/**
 *	Affiche logo info
 *
 *	@param      alt         Texte sur le alt de l'image
 *	@return     string      Retourne tag img
 */
function img_info($alt = "default")
{
    global $conf,$langs;
    if ($alt=="default") $alt=$langs->trans("Informations");
    return img_picto($alt,'info.png');
}

/**
 *	Affiche logo warning
 *
 *	@param      alt         Texte sur le alt de l'image
 *	@param      float       Si il faut afficher le style "float: right"
 *	@return     string      Retourne tag img
 */
function img_warning($alt = "default",$float=0)
{
    global $conf,$langs;
    if ($alt=="default") $alt=$langs->trans("Warning");
    return img_picto($alt,'warning.png',$float?'style="float: right"':'');
}

/**
 *  Affiche logo error
 *
 *  @param      alt         Texte sur le alt de l'image
 *  @return     string      Retourne tag img
 */
function img_error($alt = "default")
{
    global $conf,$langs;
    if ($alt=="default") $alt=$langs->trans("Error");
    return img_picto($alt,'error.png');
}

/**
 *	Affiche logo telephone
 *
 *	@param      alt         Texte sur le alt de l'image
 *	@param		option		Choose of logo
 *	@return     string      Retourne tag img
 */
function img_phone($alt = "default",$option=0)
{
    global $conf,$langs;
    if ($alt=="default") $alt=$langs->trans("Call");
    $img='call_out';
    if ($option == 1) $img='call';
    $img='object_commercial';
    return '<img src="'.DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/'.$img.'.png" border="0" alt="'.dol_escape_htmltag($alt).'" title="'.dol_escape_htmltag($alt).'">';
}


/**
 *	Affiche logo suivant
 *
 *	@param      alt         Texte sur le alt de l'image
 *	@return     string      Retourne tag img
 */
function img_next($alt = "default")
{
    global $conf,$langs;
    if ($alt=="default") {
        $alt=$langs->trans("Next");
    }
    return '<img src="'.DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/next.png" border="0" alt="'.dol_escape_htmltag($alt).'" title="'.dol_escape_htmltag($alt).'">';
}

/**
 *	Affiche logo precedent
 *
 *	@param      alt     Texte sur le alt de l'image
 *	@return     string      Retourne tag img
 */
function img_previous($alt = "default")
{
    global $conf,$langs;
    if ($alt=="default") $alt=$langs->trans("Previous");
    return '<img src="'.DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/previous.png" border="0" alt="'.dol_escape_htmltag($alt).'" title="'.dol_escape_htmltag($alt).'">';
}

/**
 *	Show logo down arrow
 *
 *	@param      alt         Texte sur le alt de l'image
 *	@param      selected    Affiche version "selected" du logo
 *	@return     string      Retourne tag img
 */
function img_down($alt = "default", $selected=0)
{
    global $conf,$langs;
    if ($alt=="default") $alt=$langs->trans("Down");
    if ($selected) return '<img src="'.DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/1downarrow_selected.png" border="0" alt="'.dol_escape_htmltag($alt).'" title="'.dol_escape_htmltag($alt).'" class="imgdown">';
    else return '<img src="'.DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/1downarrow.png" border="0" alt="'.dol_escape_htmltag($alt).'" title="'.dol_escape_htmltag($alt).'" class="imgdown">';
}

/**
 *	Show logo top arrow
 *
 *	@param      alt         Texte sur le alt de l'image
 *	@param      selected    Affiche version "selected" du logo
 *	@return     string      Retourne tag img
 */
function img_up($alt = "default", $selected=0)
{
    global $conf,$langs;
    if ($alt=="default") $alt=$langs->trans("Up");
    if ($selected) return '<img src="'.DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/1uparrow_selected.png" border="0" alt="'.dol_escape_htmltag($alt).'" title="'.dol_escape_htmltag($alt).'" class="imgup">';
    else return '<img src="'.DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/1uparrow.png" border="0" alt="'.dol_escape_htmltag($alt).'" title="'.dol_escape_htmltag($alt).'" class="imgup">';
}

/**
 *	Affiche logo gauche
 *
 *	@param      alt         Texte sur le alt de l'image
 *	@param      selected    Affiche version "selected" du logo
 *	@return     string      Retourne tag img
 */
function img_left($alt = "default", $selected=0)
{
    global $conf,$langs;
    if ($alt=="default") $alt=$langs->trans("Left");
    if ($selected) return '<img src="'.DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/1leftarrow_selected.png" border="0" alt="'.dol_escape_htmltag($alt).'" title="'.dol_escape_htmltag($alt).'">';
    else return '<img src="'.DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/1leftarrow.png" border="0" alt="'.dol_escape_htmltag($alt).'" title="'.dol_escape_htmltag($alt).'">';
}

/**
 *	Affiche logo droite
 *
 *	@param      alt         Texte sur le alt de l'image
 *	@param      selected    Affiche version "selected" du logo
 *	@return     string      Retourne tag img
 */
function img_right($alt = "default", $selected=0)
{
    global $conf,$langs;
    if ($alt=="default") $alt=$langs->trans("Right");
    if ($selected) return '<img src="'.DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/1rightarrow_selected.png" border="0" alt="'.dol_escape_htmltag($alt).'" title="'.dol_escape_htmltag($alt).'">';
    else return '<img src="'.DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/1rightarrow.png" border="0" alt="'.dol_escape_htmltag($alt).'" title="'.dol_escape_htmltag($alt).'">';
}

/**
 *	Affiche le logo tick si allow
 *
 *	@param      allow       Authorise ou non
 *	@param      alt			Alt text for img
 *	@return     string      Retourne tag img
 */
function img_allow($allow,$alt='default')
{
    global $conf,$langs;
    if ($alt=="default") $alt=$langs->trans("Active");

    if ($allow == 1)
    {
        return '<img src="'.DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/tick.png" border="0" alt="'.dol_escape_htmltag($alt).'" title="'.dol_escape_htmltag($alt).'">';
    }
    else
    {
        return "-";
    }
}


/**
 *	Show MIME img of a file
 *	@param      file		Filename
 * 	@param		alt			Alternate text to show on img mous hover
 *	@return     string     	Return img tag
 */
function img_mime($file,$alt='')
{
    require_once(DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php');

    $mimetype=dol_mimetype($file,'',1);
    $mimeimg=dol_mimetype($file,'',2);

    if (empty($alt)) $alt='Mime type: '.$mimetype;

    return '<img src="'.DOL_URL_ROOT.'/theme/common/mime/'.$mimeimg.'" border="0" alt="'.$alt.'" title="'.$alt.'">';
}


/**
 *	Show information for admin users
 *	@param      text			Text info
 *	@param      infoonimgalt	Info is shown only on alt of star picto, otherwise it is show on output after the star picto
 *	@return		string			String with info text
 */
function info_admin($text,$infoonimgalt=0)
{
    global $conf,$langs;
    $s='';
    if ($infoonimgalt)
    {
        $s.=img_picto($text,'star');
    }
    else
    {
        $s.='<div class="info">';
        $s.=img_picto($langs->trans("InfoAdmin"),'star');
        $s.=' ';
        $s.=$text;
        $s.='</div>';
    }
    return $s;
}


/**
 *	Check permissions of a user to show a page and an object. Check read permission.
 * 	If GETPOST('action') defined, we also check write and delete permission.
 *
 *	@param      user      	  	User to check
 *	@param      features	    Features to check (in most cases, it's module name)
 *	@param      objectid      	Object ID if we want to check permission on a particular record (optionnal)
 *	@param      dbtablename    	Table name where object is stored. Not used if objectid is null (optionnal)
 *	@param      feature2		Feature to check, second level of permission (optionnal)
 *  @param      dbt_keyfield    Field name for socid foreign key if not fk_soc (optionnal)
 *  @param      dbt_select      Field name for select if not rowid (optionnal)
 *  @param		objcanvas		Object canvas
 * 	@return		int				Always 1, die process if not allowed
 */
function restrictedArea($user, $features='societe', $objectid=0, $dbtablename='', $feature2='', $dbt_keyfield='fk_soc', $dbt_select='rowid', $objcanvas=null)
{
    global $db, $conf;

    //dol_syslog("functions.lib:restrictedArea $feature, $objectid, $dbtablename,$feature2,$dbt_socfield,$dbt_select");
    //print "user_id=".$user->id.", features=".$features.", feature2=".$feature2.", objectid=".$objectid;
    //print ", dbtablename=".$dbtablename.", dbt_socfield=".$dbt_keyfield.", dbt_select=".$dbt_select;
    //print ", perm: ".$features."->".$feature2."=".$user->rights->$features->$feature2->lire."<br>";

    // If we use canvas, we try to use function that overlod restrictarea if provided with canvas
    if (is_object($objcanvas))
    {
	    if (method_exists($objcanvas->control,'restrictedArea')) return $objcanvas->control->restrictedArea($user,$features,$objectid,$dbtablename,$feature2,$dbt_keyfield,$dbt_select);
    }

    if ($dbt_select != 'rowid') $objectid = "'".$objectid."'";

    // More features to check
    $features = explode("&",$features);
    //var_dump($features);

    // Check read permission from module
    // TODO Replace "feature" param into caller by first level of permission
    $readok=1;
    foreach ($features as $feature)
    {
        if ($feature == 'societe')
        {
            if (! $user->rights->societe->lire && ! $user->rights->fournisseur->lire) $readok=0;
        }
        else if ($feature == 'contact')
        {
            if (! $user->rights->societe->contact->lire) $readok=0;
        }
        else if ($feature == 'produit|service')
        {
            if (! $user->rights->produit->lire && ! $user->rights->service->lire) $readok=0;
        }
        else if ($feature == 'prelevement')
        {
            if (! $user->rights->prelevement->bons->lire) $readok=0;
        }
        else if ($feature == 'commande_fournisseur')
        {
            if (! $user->rights->fournisseur->commande->lire) $readok=0;
        }
        else if ($feature == 'cheque')
        {
            if (! $user->rights->banque->cheque) $readok=0;
        }
        else if ($feature == 'projet')
        {
            if (! $user->rights->projet->lire && ! $user->rights->projet->all->lire) $readok=0;
        }
        else if (! empty($feature2))	// This should be used for future changes
        {
            if (empty($user->rights->$feature->$feature2->lire)
            && empty($user->rights->$feature->$feature2->read)) $readok=0;
        }
        else if (! empty($feature) && ($feature!='user' && $feature!='usergroup'))		// This is for old permissions
        {
            if (empty($user->rights->$feature->lire)
            && empty($user->rights->$feature->read)
            && empty($user->rights->$feature->run)) $readok=0;
        }
    }

    if (! $readok)
    {
        //print "Read access is down";
        accessforbidden();
    }
    //print "Read access is ok";

    // Check write permission from module
    $createok=1;
    if (GETPOST("action") && GETPOST("action")  == 'create')
    {
        foreach ($features as $feature)
        {
            if ($feature == 'contact')
            {
                if (! $user->rights->societe->contact->creer) $createok=0;
            }
            else if ($feature == 'produit|service')
            {
                if (! $user->rights->produit->creer && ! $user->rights->service->creer) $createok=0;
            }
            else if ($feature == 'prelevement')
            {
                if (! $user->rights->prelevement->bons->creer) $createok=0;
            }
            else if ($feature == 'commande_fournisseur')
            {
                if (! $user->rights->fournisseur->commande->creer) $createok=0;
            }
            else if ($feature == 'banque')
            {
                if (! $user->rights->banque->modifier) $createok=0;
            }
            else if ($feature == 'cheque')
            {
                if (! $user->rights->banque->cheque) $createok=0;
            }
            else if (! empty($feature2))	// This should be used for future changes
            {
                if (empty($user->rights->$feature->$feature2->creer)
                && empty($user->rights->$feature->$feature2->write)) $createok=0;
            }
            else if (! empty($feature))		// This is for old permissions
            {
                //print '<br>feature='.$feature.' creer='.$user->rights->$feature->creer.' write='.$user->rights->$feature->write;
                if (empty($user->rights->$feature->creer)
                && empty($user->rights->$feature->write)) $createok=0;
            }
        }

        if (! $createok) accessforbidden();
        //print "Write access is ok";
    }

    // Check create user permission
    $createuserok=1;
    if ( GETPOST("action") && (GETPOST("action") == 'confirm_create_user' && GETPOST("confirm") == 'yes') )
    {
        if (! $user->rights->user->user->creer) $createuserok=0;

        if (! $createuserok) accessforbidden();
        //print "Create user access is ok";
    }

    // Check delete permission from module
    $deleteok=1;
    if ( GETPOST("action") && ( (GETPOST("action")  == 'confirm_delete' && GETPOST("confirm") && GETPOST("confirm") == 'yes') || GETPOST("action")  == 'delete') )
    {
        foreach ($features as $feature)
        {
            if ($feature == 'contact')
            {
                if (! $user->rights->societe->contact->supprimer) $deleteok=0;
            }
            else if ($feature == 'produit|service')
            {
                if (! $user->rights->produit->supprimer && ! $user->rights->service->supprimer) $deleteok=0;
            }
            else if ($feature == 'commande_fournisseur')
            {
                if (! $user->rights->fournisseur->commande->supprimer) $deleteok=0;
            }
            else if ($feature == 'banque')
            {
                if (! $user->rights->banque->modifier) $deleteok=0;
            }
            else if ($feature == 'cheque')
            {
                if (! $user->rights->banque->cheque) $deleteok=0;
            }
            else if ($feature == 'ecm')
            {
                if (! $user->rights->ecm->upload) $deleteok=0;
            }
            else if ($feature == 'ftp')
            {
                if (! $user->rights->ftp->write) $deleteok=0;
            }
            else if (! empty($feature2))	// This should be used for future changes
            {
                if (empty($user->rights->$feature->$feature2->supprimer)
                && empty($user->rights->$feature->$feature2->delete)) $deleteok=0;
            }
            else if (! empty($feature))		// This is for old permissions
            {
                //print '<br>feature='.$feature.' creer='.$user->rights->$feature->supprimer.' write='.$user->rights->$feature->delete;
                if (empty($user->rights->$feature->supprimer)
                && empty($user->rights->$feature->delete)) $deleteok=0;
            }
        }

        //print "Delete access is ko";
        if (! $deleteok) accessforbidden();
        //print "Delete access is ok";
    }

    // If we have a particular object to check permissions on, we check this object
    // is linked to a company allowed to $user.
    if (! empty($objectid) && $objectid > 0)
    {
        foreach ($features as $feature)
        {
            $sql='';

            $check = array('banque','user','usergroup','produit','service','produit|service','categorie'); // Test on entity only (Objects with no link to company)
            $checksoc = array('societe');	 // Test for societe object
            $checkother = array('contact');	 // Test on entity and link to societe. Allowed if link is empty (Ex: contacts...).
            $checkproject = array('projet'); // Test for project object
            $nocheck = array('barcode','stock','fournisseur');	// No test
            $checkdefault = 'all other not already defined'; // Test on entity and link to third party. Not allowed if link is empty (Ex: invoice, orders...).

            // If dbtable not defined, we use same name for table than module name
            if (empty($dbtablename)) $dbtablename = $feature;

            // Check permission for object with entity
            if (in_array($feature,$check))
            {
                $sql = "SELECT dbt.".$dbt_select;
                $sql.= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
                $sql.= " WHERE dbt.".$dbt_select." = ".$objectid;
                if (($feature == 'user' || $feature == 'usergroup') && ! empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && ! $user->entity)
                {
                	$sql.= " AND dbt.entity IS NOT NULL";
                }
                else
                {
                	$sql.= " AND dbt.entity IN (0,".(! empty($conf->entities[$dbtablename]) ? $conf->entities[$dbtablename] : $conf->entity).")";
                }
            }
            else if (in_array($feature,$checksoc))
            {
                // If external user: Check permission for external users
                if ($user->societe_id > 0)
                {
                    if ($user->societe_id <> $objectid) accessforbidden();
                }
                // If internal user: Check permission for internal users that are restricted on their objects
                else if (! $user->rights->societe->client->voir)
                {
                    $sql = "SELECT sc.fk_soc";
                    $sql.= " FROM (".MAIN_DB_PREFIX."societe_commerciaux as sc";
                    $sql.= ", ".MAIN_DB_PREFIX."societe as s)";
                    $sql.= " WHERE sc.fk_soc = ".$objectid;
                    $sql.= " AND sc.fk_user = ".$user->id;
                    $sql.= " AND sc.fk_soc = s.rowid";
                    $sql.= " AND s.entity IN (0,".(! empty($conf->entities[$dbtablename]) ? $conf->entities[$dbtablename] : $conf->entity).")";
                }
                // If multicompany and internal users with all permissions, check user is in correct entity
                else if (! empty($conf->multicompany->enabled))
                {
                    $sql = "SELECT s.rowid";
                    $sql.= " FROM ".MAIN_DB_PREFIX."societe as s";
                    $sql.= " WHERE s.rowid = ".$objectid;
                    $sql.= " AND s.entity IN (0,".(! empty($conf->entities[$dbtablename]) ? $conf->entities[$dbtablename] : $conf->entity).")";
                }
            }
            else if (in_array($feature,$checkother))
            {
                // If external user: Check permission for external users
                if ($user->societe_id > 0)
                {
                    $sql = "SELECT dbt.rowid";
                    $sql.= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
                    $sql.= " WHERE dbt.rowid = ".$objectid;
                    $sql.= " AND dbt.fk_soc = ".$user->societe_id;
                }
                // If internal user: Check permission for internal users that are restricted on their objects
                else if (! $user->rights->societe->client->voir)
                {
                    $sql = "SELECT dbt.rowid";
                    $sql.= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
                    $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON dbt.fk_soc = sc.fk_soc AND sc.fk_user = '".$user->id."'";
                    $sql.= " WHERE dbt.rowid = ".$objectid;
                    $sql.= " AND (dbt.fk_soc IS NULL OR sc.fk_soc IS NOT NULL)";	// Contact not linked to a company or to a company of user
                    $sql.= " AND dbt.entity IN (0,".(! empty($conf->entities[$dbtablename]) ? $conf->entities[$dbtablename] : $conf->entity).")";
                }
                // If multicompany and internal users with all permissions, check user is in correct entity
                else if (! empty($conf->multicompany->enabled))
                {
                    $sql = "SELECT dbt.rowid";
                    $sql.= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
                    $sql.= " WHERE dbt.rowid = ".$objectid;
                    $sql.= " AND dbt.entity IN (0,".(! empty($conf->entities[$dbtablename]) ? $conf->entities[$dbtablename] : $conf->entity).")";
                }
            }
            else if (in_array($feature,$checkproject))
            {
                if (! $user->rights->projet->all->lire)
                {
                    include_once(DOL_DOCUMENT_ROOT."/projet/class/project.class.php");
                    $projectstatic=new Project($db);
                    $tmps=$projectstatic->getProjectsAuthorizedForUser($user,0,1,$user->societe_id);
                    $tmparray=explode(',',$tmps);
                    if (! in_array($objectid,$tmparray)) accessforbidden();
                }
            }
            else if (! in_array($feature,$nocheck))	// By default we check with link to third party
            {
                // If external user: Check permission for external users
                if ($user->societe_id > 0)
                {
                    $sql = "SELECT dbt.".$dbt_keyfield;
                    $sql.= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
                    $sql.= " WHERE dbt.rowid = ".$objectid;
                    $sql.= " AND dbt.".$dbt_keyfield." = ".$user->societe_id;
                }
                // If internal user: Check permission for internal users that are restricted on their objects
                else if (! $user->rights->societe->client->voir)
                {
                    $sql = "SELECT sc.fk_soc";
                    $sql.= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
                    $sql.= ", ".MAIN_DB_PREFIX."societe as s";
                    $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
                    $sql.= " WHERE dbt.".$dbt_select." = ".$objectid;
                    $sql.= " AND sc.fk_soc = dbt.".$dbt_keyfield;
                    $sql.= " AND dbt.".$dbt_keyfield." = s.rowid";
                    $sql.= " AND s.entity IN (0,".(! empty($conf->entities[$dbtablename]) ? $conf->entities[$dbtablename] : $conf->entity).")";
                    $sql.= " AND sc.fk_user = ".$user->id;
                }
                // If multicompany and internal users with all permissions, check user is in correct entity
                else if (! empty($conf->multicompany->enabled))
                {
                    $sql = "SELECT dbt.".$dbt_select;
                    $sql.= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
                    $sql.= " WHERE dbt.".$dbt_select." = ".$objectid;
                    $sql.= " AND dbt.entity IN (0,".(! empty($conf->entities[$dbtablename]) ? $conf->entities[$dbtablename] : $conf->entity).")";
                }
            }

            //print $sql."<br>";
            if ($sql)
            {
                $resql=$db->query($sql);
                if ($resql)
                {
                    if ($db->num_rows($resql) == 0)	accessforbidden();
                }
                else
                {
                    dol_syslog("functions.lib:restrictedArea sql=".$sql, LOG_ERR);
                    accessforbidden();
                }
            }
        }
    }

    return 1;
}


/**
 *	Show a message to say access is forbidden and stop program
 *	Calling this function terminate execution of PHP.
 *	@param		message			    Force error message
 *	@param		printheader		    Show header before
 *  @param      printfooter         Show footer after
 *  @param      showonlymessage     Show only message parameter. Otherwise add more information.
 */
function accessforbidden($message='',$printheader=1,$printfooter=1,$showonlymessage=0)
{
    global $conf, $db, $user, $langs;
    if (! is_object($langs))
    {
        include_once(DOL_DOCUMENT_ROOT.'/core/class/translate.class.php');
        $langs=new Translate('',$conf);
    }

    $langs->load("errors");

    if ($printheader)
    {
        if (function_exists("llxHeader")) llxHeader('');
        else if (function_exists("llxHeaderVierge")) llxHeaderVierge('');
    }
    print '<div class="error">';
    if (! $message) print $langs->trans("ErrorForbidden");
    else print $message;
    print '</div>';
    print '<br>';
    if (empty($showonlymessage))
    {
        if ($user->login)
        {
            print $langs->trans("CurrentLogin").': <font class="error">'.$user->login.'</font><br>';
            print $langs->trans("ErrorForbidden2",$langs->trans("Home"),$langs->trans("Users"));
        }
        else
        {
            print $langs->trans("ErrorForbidden3");
        }
    }
    if ($printfooter && function_exists("llxFooter")) llxFooter();
    exit(0);
}


/* For backward compatibility */
function dolibarr_print_error($db='',$error='')
{
    return dol_print_error($db, $error);
}

/**
 *	Affiche message erreur system avec toutes les informations pour faciliter le diagnostic et la remontee des bugs.
 *	On doit appeler cette fonction quand une erreur technique bloquante est rencontree.
 *	Toutefois, il faut essayer de ne l'appeler qu'au sein de pages php, les classes devant
 *	renvoyer leur erreur par l'intermediaire de leur propriete "error".
 *	@param      db      	Database handler
 *	@param      error		String or array of errors strings to show
 *  @see        dol_htmloutput_errors
 */
function dol_print_error($db='',$error='')
{
    global $conf,$langs,$argv;
    global $dolibarr_main_prod;

    $out = '';
    $syslog = '';

    // Si erreur intervenue avant chargement langue
    if (! $langs)
    {
        require_once(DOL_DOCUMENT_ROOT ."/core/class/translate.class.php");
        $langs = new Translate("", $conf);
        $langs->load("main");
    }
    $langs->load("main");
    $langs->load("errors");

    if ($_SERVER['DOCUMENT_ROOT'])    // Mode web
    {
        $out.=$langs->trans("DolibarrHasDetectedError").".<br>\n";
        if (! empty($conf->global->MAIN_FEATURES_LEVEL))
        $out.="You use an experimental level of features, so please do NOT report any bugs, anywhere, until going back to MAIN_FEATURES_LEVEL = 0.<br>\n";
        $out.=$langs->trans("InformationToHelpDiagnose").":<br>\n";

        $out.="<b>".$langs->trans("Date").":</b> ".dol_print_date(time(),'dayhourlog')."<br>\n";;
        $out.="<b>".$langs->trans("Dolibarr").":</b> ".DOL_VERSION."<br>\n";;
        if (isset($conf->global->MAIN_FEATURES_LEVEL)) $out.="<b>".$langs->trans("LevelOfFeature").":</b> ".$conf->global->MAIN_FEATURES_LEVEL."<br>\n";;
        if (function_exists("phpversion"))
        {
            $out.="<b>".$langs->trans("PHP").":</b> ".phpversion()."<br>\n";
            //phpinfo();       // This is to show location of php.ini file
        }
        $out.="<b>".$langs->trans("Server").":</b> ".$_SERVER["SERVER_SOFTWARE"]."<br>\n";;
        $out.="<br>\n";
        $out.="<b>".$langs->trans("RequestedUrl").":</b> ".$_SERVER["REQUEST_URI"]."<br>\n";;
        $out.="<b>".$langs->trans("Referer").":</b> ".(isset($_SERVER["HTTP_REFERER"])?$_SERVER["HTTP_REFERER"]:'')."<br>\n";;
        $out.="<b>".$langs->trans("MenuManager").":</b> ".$conf->top_menu."<br>\n";
        $out.="<br>\n";
        $syslog.="url=".$_SERVER["REQUEST_URI"];
        $syslog.=", query_string=".$_SERVER["QUERY_STRING"];
    }
    else                              // Mode CLI
    {
        $out.='> '.$langs->transnoentities("ErrorInternalErrorDetected").":\n".$argv[0]."\n";
        $syslog.="pid=".getmypid();
    }

    if (is_object($db))
    {
        if ($_SERVER['DOCUMENT_ROOT'])  // Mode web
        {
            $out.="<b>".$langs->trans("DatabaseTypeManager").":</b> ".$db->type."<br>\n";
            $out.="<b>".$langs->trans("RequestLastAccessInError").":</b> ".($db->lastqueryerror()?$db->lastqueryerror():$langs->trans("ErrorNoRequestInError"))."<br>\n";
            $out.="<b>".$langs->trans("ReturnCodeLastAccessInError").":</b> ".($db->lasterrno()?$db->lasterrno():$langs->trans("ErrorNoRequestInError"))."<br>\n";
            $out.="<b>".$langs->trans("InformationLastAccessInError").":</b> ".($db->lasterror()?$db->lasterror():$langs->trans("ErrorNoRequestInError"))."<br>\n";
            $out.="<br>\n";
        }
        else                            // Mode CLI
        {
            $out.='> '.$langs->transnoentities("DatabaseTypeManager").":\n".$db->type."\n";
            $out.='> '.$langs->transnoentities("RequestLastAccessInError").":\n".($db->lastqueryerror()?$db->lastqueryerror():$langs->trans("ErrorNoRequestInError"))."\n";
            $out.='> '.$langs->transnoentities("ReturnCodeLastAccessInError").":\n".($db->lasterrno()?$db->lasterrno():$langs->trans("ErrorNoRequestInError"))."\n";
            $out.='> '.$langs->transnoentities("InformationLastAccessInError").":\n".($db->lasterror()?$db->lasterror():$langs->trans("ErrorNoRequestInError"))."\n";

        }
        $syslog.=", sql=".$db->lastquery();
        $syslog.=", db_error=".$db->lasterror();
    }

    if ($error)
    {
        $langs->load("errors");

        if (is_array($error)) $errors=$error;
        else $errors=array($error);

        foreach($errors as $msg)
        {
            $msg=$langs->trans($msg);
            if ($_SERVER['DOCUMENT_ROOT'])  // Mode web
            {
                $out.="<b>".$langs->trans("Message").":</b> ".$msg."<br>\n" ;
            }
            else                            // Mode CLI
            {
                $out.='> '.$langs->transnoentities("Message").":\n".$msg."\n" ;
            }
            $syslog.=", msg=".$msg;
        }
    }
    if (empty($dolibarr_main_prod) && $_SERVER['DOCUMENT_ROOT'] && function_exists('xdebug_call_file'))
    {
        xdebug_print_function_stack();
        $out.='<b>XDebug informations:</b>'."<br>\n";
        $out.='File: '.xdebug_call_file()."<br>\n";
        $out.='Line: '.xdebug_call_line()."<br>\n";
        $out.='Function: '.xdebug_call_function()."<br>\n";
        $out.="<br>\n";
    }

    if (empty($dolibarr_main_prod)) print $out;
    else define("MAIN_CORE_ERROR", 1);
    //else print 'Sorry, an error occured but the parameter $dolibarr_main_prod is defined in conf file so no message is reported to your browser. Please read the log file for error message.';
    dol_syslog("Error ".$syslog, LOG_ERR);
}

/**
 * Show email to contact if technical error
 */
function dol_print_error_email()
{
    global $langs,$conf;

    $langs->load("errors");
    print '<br><div class="error">'.$langs->trans("ErrorContactEMail",$conf->global->MAIN_INFO_SOCIETE_MAIL,'ERRORNEWPAYMENT'.dol_print_date(mktime(),'%Y%m%d')).'</div>';
}

/**
 *	Show title line of an array
 *
 *	@param	    name        Label of field
 *	@param	    file        Url used when we click on sort picto
 *	@param	    field       Field to use for new sorting
 *	@param	    begin       ("" by defaut)
 *	@param	    moreparam   Add more parameters on sort url links ("" by default)
 *	@param      td          Options of attribute td ("" by defaut)
 *	@param      sortfield   Current field used to sort
 *	@param      sortorder   Current sort order
 */
function print_liste_field_titre($name, $file="", $field="", $begin="", $moreparam="", $td="", $sortfield="", $sortorder="")
{
	print getTitleFieldOfList($name, 0, $file, $field, $begin, $moreparam, $td, $sortfield, $sortorder);
}

/**
 *	Get title line of an array
 *
 *	@param	    name        Label of field
 *	@param		thead		For thead format
 *	@param	    file        Url used when we click on sort picto
 *	@param	    field       Field to use for new sorting
 *	@param	    begin       ("" by defaut)
 *	@param	    moreparam   Add more parameters on sort url links ("" by default)
 *	@param      moreattrib  Add more attributes on th ("" by defaut)
 *	@param      sortfield   Current field used to sort
 *	@param      sortorder   Current sort order
 */
function getTitleFieldOfList($name, $thead=0, $file="", $field="", $begin="", $moreparam="", $moreattrib="", $sortfield="", $sortorder="")
{
    global $conf;
    //print "$name, $file, $field, $begin, $options, $moreattrib, $sortfield, $sortorder<br>\n";

    $out='';
	// If field is used as sort criteria we use a specific class
    // Example if (sortfield,field)=("nom","xxx.nom") or (sortfield,field)=("nom","nom")
    if ($field && ($sortfield == $field || $sortfield == preg_replace("/^[^\.]+\./","",$field)))
    {
        $out.= '<th class="liste_titre_sel" '. $moreattrib.'>';
    }
    else
    {
        $out.= '<th class="liste_titre" '. $moreattrib.'>';
    }
    $out.=$name;

    if (empty($thead) && $field)    // If this is a sort field
    {
        $options=preg_replace('/sortfield=([a-zA-Z0-9,\s\.]+)/i','',$moreparam);
        $options=preg_replace('/sortorder=([a-zA-Z0-9,\s\.]+)/i','',$options);
        $options=preg_replace('/&+/i','&',$options);
        if (! preg_match('/^&/',$options)) $options='&'.$options;

        //print "&nbsp;";
        $out.= '<img width="2" src="'.DOL_URL_ROOT.'/theme/common/transparent.png" alt="">';
        if (! $sortorder)
        {
            $out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",0).'</a>';
            $out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",0).'</a>';
        }
        else
        {
            if ($field != $sortfield)
            {
                $out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",0).'</a>';
                $out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",0).'</a>';
            }
            else {
                $sortorder=strtoupper($sortorder);
                if ($sortorder == 'DESC' ) {
                    $out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",0).'</a>';
                    $out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",1).'</a>';
                }
                if ($sortorder == 'ASC' ) {
                    $out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",1).'</a>';
                    $out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",0).'</a>';
                }
            }
        }
    }
    $out.='</th>';

    return $out;
}

/**
 *	Show a title (deprecated. use print_fiche_titre instrad)
 *	@param	titre			Title to show
 */
function print_titre($titre)
{
    print '<div class="titre">'.$titre.'</div>';
}

/**
 *	Show a title with picto
 *	@param	titre				Title to show
 *	@param	mesg				Added message to show on right
 *	@param	picto				Icon to use before title (should be a 32x32 transparent png file)
 *	@param	pictoisfullpath		1=Icon name is a full absolute url of image
 * 	@param	id					To force an id on html objects
 */
function print_fiche_titre($titre, $mesg='', $picto='title.png', $pictoisfullpath=0, $id='')
{
    print load_fiche_titre($titre, $mesg, $picto, $pictoisfullpath, $id);
}

/**
 *	Load a title with picto
 *
 *	@param	titre				Title to show
 *	@param	mesg				Added message to show on right
 *	@param	picto				Icon to use before title (should be a 32x32 transparent png file)
 *	@param	pictoisfullpath		1=Icon name is a full absolute url of image
 * 	@param	id					To force an id on html objects
 */
function load_fiche_titre($titre, $mesg='', $picto='title.png', $pictoisfullpath=0, $id='')
{
    global $conf;

    $return='';

    if ($picto == 'setup') $picto='title.png';
    if (!empty($conf->browser->ie) && $picto=='title.png') $picto='title.gif';

    $return.= "\n";
    $return.= '<table '.($id?'id="'.$id.'" ':'').'summary="" width="100%" border="0" class="notopnoleftnoright" style="margin-bottom: 2px;"><tr>';
    if ($picto) $return.= '<td class="nobordernopadding hideonsmartphone" width="40" align="left" valign="middle">'.img_picto('',$picto, 'id="pictotitle"', $pictoisfullpath).'</td>';
    $return.= '<td class="nobordernopadding" valign="middle">';
    $return.= '<div class="titre">'.$titre.'</div>';
    $return.= '</td>';
    if (dol_strlen($mesg))
    {
        $return.= '<td class="nobordernopadding" align="right" valign="middle"><b>'.$mesg.'</b></td>';
    }
    $return.= '</tr></table>'."\n";

    return $return;
}

/**
 *	Print a title with navigation controls for pagination
 *
 *	@param	titre				Title to show (required)
 *	@param	page				Numero of page (required)
 *	@param	file				Url of page (required)
 *	@param	options         	parametres complementaires lien ('' par defaut)
 *	@param	sortfield       	champ de tri ('' par defaut)
 *	@param	sortorder       	ordre de tri ('' par defaut)
 *	@param	center          	chaine du centre ('' par defaut)
 *	@param	num					number of records found by select with limit+1
 *	@param	totalnboflines		Total number of records/lines for all pages (if known)
 *	@param	picto				Icon to use before title (should be a 32x32 transparent png file)
 *	@param	pictoisfullpath		1=Icon name is a full absolute url of image
 *	@return	void
 */
function print_barre_liste($titre, $page, $file, $options='', $sortfield='', $sortorder='', $center='', $num=-1, $totalnboflines=0, $picto='title.png', $pictoisfullpath=0)
{
    global $conf,$langs;

    if ($picto == 'setup') $picto='title.png';
    if (!empty($conf->browser->ie) && $picto=='title.png') $picto='title.gif';

    if ($num > $conf->liste_limit or $num == -1)
    {
        $nextpage = 1;
    }
    else
    {
        $nextpage = 0;
    }

    print "\n";
    print "<!-- Begin title '".$titre."' -->\n";
    print '<table width="100%" border="0" class="notopnoleftnoright" style="margin-bottom: 2px;"><tr>';

    $pagelist = '';

    // Left
    if ($page > 0 || $num > $conf->liste_limit)
    {
        if ($totalnboflines)
        {
            if ($picto && $titre) print '<td class="nobordernopadding" width="40" align="left" valign="middle">'.img_picto('',$picto, '', $pictoisfullpath).'</td>';
            print '<td class="nobordernopadding">';
            print '<div class="titre">'.$titre.'</div>';
            print '</td>';

            $maxnbofpage=10;

            $nbpages=ceil($totalnboflines/$conf->liste_limit);
            $cpt=($page-$maxnbofpage);
            if ($cpt < 0) { $cpt=0; }
            $pagelist.=$langs->trans('Page');
            if ($cpt>=1)
            {
                $pagelist.=' <a href="'.$file.'?page=0'.$options.'&amp;sortfield='.$sortfield.'&amp;sortorder='.$sortorder.'">1</a>';
                if ($cpt >= 2) $pagelist.=' ...';
            }
            do
            {
                if($cpt==$page)
                {
                    $pagelist.= ' <u>'.($page+1).'</u>';
                }
                else
                {
                    $pagelist.= ' <a href="'.$file.'?page='.$cpt.$options.'&amp;sortfield='.$sortfield.'&amp;sortorder='.$sortorder.'">'.($cpt+1).'</a>';
                }
                $cpt++;
            }
            while ($cpt < $nbpages && $cpt<=$page+$maxnbofpage);
            if ($cpt<$nbpages)
            {
                if ($cpt<$nbpages-1) $pagelist.= ' ...';
                $pagelist.= ' <a href="'.$file.'?page='.($nbpages-1).$options.'&amp;sortfield='.$sortfield.'&amp;sortorder='.$sortorder.'">'.$nbpages.'</a>';
            }
        }
        else
        {
            if (empty($conf->browser->phone) && $picto && $titre) print '<td class="nobordernopadding" width="40" align="left" valign="middle">'.img_picto('',$picto, '', $pictoisfullpath).'</td>';
            print '<td class="nobordernopadding">';
            print '<div class="titre">'.$titre.'</div>';
            $pagelist.= $langs->trans('Page').' '.($page+1);
            print '</td>';
        }
    }
    else
    {
        if (empty($conf->browser->phone) && $picto && $titre) print '<td class="nobordernopadding" width="40" align="left" valign="middle">'.img_picto('',$picto, '', $pictoisfullpath).'</td>';
        print '<td class="nobordernopadding"><div class="titre">'.$titre.'</div></td>';
    }

    // Center
    if ($center)
    {
        print '<td class="nobordernopadding" align="left" valign="middle">'.$center.'</td>';
    }

    // Right
    print '<td class="nobordernopadding" align="right" valign="middle">';
    if ($sortfield) $options .= "&amp;sortfield=".$sortfield;
    if ($sortorder) $options .= "&amp;sortorder=".$sortorder;
    // Affichage des fleches de navigation
    print_fleche_navigation($page,$file,$options,$nextpage,$pagelist);
    print '</td>';

    print '</tr></table>'."\n";
    print "<!-- End title -->\n\n";
}

/**
 *	Fonction servant a afficher les fleches de navigation dans les pages de listes
 *
 *	@param	int		$page				Numero of page
 *	@param	string	$file				Lien
 *	@param	string	$options         	Autres parametres d'url a propager dans les liens ("" par defaut)
 *	@param	int		$nextpage	    	Faut-il une page suivante
 *	@param	string	$betweenarrows		HTML Content to show between arrows
 *	@return	void
 */
function print_fleche_navigation($page,$file,$options='',$nextpage,$betweenarrows='')
{
    global $conf, $langs;
    if ($page > 0)
    {
        print '<a href="'.$file.'?page='.($page-1).$options.'">'.img_previous($langs->trans("Previous")).'</a>';
    }
    if ($betweenarrows) print ($page > 0?' ':'').$betweenarrows.($nextpage>0?' ':'');
    if ($nextpage > 0)
    {
        print '<a href="'.$file.'?page='.($page+1).$options.'">'.img_next($langs->trans("Next")).'</a>';
    }
}


/**
 *	Return a string with VAT rate label formated for view output
 *	Used into pdf and HTML pages
 *
 *	@param	float	$rate			Rate value to format (19.6 19,6 19.6% 19,6%,...)
 *  @param	boolean	$addpercent		Add a percent % sign in output
 *	@param	int		$info_bits		Miscellanous information on vat (0=Default, 1=French NPR vat)
 *	@param	int		$usestarfornpr	1=Use '*' for NPR vat rate intead of MAIN_LABEL_MENTION_NPR
 *  @return	string					String with formated amounts (19,6 or 19,6% or 8.5% NPR or 8.5% *)
 */
function vatrate($rate,$addpercent=false,$info_bits=0,$usestarfornpr=0)
{
    // Test for compatibility
    if (preg_match('/%/',$rate))
    {
        $rate=str_replace('%','',$rate);
        $addpercent=true;
    }
    if (preg_match('/\*/',$rate) || preg_match('/'.constant('MAIN_LABEL_MENTION_NPR').'/i',$rate))
    {
        $rate=str_replace('*','',$rate);
        $info_bits |= 1;
    }

    $ret=price($rate,0,'',0,0).($addpercent?'%':'');
    if ($info_bits & 1) $ret.=' '.($usestarfornpr?'*':constant('MAIN_LABEL_MENTION_NPR'));
    return $ret;
}


/**
 *		Fonction qui formate un montant pour visualisation
 *		Fonction utilisee dans les pdf et les pages html
 *
 *		@param	float		$amount			Montant a formater
 *		@param	string		$form			Type de formatage, html ou pas (par defaut)
 *		@param	Translate	$outlangs		Objet langs pour formatage text
 *		@param	int			$trunc			1=Tronque affichage si trop de decimales,0=Force le non troncage
 *		@param	int			$rounding		Minimum number of decimal. If not defined we use min($conf->global->MAIN_MAX_DECIMALS_UNIT,$conf->global->MAIN_MAX_DECIMALS_TOTAL)
 *		@param	int			$forcerounding	Force the number of decimal
 *		@return	string						Chaine avec montant formate
 *
 *		@see	price2num					Revert function of price
 */
function price($amount, $form=0, $outlangs='', $trunc=1, $rounding=-1, $forcerounding=-1)
{
    global $langs,$conf;

    // Clean parameters
    if (empty($amount)) $amount=0;	// To have a numeric value if amount not defined or = ''
    if ($rounding < 0) $rounding=min($conf->global->MAIN_MAX_DECIMALS_UNIT,$conf->global->MAIN_MAX_DECIMALS_TOT);

    $nbdecimal=$rounding;

    // Output separators by default (french)
    $dec=','; $thousand=' ';

    // If $outlangs not forced, we use use language
    if (! is_object($outlangs)) $outlangs=$langs;

    if ($outlangs->trans("SeparatorDecimal") != "SeparatorDecimal")  $dec=$outlangs->trans("SeparatorDecimal");
    if ($outlangs->trans("SeparatorThousand")!= "SeparatorThousand") $thousand=$outlangs->trans("SeparatorThousand");
    if ($thousand == 'None') $thousand='';
    //print "amount=".$amount." html=".$form." trunc=".$trunc." nbdecimal=".$nbdecimal." dec='".$dec."' thousand='".$thousand."'<br>";

    //print "amount=".$amount."-";
    $amount = str_replace(',','.',$amount);	// should be useless
    //print $amount."-";
    $datas = explode('.',$amount);
    $decpart = isset($datas[1])?$datas[1]:'';
    $decpart = preg_replace('/0+$/i','',$decpart);	// Supprime les 0 de fin de partie decimale
    //print "decpart=".$decpart."<br>";
    $end='';

    // We increase nbdecimal if there is more decimal than asked (to not loose information)
    if (dol_strlen($decpart) > $nbdecimal) $nbdecimal=dol_strlen($decpart);
    // Si on depasse max
    if ($trunc && $nbdecimal > $conf->global->MAIN_MAX_DECIMALS_SHOWN)
    {
        $nbdecimal=$conf->global->MAIN_MAX_DECIMALS_SHOWN;
        if (preg_match('/\.\.\./i',$conf->global->MAIN_MAX_DECIMALS_SHOWN))
        {
            // Si un affichage est tronque, on montre des ...
            $end='...';
        }
    }

    // If force rounding
    if ($forcerounding >= 0) $nbdecimal = $forcerounding;

    // Format number
    if ($form)
    {
        $output=preg_replace('/\s/','&nbsp;',number_format($amount, $nbdecimal, $dec, $thousand));
    }
    else
    {
        $output=number_format($amount, $nbdecimal, $dec, $thousand);
    }
    $output.=$end;

    return $output;
}

/**
 *	Function that return a number with universal decimal format (decimal separator is '.') from
 *	an amount typed by a user.
 *	Function to use on each input amount before any numeric test or database insert
 *
 *	@param	float	$amount			Amount to convert/clean
 *	@param	string	$rounding		''=No rounding
 * 									'MU'=Round to Max unit price (MAIN_MAX_DECIMALS_UNIT)
 *									'MT'=Round to Max for totals with Tax (MAIN_MAX_DECIMALS_TOT)
 *									'MS'=Round to Max Shown (MAIN_MAX_DECIMALS_SHOWN)
 * 	@param	int		$alreadysqlnb	Put 1 if you know that content is already universal format number
 *	@return	string					Amount with universal numeric format (Example: '99.99999')
 *
 *	@see    price					Opposite function of price2num
 */
function price2num($amount,$rounding='',$alreadysqlnb=0)
{
    global $langs,$conf;

    // Round PHP function does not allow number like '1,234.56' nor '1.234,56' nor '1 234,56'
    // Numbers must be '1234.56'
    // Decimal delimiter for PHP and database SQL requests must be '.'
    $dec=','; $thousand=' ';
    if ($langs->trans("SeparatorDecimal") != "SeparatorDecimal")  $dec=$langs->trans("SeparatorDecimal");
    if ($langs->trans("SeparatorThousand")!= "SeparatorThousand") $thousand=$langs->trans("SeparatorThousand");
    if ($thousand == 'None') $thousand='';
    //print "amount=".$amount." html=".$form." trunc=".$trunc." nbdecimal=".$nbdecimal." dec='".$dec."' thousand='".$thousand."'<br>";

    // Convert value to universal number format (no thousand separator, '.' as decimal separator)
    if ($alreadysqlnb != 1)	// If not a PHP number or unknown, we change format
    {
        //print 'PP'.$amount.' - '.$dec.' - '.$thousand.'<br>';

        // Convert amount to format with dolibarr dec and thousand (this is because PHP convert a number
        // to format defined by LC_NUMERIC after a calculation and we want source format to be like defined by Dolibarr setup.
        if (is_numeric($amount))
        {
            // We put in temps value of decimal ("0.00001"). Works with 0 and 2.0E-5 and 9999.10
            $temps=sprintf("%0.10F",$amount-intval($amount));	// temps=0.0000000000 or 0.0000200000 or 9999.1000000000
            $temps=preg_replace('/([\.1-9])0+$/','\\1',$temps); // temps=0. or 0.00002 or 9999.1
            $nbofdec=max(0,dol_strlen($temps)-2);	// -2 to remove "0."
            $amount=number_format($amount,$nbofdec,$dec,$thousand);
        }
        //print "QQ".$amount.'<br>';

        // Now make replace (the main goal of function)
        if ($thousand != ',' && $thousand != '.') $amount=str_replace(',','.',$amount);	// To accept 2 notations for french users
        $amount=str_replace(' ','',$amount);		// To avoid spaces
        $amount=str_replace($thousand,'',$amount);	// Replace of thousand before replace of dec to avoid pb if thousand is .
        $amount=str_replace($dec,'.',$amount);
    }

    // Now, make a rounding if required
    if ($rounding)
    {
        $nbofdectoround='';
        if ($rounding == 'MU')     $nbofdectoround=$conf->global->MAIN_MAX_DECIMALS_UNIT;
        elseif ($rounding == 'MT') $nbofdectoround=$conf->global->MAIN_MAX_DECIMALS_TOT;
        elseif ($rounding == 'MS') $nbofdectoround=$conf->global->MAIN_MAX_DECIMALS_SHOWN;
        elseif ($rounding == '2')  $nbofdectoround=2; 	// For admin info page
        //print "RR".$amount.' - '.$nbofdectoround.'<br>';
        if (dol_strlen($nbofdectoround)) $amount = round($amount,$nbofdectoround);	// $nbofdectoround can be 0.
        else return 'ErrorBadParameterProvidedToFunction';
        //print 'SS'.$amount.' - '.$nbofdec.' - '.$dec.' - '.$thousand.' - '.$nbofdectoround.'<br>';

        // Convert amount to format with dolibarr dec and thousand (this is because PHP convert a number
        // to format defined by LC_NUMERIC after a calculation and we want source format to be defined by Dolibarr setup.
        if (is_numeric($amount))
        {
            // We put in temps value of decimal ("0.00001"). Works with 0 and 2.0E-5 and 9999.10
            $temps=sprintf("%0.10F",$amount-intval($amount));	// temps=0.0000000000 or 0.0000200000 or 9999.1000000000
            $temps=preg_replace('/([\.1-9])0+$/','\\1',$temps); // temps=0. or 0.00002 or 9999.1
            $nbofdec=max(0,dol_strlen($temps)-2);	// -2 to remove "0."
            $amount=number_format($amount,min($nbofdec,$nbofdectoround),$dec,$thousand);		// Convert amount to format with dolibarr dec and thousand
        }
        //print "TT".$amount.'<br>';

        // Always make replace because each math function (like round) replace
        // with local values and we want a number that has a SQL string format x.y
        if ($thousand != ',' && $thousand != '.') $amount=str_replace(',','.',$amount);	// To accept 2 notations for french users
        $amount=str_replace(' ','',$amount);		// To avoid spaces
        $amount=str_replace($thousand,'',$amount);	// Replace of thousand before replace of dec to avoid pb if thousand is .
        $amount=str_replace($dec,'.',$amount);
    }

    return $amount;
}

/**
 *	Return localtaxe rate for a particular tva
 *
 * 	@param	float		$tva			        Vat taxe
 * 	@param  int			$local		         	Local taxe to search and return
 *  @param  Societe		$societe_acheteuse    	Object of buying third party
 * 	@return	int				   					0 if not found, localtax if found
 */
function get_localtax($tva, $local, $societe_acheteuse="")
{
    global $db, $conf, $mysoc;

    $code_pays=$mysoc->pays_code;

    if (is_object($societe_acheteuse))
    {
        if ($code_pays!=$societe_acheteuse->pays_code) return 0;
        if ($local==1 && !$societe_acheteuse->localtax1_assuj) return 0;
        elseif ($local==2 && !$societe_acheteuse->localtax2_assuj) return 0;
    }

    // Search local taxes
    $sql  = "SELECT t.localtax1, t.localtax2";
    $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_pays as p";
    $sql .= " WHERE t.fk_pays = p.rowid AND p.code = '".$code_pays."'";
    $sql .= " AND t.taux = ".$tva." AND t.active = 1";
    $sql .= " ORDER BY t.localtax1 ASC, t.localtax2 ASC";

    $resql=$db->query($sql);
    if ($resql)
    {
        $obj = $db->fetch_object($resql);
        if ($local==1) return $obj->localtax1;
        elseif ($local==2) return $obj->localtax2;
    }

    return 0;
}

/**
 *	Return vat rate of a product in a particular selling country or default country
 *  vat if product is unknown
 *
 *  @param	int		$idprod          Id of product or 0 if not a predefined product
 *  @param  string	$countrycode     Country code (FR, US, IT, ...)
 *  @return int				         <0 if KO, Vat rate if OK
 *	TODO May be this should be better as a method of product class
 */
function get_product_vat_for_country($idprod, $countrycode)
{
    global $db,$mysoc;

    $ret=0;
    $found=0;

    if ($idprod > 0)
    {
        // Load product
        $product=new Product($db);
        $result=$product->fetch($idprod);

        if ($mysoc->pays_code == $countrycode) // If selling country is ours
        {
            $ret=$product->tva_tx;    // Default vat of product we defined
            $found=1;
        }
        else
        {
            // TODO Read default product vat according to countrycode and product


        }
    }

    if (! $found)
    {
        // If vat of product for the country not found or not defined, we return higher vat of country.
        $sql.="SELECT taux as vat_rate";
        $sql.=" FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_pays as p";
        $sql.=" WHERE t.active=1 AND t.fk_pays = p.rowid AND p.code='".$countrycode."'";
        $sql.=" ORDER BY t.taux DESC, t.recuperableonly ASC";
        $sql.=$db->plimit(1);

        $resql=$db->query($sql);
        if ($resql)
        {
            $obj=$db->fetch_object($resql);
            if ($obj)
            {
                $ret=$obj->vat_rate;
            }
        }
        else dol_print_error($db);
    }

    dol_syslog("get_product_vat_for_country: ret=".$ret);
    return $ret;
}

/**
 *	Return localtax rate of a product in a particular selling country
 *
 *  @param      idprod          Id of product
 *  @package    local           1 for localtax1, 2 for localtax 2
 *  @param      countrycode     Country code (FR, US, IT, ...)
 *  @return     int             <0 if KO, Vat rate if OK
 *	TODO May be this should be better as a method of product class
 */
function get_product_localtax_for_country($idprod, $local, $countrycode)
{
    global $db;

    $product=new Product($db);
    $product->fetch($idprod);

    if ($local==1) return $product->localtax1_tx;
    elseif ($local==2) return $product->localtax2_tx;

    return -1;
}

/**
 *	Function that return vat rate of a product line (according to seller, buyer and product vat rate)
 *   Si vendeur non assujeti a TVA, TVA par defaut=0. Fin de regle.
 *	 Si le (pays vendeur = pays acheteur) alors TVA par defaut=TVA du produit vendu. Fin de regle.
 *	 Si (vendeur et acheteur dans Communaute europeenne) et (bien vendu = moyen de transports neuf comme auto, bateau, avion) alors TVA par defaut=0 (La TVA doit etre paye par acheteur au centre d'impots de son pays et non au vendeur). Fin de regle.
 *	 Si (vendeur et acheteur dans Communaute europeenne) et (acheteur = particulier ou entreprise sans num TVA intra) alors TVA par defaut=TVA du produit vendu. Fin de regle
 *	 Si (vendeur et acheteur dans Communaute europeenne) et (acheteur = entreprise avec num TVA) intra alors TVA par defaut=0. Fin de regle
 *	 Sinon TVA proposee par defaut=0. Fin de regle.
 *
 *	@param	Societe		$societe_vendeuse    	Objet societe vendeuse
 *	@param  Societe		$societe_acheteuse   	Objet societe acheteuse
 *	@param  int			$idprod					Id product
 *	@return float         				      	Taux de tva a appliquer, -1 si ne peut etre determine
 */
function get_default_tva($societe_vendeuse, $societe_acheteuse, $idprod=0)
{
    global $conf;

    if (!is_object($societe_vendeuse)) return -1;
    if (!is_object($societe_acheteuse)) return -1;

    dol_syslog("get_default_tva: seller use vat=".$societe_vendeuse->tva_assuj.", seller country=".$societe_vendeuse->pays_code.", seller in cee=".$societe_vendeuse->isInEEC().", buyer country=".$societe_acheteuse->pays_code.", buyer in cee=".$societe_acheteuse->isInEEC().", idprod=".$idprod.", SERVICE_ARE_ECOMMERCE_200238EC=".$conf->global->SERVICES_ARE_ECOMMERCE_200238EC);

    // Si vendeur non assujeti a TVA (tva_assuj vaut 0/1 ou franchise/reel)
    if (is_numeric($societe_vendeuse->tva_assuj) && ! $societe_vendeuse->tva_assuj)
    {
        //print 'VATRULE 1';
        return 0;
    }
    if (! is_numeric($societe_vendeuse->tva_assuj) && $societe_vendeuse->tva_assuj=='franchise')
    {
        //print 'VATRULE 2';
        return 0;
    }

    //if (is_object($societe_acheteuse) && ($societe_vendeuse->pays_id == $societe_acheteuse->pays_id) && ($societe_acheteuse->tva_assuj == 1 || $societe_acheteuse->tva_assuj == 'reel'))
    // Le test ci-dessus ne devrait pas etre necessaire. Me signaler l'exemple du cas juridique concerne si le test suivant n'est pas suffisant.

    // Si le (pays vendeur = pays acheteur) alors la TVA par defaut=TVA du produit vendu. Fin de regle.
    if ($societe_vendeuse->pays_code == $societe_acheteuse->pays_code) // Warning ->pays_code not always defined
    {
        //print 'VATRULE 3';
        return get_product_vat_for_country($idprod,$societe_vendeuse->pays_code);
    }

    // Si (vendeur et acheteur dans Communaute europeenne) et (bien vendu = moyen de transports neuf comme auto, bateau, avion) alors TVA par defaut=0 (La TVA doit etre paye par l'acheteur au centre d'impots de son pays et non au vendeur). Fin de regle.
    // Non gere

    // Si (vendeur et acheteur dans Communaute europeenne) et (acheteur = entreprise) alors TVA par defaut=0. Fin de regle
    // Si (vendeur et acheteur dans Communaute europeenne) et (acheteur = particulier) alors TVA par defaut=TVA du produit vendu. Fin de regle
    if (($societe_vendeuse->isInEEC() && $societe_acheteuse->isInEEC()))
    {
        $isacompany=$societe_acheteuse->isACompany();
        if ($isacompany)
        {
            //print 'VATRULE 4';
            return 0;
        }
        else
        {
            //print 'VATRULE 5';
            return get_product_vat_for_country($idprod,$societe_vendeuse->pays_code);
        }
    }

    // If services are eServices according to EU Council Directive 2002/38/EC (ec.europa.eu/taxation_customs/taxation/v.../article_1610_en.htm)
    // we use the buyer VAT.
    if (! empty($conf->global->SERVICE_ARE_ECOMMERCE_200238EC))
    {
        //print "eee".$societe_acheteuse->isACompany();exit;
        if (! $societe_vendeuse->isInEEC() && $societe_acheteuse->isInEEC() && ! $societe_acheteuse->isACompany())
        {
            //print 'VATRULE 6';
            return get_product_vat_for_country($idprod,$societe_acheteuse->pays_code);
        }
    }

    // Sinon la TVA proposee par defaut=0. Fin de regle.
    // Rem: Cela signifie qu'au moins un des 2 est hors Communaute europeenne et que le pays differe
    //print 'VATRULE 7';
    return 0;
}


/**
 *	Fonction qui renvoie si tva doit etre tva percue recuperable
 *
 *	@param	Societe		$societe_vendeuse    	Objet societe vendeuse
 *	@param  Societe		$societe_acheteuse   	Objet societe acheteuse
 *  @param  int			$idprod                 Id product
 *	@return float       			        	0 or 1
 */
function get_default_npr($societe_vendeuse, $societe_acheteuse, $idprod)
{
    return 0;
}

/**
 *	Function that return localtax of a product line (according to seller, buyer and product vat rate)
 *
 *	@param	Societe		$societe_vendeuse    	Objet societe vendeuse
 *	@param  Societe		$societe_acheteuse   	Objet societe acheteuse
 *  @param	int			$local					Localtax to process (1 or 2)
 *	@param  int			$idprod					Id product
 *	@return float        				       	Taux de localtax appliquer, -1 si ne peut etre determine
 */
function get_default_localtax($societe_vendeuse, $societe_acheteuse, $local, $idprod=0)
{
    if (!is_object($societe_vendeuse)) return -1;
    if (!is_object($societe_acheteuse)) return -1;

    if ($societe_vendeuse->pays_id=='ES' || $societe_vendeuse->pays_code=='ES')
    {
        if ($local==1) //RE
        {
            // Si achatteur non assujeti a RE, localtax1 par default=0
            if (is_numeric($societe_acheteuse->localtax1_assuj) && ! $societe_acheteuse->localtax1_assuj) return 0;
            if (! is_numeric($societe_acheteuse->localtax1_assuj) && $societe_acheteuse->localtax1_assuj=='localtax1off') return 0;
        }
        elseif ($local==2) //IRPF
        {
            // Si vendeur non assujeti a IRPF, localtax2 par default=0
            if (is_numeric($societe_vendeuse->localtax2_assuj) && ! $societe_vendeuse->localtax2_assuj) return 0;
            if (! is_numeric($societe_vendeuse->localtax2_assuj) && $societe_vendeuse->localtax2_assuj=='localtax2off') return 0;
        } else return -1;

        if ($idprod) return get_product_localtax_for_country($idprod, $local, $societe_vendeuse->pays_code);
        else return -1;
    }
    return 0;
}

/**
 *	Return yes or no in current language
 *
 *	@param	yesno			Value to test (1, 'yes', 'true' or 0, 'no', 'false')
 *	@param	case			1=Yes/No, 0=yes/no
 *	@param	color			0=texte only, 1=Text is formated with a color font style ('ok' or 'error'), 2=Text is formated with 'ok' color.
 */
function yn($yesno, $case=1, $color=0)
{
    global $langs;
    $result='unknown';
    if ($yesno == 1 || strtolower($yesno) == 'yes' || strtolower($yesno) == 'true') 	// A mettre avant test sur no a cause du == 0
    {
        $result=($case?$langs->trans("Yes"):$langs->trans("yes"));
        $classname='ok';
    }
    elseif ($yesno == 0 || strtolower($yesno) == 'no' || strtolower($yesno) == 'false')
    {
        $result=($case?$langs->trans("No"):$langs->trans("no"));
        if ($color == 2) $classname='ok';
        else $classname='error';
    }
    if ($color) return '<font class="'.$classname.'">'.$result.'</font>';
    return $result;
}


/**
 *	Return a path to have a directory according to an id
 *  Examples:       '001' with level 3->"0/0/1/", '015' with level 3->"0/1/5/"
 *  Examples:       'ABC-1' with level 3 ->"0/0/1/", '015' with level 1->"5/"
 *
 *	@param      $num            Id to develop
 *	@param      $level		    Level of development (1, 2 or 3 level)
 * 	@param		$alpha		    Use alpha ref
 *  @param      withoutslash    0=With slash at end, 1=without slash at end
 */
function get_exdir($num,$level=3,$alpha=0,$withoutslash=0)
{
    $path = '';
    if (empty($alpha)) $num = preg_replace('/([^0-9])/i','',$num);
    else $num = preg_replace('/^.*\-/i','',$num);
    $num = substr("000".$num, -$level);
    if ($level == 1) $path = substr($num,0,1);
    if ($level == 2) $path = substr($num,1,1).'/'.substr($num,0,1);
    if ($level == 3) $path = substr($num,2,1).'/'.substr($num,1,1).'/'.substr($num,0,1);
    if (empty($withoutslash)) $path.='/';
    return $path;
}

// For backward compatibility
function create_exdir($dir)
{
    dol_mkdir($dir);
}

/**
 *	Creation of a directory (this can create recursive subdir)
 *
 *	@param	string	$dir	Directory to create (Separator must be '/'. Example: '/mydir/mysubdir')
 *	@return int         	< 0 if KO, 0 = already exists, > 0 if OK
 */
function dol_mkdir($dir)
{
    global $conf;

    dol_syslog("functions.lib::create_exdir: dir=".$dir,LOG_INFO);

    $dir_osencoded=dol_osencode($dir);
    if (@is_dir($dir_osencoded)) return 0;

    $nberr=0;
    $nbcreated=0;

    $ccdir = '';
    $cdir = explode("/",$dir);
    $num=count($cdir);
    for ($i = 0; $i < $num; $i++)
    {
        if ($i > 0) $ccdir .= '/'.$cdir[$i];
        else $ccdir = $cdir[$i];
        if (preg_match("/^.:$/",$ccdir,$regs)) continue;	// Si chemin Windows incomplet, on poursuit par rep suivant

        // Attention, le is_dir() peut echouer bien que le rep existe.
        // (ex selon config de open_basedir)
        if ($ccdir)
        {
            $ccdir_osencoded=dol_osencode($ccdir);
            if (! @is_dir($ccdir_osencoded))
            {
                dol_syslog("functions.lib::create_exdir: Directory '".$ccdir."' does not exists or is outside open_basedir PHP setting.",LOG_DEBUG);

                umask(0);
                $dirmaskdec=octdec('0755');
                if (! empty($conf->global->MAIN_UMASK)) $dirmaskdec=octdec($conf->global->MAIN_UMASK);
                $dirmaskdec |= octdec('0111');  // Set x bit required for directories
                if (! @mkdir($ccdir_osencoded, $dirmaskdec))
                {
                    // Si le is_dir a renvoye une fausse info, alors on passe ici.
                    dol_syslog("functions.lib::create_exdir: Fails to create directory '".$ccdir."' or directory already exists.",LOG_WARNING);
                    $nberr++;
                }
                else
                {
                    dol_syslog("functions.lib::create_exdir: Directory '".$ccdir."' created",LOG_DEBUG);
                    $nberr=0;	// On remet a zero car si on arrive ici, cela veut dire que les echecs precedents peuvent etre ignore
                    $nbcreated++;
                }
            }
            else
            {
                $nberr=0;	// On remet a zero car si on arrive ici, cela veut dire que les echecs precedents peuvent etre ignores
            }
        }
    }
    return ($nberr ? -$nberr : $nbcreated);
}


/**
 *	Return picto saying a field is required
 *
 *	@return  string		Chaine avec picto obligatoire
 */
function picto_required()
{
    return '<span class="fieldrequired">*</span>';
}


/**
 *	Clean a string from all HTML tags and entities
 *
 *	@param   	StringHtml			String to clean
 *	@param		removelinefeed		Replace also all lines feeds by a space
 *	@return  	string	    		String cleaned
 */
function dol_string_nohtmltag($StringHtml,$removelinefeed=1)
{
    $pattern = "/<[^>]+>/";
    $temp = dol_entity_decode($StringHtml);
    $temp = preg_replace($pattern,"",$temp);

    // Supprime aussi les retours
    if ($removelinefeed) $temp=str_replace("\n"," ",$temp);

    // et les espaces doubles
    while(strpos($temp,"  "))
    {
        $temp = str_replace("  "," ",$temp);
    }
    $CleanString = trim($temp);
    return $CleanString;
}


/**
 *	Replace CRLF in string with a HTML BR tag
 *
 *	@param		stringtoencode		String to encode
 *	@param		nl2brmode			0=Adding br before \n, 1=Replacing \n by br
 *  @param      forxml              false=Use <br>, true=Use <br />
 *	@return		string				String encoded
 */
function dol_nl2br($stringtoencode,$nl2brmode=0,$forxml=false)
{
    if (! $nl2brmode)
    {
        // We use @ to avoid warning on PHP4 that does not support entity encoding from UTF8;
        if (version_compare(PHP_VERSION, '5.3.0') < 0) return @nl2br($stringtoencode);
        else return @nl2br($stringtoencode,$forxml);
    }
    else
    {
        $ret=preg_replace('/(\r\n|\r|\n)/i',($forxml?'<br />':'<br>'),$stringtoencode);
        return $ret;
    }
}

/**
 *	This function is called to encode a string into a HTML string but differs from htmlentities because
 * 	all entities but &,<,> are converted. This permits to encode special chars to entities with no double
 *  encoding for already encoded HTML strings.
 * 	This function also remove last CR/BR.
 *  For PDF usage, you can show text by 2 ways:
 *              - writeHTMLCell -> param must be encoded into HTML.
 *              - MultiCell -> param must not be encoded into HTML.
 *              Because writeHTMLCell convert also \n into <br>, if function
 *              is used to build PDF, nl2brmode must be 1
 *
 *	@param		stringtoencode		String to encode
 *	@param		nl2brmode			0=Adding br before \n, 1=Replacing \n by br (for use with FPDF writeHTMLCell function for example)
 *  @param      pagecodefrom        Pagecode stringtoencode is encoded
 */
function dol_htmlentitiesbr($stringtoencode,$nl2brmode=0,$pagecodefrom='UTF-8')
{
    if (dol_textishtml($stringtoencode))
    {
        $newstring=$stringtoencode;
        $newstring=preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>/i','<br>',$newstring);	// Replace "<br type="_moz" />" by "<br>". It's same and avoid pb with FPDF.
        $newstring=preg_replace('/<br>$/i','',$newstring);	// Remove last <br>
        $newstring=strtr($newstring,array('&'=>'__and__','<'=>'__lt__','>'=>'__gt__','"'=>'__dquot__'));
        $newstring=dol_htmlentities($newstring,ENT_COMPAT,$pagecodefrom);	// Make entity encoding
        $newstring=strtr($newstring,array('__and__'=>'&','__lt__'=>'<','__gt__'=>'>','__dquot__'=>'"'));
        //$newstring=strtr($newstring,array('__li__'=>"<li>\n")); // Restore <li>\n
    }
    else {
        $newstring=dol_nl2br(dol_htmlentities($stringtoencode,ENT_COMPAT,$pagecodefrom),$nl2brmode);
    }
    // Other substitutions that htmlentities does not do
    $newstring=str_replace(chr(128),'&euro;',$newstring);	// 128 = 0x80. Not in html entity table.
    return $newstring;
}

/**
 *	This function is called to decode a HTML string (it decodes entities and br tags)
 *
 *	@param		stringtodecode		String to decode
 *	@param		pagecodeto			Page code for result
 */
function dol_htmlentitiesbr_decode($stringtodecode,$pagecodeto='UTF-8')
{
    $ret=dol_html_entity_decode($stringtodecode,ENT_COMPAT,$pagecodeto);
    $ret=preg_replace('/'."\r\n".'<br(\s[\sa-zA-Z_="]*)?\/?>/i',"<br>",$ret);
    $ret=preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>'."\r\n".'/i',"\r\n",$ret);
    $ret=preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>'."\n".'/i',"\n",$ret);
    $ret=preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>/i',"\n",$ret);
    return $ret;
}

/**
 *	This function remove all ending \n and br at end
 *
 *	@param		stringtodecode		String to decode
 */
function dol_htmlcleanlastbr($stringtodecode)
{
    $ret=preg_replace('/(<br>|<br(\s[\sa-zA-Z_="]*)?\/?>|'."\n".'|'."\r".')+$/i',"",$stringtodecode);
    return $ret;
}

/**
 *	This function is called to decode a string with HTML entities (it decodes entities tags)
 *
 * 	@param   	stringhtml      stringhtml
 *  @param      pagecodeto      Encoding of input string
 * 	@return  	string	  	    decodestring
 */
function dol_entity_decode($stringhtml,$pagecodeto='UTF-8')
{
    $ret=dol_html_entity_decode($stringhtml,ENT_COMPAT,$pagecodeto);
    return $ret;
}

/**
 * Replace html_entity_decode functions to manage errors
 *
 * @param   a
 * @param   b
 * @param   c
 * @return  string      String decoded
 */
function dol_html_entity_decode($a,$b,$c)
{
    // We use @ to avoid warning on PHP4 that does not support entity decoding to UTF8;
    $ret=@html_entity_decode($a,$b,$c);
    return $ret;
}

/**
 * Replace htmlentities functions to manage errors
 *
 * @param   a
 * @param   b
 * @param   c
 * @return  string      String encoded
 */
function dol_htmlentities($a,$b,$c)
{
    // We use @ to avoid warning on PHP4 that does not support entity decoding to UTF8;
    $ret=@htmlentities($a,$b,$c);
    return $ret;
}


/**
 *	Check if a string is a correct iso string
 *	If not, it will we considered not HTML encoded even if it is by FPDF.
 *	Example, if string contains euro symbol that has ascii code 128
 *
 *	@param       s       String to check
 *	@return	     int     0 if bad iso, 1 if good iso
 */
function dol_string_is_good_iso($s)
{
    $len=dol_strlen($s);
    $ok=1;
    for($scursor=0;$scursor<$len;$scursor++)
    {
        $ordchar=ord($s{$scursor});
        //print $scursor.'-'.$ordchar.'<br>';
        if ($ordchar < 32 && $ordchar != 13 && $ordchar != 10) { $ok=0; break; }
        if ($ordchar > 126 && $ordchar < 160) { $ok=0; break; }
    }
    return $ok;
}


/**
 *	Return nb of lines of a clear text
 *
 *	@param		s			String to check
 * 	@param		maxchar		Not yet used
 *	@return		int			Number of lines
 */
function dol_nboflines($s,$maxchar=0)
{
    if ($s == '') return 0;
    $arraystring=explode("\n",$s);
    $nb=count($arraystring);

    return $nb;
}


/**
 *	Return nb of lines of a formated text with \n and <br>
 *
 *	@param	   	text      		Text
 *	@param	   	maxlinesize  	Largeur de ligne en caracteres (ou 0 si pas de limite - defaut)
 * 	@param		charset			Give the charset used to encode the $text variable in memory.
 *	@return    	int				Number of lines
 */
function dol_nboflines_bis($text,$maxlinesize=0,$charset='UTF-8')
{
    //print $text;
    $repTable = array("\t" => " ", "\n" => "<br>", "\r" => " ", "\0" => " ", "\x0B" => " ");
    $text = strtr($text, $repTable);
    if ($charset == 'UTF-8') { $pattern = '/(<[^>]+>)/Uu'; }	// /U is to have UNGREEDY regex to limit to one html tag. /u is for UTF8 support
    else $pattern = '/(<[^>]+>)/U';								// /U is to have UNGREEDY regex to limit to one html tag.
    $a = preg_split($pattern, $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
    $nblines = floor((count($a)+1)/2);
    // count possible auto line breaks
    if($maxlinesize)
    {
        foreach ($a as $line)
        {
            if (dol_strlen($line)>$maxlinesize)
            {
                //$line_dec = html_entity_decode(strip_tags($line));
                $line_dec = html_entity_decode($line);
                if(dol_strlen($line_dec)>$maxlinesize)
                {
                    $line_dec=wordwrap($line_dec,$maxlinesize,'\n',true);
                    $nblines+=substr_count($line_dec,'\n');
                }
            }
        }
    }
    return $nblines;
}

/**
 *	 Same function than microtime in PHP 5 but compatible with PHP4
 *
 *	 @return		float		Time (millisecondes) with microsecondes in decimal part
 */
function dol_microtime_float()
{
    list($usec, $sec) = explode(" ", microtime());
    return ((float) $usec + (float) $sec);
}

/**
 *		Return if a text is a html content
 *
 *		@param	string	$msg		Content to check
 *		@param	int		$option		0=Full detection, 1=Fast check
 *		@return	boolean				true/false
 */
function dol_textishtml($msg,$option=0)
{
    if ($option == 1)
    {
        if (preg_match('/<html/i',$msg))				return true;
        elseif (preg_match('/<body/i',$msg))			return true;
        elseif (preg_match('/<br/i',$msg))				return true;
        return false;
    }
    else
    {
        if (preg_match('/<html/i',$msg))				return true;
        elseif (preg_match('/<body/i',$msg))			return true;
        elseif (preg_match('/<br/i',$msg))				return true;
        elseif (preg_match('/<span/i',$msg))			return true;
        elseif (preg_match('/<div/i',$msg))				return true;
        elseif (preg_match('/<li/i',$msg))				return true;
        elseif (preg_match('/<table/i',$msg))			return true;
        elseif (preg_match('/<font/i',$msg))			return true;
        elseif (preg_match('/<strong/i',$msg))			return true;
        elseif (preg_match('/<img/i',$msg))				return true;
        elseif (preg_match('/<i>/i',$msg))				return true;
        elseif (preg_match('/<b>/i',$msg))				return true;
        elseif (preg_match('/&[A-Z0-9]{1,6};/i',$msg))	return true;
        return false;
    }
}

/**
 *    	Make substition into a string
 *      There is two type of substitions:
 * 		- From $substitutionarray (oldval=>newval)
 * 		- From special constants (__XXX__=>f(objet->xxx)) by substitutions modules
 *
 *    	@param	string	$chaine      			Source string in which we must do substitution
 *    	@param  array	$substitutionarray		Array with key->val to substitute
 *    	@return string  		    			Output string after subsitutions
 */
function make_substitutions($chaine,$substitutionarray)
{
    if (! is_array($substitutionarray)) return 'ErrorBadParameterSubstitutionArrayWhenCalling_make_substitutions';

    // Make substitition
    foreach ($substitutionarray as $key => $value)
    {
        $chaine=str_replace("$key","$value",$chaine);	// We must keep the " to work when value is 123.5 for example
    }
    return $chaine;
}

/**
 *      Complete the $substitutionarray with more entries
 *
 *      @param  array		$substitutionarray       Array substitution old value => new value value
 *      @param  Translate	$outputlangs             If we want substitution from special constants, we provide a language
 *      @param  Object		$object                  If we want substitution from special constants, we provide data in a source object
 *      @return	void
 */
function complete_substitutions_array(&$substitutionarray,$outputlangs,$object='')
{
    global $conf,$user;

    require_once(DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php');

    // Check if there is external substitution to do asked by plugins
    // We look files into the core/modules/substitutions directory
    // By default, there is no such external plugins.
    foreach ($conf->file->dol_document_root as $dirroot)
    {
        $substitfiles=dol_dir_list($dirroot.'/core/modules/substitutions','files',0,'functions_');
        foreach($substitfiles as $substitfile)
        {
            if (preg_match('/functions_(.*)\.lib\.php/i',$substitfile['name'],$reg))
            {
                $module=$reg[1];
                if (! empty($conf->$module->enabled))   // If module enabled
                {
                    dol_syslog("Library functions_".$module.".lib.php found into ".$dirroot);
                    require_once($dirroot."/core/modules/substitutions/functions_".$module.".lib.php");
                    $function_name=$module."_completesubstitutionarray";
                    $function_name($substitutionarray,$outputlangs,$object);
                }
            }
        }
    }
}

/**
 *    Format output for start and end date
 *
 *    @param	timestamp	$date_start    Start date
 *    @param    timestamp	$date_end      End date
 *    @param    string		$format        Output format
 *    @param	Translate	$outputlangs   Output language
 *    @return	void
 */
function print_date_range($date_start,$date_end,$format = '',$outputlangs='')
{
    print get_date_range($date_start,$date_end,$format,$outputlangs);
}

/**
 *    Format output for start and end date
 *
 *    @param	timestamp	$date_start    Start date
 *    @param    timestamp	$date_end      End date
 *    @param    string		$format        Output format
 *    @param	Translate	$outputlangs   Output language
 *    @return	string						String
 */
function get_date_range($date_start,$date_end,$format = '',$outputlangs='')
{
    global $langs;

    $out='';

    if (! is_object($outputlangs)) $outputlangs=$langs;

    if ($date_start && $date_end)
    {
        $out.= ' ('.$outputlangs->trans('DateFromTo',dol_print_date($date_start, $format, false, $outputlangs),dol_print_date($date_end, $format, false, $outputlangs)).')';
    }
    if ($date_start && ! $date_end)
    {
        $out.= ' ('.$outputlangs->trans('DateFrom',dol_print_date($date_start, $format, false, $outputlangs)).')';
    }
    if (! $date_start && $date_end)
    {
        $out.= ' ('.$outputlangs->trans('DateUntil',dol_print_date($date_end, $format, false, $outputlangs)).')';
    }

    return $out;
}


/**
 *	Get formated messages to output (Used to show messages on html output).
 *
 *	@param	string		$mesgstring		Message string
 *	@param	array		$mesgarray      Messages array
 *  @param  string		$style          Style of message output ('ok' or 'error')
 *  @param  int			$keepembedded   Set to 1 in error message must be kept embedded into its html place (this disable jnotify)
 *	@return	string						Return html output
 *
 *  @see        dol_print_error
 *  @see        dol_htmloutput_errors
 */
function get_htmloutput_mesg($mesgstring='',$mesgarray='', $style='ok', $keepembedded=0)
{
    global $conf, $langs;

    $ret='';
    $out='';
    $divstart=$divend='';

    // Use session mesg
    if (isset($_SESSION['mesg']))
    {
    	$mesgstring=$_SESSION['mesg'];
    	unset($_SESSION['mesg']);
    }
	if (isset($_SESSION['mesgarray']))
    {
    	$mesgarray=$_SESSION['mesgarray'];
    	unset($_SESSION['mesgarray']);
    }

    // If inline message with no format, we add it.
    if ((! empty($conf->global->MAIN_DISABLE_JQUERY_JNOTIFY) || $keepembedded) && ! preg_match('/<div class=".*">/i',$out))
    {
        $divstart='<div class="'.$style.'">';
        $divend='</div>';
    }

    if ((is_array($mesgarray) && count($mesgarray)) || $mesgstring)
    {
        $langs->load("errors");
        $out.=$divstart;
        if (is_array($mesgarray) && count($mesgarray))
        {
            foreach($mesgarray as $message)
            {
                $ret++;
                $out.= $langs->trans($message);
                if ($ret < count($mesgarray)) $out.= "<br>\n";
            }
        }
        if ($mesgstring)
        {
            $langs->load("errors");
            $ret++;
            $out.= $langs->trans($mesgstring);
        }
        $out.=$divend;
    }

    if ($out)
    {
        if (empty($conf->global->MAIN_DISABLE_JQUERY_JNOTIFY) && empty($keepembedded))
        {
            $return = '<script type="text/javascript">
    				jQuery(document).ready(function() {
    					jQuery.jnotify("'.dol_escape_js($out).'",
    					"'.($style=="ok" ? 3000 : $style).'",
    					'.($style=="ok" ? "false" : "true").',
    					{ remove: function (){} } );
    				});
    			</script>';
        }
        else
        {
            $return = $out;
        }
    }

    return $return;
}

/**
 *  Get formated error messages to output (Used to show messages on html output).
 *
 *  @param	string	$mesgstring         Error message
 *  @param  array	$mesgarray          Error messages array
 *  @param  int		$keepembedded       Set to 1 in error message must be kept embedded into its html place (this disable jnotify)
 *  @return string                		Return html output
 *
 *  @see        dol_print_error
 *  @see        dol_htmloutput_mesg
 */
function get_htmloutput_errors($mesgstring='', $mesgarray='', $keepembedded=0)
{
    return get_htmloutput_mesg($mesgstring, $mesgarray,'error',$keepembedded);
}

/**
 *	Print formated messages to output (Used to show messages on html output).
 *
 *	@param	string	$mesgstring		Message
 *	@param	array	$mesgarray       Messages array
 *  @param  string	$style           Which style to use ('ok', 'error')
 *  @param  int		$keepembedded    Set to 1 if message must be kept embedded into its html place (this disable jnotify)
 *  @return	void
 *
 *  @see        dol_print_error
 *  @see        dol_htmloutput_errors
 */
function dol_htmloutput_mesg($mesgstring='',$mesgarray='', $style='ok', $keepembedded=0)
{
    if (empty($mesgstring) && (! is_array($mesgarray) || count($mesgarray) == 0)) return;

    $iserror=0;
    if (is_array($mesgarray))
    {
        foreach($mesgarray as $val)
        {
            if ($val && preg_match('/class="error"/i',$val)) { $iserror++; break; }
        }
    }
    else if ($mesgstring && preg_match('/class="error"/i',$mesgstring)) $iserror++;
    if ($style=='error') $iserror++;

    if ($iserror)
    {
        // Remove div from texts
        $mesgstring=preg_replace('/<\/div><div class="error">/','<br>',$mesgstring);
        $mesgstring=preg_replace('/<div class="error">/','',$mesgstring);
        $mesgstring=preg_replace('/<\/div>/','',$mesgstring);
        // Remove div from texts array
        if (is_array($mesgarray))
        {
            $newmesgarray=array();
            foreach($mesgarray as $val)
            {
                $tmpmesgstring=preg_replace('/<\/div><div class="error">/','<br>',$val);
                $tmpmesgstring=preg_replace('/<div class="error">/','',$tmpmesgstring);
                $tmpmesgstring=preg_replace('/<\/div>/','',$tmpmesgstring);
                $newmesgarray[]=$tmpmesgstring;
            }
            $mesgarray=$newmesgarray;
        }
        print get_htmloutput_mesg($mesgstring,$mesgarray,'error',$keepembedded);
    }
    else print get_htmloutput_mesg($mesgstring,$mesgarray,'ok',$keepembedded);
}

/**
 *  Print formated error messages to output (Used to show messages on html output).
 *
 *  @param	string	$mesgstring          Error message
 *  @param  array	$mesgarray           Error messages array
 *  @param  int		$keepembedded        Set to 1 in error message must be kept embedded into its html place (this disable jnotify)
 *  @return	void
 *
 *  @see        dol_print_error
 *  @see        dol_htmloutput_mesg
 */
function dol_htmloutput_errors($mesgstring='', $mesgarray='', $keepembedded=0)
{
    dol_htmloutput_mesg($mesgstring, $mesgarray, 'error', $keepembedded);
}

/**
 * 	Advanced sort array by second index function, which produces ascending (default)
 *  or descending output and uses optionally natural case insensitive sorting (which
 *  can be optionally case sensitive as well).
 *
 *  @param      array		$array      		Array to sort
 *  @param      string		$index				Key in array to use for sorting criteria
 *  @param      int			$order				Sort order
 *  @param      int			$natsort			1=use "natural" sort (natsort), 0=use "standard sort (asort)
 *  @param      int			$case_sensitive		1=sort is case sensitive, 0=not case sensitive
 *  @return     array							Sorted array
 */
function dol_sort_array(&$array, $index, $order='asc', $natsort=0, $case_sensitive=0)
{
    // Clean parameters
    $order=strtolower($order);

    $sizearray=count($array);
    if (is_array($array) && $sizearray>0)
    {
        foreach(array_keys($array) as $key) $temp[$key]=$array[$key][$index];
        if (!$natsort) ($order=='asc') ? asort($temp) : arsort($temp);
        else
        {
            ($case_sensitive) ? natsort($temp) : natcasesort($temp);
            if($order!='asc') $temp=array_reverse($temp,TRUE);
        }
        foreach(array_keys($temp) as $key) (is_numeric($key))? $sorted[]=$array[$key] : $sorted[$key]=$array[$key];
        return $sorted;
    }
    return $array;
}


/**
 *      Check if a string is in UTF8
 *
 *      @param	string	$str        String to check
 * 		@return	boolean				True if string is UTF8 or ISO compatible with UTF8, False if not (ISO with special char or Binary)
 */
function utf8_check($str)
{
    // We must use here a binary strlen function (so not dol_strlen)
    $strLength = dol_strlen($str);
    for ($i=0; $i<$strLength; $i++)
    {
        if (ord($str[$i]) < 0x80) continue; // 0bbbbbbb
        elseif ((ord($str[$i]) & 0xE0) == 0xC0) $n=1; // 110bbbbb
        elseif ((ord($str[$i]) & 0xF0) == 0xE0) $n=2; // 1110bbbb
        elseif ((ord($str[$i]) & 0xF8) == 0xF0) $n=3; // 11110bbb
        elseif ((ord($str[$i]) & 0xFC) == 0xF8) $n=4; // 111110bb
        elseif ((ord($str[$i]) & 0xFE) == 0xFC) $n=5; // 1111110b
        else return false; // Does not match any model
        for ($j=0; $j<$n; $j++) { // n bytes matching 10bbbbbb follow ?
            if ((++$i == strlen($str)) || ((ord($str[$i]) & 0xC0) != 0x80))
            return false;
        }
    }
    return true;
}


/**
 *      Return an UTF-8 string encoded into OS filesystem encoding. This function is used to define
 * 	    value to pass to filesystem PHP functions.
 *
 *      @param	string	$str        String to encode (UTF-8)
 * 		@return	string				Encoded string (UTF-8, ISO-8859-1)
 */
function dol_osencode($str)
{
    global $conf;

    $tmp=ini_get("unicode.filesystem_encoding");						// Disponible avec PHP 6.0
    if (empty($tmp) && ! empty($_SERVER["WINDIR"])) $tmp='iso-8859-1';	// By default for windows
    if (empty($tmp)) $tmp='utf-8';										// By default for other
    if (! empty($conf->global->MAIN_FILESYSTEM_ENCODING)) $tmp=$conf->global->MAIN_FILESYSTEM_ENCODING;

    if ($tmp == 'iso-8859-1') return utf8_decode($str);
    return $str;
}


/**
 *      Return an id or code from a code or id. Store Code-Id in a cache.
 *
 * 		@param	DoliDB	$db			Database handler
 * 		@param	string	$key		Code to get Id
 * 		@param	string	$tablename	Table name without prefix
 * 		@param	string	$fieldkey	Field for code
 * 		@param	string	$fieldid	Field for id
 *      @return int					Id of code
 */
function dol_getIdFromCode($db,$key,$tablename,$fieldkey='code',$fieldid='id')
{
    global $cache_codes;

    // If key empty
    if ($key == '') return '';

    // Check in cache
    if (isset($cache_codes[$tablename][$key]))	// Can be defined to 0 or ''
    {
        return $cache_codes[$tablename][$key];   // Found in cache
    }

    $sql = "SELECT ".$fieldid." as id";
    $sql.= " FROM ".MAIN_DB_PREFIX.$tablename;
    $sql.= " WHERE ".$fieldkey." = '".$key."'";
    dol_syslog('dol_getIdFromCode sql='.$sql,LOG_DEBUG);
    $resql = $db->query($sql);
    if ($resql)
    {
        $obj = $db->fetch_object($resql);
        if ($obj) $cache_codes[$tablename][$key]=$obj->id;
        else $cache_codes[$tablename][$key]='';
        $db->free($resql);
        return $cache_codes[$tablename][$key];
    }
    else
    {
        dol_syslog("dol_getIdFromCode error=".$db->lasterror(),LOG_ERR);
        return -1;
    }
}

/**
 * Verify if condition in string is ok or not
 *
 * @param 	string		$strRights		String with condition to check
 * @return 	boolean						true or false
 */
function verifCond($strRights)
{
    global $user,$conf,$langs;
    global $leftmenu;
    global $rights;    // To export to dol_eval function

    //print $strRights."<br>\n";
    $rights = true;
    if ($strRights != '')
    {
        //$tab_rights = explode('&&', $strRights);
        //$i = 0;
        //while (($i < count($tab_rights)) && ($rights == true)) {
        $str = 'if(!(' . $strRights . ')) { $rights = false; }';
        dol_eval($str);
        //	$i++;
        //}
    }
    return $rights;
}

/**
 * Replace eval function to add more security.
 * This function is called by verifCond()
 *
 * @param 	string	$s
 * @return	void
 */
function dol_eval($s)
{
    // Only global variables can be changed by eval function and returned to caller
    global $langs, $user, $conf;
    global $leftmenu;
    global $rights;

    //print $s."<br>\n";
    eval($s);
}

/**
* Return if var element is ok
*
* @param   string      $element    Variable to check
* @return  boolean                 Return true of variable is not empty
*/
function dol_validElement($element)
{
	return (trim($element) != '');
}

/**
 * 	Return img flag of country for a language code or country code
 *
 * 	@param	string	$codelang	Language code (en_IN, fr_CA...) or Country code (IN, FR)
 * 	@return	string				HTML img string with flag.
 */
function picto_from_langcode($codelang)
{
    $ret='';
    if (! empty($codelang))
    {
        if ($codelang == 'auto') $ret=img_picto('',DOL_URL_ROOT.'/theme/common/flags/int.png','',1);
        else {
            //print $codelang;
            $langtocountryflag=array('ar_AR'=>'','ca_ES'=>'catalonia','da_DA'=>'dk','fr_CA'=>'mq','sv_SV'=>'se');
            $tmpcode='';
            if (isset($langtocountryflag[$codelang])) $tmpcode=$langtocountryflag[$codelang];
            else
            {
                $tmparray=explode('_',$codelang);
                $tmpcode=empty($tmparray[1])?$tmparray[0]:$tmparray[1];
            }
            if ($tmpcode) $ret.=img_picto($codelang,DOL_URL_ROOT.'/theme/common/flags/'.strtolower($tmpcode).'.png','',1);
        }
    }
    return $ret;
}

/**
 *  Complete or removed entries into a head array (used to build tabs) with value added by external modules
 *
 *  @param	Conf		$conf           Object conf
 *  @param  Translate	$langs          Object langs
 *  @param  Object		$object         Object object
 *  @param  array		$head           Object head
 *  @param  int			$h              New position to fill
 *  @param  string		$type           Value for object where objectvalue can be
 *                              		'thirdparty'       to add a tab in third party view
 *		                              	'intervention'     to add a tab in intervention view
 *     		                         	'supplier_order'   to add a tab in supplier order view
 *          		                    'supplier_invoice' to add a tab in supplier invoice view
 *                  		            'invoice'          to add a tab in customer invoice view
 *                          		    'order'            to add a tab in customer order view
 *                      		        'product'          to add a tab in product view
 *                              		'propal'           to add a tab in propal view
 *                              		'user'             to add a tab in user view
 *                              		'group'            to add a tab in group view
 * 		        	                    'member'           to add a tab in fundation member view
 *      		                        'categories_x'	   to add a tab in category view ('x': type of category (0=product, 1=supplier, 2=customer, 3=member)
 *  @param  string		$mode  	        'add' to complete head, 'remove' to remove entries
 *	@return	void
 */
function complete_head_from_modules($conf,$langs,$object,&$head,&$h,$type,$mode='add')
{
    if (is_array($conf->tabs_modules[$type]))
    {
        foreach ($conf->tabs_modules[$type] as $value)
        {
            $values=explode(':',$value);

            if ($mode == 'add')
            {
                if (count($values) == 6)       // new declaration with permissions
                {
                    if ($values[0] != $type) continue;
                    //print 'ee'.$values[4];
                    if (verifCond($values[4]))
                    {
                        if ($values[3]) $langs->load($values[3]);
                        $head[$h][0] = dol_buildpath(preg_replace('/__ID__/i',$object->id,$values[5]),1);
                        $head[$h][1] = $langs->trans($values[2]);
                        $head[$h][2] = str_replace('+','',$values[1]);
                        $h++;
                    }
                }
                else if (count($values) == 5)       // new declaration
                {
                    if ($values[0] != $type) continue;
                    if ($values[3]) $langs->load($values[3]);
                    $head[$h][0] = dol_buildpath(preg_replace('/__ID__/i',$object->id,$values[4]),1);
                    $head[$h][1] = $langs->trans($values[2]);
                    $head[$h][2] = str_replace('+','',$values[1]);
                    $h++;
                }
                else if (count($values) == 4)   // old declaration, for backward compatibility
                {
                    if ($values[0] != $type) continue;
                    if ($values[2]) $langs->load($values[2]);
                    $head[$h][0] = dol_buildpath(preg_replace('/__ID__/i',$object->id,$values[3]),1);
                    $head[$h][1] = $langs->trans($values[1]);
                    $head[$h][2] = 'tab'.$values[1];
                    $h++;
                }
            }
            else if ($mode == 'remove')
            {
                if ($values[0] != $type) continue;
                $tabname=str_replace('-','',$values[1]);
                foreach($head as $key => $val)
                {
                    if ($head[$key][2]==$tabname)
                    {
                        //print 'on vire '.$tabname.' key='.$key;
                        unset($head[$key]);
                        break;
                    }
                }
            }
        }
    }
}

/**
 * Print common footer :
 * 		conf->global->MAIN_HTML_FOOTER
 * 		conf->global->MAIN_GOOGLE_AN_ID
 * 		DOL_TUNING
 * 		conf->logbuffer
 *
 * @param	string	$zone	'private' (for private pages) or 'public' (for public pages)
 * @return	void
 */
function printCommonFooter($zone='private')
{
    global $conf;

    if ($zone == 'private') print "\n".'<!-- Common footer for private page -->'."\n";
    else print "\n".'<!-- Common footer for public page -->'."\n";

    if (! empty($conf->global->MAIN_HTML_FOOTER)) print $conf->global->MAIN_HTML_FOOTER."\n";

    // Google Analytics (need Google module)
    if (! empty($conf->global->MAIN_GOOGLE_AN_ID))
    {
        print "\n";
        print '<script type="text/javascript">'."\n";
            print '  var _gaq = _gaq || [];'."\n";
            print '  _gaq.push([\'_setAccount\', \''.$conf->global->MAIN_GOOGLE_AN_ID.'\']);'."\n";
            print '  _gaq.push([\'_trackPageview\']);'."\n";
            print ''."\n";
        print '  (function() {'."\n";
            print '    var ga = document.createElement(\'script\'); ga.type = \'text/javascript\'; ga.async = true;'."\n";
            print '    ga.src = (\'https:\' == document.location.protocol ? \'https://ssl\' : \'http://www\') + \'.google-analytics.com/ga.js\';'."\n";
            print '    var s = document.getElementsByTagName(\'script\')[0]; s.parentNode.insertBefore(ga, s);'."\n";
            print '  })();'."\n";
            print '</script>'."\n";
    }

    // End of tuning
    if (! empty($_SERVER['DOL_TUNING']))
    {
        $micro_end_time=dol_microtime_float(true);
        print "\n".'<script type="text/javascript">console.log("';
        if (! empty($conf->global->MEMCACHED_SERVER)) print 'MEMCACHED_SERVER='.$conf->global->MEMCACHED_SERVER.' - ';
        print 'MAIN_OPTIMIZE_SPEED='.(isset($conf->global->MAIN_OPTIMIZE_SPEED)?$conf->global->MAIN_OPTIMIZE_SPEED:'off');
        print ' - Build time: '.ceil(1000*($micro_end_time-$micro_start_time)).' ms';
        if (function_exists("memory_get_usage"))
        {
            print ' - Mem: '.memory_get_usage();
        }
        if (function_exists("xdebug_memory_usage"))
        {
            print ' - XDebug time: '.ceil(1000*xdebug_time_index()).' ms';
            print ' - XDebug mem: '.xdebug_memory_usage();
            print ' - XDebug mem peak: '.xdebug_peak_memory_usage();
        }
        if (function_exists("zend_loader_file_encoded"))
        {
            print ' - Zend encoded file: '.(zend_loader_file_encoded()?'yes':'no');
        }
        print '")</script>'."\n";

        // Add Xdebug coverage of code
        if (defined('XDEBUGCOVERAGE')) {
            var_dump(xdebug_get_code_coverage());
        }
    }

    // If there is some logs in buffer to show
    if (count($conf->logbuffer))
    {
        print "\n";
        print "<!-- Start of log output\n";
        //print '<div class="hidden">'."\n";
        foreach($conf->logbuffer as $logline)
        {
            print $logline."<br>\n";
        }
        //print '</div>'."\n";
        print "End of log output -->\n";
    }

}

?>
Back to Top