/home/mjc1/public_html/j3demo/lib/common2.lib.php


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
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
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
<?php

/*************************************************************************
**
**  일반 함수 모음
**
*************************************************************************/


// 마이크로 타임을 얻어 계산 형식으로 만듦
function get_microtime()
{
    list(
$usec$sec) = explode(" ",microtime());
    return ((float)
$usec + (float)$sec);
}


// 한페이지에 보여줄 행, 현재페이지, 총페이지수, URL
function get_paging($write_pages$cur_page$total_page$url$add="")
{
    
$v explode("&",substr($url,1,strlen($url)));
    
$new_url "?";
    foreach(
$v as $key=>$val){
        
$vv explode("=",$val);
        if(
$vv[0]!='page'){
            
$new_url .= "{$vv[0]}={$vv[1]}&";
        }
    }
    
$url substr($new_url,0,strlen($new_url)-1);
    
//$url = preg_replace('#&amp;page=[0-9]*(&amp;page=)$#', '$1', $url);
    
if($url==''){
        
$url "?page=";
    } else {
        
$url preg_replace('#&amp;page=[0-9]*#'''$url) . '&amp;page=';
    }

    
$str '';
    if (
$cur_page 1) {
        
$str .= '<a href="'.$url.'1'.$add.'" class="pg_page pg_start">처음</a>'.PHP_EOL;
    }

    
$start_page = ( ( (int)( ($cur_page ) / $write_pages ) ) * $write_pages ) + 1;
    
$end_page $start_page $write_pages 1;

    if (
$end_page >= $total_page$end_page $total_page;

    if (
$start_page 1$str .= '<a href="'.$url.($start_page-1).$add.'" class="pg_page pg_prev">이전</a>'.PHP_EOL;

    if (
$total_page 1) {
        for (
$k=$start_page;$k<=$end_page;$k++) {
            if (
$cur_page != $k)
                
$str .= '<a href="'.$url.$k.$add.'" class="pg_page">'.$k.'<span class="sound_only">페이지</span></a>'.PHP_EOL;
            else
                
$str .= '<span class="sound_only">열린</span><strong class="pg_current">'.$k.'</strong><span class="sound_only">페이지</span>'.PHP_EOL;
        }
    }

    if (
$total_page $end_page$str .= '<a href="'.$url.($end_page+1).$add.'" class="pg_page pg_next">다음</a>'.PHP_EOL;

    if (
$cur_page $total_page) {
        
$str .= '<a href="'.$url.$total_page.$add.'" class="pg_page pg_end">맨끝</a>'.PHP_EOL;
    }

    if (
$str)
        return 
"<nav class=\"pg_wrap\"><span class=\"pg\">{$str}</span></nav>";
    else
        return 
"";
}

// 한페이지에 보여줄 행, 현재페이지, 총페이지수, URL
function get_paging2($write_pages$cur_page$total_page$url$add="")
{
    
$str '';
    if (
$cur_page 1) {
        
$str .= '<a href="'.$url.'1'.$add.')" class="pg_page pg_start">처음</a>'.PHP_EOL;
    }

    
$start_page = ( ( (int)( ($cur_page ) / $write_pages ) ) * $write_pages ) + 1;
    
$end_page $start_page $write_pages 1;

    if (
$end_page >= $total_page$end_page $total_page;

    if (
$start_page 1$str .= '<a href="'.$url.($start_page-1).$add.')" class="pg_page pg_prev">이전</a>'.PHP_EOL;

    if (
$total_page 1) {
        for (
$k=$start_page;$k<=$end_page;$k++) {
            if (
$cur_page != $k)
                
$str .= '<a href="'.$url.$k.$add.')" class="pg_page">'.$k.'<span class="sound_only">페이지</span></a>'.PHP_EOL;
            else
                
$str .= '<span class="sound_only">열린</span><strong class="pg_current">'.$k.'</strong><span class="sound_only">페이지</span>'.PHP_EOL;
        }
    }

    if (
$total_page $end_page$str .= '<a href="'.$url.($end_page+1).$add.')" class="pg_page pg_next">다음</a>'.PHP_EOL;

    if (
$cur_page $total_page) {
        
$str .= '<a href="'.$url.$total_page.$add.')" class="pg_page pg_end">맨끝</a>'.PHP_EOL;
    }

    if (
$str)
        return 
"<nav class=\"pg_wrap\"><span class=\"pg\">{$str}</span></nav>";
    else
        return 
"";
}

// 페이징 코드의 <nav><span> 태그 다음에 코드를 삽입
function page_insertbefore($paging_html$insert_html)
{
    if(!
$paging_html)
        
$paging_html '<nav class="pg_wrap"><span class="pg"></span></nav>';

    return 
preg_replace("/^(<nav[^>]+><span[^>]+>)/"'$1'.$insert_html.PHP_EOL$paging_html);
}

// 페이징 코드의 </span></nav> 태그 이전에 코드를 삽입
function page_insertafter($paging_html$insert_html)
{
    if(!
$paging_html)
        
$paging_html '<nav class="pg_wrap"><span class="pg"></span></nav>';

    if(
preg_match("#".PHP_EOL."</span></nav>#"$paging_html))
        
$php_eol '';
    else
        
$php_eol PHP_EOL;

    return 
preg_replace("#(</span></nav>)$#"$php_eol.$insert_html.'$1'$paging_html);
}

// 변수 또는 배열의 이름과 값을 얻어냄. print_r() 함수의 변형
function print_r2($var)
{
    
ob_start();
    
print_r($var);
    
$str ob_get_contents();
    
ob_end_clean();
    
$str str_replace(" ""&nbsp;"$str);
    echo 
nl2br("<span style='font-family:Tahoma, 굴림; font-size:9pt;'>$str</span>");
}


// 메타태그를 이용한 URL 이동
// header("location:URL") 을 대체
function goto_url($url)
{
    
$url str_replace("&amp;""&"$url);
    
//echo "<script> location.replace('$url'); </script>";

    
if (!headers_sent())
        
header('Location: '.$url);
    else {
        echo 
'<script>';
        echo 
'location.replace("'.$url.'");';
        echo 
'</script>';
        echo 
'<noscript>';
        echo 
'<meta http-equiv="refresh" content="0;url='.$url.'" />';
        echo 
'</noscript>';
    }
    exit;
}

function 
go_url($url){ // 간단하게 처리
    
echo "<script>
        document.location.href='
$url';
    </script>"
;
    exit;
}


// 세션변수 생성
function set_session($session_name$value)
{
    if (
PHP_VERSION '5.3.0')
        
session_register($session_name);
    
// PHP 버전별 차이를 없애기 위한 방법
    
$$session_name $_SESSION[$session_name] = $value;
}


// 세션변수값 얻음
function get_session($session_name)
{
    return isset(
$_SESSION[$session_name]) ? $_SESSION[$session_name] : '';
}


// 쿠키변수 생성
function set_cookie($cookie_name$value$expire)
{
    global 
$g5;

    
setcookie(md5($cookie_name), base64_encode($value), G5_SERVER_TIME $expire'/'G5_COOKIE_DOMAIN);
}


// 쿠키변수값 얻음
function get_cookie($cookie_name)
{
    
$cookie md5($cookie_name);
    if (
array_key_exists($cookie$_COOKIE))
        return 
base64_decode($_COOKIE[$cookie]);
    else
        return 
"";
}


// 경고메세지를 경고창으로
function alert($msg=''$url=''$error=true$post=false)
{
    global 
$j3;

    echo 
"<script>";
    echo 
"alert('{$msg}');";
    if(
$url!=''){
        echo 
"document.location.href='{$url}';";
    } else if(
$url!='-1'){
        echo 
"window.history.go(-1);";
    }
    echo 
"</script>";
    exit;
}


// 경고메세지 출력후 창을 닫음
function alert_close($msg$error=true)
{
    global 
$j3;

    echo 
"<script>";
    echo 
"alert('{$msg}');";
    echo 
"window.close();";
    echo 
"</script>";
    exit;
}

// 경고메시지 출력후 창닫고 부모창 리로드
function alert_close_reload($msg){
    global 
$j3;

    echo 
"<script>";
    echo 
"alert('{$msg}');";
    echo 
"parent.window.opener.location.reload();";
    echo 
"window.close();";
    echo 
"</script>";
    exit;
}

// way.co.kr 의 wayboard 참고
function url_auto_link($str)
{
    global 
$g5;
    global 
$config;

    
// 140326 유창화님 제안코드로 수정
    // http://sir.co.kr/bbs/board.php?bo_table=pg_lecture&wr_id=461
    // http://sir.co.kr/bbs/board.php?bo_table=pg_lecture&wr_id=463
    
$str str_replace(array("&lt;""&gt;""&amp;""&quot;""&nbsp;""&#039;"), array("\t_lt_\t""\t_gt_\t""&""\"""\t_nbsp_\t""'"), $str);
    
//$str = preg_replace("`(?:(?:(?:href|src)\s*=\s*(?:\"|'|)){0})((http|https|ftp|telnet|news|mms)://[^\"'\s()]+)`", "<A HREF=\"\\1\" TARGET='{$config['cf_link_target']}'>\\1</A>", $str);
    
$str preg_replace("/([^(href=\"?'?)|(src=\"?'?)]|\(|^)((http|https|ftp|telnet|news|mms):\/\/[a-zA-Z0-9\.-]+\.[가-힣\xA1-\xFEa-zA-Z0-9\.:&#=_\?\/~\+%@;\-\|\,\(\)]+)/i""\\1<A HREF=\"\\2\" TARGET=\"{$config['cf_link_target']}\">\\2</A>"$str);
    
$str preg_replace("/(^|[\"'\s(])(www\.[^\"'\s()]+)/i""\\1<A HREF=\"http://\\2\" TARGET=\"{$config['cf_link_target']}\">\\2</A>"$str);
    
$str preg_replace("/[0-9a-z_-]+@[a-z0-9._-]{4,}/i""<a href=\"mailto:\\0\">\\0</a>"$str);
    
$str str_replace(array("\t_nbsp_\t""\t_lt_\t""\t_gt_\t""'"), array("&nbsp;""&lt;""&gt;""&#039;"), $str);

    
/*
    // 속도 향상 031011
    $str = preg_replace("/&lt;/", "\t_lt_\t", $str);
    $str = preg_replace("/&gt;/", "\t_gt_\t", $str);
    $str = preg_replace("/&amp;/", "&", $str);
    $str = preg_replace("/&quot;/", "\"", $str);
    $str = preg_replace("/&nbsp;/", "\t_nbsp_\t", $str);
    $str = preg_replace("/([^(http:\/\/)]|\(|^)(www\.[^[:space:]]+)/i", "\\1<A HREF=\"http://\\2\" TARGET='{$config['cf_link_target']}'>\\2</A>", $str);
    //$str = preg_replace("/([^(HREF=\"?'?)|(SRC=\"?'?)]|\(|^)((http|https|ftp|telnet|news|mms):\/\/[a-zA-Z0-9\.-]+\.[\xA1-\xFEa-zA-Z0-9\.:&#=_\?\/~\+%@;\-\|\,]+)/i", "\\1<A HREF=\"\\2\" TARGET='$config['cf_link_target']'>\\2</A>", $str);
    // 100825 : () 추가
    // 120315 : CHARSET 에 따라 링크시 글자 잘림 현상이 있어 수정
    $str = preg_replace("/([^(HREF=\"?'?)|(SRC=\"?'?)]|\(|^)((http|https|ftp|telnet|news|mms):\/\/[a-zA-Z0-9\.-]+\.[가-힣\xA1-\xFEa-zA-Z0-9\.:&#=_\?\/~\+%@;\-\|\,\(\)]+)/i", "\\1<A HREF=\"\\2\" TARGET='{$config['cf_link_target']}'>\\2</A>", $str);

    // 이메일 정규표현식 수정 061004
    //$str = preg_replace("/(([a-z0-9_]|\-|\.)+@([^[:space:]]*)([[:alnum:]-]))/i", "<a href='mailto:\\1'>\\1</a>", $str);
    $str = preg_replace("/([0-9a-z]([-_\.]?[0-9a-z])*@[0-9a-z]([-_\.]?[0-9a-z])*\.[a-z]{2,4})/i", "<a href='mailto:\\1'>\\1</a>", $str);
    $str = preg_replace("/\t_nbsp_\t/", "&nbsp;" , $str);
    $str = preg_replace("/\t_lt_\t/", "&lt;", $str);
    $str = preg_replace("/\t_gt_\t/", "&gt;", $str);
    */

    
return $str;
}


// url에 http:// 를 붙인다
function set_http($url)
{
    if (!
trim($url)) return;

    if (!
preg_match("/^(http|https|ftp|telnet|news|mms)\:\/\//i"$url))
        
$url "http://" $url;

    return 
$url;
}


// 파일의 용량을 구한다.
//function get_filesize($file)
function get_filesize($size)
{
    
//$size = @filesize(addslashes($file));
    
if ($size >= 1048576) {
        
$size number_format($size/10485761) . "M";
    } else if (
$size >= 1024) {
        
$size number_format($size/10241) . "K";
    } else {
        
$size number_format($size0) . "byte";
    }
    return 
$size;
}


// 게시글에 첨부된 파일을 얻는다. (배열로 반환)
function get_file($bo_table$wr_id)
{
    global 
$g5$qstr;

    
$file['count'] = 0;
    
$sql " select * from {$g5['board_file_table']} where bo_table = '$bo_table' and wr_id = '$wr_id' order by bf_no ";
    
$result sql_query($sql);
    while (
$row sql_fetch_array($result))
    {
        
$no $row['bf_no'];
        
$file[$no]['href'] = G5_BBS_URL."/download.php?bo_table=$bo_table&amp;wr_id=$wr_id&amp;no=$no$qstr;
        
$file[$no]['download'] = $row['bf_download'];
        
// 4.00.11 - 파일 path 추가
        
$file[$no]['path'] = G5_DATA_URL.'/file/'.$bo_table;
        
$file[$no]['size'] = get_filesize($row['bf_filesize']);
        
$file[$no]['datetime'] = $row['bf_datetime'];
        
$file[$no]['source'] = addslashes($row['bf_source']);
        
$file[$no]['bf_content'] = $row['bf_content'];
        
$file[$no]['content'] = get_text($row['bf_content']);
        
//$file[$no]['view'] = view_file_link($row['bf_file'], $file[$no]['content']);
        
$file[$no]['view'] = view_file_link($row['bf_file'], $row['bf_width'], $row['bf_height'], $file[$no]['content']);
        
$file[$no]['file'] = $row['bf_file'];
        
$file[$no]['image_width'] = $row['bf_width'] ? $row['bf_width'] : 640;
        
$file[$no]['image_height'] = $row['bf_height'] ? $row['bf_height'] : 480;
        
$file[$no]['image_type'] = $row['bf_type'];
        
$file['count']++;
    }

    return 
$file;
}


// 폴더의 용량 ($dir는 / 없이 넘기세요)
function get_dirsize($dir)
{
    
$size 0;
    
$d dir($dir);
    while (
$entry $d->read()) {
        if (
$entry != '.' && $entry != '..') {
            
$size += filesize($dir.'/'.$entry);
        }
    }
    
$d->close();
    return 
$size;
}


/*************************************************************************
**
**  그누보드 관련 함수 모음
**
*************************************************************************/

// 제목을 변환
function conv_subject($subject$len$suffix='')
{
    return 
get_text(cut_str($subject$len$suffix));
}

// 내용을 변환
function conv_content($content$html$filter=true)
{
    global 
$config$board;

    if (
$html)
    {
        
$source = array();
        
$target = array();

        
$source[] = "//";
        
$target[] = "";

        if (
$html == 2) { // 자동 줄바꿈
            
$source[] = "/\n/";
            
$target[] = "<br/>";
        }

        
// 테이블 태그의 개수를 세어 테이블이 깨지지 않도록 한다.
        
$table_begin_count substr_count(strtolower($content), "<table");
        
$table_end_count substr_count(strtolower($content), "</table");
        for (
$i=$table_end_count$i<$table_begin_count$i++)
        {
            
$content .= "</table>";
        }

        
$content preg_replace($source$target$content);

        if(
$filter)
            
$content html_purifier($content);
    }
    else 
// text 이면
    
{
        
// & 처리 : &amp; &nbsp; 등의 코드를 정상 출력함
        
$content html_symbol($content);

        
// 공백 처리
        //$content = preg_replace("/  /", "&nbsp; ", $content);
        
$content str_replace("  ""&nbsp; "$content);
        
$content str_replace("\n ""\n&nbsp;"$content);

        
$content get_text($content1);
        
$content url_auto_link($content);
    }

    return 
$content;
}


// http://htmlpurifier.org/
// Standards-Compliant HTML Filtering
// Safe  : HTML Purifier defeats XSS with an audited whitelist
// Clean : HTML Purifier ensures standards-compliant output
// Open  : HTML Purifier is open-source and highly customizable
function html_purifier($html)
{
    
$f file(G5_PLUGIN_PATH.'/htmlpurifier/safeiframe.txt');
    
$domains = array();
    foreach(
$f as $domain){
        
// 첫행이 # 이면 주석 처리
        
if (!preg_match("/^#/"$domain)) {
            
$domain trim($domain);
            if (
$domain)
                
array_push($domains$domain);
        }
    }
    
// 내 도메인도 추가
    
array_push($domains$_SERVER['HTTP_HOST'].'/');
    
$safeiframe implode('|'$domains);

    include_once(
G5_PLUGIN_PATH.'/htmlpurifier/HTMLPurifier.standalone.php');
    
$config HTMLPurifier_Config::createDefault();
    
// data/cache 디렉토리에 CSS, HTML, URI 디렉토리 등을 만든다.
    
$config->set('Cache.SerializerPath'G5_DATA_PATH.'/cache');
    
$config->set('HTML.SafeEmbed'true);
    
$config->set('HTML.SafeObject'true);
    
$config->set('HTML.SafeIframe'true);
    
$config->set('URI.SafeIframeRegexp','%^(https?:)?//('.$safeiframe.')%');
    
$config->set('Attr.AllowedFrameTargets', array('_blank'));
    
$purifier = new HTMLPurifier($config);
    return 
$purifier->purify($html);
}

// 관리자 정보를 얻음
function get_admin($admin='super'$fields='*')
{
    global 
$config$group$board;
    global 
$g5;

    
$is false;
    if (
$admin == 'board') {
        
$mb sql_fetch("select {$fields} from {$g5['member_table']} where mb_id in ('{$board['bo_admin']}') limit 1 ");
        
$is true;
    }

    if ((
$is && !$mb['mb_id']) || $admin == 'group') {
        
$mb sql_fetch("select {$fields} from {$g5['member_table']} where mb_id in ('{$group['gr_admin']}') limit 1 ");
        
$is true;
    }

    if ((
$is && !$mb['mb_id']) || $admin == 'super') {
        
$mb sql_fetch("select {$fields} from {$g5['member_table']} where mb_id in ('{$config['cf_admin']}') limit 1 ");
    }

    return 
$mb;
}


// 관리자인가?
function is_admin($mb_id)
{
    global 
$config$group$board;

    if (!
$mb_id) return;

    if (
$config['cf_admin'] == $mb_id) return 'super';
    if (isset(
$group['gr_admin']) && ($group['gr_admin'] == $mb_id)) return 'group';
    if (isset(
$board['bo_admin']) && ($board['bo_admin'] == $mb_id)) return 'board';
    return 
'';
}


// '예', '아니오'를 SELECT 형식으로 얻음
function get_yn_select($name$selected='1'$event='')
{
    
$str "<select name=\"$name\" $event>\n";
    if (
$selected) {
        
$str .= "<option value=\"1\" selected>예</option>\n";
        
$str .= "<option value=\"0\">아니오</option>\n";
    } else {
        
$str .= "<option value=\"1\">예</option>\n";
        
$str .= "<option value=\"0\" selected>아니오</option>\n";
    }
    
$str .= "</select>";
    return 
$str;
}

function 
cut_str($str$len$suffix="…")
{
    
$arr_str preg_split("//u"$str, -1PREG_SPLIT_NO_EMPTY);
    
$str_len count($arr_str);

    if (
$str_len >= $len) {
        
$slice_str array_slice($arr_str0$len);
        
$str join(""$slice_str);

        return 
$str . ($str_len $len $suffix '');
    } else {
        
$str join(""$arr_str);
        return 
$str;
    }
}


// TEXT 형식으로 변환
function get_text($str$html=0)
{
    
/* 3.22 막음 (HTML 체크 줄바꿈시 출력 오류때문)
    $source[] = "/  /";
    $target[] = " &nbsp;";
    */

    // 3.31
    // TEXT 출력일 경우 &amp; &nbsp; 등의 코드를 정상으로 출력해 주기 위함
    
if ($html == 0) {
        
$str html_symbol($str);
    }

    
$source[] = "/</";
    
$target[] = "&lt;";
    
$source[] = "/>/";
    
$target[] = "&gt;";
    
//$source[] = "/\"/";
    //$target[] = "&#034;";
    
$source[] = "/\'/";
    
$target[] = "&#039;";
    
//$source[] = "/}/"; $target[] = "&#125;";
    
if ($html) {
        
$source[] = "/\n/";
        
$target[] = "<br/>";
    }

    return 
preg_replace($source$target$str);
}


/*
// HTML 특수문자 변환 htmlspecialchars
function hsc($str)
{
    $trans = array("\"" => "&#034;", "'" => "&#039;", "<"=>"&#060;", ">"=>"&#062;");
    $str = strtr($str, $trans);
    return $str;
}
*/

// 3.31
// HTML SYMBOL 변환
// &nbsp; &amp; &middot; 등을 정상으로 출력
function html_symbol($str)
{
    return 
preg_replace("/\&([a-z0-9]{1,20}|\#[0-9]{0,3});/i""&#038;\\1;"$str);
}


/*************************************************************************
**
**  SQL 관련 함수 모음
**
*************************************************************************/

// 쿼리를 실행한 후 결과값에서 한행을 얻는다.
function sql_fetch($sql$connect$error=G5_DISPLAY_SQL_ERROR)
{
    
$result mysql_query($sql$connect);
    
//$row = @sql_fetch_array($result) or die("<p>$sql<p>" . mysql_errno() . " : " .  mysql_error() . "<p>error file : $_SERVER['SCRIPT_NAME']");
    
$row mysql_fetch_array($result);
    return 
$row;
}

// PHPMyAdmin 참고
function get_table_define($table$crlf="\n")
{
    global 
$g5;

    
// For MySQL < 3.23.20
    
$schema_create .= 'CREATE TABLE ' $table ' (' $crlf;

    
$sql 'SHOW FIELDS FROM ' $table;
    
$result sql_query($sql);
    while (
$row sql_fetch_array($result))
    {
        
$schema_create .= '    ' $row['Field'] . ' ' $row['Type'];
        if (isset(
$row['Default']) && $row['Default'] != '')
        {
            
$schema_create .= ' DEFAULT \'' $row['Default'] . '\'';
        }
        if (
$row['Null'] != 'YES')
        {
            
$schema_create .= ' NOT NULL';
        }
        if (
$row['Extra'] != '')
        {
            
$schema_create .= ' ' $row['Extra'];
        }
        
$schema_create     .= ',' $crlf;
    } 
// end while
    
sql_free_result($result);

    
$schema_create preg_replace('/,' $crlf '$/'''$schema_create);

    
$sql 'SHOW KEYS FROM ' $table;
    
$result sql_query($sql);
    while (
$row sql_fetch_array($result))
    {
        
$kname    $row['Key_name'];
        
$comment  = (isset($row['Comment'])) ? $row['Comment'] : '';
        
$sub_part = (isset($row['Sub_part'])) ? $row['Sub_part'] : '';

        if (
$kname != 'PRIMARY' && $row['Non_unique'] == 0) {
            
$kname "UNIQUE|$kname";
        }
        if (
$comment == 'FULLTEXT') {
            
$kname 'FULLTEXT|$kname';
        }
        if (!isset(
$index[$kname])) {
            
$index[$kname] = array();
        }
        if (
$sub_part 1) {
            
$index[$kname][] = $row['Column_name'] . '(' $sub_part ')';
        } else {
            
$index[$kname][] = $row['Column_name'];
        }
    } 
// end while
    
sql_free_result($result);

    while (list(
$x$columns) = @each($index)) {
        
$schema_create     .= ',' $crlf;
        if (
$x == 'PRIMARY') {
            
$schema_create .= '    PRIMARY KEY (';
        } else if (
substr($x06) == 'UNIQUE') {
            
$schema_create .= '    UNIQUE ' substr($x7) . ' (';
        } else if (
substr($x08) == 'FULLTEXT') {
            
$schema_create .= '    FULLTEXT ' substr($x9) . ' (';
        } else {
            
$schema_create .= '    KEY ' $x ' (';
        }
        
$schema_create     .= implode($columns', ') . ')';
    } 
// end while

    
$schema_create .= $crlf ') ENGINE=MyISAM DEFAULT CHARSET=utf8';

    return 
$schema_create;
// end of the 'PMA_getTableDef()' function


// 리퍼러 체크
function referer_check($url='')
{
    
/*
    // 제대로 체크를 하지 못하여 주석 처리함
    global $g5;

    if (!$url)
        $url = G5_URL;

    if (!preg_match("/^http['s']?:\/\/".$_SERVER['HTTP_HOST']."/", $_SERVER['HTTP_REFERER']))
        alert("제대로 된 접근이 아닌것 같습니다.", $url);
    */
}


// 한글 요일
function get_yoil($date$full=0)
{
    
$arr_yoil = array ('일''월''화''수''목''금''토');

    
$yoil date("w"strtotime($date));
    
$str $arr_yoil[$yoil];
    if (
$full) {
        
$str .= '요일';
    }
    return 
$str;
}

// 문자열이 한글, 영문, 숫자, 특수문자로 구성되어 있는지 검사
function check_string($str$options)
{
    global 
$g5;

    
$s '';
    for(
$i=0;$i<strlen($str);$i++) {
        
$c $str[$i];
        
$oc ord($c);

        
// 한글
        
if ($oc >= 0xA0 && $oc <= 0xFF) {
            if (
$options G5_HANGUL) {
                
$s .= $c $str[$i+1] . $str[$i+2];
            }
            
$i+=2;
        }
        
// 숫자
        
else if ($oc >= 0x30 && $oc <= 0x39) {
            if (
$options G5_NUMERIC) {
                
$s .= $c;
            }
        }
        
// 영대문자
        
else if ($oc >= 0x41 && $oc <= 0x5A) {
            if ((
$options G5_ALPHABETIC) || ($options G5_ALPHAUPPER)) {
                
$s .= $c;
            }
        }
        
// 영소문자
        
else if ($oc >= 0x61 && $oc <= 0x7A) {
            if ((
$options G5_ALPHABETIC) || ($options G5_ALPHALOWER)) {
                
$s .= $c;
            }
        }
        
// 공백
        
else if ($oc == 0x20) {
            if (
$options G5_SPACE) {
                
$s .= $c;
            }
        }
        else {
            if (
$options G5_SPECIAL) {
                
$s .= $c;
            }
        }
    }

    
// 넘어온 값과 비교하여 같으면 참, 틀리면 거짓
    
return ($str == $s);
}


// 한글(2bytes)에서 마지막 글자가 1byte로 끝나는 경우
// 출력시 깨지는 현상이 발생하므로 마지막 완전하지 않은 글자(1byte)를 하나 없앰
function cut_hangul_last($hangul)
{
    global 
$g5;

    
// 한글이 반쪽나면 ?로 표시되는 현상을 막음
    
$cnt 0;
    for(
$i=0;$i<strlen($hangul);$i++) {
        
// 한글만 센다
        
if (ord($hangul[$i]) >= 0xA0) {
            
$cnt++;
        }
    }

    return 
$hangul;
}


// 테이블에서 INDEX(키) 사용여부 검사
function explain($sql)
{
    if (
preg_match("/^(select)/i"trim($sql))) {
        
$q "explain $sql";
        echo 
$q;
        
$row sql_fetch($q);
        if (!
$row['key']) $row['key'] = "NULL";
        echo 
" <font color=blue>(type={$row['type']} , key={$row['key']})</font>";
    }
}

// 악성태그 변환
function bad_tag_convert($code)
{
    global 
$view;
    global 
$member$is_admin;

    if (
$is_admin && $member['mb_id'] != $view['mb_id']) {
        
//$code = preg_replace_callback("#(\<(embed|object)[^\>]*)\>(\<\/(embed|object)\>)?#i",
        // embed 또는 object 태그를 막지 않는 경우 필터링이 되도록 수정
        
$code preg_replace_callback("#(\<(embed|object)[^\>]*)\>?(\<\/(embed|object)\>)?#i",
                    
create_function('$matches''return "<div class=\"embedx\">보안문제로 인하여 관리자 아이디로는 embed 또는 object 태그를 볼 수 없습니다. 확인하시려면 관리권한이 없는 다른 아이디로 접속하세요.</div>";'),
                    
$code);
    }

    return 
preg_replace("/\<([\/]?)(script|iframe|form)([^\>]*)\>?/i""&lt;$1$2$3&gt;"$code);
}


// 토큰 생성
function _token()
{
    return 
md5(uniqid(rand(), true));
}


// 불법접근을 막도록 토큰을 생성하면서 토큰값을 리턴
function get_token()
{
    
$token md5(uniqid(rand(), true));
    
set_session('ss_token'$token);

    return 
$token;
}


// POST로 넘어온 토큰과 세션에 저장된 토큰 비교
function check_token()
{
    
set_session('ss_token''');
    return 
true;
}


// 문자열에 utf8 문자가 들어 있는지 검사하는 함수
// 코드 : http://in2.php.net/manual/en/function.mb-check-encoding.php#95289
function is_utf8($str)
{
    
$len strlen($str);
    for(
$i 0$i $len$i++) {
        
$c ord($str[$i]);
        if (
$c 128) {
            if ((
$c 247)) return false;
            elseif (
$c 239$bytes 4;
            elseif (
$c 223$bytes 3;
            elseif (
$c 191$bytes 2;
            else return 
false;
            if ((
$i $bytes) > $len) return false;
            while (
$bytes 1) {
                
$i++;
                
$b ord($str[$i]);
                if (
$b 128 || $b 191) return false;
                
$bytes--;
            }
        }
    }
    return 
true;
}


// UTF-8 문자열 자르기
// 출처 : https://www.google.co.kr/search?q=utf8_strcut&aq=f&oq=utf8_strcut&aqs=chrome.0.57j0l3.826j0&sourceid=chrome&ie=UTF-8
function utf8_strcut$str$size$suffix='...' )
{
        
$substr substr$str0$size );
        
$multi_size preg_match_all'/[\x80-\xff]/'$substr$multi_chars );

        if ( 
$multi_size )
            
$size $size intval$multi_size ) - 1;

        if ( 
strlen$str ) > $size ) {
            
$str substr$str0$size );
            
$str preg_replace'/(([\x80-\xff]{3})*?)([\x80-\xff]{0,2})$/''$1'$str );
            
$str .= $suffix;
        }

        return 
$str;
}


/*
-----------------------------------------------------------
    Charset 을 변환하는 함수
-----------------------------------------------------------
iconv 함수가 있으면 iconv 로 변환하고
없으면 mb_convert_encoding 함수를 사용한다.
둘다 없으면 사용할 수 없다.
*/
function convert_charset($from_charset$to_charset$str)
{

    if( 
function_exists('iconv') )
        return 
iconv($from_charset$to_charset$str);
    elseif( 
function_exists('mb_convert_encoding') )
        return 
mb_convert_encoding($str$to_charset$from_charset);
    else
        die(
"Not found 'iconv' or 'mbstring' library in server.");
}


// mysql_real_escape_string 의 alias 기능을 한다.
function sql_real_escape_string($field)
{
    global 
$g5;

    return 
mysql_real_escape_string($field$g5['connect_db']);
}

function 
escape_trim($field)
{
    
$str call_user_func(G5_ESCAPE_FUNCTION$field);
    return 
$str;
}


// $_POST 형식에서 checkbox 엘리먼트의 checked 속성에서 checked 가 되어 넘어 왔는지를 검사
function is_checked($field)
{
    return !empty(
$_POST[$field]);
}


function 
abs_ip2long($ip='')
{
    
$ip $ip $ip $_SERVER['REMOTE_ADDR'];
    return 
abs(ip2long($ip));
}


function 
get_selected($field$value)
{
    return (
$field==$value) ? ' selected="selected"' '';
}


function 
get_checked($field$value)
{
    return (
$field==$value) ? ' checked="checked"' '';
}


function 
is_mobile()
{
    return 
preg_match('/'.G5_MOBILE_AGENT.'/i'$_SERVER['HTTP_USER_AGENT']);
}


/*******************************************************************************
    유일한 키를 얻는다.

    결과 :

        년월일시분초00 ~ 년월일시분초99
        년(4) 월(2) 일(2) 시(2) 분(2) 초(2) 100분의1초(2)
        총 16자리이며 년도는 2자리로 끊어서 사용해도 됩니다.
        예) 2008062611570199 또는 08062611570199 (2100년까지만 유일키)

    사용하는 곳 :
    1. 게시판 글쓰기시 미리 유일키를 얻어 파일 업로드 필드에 넣는다.
    2. 주문번호 생성시에 사용한다.
    3. 기타 유일키가 필요한 곳에서 사용한다.
*******************************************************************************/
// 기존의 get_unique_id() 함수를 사용하지 않고 get_uniqid() 를 사용한다.

// CHARSET 변경 : euc-kr -> utf-8
function iconv_utf8($str)
{
    return 
iconv('euc-kr''utf-8'$str);
}


// CHARSET 변경 : utf-8 -> euc-kr
function iconv_euckr($str)
{
    return 
iconv('utf-8''euc-kr'$str);
}


// PC 또는 모바일 사용인지를 검사
function check_device($device)
{
    global 
$is_admin;

    if (
$is_admin) return;

    if (
$device=='pc' && G5_IS_MOBILE) {
        
alert('PC 전용 게시판입니다.'G5_URL);
    } else if (
$device=='mobile' && !G5_IS_MOBILE) {
        
alert('모바일 전용 게시판입니다.'G5_URL);
    }
}

// 로그인 후 이동할 URL
function login_url($url='')
{
    if (!
$url$url G5_URL;
    
/*
    $p = parse_url($url);
    echo urlencode($_SERVER['REQUEST_URI']);
    return $url.urldecode(preg_replace("/^".urlencode($p['path'])."/", "", urlencode($_SERVER['REQUEST_URI'])));
    */
    
return $url;
}


// $dir 을 포함하여 https 또는 http 주소를 반환한다.
function https_url($dir$https=true)
{
    if (
$https) {
        if (
G5_HTTPS_DOMAIN) {
            
$url G5_HTTPS_DOMAIN.'/'.$dir;
        } else {
            
$url G5_URL.'/'.$dir;
        }
    } else {
        if (
G5_DOMAIN) {
            
$url G5_DOMAIN.'/'.$dir;
        } else {
            
$url G5_URL.'/'.$dir;
        }
    }

    return 
$url;
}


// goo.gl 짧은주소 만들기
function googl_short_url($longUrl)
{
    global 
$config;

    
// Get API key from : http://code.google.com/apis/console/
    // URL Shortener API ON
    
$apiKey $config['cf_googl_shorturl_apikey'];

    
$postData = array('longUrl' => $longUrl);
    
$jsonData json_encode($postData);

    
$curlObj curl_init();

    
curl_setopt($curlObjCURLOPT_URL'https://www.googleapis.com/urlshortener/v1/url?key='.$apiKey);
    
curl_setopt($curlObjCURLOPT_RETURNTRANSFER1);
    
curl_setopt($curlObjCURLOPT_SSL_VERIFYPEER0);
    
curl_setopt($curlObjCURLOPT_HEADER0);
    
curl_setopt($curlObjCURLOPT_HTTPHEADER, array('Content-type:application/json'));
    
curl_setopt($curlObjCURLOPT_POST1);
    
curl_setopt($curlObjCURLOPT_POSTFIELDS$jsonData);

    
$response curl_exec($curlObj);

    
//change the response json string to object
    
$json json_decode($response);

    
curl_close($curlObj);

    return 
$json->id;
}


// get_sock 함수 대체
if (!function_exists("get_sock")) {
    function 
get_sock($url)
    {
        
// host 와 uri 를 분리
        //if (ereg("http://([a-zA-Z0-9_\-\.]+)([^<]*)", $url, $res))
        
if (preg_match("/http:\/\/([a-zA-Z0-9_\-\.]+)([^<]*)/"$url$res))
        {
            
$host $res[1];
            
$get  $res[2];
        }

        
// 80번 포트로 소캣접속 시도
        
$fp fsockopen ($host80$errno$errstr30);
        if (!
$fp)
        {
            die(
"$errstr ($errno)\n");
        }
        else
        {
            
fputs($fp"GET $get HTTP/1.0\r\n");
            
fputs($fp"Host: $host\r\n");
            
fputs($fp"\r\n");

            
// header 와 content 를 분리한다.
            
while (trim($buffer fgets($fp,1024)) != "")
            {
                
$header .= $buffer;
            }
            while (!
feof($fp))
            {
                
$buffer .= fgets($fp,1024);
            }
        }
        
fclose($fp);

        
// content 만 return 한다.
        
return $buffer;
    }
}

// input vars 체크
function check_input_vars()
{
    
$max_input_vars ini_get('max_input_vars');

    if(
$max_input_vars) {
        
$post_vars count($_POSTCOUNT_RECURSIVE);
        
$get_vars count($_GETCOUNT_RECURSIVE);
        
$cookie_vars count($_COOKIECOUNT_RECURSIVE);

        
$input_vars $post_vars $get_vars $cookie_vars;

        if(
$input_vars $max_input_vars) {
            
alert('폼에서 전송된 변수의 개수가 max_input_vars 값보다 큽니다.\\n전송된 값중 일부는 유실되어 DB에 기록될 수 있습니다.\\n\\n문제를 해결하기 위해서는 서버 php.ini의 max_input_vars 값을 변경하십시오.');
        }
    }
}

// HTML 특수문자 변환 htmlspecialchars
function htmlspecialchars2($str)
{
    
$trans = array("\"" => "&#034;""'" => "&#039;""<"=>"&#060;"">"=>"&#062;");
    
$str strtr($str$trans);
    return 
$str;
}

// date 형식 변환
function conv_date_format($format$date$add='')
{
    if(
$add)
        
$timestamp strtotime($addstrtotime($date));
    else
        
$timestamp strtotime($date);

    return 
date($format$timestamp);
}

// 검색어 특수문자 제거
function get_search_string($stx)
{
    
$stx_pattern = array();
    
$stx_pattern[] = '#\.*/+#';
    
$stx_pattern[] = '#\\\*#';
    
$stx_pattern[] = '#\.{2,}#';
    
$stx_pattern[] = '#[/\'\"%=*\#\(\)\|\+\&\!\$~\{\}\[\]`;:\?\^\,]+#';

    
$stx_replace = array();
    
$stx_replace[] = '';
    
$stx_replace[] = '';
    
$stx_replace[] = '.';
    
$stx_replace[] = '';

    
$stx preg_replace($stx_pattern$stx_replace$stx);

    return 
$stx;
}

// XSS 관련 태그 제거
function clean_xss_tags($str)
{
    
$str preg_replace('#</*(?:applet|b(?:ase|gsound|link)|embed|frame(?:set)?|i(?:frame|layer)|l(?:ayer|ink)|meta|object|s(?:cript|tyle)|title|xml)[^>]*+>#i'''$str);

    return 
$str;
}

// unescape nl 얻기
function conv_unescape_nl($str)
{
    
$search = array('\\r''\r''\\n''\n');
    
$replace = array(''''"\n""\n");

    return 
str_replace($search$replace$str);
}

// 이메일 주소 추출
function get_email_address($email)
{
    
preg_match("/[0-9a-z._-]+@[a-z0-9._-]{4,}/i"$email$matches);

    return 
$matches[0];
}

// 파일명에서 특수문자 제거
function get_safe_filename($name)
{
    
$pattern '/["\'<>=#&!%\\\\(\)\*\+\?]/';
    
$name preg_replace($pattern''$name);

    return 
$name;
}

// 문자열 암호화
function get_encrypt_string($str)
{
    if(
defined('G5_STRING_ENCRYPT_FUNCTION') && G5_STRING_ENCRYPT_FUNCTION) {
        
$encrypt call_user_func(G5_STRING_ENCRYPT_FUNCTION$str);
    } else {
        
$encrypt sql_password($str);
    }

    return 
$encrypt;
}

// 비밀번호 비교
function check_password($pass$hash)
{
    
$password get_encrypt_string($pass);

    return (
$password === $hash);
}

// 동일한 host url 인지
function check_url_host($url$msg=''$return_url=G5_URL)
{
    if(!
$msg)
        
$msg 'url에 타 도메인을 지정할 수 없습니다.';

    
$p parse_url($url);
    
$host preg_replace('/:[0-9]+$/'''$_SERVER['HTTP_HOST']);

    if ((isset(
$p['scheme']) && $p['scheme']) || (isset($p['host']) && $p['host'])) {
        
//if ($p['host'].(isset($p['port']) ? ':'.$p['port'] : '') != $_SERVER['HTTP_HOST']) {
        
if ($p['host'] != $host) {
            echo 
'<script>'.PHP_EOL;
            echo 
'alert("url에 타 도메인을 지정할 수 없습니다.");'.PHP_EOL;
            echo 
'document.location.href = "'.$return_url.'";'.PHP_EOL;
            echo 
'</script>'.PHP_EOL;
            echo 
'<noscript>'.PHP_EOL;
            echo 
'<p>'.$msg.'</p>'.PHP_EOL;
            echo 
'<p><a href="'.$return_url.'">돌아가기</a></p>'.PHP_EOL;
            echo 
'</noscript>'.PHP_EOL;
            exit;
        }
    }
}

// QUERY STRING 에 포함된 XSS 태그 제거
function clean_query_string($query$amp=true)
{
    
$qstr trim($query);

    
parse_str($qstr$out);

    if(
is_array($out)) {
        
$q = array();

        foreach(
$out as $key=>$val) {
            
$key strip_tags(trim($key));
            
$val trim($val);

            switch(
$key) {
                case 
'wr_id':
                    
$val = (int)preg_replace('/[^0-9]/'''$val);
                    
$q[$key] = $val;
                    break;
                case 
'sca':
                    
$val clean_xss_tags($val);
                    
$q[$key] = $val;
                    break;
                case 
'sfl':
                    
$val preg_replace("/[\<\>\'\"\\\'\\\"\%\=\(\)\s]/"""$val);
                    
$q[$key] = $val;
                    break;
                case 
'stx':
                    
$val get_search_string($val);
                    
$q[$key] = $val;
                    break;
                case 
'sst':
                    
$val preg_replace("/[\<\>\'\"\\\'\\\"\%\=\(\)\s]/"""$val);
                    
$q[$key] = $val;
                    break;
                case 
'sod':
                    
$val preg_match("/^(asc|desc)$/i"$val) ? $val '';
                    
$q[$key] = $val;
                    break;
                case 
'sop':
                    
$val preg_match("/^(or|and)$/i"$val) ? $val '';
                    
$q[$key] = $val;
                    break;
                case 
'spt':
                    
$val = (int)preg_replace('/[^0-9]/'''$val);
                    
$q[$key] = $val;
                    break;
                case 
'page':
                    
$val = (int)preg_replace('/[^0-9]/'''$val);
                    
$q[$key] = $val;
                    break;
                case 
'w':
                    
$val substr($val02);
                    
$q[$key] = $val;
                    break;
                case 
'bo_table':
                    
$val preg_replace('/[^a-z0-9_]/i'''$val);
                    
$val substr($val020);
                    
$q[$key] = $val;
                    break;
                case 
'gr_id':
                    
$val preg_replace('/[^a-z0-9_]/i'''$val);
                    
$q[$key] = $val;
                    break;
                default:
                    
$val clean_xss_tags($val);
                    
$q[$key] = $val;
                    break;
            }
        }

        if(
$amp)
            
$sep '&amp;';
        else
            
$sep ='&';

        
$str http_build_query($q''$sep);
    } else {
        
$str clean_xss_tags($qstr);
    }

    return 
$str;
}

function 
get_device_change_url()
{
    
$p parse_url(G5_URL);
    
$href $p['scheme'].'://'.$p['host'];
    if(isset(
$p['port']) && $p['port'])
        
$href .= ':'.$p['port'];
    
$href .= $_SERVER['SCRIPT_NAME'];

    
$q = array();
    
$device 'device='.(G5_IS_MOBILE 'pc' 'mobile');

    if(
$_SERVER['QUERY_STRING']) {
        foreach(
$_GET as $key=>$val) {
            if(
$key == 'device')
                continue;

            
$key strip_tags($key);
            
$val strip_tags($val);

            if(
$key && $val)
                
$q[$key] = $val;
        }
    }

    if(!empty(
$q)) {
        
$query http_build_query($q'''&amp;');
        
$href .= '?'.$query.'&amp;'.$device;
    } else {
        
$href .= '?'.$device;
    }

    return 
$href;
}

function 
_pr($v){
    echo 
"<pre>";
    
print_r($v);
    echo 
"</pre>";
}

function 
_ta($v){
    echo 
"<textarea rows=5 cols=60>";print_r($v);echo "</textarea>";
}

$mg_array = array();

function 
desc_table($table,$exp=""){
    
$sql "DESCRIBE $table ";
    
$res2 sql_query($sql);
    while(
$info2=mysql_fetch_array($res2)){
        if(
$info2[0]!=$exp){
            
$orderinfo_fa[] = $info2[0];
        }
    }
    return 
$orderinfo_fa;
}

function 
array_utf8($info){
    
$newinfo null;
    foreach(
$info as $key => $val){
        if(
is_array($val)){
            
$ninfo null;
            foreach(
$val as $k => $v){
                
$ninfo[$k] = stripslashes(iconv_utf8($v));
            }
            
$newinfo[$key] = $ninfo;
        } else {
            
$newinfo[$key] = stripslashes(iconv_utf8($val));
        }
    }
    return 
$newinfo;
}

function 
array_euckr($info){
    
$newinfo null;
    foreach(
$info as $key => $val){
        if(
is_array($val)){
            
$ninfo null;
            foreach(
$val as $k => $v){
                
$ninfo[$k] = stripslashes(iconv_euckr($v));
            }
            
$newinfo[$key] = $ninfo;
        } else {
            
$newinfo[$key] = stripslashes(iconv_euckr($val));
        }
    }
    return 
$newinfo;
}

function 
paging_select($list_num){
    Global 
$config;
    
    
$line_array = array($config['page_line'],30,50,100);

    
$html "<select name='page_sel' class='paging_sel_class'>";
    foreach(
$line_array as $key=>$val){
        if(
$val==$list_num){
            
$html .= "<option value='{$val}' selected>{$val}라인</option>";
        } else {
            
$html .= "<option value='{$val}'>{$val}라인</option>";
        }
    }
    
$html .= "</select>";

    return 
$html;
}

function 
vattype_select($vattype){
    if(
$vattype=='0'){ $sel1 " selected"; }
    if(
$vattype=='1' || $vattype==''){ $sel2 " selected"; }
    if(
$vattype=='2'){ $sel3 " selected"; }
    
$html "<select name='vattype' class='vattype_sel_class'>";
    
$html .= "<option value='0' {$sel1}>안함</option>";
    
$html .= "<option value='1' {$sel2}>부가세포함</option>";    
    
$html .= "<option value='2' {$sel3}>부가세별도</option>";    
    
$html .= "</select>";

    return 
$html;
}

function 
vattype_select2($vattype){
    if(
$vattype=='0'){ $sel1 " selected"; }
    if(
$vattype=='1' || $vattype==''){ $sel2 " selected"; }
    if(
$vattype=='2'){ $sel3 " selected"; }
    
$html "<select name='vattype[]' class='vattype_sel_class'>";
    
$html .= "<option value='0' {$sel1}>안함</option>";
    
$html .= "<option value='1' {$sel2}>부가세포함</option>";    
    
$html .= "<option value='2' {$sel3}>부가세별도</option>";    
    
$html .= "</select>";

    return 
$html;
}

function 
taxyn_select($tax_yn){
    if(
$tax_yn=='0'){ $sel1 " selected"; }
    if(
$tax_yn=='1' || $tax_yn==''){ $sel2 " selected"; }
    if(
$tax_yn=='2'){ $sel3 " selected"; }
    
$html "<select name='tax_yn' class='tax_yn_sel_class'>";
    
$html .= "<option value='0' {$sel1}>면세</option>";
    
$html .= "<option value='1' {$sel2}>과세</option>";    
    
$html .= "<option value='2' {$sel3}>영세</option>";    
    
$html .= "</select>";

    return 
$html;
}

function 
qstr_extract($qstr){ // qstr같은 문자를 extract로 변수로 만들어줌
    
Global $_GET;

    
$v explode("&",$qstr);
    foreach(
$v as $key=>$val){
        
$vv explode("=",$val);
        
$_GET[$vv[0]] = $vv[1];
    }
}

function 
Number($v){
    return 
preg_replace("/[^0-9]/"""$v);
}

function 
urltopdf_rand($lenth=16){
    
$len $lenth;
    
$chars "abcdefghijklmnopqrstuvwxyz123456789";

    
srand((double)microtime()*1000000);

    
$i 0;
    
$str '';

    while (
$i $len) {
        
$num rand() % strlen($chars);
        
$tmp substr($chars$num1);
        
$str .= $tmp;
        
$i++;
    }

    return 
$str;
}

function 
mcr_time_rnd(){
    
$v microtime();
    
$v1 substr($v,0,10);    $v2 substr($v,11,8);
    
$rnd $v1.$v2;

    return 
$rnd;
}

function 
micro_time_6(){
    
$v explode(".",mcr_time_rnd());
    return 
substr($v[1],0,6);

}

function 
encrypt($string$key) {
  
$result '';
  for(
$i=0$i<strlen($string); $i++) {
    
$char substr($string$i1);
    
$keychar substr($key, ($i strlen($key))-11);
    
$char chr(ord($char)+ord($keychar));
    
$result.=$char;
  }
  return 
base64_encode($result);
}

function 
decrypt($string$key) {
  
$result '';
  
$string base64_decode($string);
  for(
$i=0$i<strlen($string); $i++) {
    
$char substr($string$i1);
    
$keychar substr($key, ($i strlen($key))-11);
    
$char chr(ord($char)-ord($keychar));
    
$result.=$char;
  }
  return 
$result;
}

/*function get_customers_info($ccode){
    Global $connect_j3;

    $sql = "select * from customers where code = $ccode limit 1";
    $res = mysql_query($sql,$connect_j3);
    $minfo = mysql_fetch_array($res);
    
    return $minfo;
}*/

function array_sort($array$on$order=SORT_ASC// 배열 정렬 array_sort($list_array,"pos", SORT_ASC)
{
    
$new_array = array();
    
$sortable_array = array();

    if (
count($array) > 0) {
        foreach (
$array as $k => $v) {
            if (
is_array($v)) {
                foreach (
$v as $k2 => $v2) {
                    if (
$k2 == $on) {
                        
$sortable_array[$k] = $v2;
                    }
                }
            } else {
                
$sortable_array[$k] = $v;
            }
        }

        switch (
$order) {
            case 
SORT_ASC:
                
asort($sortable_array);
            break;
            case 
SORT_DESC:
                
arsort($sortable_array);
            break;
        }

        foreach (
$sortable_array as $k => $v) {
            
$new_array[$k] = $array[$k];
        }
    }

    return 
$new_array;
}

function 
number_change($str){
    
$testlen strlen($str);
    
$tests "";
    for(
$i=0$i $testlen$i++){
        
$test_substr substr($str,$i,1);
        if(
preg_match("/[-0-9]/",$test_substr) == true){
            
$str1 .= $test_substr;
        }
    }
    return 
$str1;
}

function 
curl_call($loginUrl,$login_data){
    
$ch curl_init(); 
    
curl_setopt ($chCURLOPT_URL,$loginUrl); //접속할 URL 주소 
    
curl_setopt ($chCURLOPT_SSL_VERIFYPEERfalse); 
    
curl_setopt ($chCURLOPT_SSLVERSION,1); 
    
curl_setopt ($chCURLOPT_HEADER0); 
    
curl_setopt ($chCURLOPT_POST1); 
    
curl_setopt($chCURLOPT_POSTFIELDS$login_data); 
    
curl_setopt ($chCURLOPT_TIMEOUT30); 
    
curl_setopt ($chCURLOPT_RETURNTRANSFER1); 
    
$result curl_exec($ch); 
    return 
$result;
}

function 
curl_call_get($loginUrl){
    
$ch curl_init(); 
    
curl_setopt ($chCURLOPT_URL,$loginUrl); //접속할 URL 주소 
    
curl_setopt ($chCURLOPT_SSL_VERIFYPEERfalse); 
    
curl_setopt ($chCURLOPT_SSLVERSION,1); 
    
curl_setopt ($chCURLOPT_HEADER0); 
    
curl_setopt ($chCURLOPT_POST0); 
    
curl_setopt ($chCURLOPT_TIMEOUT30); 
    
curl_setopt ($chCURLOPT_RETURNTRANSFER1); 
    
$result curl_exec ($ch); 
    return 
$result;
}

function 
sms_send_log($id,$url,$result){
    Global 
$j3$_SESSION;

    
$date_dir date("Ymd",time());
    @
mkdir($j3['j3_data_path']."/sms_log/");
    
$fp fopen($j3['j3_data_path']."/sms_log/{$date_dir}.txt",'a');
    
$content "[".$id."]".chr(10).$url.chr(10).$result.chr(10).chr(10);
    
fwrite($fp,$content);
    
fclose($fp);
}

function 
kakao_send_log($id,$url,$parameters,$result){
    Global 
$j3$_SESSION;

    
//echo "<textarea>".$result."</textarea>";
    
$json json_encode($parameters);

    
$date_dir date("Ymd",time());
    @
mkdir($j3['j3_data_path']."/kakao_log/");
    
$fp fopen($j3['j3_data_path']."/kakao_log/{$date_dir}.txt",'a');
    
$content date("Y-m-d H:i:s",time()).chr(10)."[".$id."]".chr(10).$url.chr(10).$json.chr(10).$result.chr(10).chr(10);
    
//echo "<textarea>".$content."</textarea>";
    
fwrite($fp,$content);
    
fclose($fp);
}

function 
make_thumb($file$thumb$t_width,$t_height){
  
$source_image imagecreatefromstring(file_get_contents($file)); //파일읽기
  
$width imagesx($source_image);
  
$height imagesy($source_image);

  
$virtual_image imagecreatetruecolor($t_width$t_height); //가상 이미지 만들기
  
imagecopyresampled($virtual_image$source_image0000$t_width$t_height$width$height); //사이즈 변경하여 복사
  
imagepng($virtual_image$thumb); // png파일로 썸네일 생성
}

function 
get_it_thumbnail($code,$pics,$width,$height=0){
    Global 
$j3;

    
$v explode("/",$pics);
    
$pic $v[count($v)-1];
    
$f_path "{$j3['j3_data_path']}/product/{$code}/{$pic}";
    if(
$pic!='' && file_exists($f_path)){
        if(
$height==0){
            
$fsize getimagesize($f_path);
            
$fb $width/$fsize[0];
            
$height round($fsize[1]*$fb);
        }
        
$thumb "{$j3['j3_data_path']}/product/{$code}/{$pic}_{$width}_{$height}";
        if(!
file_exists($thumb)){
            
$v getimagesize($f_path);
            if(
$v[0]>5500 || $v[1]>5500){ // 픽셀이 7~8천넘는경우 쎔네일할때 오류(용량문제일수 있음)가 발생해서 썸네일 제외하게 처리(오류난파일 9804*7211에 12메가였음)

            
} else {
                
make_thumb($f_path$thumb$width$height);
            }
        }
        return 
"{$j3['j3_data_url']}/product/{$code}/{$pic}_{$width}_{$height}";
    } else {
        if(
$j3['app_id']=='jaeshim1439'){ // 현동몰만 다른 이미지 처리
            
return "../img/no_image.jpg";
        } else {
            return 
"http://via.placeholder.com/{$width}x{$height}";
        }
    }
}

function 
get_img_thumbnail($img_path,$img_url,$img_name,$width,$height=0){
    Global 
$j3;

    
$f_path $img_path;
    if(
$img_name!='' && file_exists($f_path)){
        if(
$height==0){
            
$fsize getimagesize($f_path);
            
$fb $width/$fsize[0];
            
$height round($fsize[1]*$fb);
        }
        
$thumb "{$img_path}/{$img_name}_{$width}_{$height}";
        if(!
file_exists($thumb)){
            
make_thumb($f_path."/".$img_name$thumb$width$height);
        }
        return 
"{$img_url}/{$img_name}_{$width}_{$height}";
    } else {
        if(
$j3['app_id']=='jaeshim1439'){ // 현동몰만 다른 이미지 처리
            
return "../img/no_image.jpg";
        } else {
            return 
"http://via.placeholder.com/{$width}x{$height}";
        }
    }
}

// 배송업체 리스트 얻기
function get_delivery_company($company)
{
    
$option '<option value="">없음</option>'.PHP_EOL;
    
$option .= '<option value="자체배송" '.get_selected($company'자체배송').'>자체배송</option>'.PHP_EOL;

    
$dlcomp explode(")"str_replace("("""G5_DELIVERY_COMPANY));
    for (
$i=0$i<count($dlcomp); $i++) {
        if (
trim($dlcomp[$i])=="") continue;
        list(
$value$url$tel) = explode("^"$dlcomp[$i]);
        
$option .= '<option value="'.$value.'" '.get_selected($company$value).'>'.$value.'</option>'.PHP_EOL;
    }

    return 
$option;
}


function 
email_send($mail$m_subj$m_cont$m_send$m_recv){
    Global 
$j3$config$configshop;
    if(
$config['mail_use']=='1'){
        if(
$config['smtp_use']=='1'){
            
$mail->IsSMTP();
            
$mail->Host $config['uc_smtp'];
            
$mail->SMTPAuth true;
            
$mail->Port $config['uc_port'];
            if(
$config['uc_port']=='465'){
                
$mail->SMTPSecure "ssl";        // SSL을 사용함
            
} else if($config['uc_port']=='587'){
                
$mail->SMTPSecure "tls";        // TLS을 사용함
            
}
            
$mail->Username $config['uc_id'];
            
$mail->Password $config['uc_pw'];
        }
        
//echo $mail->Host."-".$mail->Port."-".$mail->SMTPSecure."-".$mail->Username."-".$mail->Password;
        
$mail->Debugoutput 'html';
        
$mail->SMTPDebug 0;
        
$mail->setFrom($m_send$config['shop_title']);
        
$v explode(",",$m_recv); // 받는사람 추가 , 로 여러명 지원
        
foreach($v as $key=>$val){
            if(
trim($val)!=''){
                
$mail->addAddress($val);
            }
        }
        
$mail->Subject $m_subj;
        
$mail->isHTML(true); 
        
$mail->Body "{$m_cont}<br>";
        
//return;
        
if (!$mail->send()) {
            return 
"메일 전송에 실패하였습니다. <br>보내는 메일 설정이나 여러가지를 확인해보시기 바랍니다. <br>기본환경설정->메일설정에서 설정을 확인하시기 바랍니다.<br>".$mail->ErrorInfo;
        } else {
            return 
"OK";
        }
    } else {
        return 
"메일 사용안함 설정됨";
    }

}

function 
array2txt($info){ // 배열을 json비슷하게 정보처리 json_encode시엔 한글깨져서
    
$txt "";
    foreach(
$info as $key=>$val){
        
$txt .= "\"{$key}\":\"{$val}\",";
    }
    
$txt substr($txt,0,strlen($txt));
    return 
"{".$txt."}";
}

function 
update_del_log($table$idx$idx_val,$mode=""){ // 업데이트나 삭제시 마지막정보 로그 남김
    
Global $j3$_SESSION$where_update$_SERVER;

    if(
$_SESSION['where_update']!=''){  $where_update $_SESSION['where_update']; }

    if(
$mode==""){ $mode "update"; }

    
$yearmonth date("Ymd",time());
    
$dateinfo date("Y-m-d H:i:s",time());
    
$content "";
    
$content .= $dateinfo." / ".$_SESSION['id']."/".$_SESSION['id_cust']." / ".$_SERVER['REMOTE_ADDR']." / ".$mode.chr(10)."
"
;

    if(
$mode=="where" || $mode=="where_del"){
        
$sql "select * from {$table} where {$idx} = '{$idx_val}' ";
        
$result mysql_query($sql,$j3['connect_j3']);
        while(
$info=mysql_fetch_array($result)){
            
$content .= json_encode($info,JSON_UNESCAPED_UNICODE).chr(10)."
"
;        
        }
    } else if(
$mode=="update" || $mode=="del" || $mode=="insert"){ // 일반 추가나 업데이트나 삭제시
        
if($where_update!=''){
                
$content .= "update {$table} set {$where_update} where {$idx} in ({$idx_val}) ".chr(10)."
"
;        
        } else {
            
$sql "select * from {$table} where {$idx} in ({$idx_val}) ";
            
$result mysql_query($sql,$j3['connect_j3']);
            while(
$info=mysql_fetch_array($result)){
                
$content .= json_encode($info,JSON_UNESCAPED_UNICODE).chr(10)."
"
;        
            }
            
$content .= chr(10);
        }
    } else if(
$mode=="bankbook"){ // 뱅크북일때 
        
$sql "select * from {$table} where {$idx} = '{$idx_val}'";
        
$result mysql_query($sql,$j3['connect_j3']);
        while(
$info=mysql_fetch_array($result)){
            
$content .= json_encode($info,JSON_UNESCAPED_UNICODE).chr(10)."
"
;
        }
        
$content .= chr(10);
    } else if(
$mode=="config_shop"){ // 쇼핑몰환경 일때 
        
$sql "select * from {$table} where {$idx} = '{$idx_val}'";
        
$result mysql_query($sql,$j3['connect_j3']);
        while(
$info=mysql_fetch_array($result)){
            
$content .= json_encode($info,JSON_UNESCAPED_UNICODE).chr(10)."
"
;        
        }
        
$content .= chr(10);
    }
    
$content iconv("UTF-8","EUCKR",$content);
    
$fp fopen($j3['j3_data_path']."/log/{$yearmonth}_db_{$table}.txt",'a');
    
fwrite($fp,$content);
    
fclose($fp);
}

function 
insert_log($table$idx$sql){ // 입력시 sql 로그
    
Global $j3$_SESSION$_SERVER;

    
$mode "insert";
    
$yearmonth date("Ymd",time());
    
$dateinfo date("Y-m-d H:i:s",time());
    
$content "";
    
$content .= 
"{$dateinfo} / {$_SESSION['id']} / {$_SESSION['id_cust']} / {$_SERVER['REMOTE_ADDR']} / {$mode}
{$idx} / {$sql}
"
;
    
$content iconv("UTF-8","EUCKR",$content);
    
$fp fopen($j3['j3_data_path']."/log/{$yearmonth}_db_{$table}.txt",'a');
    
fwrite($fp,$content);
    
fclose($fp);
}    

function 
table_Field_array_get($v){ // 테이블들의 필드를 정리해서 가져옴 ,로 여러테이블 가능
    
Global $j3;
    
$vv explode(",",$v);

    
$filed_array = array();
    foreach(
$vv as $key=>$table){
        
$sql "desc $table";
        
$res mysql_query($sql,$j3['connect_j3']);
        
$cnt 0;
        while(
$info=mysql_fetch_array($res)){
            if(
$cnt==0){
                
$key_Field $info['Field'];
            }
            
$va = array($table,$key_Field);
            
$filed_array[$info['Field']] = $va;
            
$cnt++;
        }
    }

    return 
$filed_array;
}

function 
cust_cur_point_cal($ccode){ // 쇼핑몰 포인트 정리
    
Global $j3$configshop;

    
$sql "select sum(pt) as sum_pt from
                (select begin_pt as pt from customer_begin_balance where ccode = '
{$ccode}'
                    union
                    select sum(point) as pt from point_edit where ccode = '
{$ccode}' and ocode = '{$configshop['office_code']}'
                    union
                    select sum(savepoint)-sum(usepoint) as pt from receive where ccode = '
{$ccode}' and ocode = '{$configshop['office_code']}'
                    union
                    select sum(b.savepoint) as pt from sale_m a left join sale_d b on a.midx = b.midx where a.ccode = '
{$ccode}' and ocode = '{$configshop['office_code']}'
                    union
                    select ifnull(sum(use_point),0)*-1 as pt
                        from
                        (select use_point , ifnull(sd.cnt,0) as cnt
                            from sale_ord_m m 
                            inner join sale_ord_s s on m.midx = s.midx 
                            left join (select midx, count(*) as cnt from sale_ord_sd group by midx) sd on m.midx = sd.midx
                            where m.ccode = '
{$ccode}'  and m.ocode = '{$configshop['office_code']}' and s.ord_cancel <> 1) aa
                        where cnt = 0
                ) aa "
;
    
//_pr($sql);
    
$pt_info sql_fetch($sql,$j3['connect_j3']);
    
$sum_pt $pt_info['sum_pt'];

    
// 쇼핑몰 포인트로 업데이트
    
$sql "update customers_s set cur_point = '{$sum_pt}' where ccode = '{$ccode}' ";
    
mysql_query($sql,$j3['connect_j3']);
}

function 
update_shop_point($ccode$od_id){ // 주문에 따른 포인트 업데이트 // 이거 사용은 아직 대기
    
Global $j3$configshop;
    if(
$configshop['po_use']=='1'){ // 포인트 사용일경우만
        
$sql "select a.save_point, a.save_point_comp, b.ordstate 
                    from sale_ord_s a inner join sale_ord_m b on a.midx = b.midx
                    where a.od_id = '
{$od_id}' ";
        
$od_info sql_fetch($sql,$j3['connect_j3']);
        if(
$od_info['save_point']>0){
            if(
$od_info['save_point_comp']=='0' && $od_info['ordstate']=='3'){
                
$sql "";
            }
        }
    }
}

function 
customer_ocode($ccode){ // 거래처의 ocode 가져옴
    
Global $j3;

    
$sql "select ocode from customers where code = '{$ccode}' ";
    
$info sql_fetch($sql,$j3['connect_j3']);
    return 
$info['ocode'];
}

function 
product_maker_get(){ // 상품 메이커 정보 가져온다.
    
Global $j3$configshop;

    
$sql "select * from product_maker where 1=1 order by name";
    
$res mysql_query($sql,$j3['connect_j3']);
    while(
$info=mysql_fetch_array($res)){
        
$maker_array[] = $info;        
    }
    return 
$maker_array;
}

/*function product_stock_get($pcode){ // 상품 재고 구함
    Global $j3, $configshop;

    $sql = "select sum(qty) as sum_qty from
                (select qty from stock_begin where pcode = '{$pcode}' and ocode = '{$configshop['office_code']}'
                    union
                    select ifnull(sum(qty),0) as qty     from stock_edit where pcode = '{$pcode}' and ocode = '{$configshop['office_code']}'
                    union
                    select ifnull(sum(qty),0) as qty from buy_m a left join buy_d b on a.midx = b.midx where b.pcode = '{$pcode}' and a.ocode = '{$configshop['office_code']}'
                    union
                    select ifnull(sum(qty),0)*-1 as qty from sale_m a left join sale_d b on a.midx = b.midx where b.pcode = '{$pcode}' and a.ocode = '{$configshop['office_code']}'
                ) aa
            where 1=1
    ";
    $qty_info = sql_fetch($sql,$j3['connect_j3']);
    return $qty_info['sum_qty'];
}*/

function product_info_get($pcode,$admin_info=""){ // 상품정보 정보 가져오게
    
Global $j3$configshop$jego_get_table_sql$id_ccode$cinfo$ev_code;

    
$tmp_id_ccode $id_ccode;
    if(
strlen($pcode)==6){ // code1 일경우
        
$where " and a.code1 = '{$pcode}' ";
    } else { 
// 일반 code 일경우
        
$where " and a.code = '{$pcode}' ";
    }

    Global 
$Global_Where;
    
$where .= $Global_Where;

    
/*$sql = "select sale_dcrate from customers where code = '{$id_ccode}' "; // 다중단가용 거래처할인율 가져오기
    $cinfo = sql_fetch($sql,$j3['connect_j3']);*/

    
$sql "select a.*, b.*, c.*, a.hidden as hid_item, d.code2, d.name as cate_name, e.name as maker_name, c.p_deli_type
            from 
                product_m a 
                inner join product_d b on a.code = b.pcode and b.ocode = '
{$configshop['office_code']}
                inner join product_s c on a.code = c.pcode
                left join product_category_s d on c.prod_cate_code_s = d.code
                left join product_maker e on a.maker_code = e.code
            where 1=1 
{$where} ";
    
//_pr($sql);
    
$pinfo sql_fetch($sql,$j3['connect_j3']);
    if(
$admin_info==""){ // 관리자 아닐때만 다중단자 처리 적용
        
$pinfo['saleprice'] = prod_multi_price_get($pinfo['saleprice'], $pinfo['code'], $cinfo['sale_dcrate'],$pinfo['prod_cate_code']); // 특별단가,다중단가,할인등 처리 함수
    
}
    
$pinfo['point'] = round($pinfo['saleprice']*$pinfo['pointrate']/100); // 상품 포인트
    
if(($configshop['deli_type']=='f' && $pinfo['p_deli_type']=='0') || $pinfo['p_deli_type']=='1'){ // 배송비 처리
        
$pinfo['deli_txt'] = "무료배송";
    } else if(
$configshop['deli_type']=='p' && $pinfo['p_deli_type']=='0'){
        
$pinfo['deli_txt'] = number_format($configshop['deli_price'])."원 (".number_format($configshop['deli_amount'])."원 이상 무료배송)";
    } else if(
$pinfo['p_deli_type']=='2'){
        
$pinfo['deli_txt'] = number_format($pinfo['p_deli_price'])."원 (".number_format($pinfo['p_deli_mm'])."원 이상 무료배송)";
    } else if(
$pinfo['p_deli_type']=='3'){
        
$pinfo['deli_txt'] = number_format($pinfo['p_deli_price'])."원";
    } else if(
$pinfo['p_deli_type']=='4'){
        
$pinfo['deli_txt'] = number_format($pinfo['p_deli_price'])."원 (수량 ".number_format($pinfo['p_deli_mm'])."개 마다 배송비책정)";
    } else if(
$pinfo['p_deli_type']=='5'){
        
$pinfo['deli_txt'] = number_format($pinfo['p_deli_price'])."원 (수량 ".number_format($pinfo['p_deli_mm'])."개 초과시마다 배송비책정)";
    } 
    if(
$admin_info==""){ // 관리자 아닐때만 비고옵션 처리 적용
        
if($configshop['bigo_view_type']=='0'){ $pinfo['remarks'] = ""; } // 옵션에따라서 표시할 비고를 처리
        
else if($configshop['bigo_view_type']=='2'){ $pinfo['remarks'] = $pinfo['p_bigo']; }
    }
    
$pinfo['jego'] = product_jego_get($pinfo['code']);

    if(
$configshop['ev_cart_saleprice']=='1' && $ev_code!=''){ // 이벤트 전용단가가 있을경우
        
$ev_saleprice event_saleprice_get($pinfo['code'], $ev_code);
        if(
$ev_saleprice>0){
            
$pinfo['saleprice'] = $ev_saleprice;
        }
    }

    
$id_ccode $tmp_id_ccode;

    return 
$pinfo;
}

function 
product_jego_get($pcode){
    Global 
$j3$configshop$jego_get_table_sql$jego_get_box_sql;

    
$sql "select code, set_yn, p_jegomax from product_m m inner join product_s s on m.code = s.pcode where m.code = '{$pcode}' ";
    
$pinfo sql_fetch($sql,$j3['connect_j3']);

    if(
$pinfo['p_jegomax']=='1'){ // 쇼핑몰 무한재고체크한경우 신박스던 셋트던 무조건 무한으로 처리되게 수정
            
$jego_info['jego'] = 9999;
    } else {
        if(
$pinfo['set_yn']=='0'){

            
// 단일 상품 재고 검색시엔 속도 개선을 위해서 아래 추가2개의 코드를 치환 적용해서 처리함
            
$one_pcode_sql str_replace("product_s s on a.pcode = s.pcode","product_s s on a.pcode = s.pcode and a.pcode = '{$pcode}'",$jego_get_table_sql);
            
$one_pcode_sql str_replace("group by pcode"," and a.pcode = '{$pcode}' group by pcode",$one_pcode_sql);
            
//_pr($one_pcode_sql);
            
$sql "select aaa.jego from ({$one_pcode_sql}) aaa where aaa.pcode = '{$pcode}' ";
            
$jego_info sql_fetch($sql,$j3['connect_j3']);
            if(
$jego_info['jego']==''){ $jego_info['jego'] = 0; }
        } else if(
$pinfo['set_yn']=='2'){
            
$sql "select box_qty as jego from ({$jego_get_box_sql}) bbb where bbb.parent_pcode = '{$pcode}' ";
            
$jego_info sql_fetch($sql,$j3['connect_j3']);
        } else if(
$pinfo['set_yn']=='1'){
            
$jego_info['jego'] = get_set_jego($pcode);
        } else {
            
$jego_info['jego'] = 9999;
        }
    }

    return 
$jego_info['jego'];
}

function 
product_jego_list_get($pcode_list){ // 일반상품(셋트아닌)기준으로 한꺼번에 재고를 가져오는 방식 product_jego_get($pcode)로 일일히 가져오는것보다 속도가 빠름
    
Global $j3$configshop$jego_get_table_sql$jego_get_box_sql;

    
$sql "select aaa.pcode, ifnull(aaa.jego,0) as jego from ({$jego_get_table_sql}) aaa where aaa.pcode in ({$pcode_list}) ";
    
$res mysql_query($sql,$j3['connect_j3']);
    while(
$info=mysql_fetch_array($res)){
        
$jego_array[$info['pcode']] = $info;
    }
    return 
$jego_array;
}

function 
get_set_jego($code){ // 셋트상품 set_yn = 1일경우의 재고 가져오는 함수
    
Global $j3$configshop$jego_get_table_sql$jego_get_box_sql;

    if(
$configshop['jego_disp_type']=='0'){ // 쇼핑몰 재고
        /*$sql = "select min(aa.s_qty)-sale_ord_qty as jego from 
                (select a.parent_pcode, a.child_pcode, a.child_qty, s.qty, floor(s.qty/a.child_qty) as s_qty, sale_ord_qty
                    from product_set a 
                    inner join product_d d on a.child_pcode = d.pcode and d.ocode = '{$configshop['office_code']}'
                    inner join stock_current s on d.pcode = s.pcode and d.ocode = s.ocode and s.scode = '1'
                    left join (select pcode, sum(qty-out_tot_qty) as sale_ord_qty from sale_ord_d a inner join sale_ord_m b on a.midx = b.midx and b.ocode = '{$configshop['office_code']}' group by pcode )  ss 
                        on ss.pcode = a.parent_pcode
                    where parent_pcode = '{$code}') aa"; // old_sql*/

        
$sql "select min(aa.s_qty)-sale_ord_qty as jego from 
                (select a.parent_pcode, a.child_pcode, a.child_qty, s.qty, floor((s.qty-ifnull(od.sell_qty,0))/a.child_qty) as s_qty, ifnull(od.sell_qty,0), sale_ord_qty
                    from product_set a 
                    inner join product_d d on a.child_pcode = d.pcode and d.ocode = '1'
                    inner join stock_current s on d.pcode = s.pcode and d.ocode = s.ocode and s.scode = '
{$configshop['office_code']}'
                    left join (select pcode, sum(qty-out_tot_qty-cancel_qty) as sell_qty from sale_ord_d a group by pcode) od on a.child_pcode = od.pcode
                    left join (select pcode, sum(qty-out_tot_qty-cancel_qty) as sale_ord_qty from sale_ord_d a inner join sale_ord_m b on a.midx = b.midx and b.ocode = '
{$configshop['office_code']}' group by pcode )  ss 
                        on ss.pcode = a.parent_pcode
                    where parent_pcode = '
{$code}') aa";
    } else {
        
$sql "select min(aa.s_qty) as jego from 
                (select a.parent_pcode, a.child_pcode, a.child_qty, s.qty, floor(s.qty/a.child_qty) as s_qty
                    from product_set a 
                    inner join product_d d on a.child_pcode = d.pcode and d.ocode = '
{$configshop['office_code']}'
                    inner join stock_current s on d.pcode = s.pcode and d.ocode = s.ocode and s.scode = '1'
                where parent_pcode = '
{$code}') aa";
    }
    
//_pr($sql);
    
$info sql_fetch($sql,$j3['connect_j3']);
    return 
$info['jego'];
}

function 
product_s_check($pcode){ // product_s 레코드가 없으면 생성함
    
Global $j3$configshop;
    
$pinfo product_info_get($pcode);
    
    if(
$pinfo['p_soldout'] == NULL || $pinfo['p_soldout'] == ''){
        
$sql "insert into product_s set
                        pcode = '
{$pcode}', p_sort = '0', p_naver = '0', p_type1 = '0', p_type2 = '0', p_type3 = '0', p_type4 = '0', 
                        p_soldout = '0', p_use = '1', p_min_buy = '0', 
                        p_max_buy = '0', p_deli_type = '0', marketprice = '0',
                        item_explain = '', item_mobile_explain = ''
            "
;
        
//_pr($sql);
        
mysql_query($sql,$j3['connect_j3']);

    }

    
$sql "select * from product_s where pcode = '{$pcode}' ";
    
$res mysql_query($sql,$j3['connect_j3']);
    
$info mysql_fetch_array($res);
    if(
$info['prod_cate_code_s']=='0'){
        
$sql "select * from product_m where code = '{$pcode}' ";
        
$res2 mysql_query($sql,$j3['connect_j3']);
        
$info2 mysql_fetch_array($res2);

        
$sql "update product_s set prod_cate_code_s = '{$info2['prod_cate_code']}' where pcode = '{$pcode}' ";
        
mysql_query($sql,$j3['connect_j3']);
    }

}

function 
customer_order_list($ccode$where2$page$list_num){ // 고객의 주문 리스트 가져오게
    
Global $j3$configshop$is_admin$od_state_tit$admin_page$get_row$_SESSION;

    
    if(
$admin_page!='Y'){
        if(
$ccode=='0'){ // 비회원 조회일 경우
            
$where " and a.order_id = 'GUEST' and a.s_name = '{$_SESSION['ss_s_name']}' and (a.s_email = '{$_SESSION['ss_s_email']}' or a.s_hpno = '{$_SESSION['ss_s_email']}') ";
        } else {
            
$where " and b.ccode = '{$ccode}' ";
        }
    } else if(
$ccode!='' && $admin_page=='Y'){ // 관리자 상품 검색일때 처리
        
$add_left_join " left join (select midx, count(*) as p_cnt from sale_ord_d where pname like '%{$ccode}%' group by midx) e on b.midx = e.midx ";
        
$add_where " and p_cnt > 0 ";
    }
    
$orderby " a.midx desc {$add_limit} ";

    
$sql "select [field_list]  
                from sale_ord_s a
                inner join sale_ord_m b on a.midx = b.midx
                left join (select midx, sum(qty) as sum_qty from sale_ord_d where pname <> '쇼핑몰배송비' group by midx) c on a.midx = c.midx
                left join customers d on b.ccode = d.code
                [add_left_join]
            where 1=1  
{$where} {$where2} {$add_where}";

    
$sql_cnt str_replace("[add_left_join]",$add_left_join,$sql);
    
$sql_cnt str_replace("[field_list]","count(*) as cnt",$sql_cnt); // 총 갯수 구함
    
$row sql_fetch($sql_cnt,$j3['connect_j3']);
    
$total_count $row['cnt'];
    if(
$list_num==''){ $list_num 15; }
    
$total_page  ceil($total_count $list_num);  // 전체 페이지 계산
    
$from_record = ($page 1) * $list_num// 시작 열을 구함
    
$limit_add " limit {$from_record},{$list_num}";

    
$sql str_replace("[add_left_join]",$add_left_join,$sql);
    if(
$list_num=='999999'){ // 엑셀다운일때 필드 리스트 처리처리
        
$field_list "a.od_id, d.login_id, c.sum_qty, a.cart_price, a.deli_price, (a.cart_price+a.deli_price+a.deli_price2-a.dc_price-a.use_point-a.deposit_price) as wdeposit_price, a.deposit_price, a.pay_type, b.ordstate, a.dc_price, a.use_point, a.save_point, a.s_name, a.s_telno, a.s_hpno, a.s_zipcode, concat(a.s_addr_m,a.s_addr_d) as s_addr, a.s_email, b.consignee_name, b.consignee_telno, b.consignee_hpno, b.consignee_zipcode, concat(b.consignee_addr_m,b.consignee_addr_d) as consignee_addr, b.transport_msg, a.deli_company, b.tracking_number, a.deposit, a.ord_cancel ";
    } else {
        
$field_list "a.*, b.*, c.*, d.login_id, (a.cart_price+a.deli_price+a.deli_price2) as ord_price, (a.cart_price+a.deli_price+a.deli_price2-a.dc_price-a.use_point-a.deposit_price) as wdeposit_price";
    }
    
$sql str_replace("[field_list]",$field_list,$sql)." order by {$orderby} {$limit_add}";
    
$res mysql_query($sql,$j3['connect_j3']);
    
//echo $sql;
    
if($list_num=='999999'){ // 엑셀다운일때 필드 리스트 처리처리
        
while($ordinfo=mysql_fetch_object($res)){
            
$info null;
            
$col_cnt 0;
            foreach(
$ordinfo as $key=>$val){
                
$info[$key] = $val;
                
$col_cnt++;
            }
            if(
$info['ord_cancel']=='1'){
                
$od_state $od_state_tit['9'];
            } else if(
$info['ordstate']>0){
                
$od_state $od_state_tit[$info['ordstate']];
            } else if(
$info['deposit']=='1'){
                
$od_state $od_state_tit['01'];
            } else {
                
$od_state $od_state_tit['00'];
            }
            
$info['ordstate'] = $od_state;            
            
array_pop($info); array_pop($info); // 배열에서 입금과 취소의 부분을 날림
            
$ord_array[] = $info;
        }
        
$ord_array[0]['col_cnt'] = $col_cnt;
    } else {
        while(
$info=mysql_fetch_array($res)){
            if(
$info['ord_cancel']=='1'){
                
$od_state $od_state_tit['9'];
            } else if(
$info['ordstate']>0){
                
$od_state $od_state_tit[$info['ordstate']];
            } else if(
$info['deposit']=='1'){
                
$od_state $od_state_tit['01'];
            } else {
                
$od_state $od_state_tit['00'];
            }
            
$info['od_state'] = $od_state;

            if(
$list_num=='999998' || $get_row=="Y" || $configshop['prod_danga_view']){ // 주문출력일 경우 상품배열 가져옴                
                
$sql "select c.pcode as sc_pcode, c.opt_mode, c.ct_name, c.ct_price, c.opt_price, c.idx as ct_idx, a.*, b.pic1, ifnull(e.idx,0) as use_idx, c.opt_pcode, c.opt_name, b.norm, b.code1
                            from sale_ord_d a 
                            left join shop_cart c on a.remarks = c.idx
                            left join product_m b on c.pcode = b.code 
                            left join shop_prod_use e on c.idx = e.ct_idx
                        where a.midx = '
{$info['midx']}'
                        order by c.od_id desc, sc_pcode, if(c.opt_mode='','1',if(c.opt_mode='opt','2','3')) asc "
;
                
//echo $sql;
                
$res2 mysql_query($sql,$j3['connect_j3']);
                
$tmp_cart_price 0;
                while(
$row=mysql_fetch_array($res2)){
                    if(
$configshop['prod_danga_view']=='1'){
                        
$row['tot_amt'] = $row['price']*$row['qty'];
                        if(
$row['ct_idx']!=''){ // 배송비나 기타부분 제외하기위해서
                            
$tmp_cart_price += $row['tot_amt'];
                        }
                    }
                    
                    
$info['row'][] = $row;
                }
            }

            if(
$configshop['prod_danga_view']=='1'){
                
$info['wdeposit_price'] = $info['wdeposit_price']-$info['cart_price']+$tmp_cart_price;
                
$info['tot_sale_price'] = $info['tot_sale_price']-$info['cart_price']+$tmp_cart_price;
                
$info['tot_pay_price'] = $info['tot_pay_price']-$info['cart_price']+$tmp_cart_price;
                
$info['ord_price'] = $info['ord_price']-$info['cart_price']+$tmp_cart_price;
                
$info['cart_price'] = $tmp_cart_price;
            }

            
$ord_array[] = $info;
        }
        
$ord_array[0]['total_page'] = $total_page;
        
$ord_array[0]['list_num'] = $list_num;
        
$ord_array[0]['total_count'] = $total_count;
    } 
    return 
$ord_array;
}

function 
customer_info_get($ccode){ // 거래처 정보 가져오게
    
Global $j3$configshop$ocode_where// $ocode_where 정보 조작은 common.php에 있습니다.

    
$sql "select *
                from customers a 
                left join customer_begin_balance b on a.code = b.ccode
                left join customers_s c on a.code = c.ccode
            where 1=1 and code = '
{$ccode}{$ocode_where} ";
    
//_pr($sql);
    
$cinfo sql_fetch($sql,$j3['connect_j3']);
    if(
$cinfo['ccode']==''){
        
//if($cinfo['per_biz_type']=='0' && $cinfo['comp_name']==''){ $cinfo['comp_name'] = $cinfo['ceo_name']; }
        
$cinfo['mb_lv'] = 1;
    } else {
        if(
$cinfo['hidden']=='1'){
            
$_SESSION['id_cust'] = "";
            
$_SESSION['id_ccode'] = "";
            
$_SESSION['id_cname'] = "";
            
$_SESSION['id_ceo'] = "";
            
$_SESSION['ss_od_id'] = "";
            
alert('관리종결된 거래처입니다. 고객센터 연락바랍니다.','./index.php'); exit;
        }
    }
    return 
$cinfo;
}

function 
customer_info_get_by_id($login_id){ // 거래처 정보 가져오게 아이디로
    
Global $j3$configshop$ocode_where// $ocode_where 정보 조작은 common.php에 있습니다.

    
if($login_id==''){ return; }

    
$login_id strtoupper($login_id);
    
$sql "select *
                from customers a 
                left join customer_begin_balance b on a.code = b.ccode
                left join customers_s c on a.code = c.ccode
            where 1=1 and upper(login_id) = '
{$login_id}{$ocode_where} ";
    
//_pr($sql);
    
$cinfo sql_fetch($sql,$j3['connect_j3']);
    
//if($cinfo['per_biz_type']=='0' && $cinfo['comp_name']==''){ $cinfo['comp_name'] = $cinfo['ceo_name']; }
    
return $cinfo;
}

function 
customers_s_check($code$mode=""){ // customer_s 레코드가 없으면 생성함
    
Global $j3$config$configshop$_SERVER;
    
$cinfo customer_info_get($code);
    
    if(
$cinfo['sms_ok'] == NULL){
        
$sql "insert into customers_s set
                        ccode = '
{$code}', sms_ok = '0', mail_ok = '0', deli_free = '0', mb_lv = '{$config['m_level']}', 
                        last_datetime = '"
.date("Y-m-d H:i:s",time())."', last_ip = '192.168.0.1'
            "
;
        
//echo $sql;
        
mysql_query($sql,$j3['connect_j3']);

        
$sql "";
    }

    if(
$mode=='login'){
        
$sql "update customers_s set last_datetime = '".date("Y-m-d H:i:s",time())."', last_ip = '".$_SERVER['REMOTE_ADDR']."' where ccode = '{$code}' ";
        
mysql_query($sql,$j3['connect_j3']);
    }
}

function 
product_category_info_get($pccode){ // 카테고리 정보 가져오게
    
Global $j3$configshop;

    
$sql "select a.*, c.name as parent_name from product_category_s a
                left join product_category_s c on a.parent_code = c.code
            where a.code = '
{$pccode}' ";
    
//_pr($sql);
    
$pcinfo sql_fetch($sql,$j3['connect_j3']);
    return 
$pcinfo;
}

function 
product_category_s_check($code){ // product_category_s 레코드가 없으면 생성함
    
return; // 사용 안함

    
Global $j3$configshop;
    
$pcinfo product_category_info_get($code);
    
    if(
$pcinfo['pccode'] == NULL){
        
$sql "insert into product_category_s set
                        pccode = '
{$code}', pc_use = '1'
            "
;
        
//echo $sql;
        
mysql_query($sql,$j3['connect_j3']);

        
$sql "";
    }
}

// 이미지 URL 을 얻는다.
function get_prod_imageurl($code,$picd="")
{
   Global 
$j3$configshop;

    
$filepath '';

   if(
$picd!=''){
        
$v explode("/",$picd); $pic $v[count($v)-1];
        if(
$pic==''){
            continue;                    
        }
        if(
file_exists("{$j3['j3_data_path']}/product/{$code}/{$pic}")){
            
$filepath "{$j3['j3_data_url']}/product/{$code}/{$pic}";
        }
   } else {

        
$sql " select pic1, pic2, pic3, pic4, pic5
                    from product_m
                    where code = '
$code' ";
        
$row sql_fetch($sql,$j3['connect_j3']);

        for(
$i=1$i<=5$i++) {
            
$v explode("/",$row['pic'.$i]); $pic $v[count($v)-1];
            if(
$row['pic'.$i]==''){
                continue;                    
            }
            if(
file_exists("{$j3['j3_data_path']}/product/{$code}/{$pic}")){
                
$filepath "{$j3['j3_data_url']}/product/{$code}/{$pic}";
                break;
            }
        }
    }

    if(
$filepath)
        
$str $filepath;
    else
        
$str $j3['j3_img_url'].'/no_image.gif';

    return 
$str;
}

function 
get_prod_point($code){ // 상품 포인트 계산
    
Global $j3$configshop;

    
$row product_info_get($code);

    if(
$row['pointrate']==0){ return "0"; }
    else {
        return 
round($row['saleprice'] * $row['pointrate'] / 100);
    }
}

function 
cate_info_get($code){ // 현재 카테고리 코드 정보 가져옴
    
Global $j3$configshop;
    
$sql "select * from product_category_s where 1=1 and code2 = '$code' ";
    
$info sql_fetch($sql,$j3['connect_j3']);
    
$info['code2_1'] = substr($info['code2'],0,3);
    
$info['code2_2'] = substr($info['code2'],3,3);
    
$info['code2_3'] = substr($info['code2'],6,3);
    if(
$info['lv']>0){ // 중분류일경우 대분류의 코드를 가져옴
        
$sql "select code from product_category_s where 1=1 and substring(code2,1,3) = '{$info['code2_1']}' and lv = '0' order by code2";
        
$row sql_fetch($sql,$j3['connect_j3']);
        
$info['pcode_0'] = $row['code'];
    }
    if(
$info['lv']>0){ // 소분류일경우 중분류의 코드를 가져옴
        
$sql "select code from product_category_s where 1=1 and substring(code2,4,3) = '{$info['code2_1']}' and lv = '1' order by code2";
        
$row sql_fetch($sql,$j3['connect_j3']);
        
$info['pcode_1'] = $row['code'];
    }
    
$lv2_cate_codes "";
    if(
$info['lv']=='0'){
        
$info['c1_name'] = $info['name'];
        
$sql "select code from product_category_s a where substring(a.code2,1,3) = '{$info['code2_1']}' and lv = 2 order by code2";
        
$res mysql_query($sql,$j3['connect_j3']);
        while(
$row=mysql_fetch_array($res)){
            
$lv2_cate_code .= "{$row['code']},";
        }
    }
    if(
$info['lv']=='1'){
        
$info['c1_name'] = $info['cate1_name'];
        
$info['c2_name'] = $info['name'];
        
$sql "select code from product_category_s a where substring(a.code2,1,6) = '{$info['code2_1']}{$info['code2_2']}' and lv = 2 order by code2";
        
$res mysql_query($sql,$j3['connect_j3']);
        while(
$row=mysql_fetch_array($res)){
            
$lv2_cate_code .= "{$row['code']},";
        }
    }
    if(
$info['lv']=='2'){
        
$info['c1_name'] = $info['cate1_name'];
        
$info['c2_name'] = $info['cate2_name'];
        
$info['c3_name'] = $info['name'];
        
$lv2_cate_code "{$info['code']},";
    }
    
$info['lv2_cate_code'] = substr($lv2_cate_code,0,strlen($lv2_cate_code)-1);

    if(
$info['lv']=='2'){
        
$info['sub_codes'] = $info['code'].",";
    }
    if(
$info['lv']=='1'){
        
$sql "select code from product_category_s where lv = 2 and code2 like '".substr($code,0,6)."%'  order by code2";
        
$res mysql_query($sql,$j3['connect_j3']);
        while(
$row=mysql_fetch_array($res)){
            
$info['sub_codes'] .= $row['code'].",";
        }
    }
    if(
$info['lv']=='0'){
        
$sql "select code from product_category_s where lv = 2 and code2 like '".substr($code,0,3)."%'  order by code2";
        
$res mysql_query($sql,$j3['connect_j3']);
        while(
$row=mysql_fetch_array($res)){
            
$info['sub_codes'] .= $row['code'].",";
        }
    }
    
$info['sub_codes'] = substr($info['sub_codes'],0,strlen($info['sub_codes'])-1);

    return 
$info;
}

function 
cate_lv0_list_get(){ // 카테고리 레벨 1 가져오기
    
Global $j3$configshop,$jego_get_table_sql$app_id;

    if(
$app_id=='lulucosmetic'){ // 루루샵일경우 btob 분류 제외함
        
$sql "select * from product_category_s where 1=1 and lv = 0 and pc_use = '1' and code2 <> '008000000'  order by code2";
    } else{
        
$sql "select * from product_category_s where 1=1 and lv = 0 and pc_use = '1'  order by code2";
    }
    
$res mysql_query($sql,$j3['connect_j3']);
    while(
$info=mysql_fetch_array($res)){
        if(
$configshop['soldout_hidden']=='1'){ // 품절 숨김일 경우
            
$sql "select count(*) as cnt 
                    from product_m a 
                    inner join product_d b on a.code = b.pcode and b.ocode = '
{$configshop['office_code']}
                    inner join product_s c on a.code = c.pcode
                    where c.prod_cate_code_s in (select code from product_category_s a where a.lv > 0 and a.code2 like '"
.substr($info['code2'],0,3)."%') and c.p_use = 1 and a.hidden<>1 and p_soldout <> 1 and a.code not in ({$soldout_pcode_list});";
        } else {
            
$sql "select count(*) as cnt 
                    from product_m a inner join product_s c on a.code = c.pcode
                    where c.prod_cate_code_s in (select code from product_category_s a where a.lv > 0 and a.code2 like '"
.substr($info['code2'],0,3)."%') and c.p_use = 1 and a.hidden<>1  order by code2;";
        }
        
//_pr($sql);
        
if($no_prod_cnt!="Y"){ // 분류 상품수가 필요 없응경우
            
$row sql_fetch($sql,$j3['connect_j3']);
            
$info['prod_cnt'] = $row['cnt'];
        }
        
$cate_array[] = $info;        
    }
    return 
$cate_array;
}

function 
cate_lv1_list_get($pcode=""){ // 카테고리 레벨 2 가져오기
    
Global $j3$configshop,$jego_get_table_sql$soldout_pcode_list$no_prod_cnt$app_id;

    
$where "";
    if(
$pcode!=''){
        
$where " and substring(code2,1,3) = '$pcode' ";
    }
    if(
$app_id=='lulucosmetic'){ // 루루샵일경우 btob 분류 제외함
        
$where .= " and not(code2 like '008%') ";
    } 
    
$sql "select * from product_category_s where 1=1 and lv = 1 and pc_use = '1' $where  order by code2";
    
//_pr($sql);
    
$res mysql_query($sql,$j3['connect_j3']);
    while(
$info=mysql_fetch_array($res)){
        if(
$configshop['soldout_hidden']=='1'){ // 품절 숨김일 경우
            
$sql "select count(*) as cnt 
                    from product_m a 
                    inner join product_d b on a.code = b.pcode and b.ocode = '
{$configshop['office_code']}
                    inner join product_s c on a.code = c.pcode
                    where c.prod_cate_code_s in (select code from product_category_s a where a.lv = '2' and a.parent_code = '
{$info['code']}') and c.p_use = 1 and a.hidden<>1 and p_soldout <> 1 and a.code not in ({$soldout_pcode_list});";
        } else {
            
$sql "select count(*) as cnt 
                    from product_m a inner join product_s c on a.code = c.pcode
                    where c.prod_cate_code_s in (select code from product_category_s a where a.lv = '2' and a.parent_code = '
{$info['code']}') and c.p_use = 1 and a.hidden<>1  order by code2;";
        }
        if(
$no_prod_cnt!="Y"){ // 분류 상품수가 필요 없응경우
            
$row sql_fetch($sql,$j3['connect_j3']);
            
$info['prod_cnt'] = $row['cnt'];
        }
        
$cate_array[] = $info;        
    }
    return 
$cate_array;
}

function 
cate_lv2_list_get($pcode=""){ // 카테고리 레벨 3 가져오기
    
Global $j3$configshop,$jego_get_table_sql$soldout_pcode_list$no_prod_cnt$app_id;

    
$where "";
    if(
$pcode!=''){
        
$where " and substring(code2,1,6) = '$pcode' ";
    }
    if(
$app_id=='lulucosmetic'){ // 루루샵일경우 btob 분류 제외함
        
$where .= " and not(code2 like '008%') ";
    } 
    
    
$sql "select * from product_category_s where 1=1 and lv = 2 and pc_use = '1' $where  order by code2";
    
$res mysql_query($sql,$j3['connect_j3']);
    while(
$info=mysql_fetch_array($res)){

        if(
$configshop['soldout_hidden']=='1'){ // 품절 숨김일 경우
            
$sql "select count(*) as cnt 
                    from product_m a 
                    inner join product_d b on a.code = b.pcode and b.ocode = '
{$configshop['office_code']}
                    inner join product_s c on a.code = c.pcode
                    where c.prod_cate_code_s = '
{$info['code']}' and c.p_use = 1 and a.hidden<>1 and p_soldout <> 1 and a.code not in ({$soldout_pcode_list});";
        } else {
            
$sql "select count(*) as cnt 
                    from product_m a 
                    inner join product_s c on a.code = c.pcode
                    where c.prod_cate_code_s = '
{$info['code']}' and c.p_use = 1 and a.hidden<>1";
        }
        if(
$no_prod_cnt!="Y"){ // 분류 상품수가 필요 없응경우
            
$row sql_fetch($sql,$j3['connect_j3']);
            
$info['prod_cnt'] = $row['cnt'];
        }
        
$cate_array[] = $info;        
    }
    return 
$cate_array;
}

function 
cate_lv2_list_get_adm(){ // 관리자 분류3차만 가져오기
    
Global $j3$configshop;

    
$sql "select a.* from product_category_s a where 1=1 and lv = 2  order by code2";
    
$result      =    mysql_query($sql,$j3['connect_j3']);
    while(
$cus_info=mysql_fetch_array($result)){
        if(
$cus_info['pc_use']=='0'){ $cus_info['name'] = $cus_info['name']." (x)"; }
        
$cate_array[] = $cus_info;
    }
    return 
$cate_array;
}

function 
event_code_info($code){
    Global 
$j3$configshop;

    
$sql "select * from shop_event where idx = '{$code}' ";
    
$info sql_fetch($sql,$j3['connect_j3']);
    return 
$info;
}

function 
event_saleprice_get($code$ev_code){
    Global 
$j3;
    
$sql "select * from shop_event_prod where ev_idx = '{$ev_code}' and pcode = '{$code}' ";
    
$info sql_fetch($sql,$j3['connect_j3']);
    return 
$info['ev_saleprice'];
}

function 
menu_get_pc(){ // 메뉴 PC꺼 가져오기
    
Global $j3$configshop;

    
$sql "select * from shop_menu where me_use = '1' order by me_order";
    
$res mysql_query($sql,$j3['connect_j3']);
    while(
$info=mysql_fetch_array($res)){
        
$menu_array[] = $info;        
    }
    return 
$menu_array;
}

function 
menu_get_mobile(){ // 메뉴 모바일꺼 가져오기
    
Global $j3$configshop;

    
$sql "select * from shop_menu where me_mobile_use = '1' order by me_order";
    
$res mysql_query($sql,$j3['connect_j3']);
    while(
$info=mysql_fetch_array($res)){
        
$menu_array[] = $info;        
    }
    return 
$menu_array;
}

function 
banner_display($bn_pos,$skin="",$sk_idx=""){ // 배너 표시
    
Global $j3$configshop$is_mobile$main_slider;

    if(
$is_mobile){
        
$j3['j3_skin_path'] = $j3['j3_skinm_path'];
    }

    
$date date("Y-m-d",time());
    
$sql "select * from shop_banner where bn_pos = '{$bn_pos}' and bn_sdate <= '{$date}' and bn_edate >= '{$date}' order by bn_seq, idx desc";
    
$res mysql_query($sql,$j3['connect_j3']);
    while(
$info=mysql_fetch_array($res)){
        
$bn_array[] = $info;        
    }
    if(
$skin==""){ $skin "banner00.php"; }
    if(
file_exists("{$j3['j3_skin_path']}/banner/{$skin}")){
        include(
"{$j3['j3_skin_path']}/banner/{$skin}");
    }
}

function 
event_display($ev_pos,$skin="",$sk_idx=""){ // 배너 표시
    
Global $j3$configshop$is_mobile$main_slider;

    if(
$is_mobile){
        
$j3['j3_skin_path'] = $j3['j3_skinm_path'];
    }

    
$date date("Y-m-d",time());
    
$sql "select * from shop_event where ev_type = '{$ev_pos}' and ev_use = '1' order by idx desc";
    
//_pr($sql);
    
$res mysql_query($sql,$j3['connect_j3']);
    while(
$info=mysql_fetch_array($res)){
        
$ev_array[] = $info;        
    }
    if(
$skin==""){ $skin "ev_banner01.php"; }
    if(
file_exists("{$j3['j3_skin_path']}/banner/{$skin}")){
        include(
"{$j3['j3_skin_path']}/banner/{$skin}");
    }
}

function 
event_list_pos_get($ev_pos){
    Global 
$j3$configshop;

    
$sql "select * from shop_event where ev_type = '{$ev_pos}' and ev_use = '1' order by idx desc";
    
$res mysql_query($sql,$j3['connect_j3']);
    while(
$info=mysql_fetch_array($res)){
        
$ev_array[] = $info;        
    }
    return 
$ev_array;
}

function 
prod_type_get($type$where2$page$list_num){ // 상품유형에 해당되는 상품 가져오기
    
Global $j3$configshop$jego_get_table_sql$orderkey$soldout_pcode_list

    if(
$type!=''){    $where " and c.p_{$type} = '1' ";    } else { $where ""; }
    
$orderby " c.p_sort, a.code ";
    if(
$orderkey!=''){    $orderby $orderkey; }

    Global 
$Global_Where;
    
$where .= $Global_Where;

    if(
$configshop['soldout_hidden']=='1'){ // 품절 숨김일 경우
        
$sql "select [field_list] 
                from 
                    product_m a 
                    inner join product_d b on a.code = b.pcode and b.ocode = '
{$configshop['office_code']}
                    inner join product_s c on a.code = c.pcode
                    /*left join (
{$jego_get_table_sql}) aaa on a.code = aaa.pcode and b.ocode = aaa.ocode */
                    [add_left_join]
                where 1=1 
{$where} {$where2} and c.p_use = 1 and a.hidden<>1 and p_soldout <> 1 /*and aaa.jego>0*/ and a.code not in ({$soldout_pcode_list})";
    } else {
        
$sql "select [field_list] 
                from 
                    product_m a 
                    inner join product_d b on a.code = b.pcode and b.ocode = '
{$configshop['office_code']}
                    inner join product_s c on a.code = c.pcode
                    [add_left_join]
                where 1=1 
{$where} {$where2} and c.p_use = 1 and a.hidden<>1 ";
    }

    
$sql_cnt str_replace("[add_left_join]","",$sql);
    
$sql_cnt str_replace("[field_list]","count(*) as cnt",$sql_cnt); // 총 갯수 구함
    
$row sql_fetch($sql_cnt,$j3['connect_j3']);
    
$total_count $row['cnt'];
    if(
$list_num==''){ $list_num 15; }
    
$total_page  ceil($total_count $list_num);  // 전체 페이지 계산
    
$from_record = ($page 1) * $list_num// 시작 열을 구함
    
$limit_add " limit {$from_record},{$list_num}";

    
$sql str_replace("[add_left_join]","",$sql);
    
$sql str_replace("[field_list]","*",$sql)." order by {$orderby} {$limit_add}";
    
//_pr($sql);

    /*$res = mysql_query($sql,$j3['connect_j3']);
    while($info=mysql_fetch_array($res)){
        $info['href'] = "{$j3['j3_shop_url']}/item.php?code={$info['code1']}";
        $listtype_array[] = $info;
    }*/
    
$listtype_array prod_list_get($sql); // 리스트 가져오기 1원화 처리로 변경

    
$listtype_array[0]['total_page'] = $total_page;
    
$listtype_array[0]['list_num'] = $list_num;
    
$listtype_array[0]['total_count'] = $total_count;
    return 
$listtype_array;
}

function 
prod_event_get($ev_code$where2$page$list_num$admin){ // 이벤트에 등록된 상품 해당되는 상품 가져오기
    
Global $j3$configshop$jego_get_table_sql$soldout_pcode_list

    if(
$limit!=''){ $limit_add " limit $limit"; }

    
$orderby " a.seq, d.p_sort, b.code ";
    if(
$orderkey!=''){    $orderby $orderkey; }

    if(
$configshop['soldout_hidden']=='1' && $admin==''){ // 품절 숨김일 경우
        
$where " and d.p_soldout <> 1 /*and aaa.jego>0*/ and b.code not in ({$soldout_pcode_list}) ";
    } else {
        
$where "  ";
    }

    Global 
$Global_Where;
    
$where .= $Global_Where;

    
$sql "select [field_list]
                from shop_event_prod a
                inner join product_m b on a.pcode = b.code
                inner join product_d c on a.pcode = c.pcode and c.ocode = '
{$configshop['office_code']}'
                inner join product_s d on b.code = d.pcode
                inner join product_category_s e on d.prod_cate_code_s = e.code
                /*left join (
{$jego_get_table_sql}) aaa on b.code = aaa.pcode and c.ocode = aaa.ocode */
                [add_left_join]
            where a.ev_idx = '
{$ev_code}' and d.p_use = 1 and b.hidden<>1 {$where} {$where2}";
    
    
$sql_cnt str_replace("[add_left_join]","",$sql);
    
$sql_cnt str_replace("[field_list]","count(*) as cnt",$sql_cnt); // 총 갯수 구함
    
$row sql_fetch($sql_cnt,$j3['connect_j3']);
    
$total_count $row['cnt'];
    if(
$list_num==''){ $list_num 15; }
    
$total_page  ceil($total_count $list_num);  // 전체 페이지 계산
    
$from_record = ($page 1) * $list_num// 시작 열을 구함
    
$limit_add " limit {$from_record},{$list_num}";

    
$sql str_replace("[add_left_join]","",$sql);
    
$sql str_replace("[field_list]","a.*, b.*, c.*, d.*, e.name as cate_name/*, aaa.jego*/",$sql)." order by {$orderby} {$limit_add}";
    
    
/*$res = mysql_query($sql,$j3['connect_j3']);
    while($info=mysql_fetch_array($res)){
        $info['href'] = "{$j3['j3_shop_url']}/item.php?code={$info['code1']}";
        $event_array[] = $info;
    }*/
    //_pr($sql);
    
$event_array prod_list_get($sql$ev_code); // 리스트 가져오기 1원화 처리로 변경

    
$event_array[0]['total_page'] = $total_page;
    
$event_array[0]['list_num'] = $list_num;
    
$event_array[0]['total_count'] = $total_count;
    return 
$event_array;
}

function 
prod_opt_get($pcode$admin ,$limit){ // 옵션으로 등록된 상품 해당되는 상품 가져오기
    
Global $j3$configshop$jego_get_table_sql$orderkey$ev_code$soldout_pcode_list
    Global 
$configshop$cinfo;

    
$pinfo product_info_get($pcode); // 원 상품 정보 가져옴

    
if($limit!=''){ $limit_add " limit $limit"; }

    if(
$configshop['soldout_hidden']=='1' && $admin==''){ // 품절 숨김일 경우
        
$where " and d.p_soldout <> 1 /*and aaa.jego>0*/ and b.code not in ({$soldout_pcode_list}) ";
    } else {
        
$where "  ";
    }

    Global 
$Global_Where;
    
$where .= $Global_Where;

    
$sql "select a.*, b.*, c.*, e.name as cate_name/*, aaa.jego*/ from product_so a
                    inner join product_m b on a.child_pcode = b.code
                    inner join product_d c on a.child_pcode = c.pcode and c.ocode = '
{$configshop['office_code']}'
                    inner join product_s d on b.code = d.pcode
                    inner join product_category_s e on d.prod_cate_code_s = e.code
                    /*left join (
{$jego_get_table_sql}) aaa on b.code = aaa.pcode and c.ocode = aaa.ocode */
                where a.parent_pcode = '
{$pcode}' and d.p_use = 1 and b.hidden<>1 {$where}
                order by a.child_seq 
{$limit_add} ";
    
//_pr($sql);
    
$prod_array prod_list_get($sql,$ev_code);
    for(
$i=0;$i<count($prod_array);$i++){ // 옵션차액금액 계산
        
if($ev_code!='' && $configshop['ev_cart_saleprice']=='1'){
            
$prod_array[$i]['saleprice'] = prod_event_price_get($ev_code,$prod_array[$i]['pcode']); // 상품의 이벤트 전용단가 가져옴
        
}

        
$val $prod_array[$i];
        if(
$configshop['price_level']<=$cinfo['mb_lv']){ // 가격표시권한이 있을경우만
            
$prod_array[$i]['opt_price'] = Number($val['saleprice'])-$pinfo['saleprice'];
            if(
$prod_array[$i]['opt_price']>=0){ $prod_array[$i]['opt_price'] = "+".number_format($prod_array[$i]['opt_price'])."원"; } else { $prod_array[$i]['opt_price'] = number_format($prod_array[$i]['opt_price'])."원"; }
        }
    }
    return 
$prod_array;
}

function 
prod_addopt_get($pcode$admin ,$limit){ // 추가옵션으로 등록된 상품 해당되는 상품 가져오기
    
Global $j3$configshop$jego_get_table_sql$ev_code$soldout_pcode_list
    Global 
$configshop$cinfo;

    if(
$limit!=''){ $limit_add " limit $limit"; }

    if(
$configshop['soldout_hidden']=='1' && $admin==''){ // 품절 숨김일 경우
        
$where " and d.p_soldout <> 1 /*and aaa.jego>0*/ and b.code not in ({$soldout_pcode_list}) ";
    } else {
        
$where "  ";




    }

    Global 
$Global_Where;
    
$where .= $Global_Where;

    
$sql "select a.*, b.*, c.*, e.name as cate_name/*, aaa.jego*/ from product_sa a
                inner join product_m b on a.add_pcode = b.code
                inner join product_d c on a.add_pcode = c.pcode and c.ocode = '
{$configshop['office_code']}'
                inner join product_s d on b.code = d.pcode
                inner join product_category_s e on d.prod_cate_code_s = e.code
                /*left join (
{$jego_get_table_sql}) aaa on b.code = aaa.pcode and c.ocode = aaa.ocode */
            where a.pcode = '
{$pcode}' and d.p_use = 1 and b.hidden<>1 {$where}
            order by a.seq 
{$limit_add} ";
    
//_pr($sql);
    
$prod_array prod_list_get($sql);
    for(
$i=0;$i<count($prod_array);$i++){ // 옵션차액금액 계산
        
if($ev_code!='' && $configshop['ev_cart_saleprice']=='1'){
            
$prod_array[$i]['saleprice'] = prod_event_price_get($ev_code,$prod_array[$i]['pcode']); // 상품의 이벤트 전용단가 가져옴
        
}

        
$val $prod_array[$i];
        if(
$configshop['price_level']<=$cinfo['mb_lv']){ // 가격표시권한이 있을경우만
            
$prod_array[$i]['opt_price'] = Number($val['saleprice'])-$pinfo['saleprice'];
            if(
$prod_array[$i]['opt_price']>=0){ $prod_array[$i]['opt_price'] = "+".number_format($prod_array[$i]['opt_price'])."원"; } else { $prod_array[$i]['opt_price'] = number_format($prod_array[$i]['opt_price'])."원"; }
        }
    }
    return 
$prod_array;
}

function 
prod_rel_get($pcode$admin ,$limit){ // 관련상품으로 등록된 상품 해당되는 상품 가져오기
    
Global $j3$configshop$jego_get_table_sql$ev_code$soldout_pcode_list

    if(
$limit!=''){ $limit_add " limit $limit"; } else { $limit_add " limit {$configshop['rel_list_cnt']}"; }

    if(
$configshop['soldout_hidden']=='1' && $admin==''){ // 품절 숨김일 경우
        
$where " and d.p_soldout <> 1 /*and aaa.jego>0*/ and b.code not in ({$soldout_pcode_list}) ";
    } else {
        
$where "  ";
    }

    Global 
$Global_Where;
    
$where .= $Global_Where;

    
$sql "select a.*, b.*, c.*, e.name as cate_name/*, aaa.jego*/ from shop_prod_rel a
                inner join product_m b on a.rel_pcode = b.code
                inner join product_d c on a.rel_pcode = c.pcode and c.ocode = '
{$configshop['office_code']}'
                inner join product_s d on b.code = d.pcode
                inner join product_category_s e on d.prod_cate_code_s = e.code
                /*left join (
{$jego_get_table_sql}) aaa on b.code = aaa.pcode and c.ocode = aaa.ocode */
            where a.pcode = '
{$pcode}' and d.p_use = 1 and b.hidden<>1 {$where}
            order by a.seq 
{$limit_add} ";
    
//_pr($sql);
    
$prod_array prod_list_get($sql);
    return 
$prod_array;
}

function 
prod_paral_get($pcode$admin ,$limit){ // 병행상품으로 등록된 상품 해당되는 상품 가져오기
    
Global $j3$configshop$jego_get_table_sql$soldout_pcode_list

    if(
$limit!=''){ $limit_add " limit $limit"; } else { $limit_add " limit {$configshop['rel_list_cnt']}"; }

    if(
$configshop['soldout_hidden']=='1' && $admin==''){ // 품절 숨김일 경우
        
$where " and d.p_soldout <> 1 /*and aaa.jego>0*/ and b.code not in ({$soldout_pcode_list}) ";
    } else {
        
$where "  ";
    }

    Global 
$Global_Where;
    
$where .= $Global_Where;

    
$sql "select a.*, b.*, c.*, e.name as cate_name/*, aaa.jego*/ from shop_prod_paral a
                inner join product_m b on a.paral_pcode = b.code
                inner join product_d c on a.paral_pcode = c.pcode and c.ocode = '
{$configshop['office_code']}'
                inner join product_s d on b.code = d.pcode
                inner join product_category_s e on d.prod_cate_code_s = e.code
                /*left join (
{$jego_get_table_sql}) aaa on b.code = aaa.pcode and c.ocode = aaa.ocode */
            where a.pcode = '
{$pcode}' and d.p_use = 1 and b.hidden<>1 {$where}
            order by a.seq 
{$limit_add} ";
    
//_pr($sql);
    
$prod_array prod_list_get($sql);
    return 
$prod_array;
}

function 
prod_list_by_cate($code$orderby$page$rowcnt$colcnt){ // 분류에 따른 상품 가져오기
    
Global $j3$configshop$jego_get_table_sql,$cate_item_search$soldout_pcode_list$app_id

    if(
$code==''){ return; }

    if(
$code=='all'){ 
        if(
$app_id=='lulucosmetic'){ // 루루샵일경우 btob 분류 제외한 모든 상품 가져옴
            
$sql "select * from product_category_s where substring(code2,1,3)='008' and lv=2";
            
$res mysql_query($sql,$j3['connect_j3']);
            
$code "";
            while(
$info=mysql_fetch_array($res)){
                
$code .= "{$info['code']},";
            }
            
$code substr($code,0,strlen($code)-1);
            
$code_where "c.prod_cate_code_s not in ($code)"
        } else {
            
$code_where "1"
        }
    } else { 
$code_where "c.prod_cate_code_s in ($code)"; }

    
$where "";
    if(
$cate_item_search!=''){ $where " and (a.name like '%{$cate_item_search}%' or c.item_explain like '%{$cate_item_search}%') "; }


    Global 
$Global_Where;
    
$where .= $Global_Where;

    if(
$configshop['soldout_hidden']=='1'){ // 품절 숨김일 경우
        
$sql "select [field_list] 
                from 
                    product_m a 
                    inner join product_d b on a.code = b.pcode and b.ocode = '
{$configshop['office_code']}
                    inner join product_s c on a.code = c.pcode
                    inner join product_category_s d on c.prod_cate_code_s = d.code and d.pc_use = '1'
                    [add_left_join]
                where 
{$code_where} and c.p_use = 1 and a.hidden<>1 and p_soldout <> 1 and a.code not in ({$soldout_pcode_list}{$where} ";
    } else {
        
$sql "select [field_list] 
                from 
                    product_m a 
                    inner join product_d b on a.code = b.pcode and b.ocode = '
{$configshop['office_code']}
                    inner join product_s c on a.code = c.pcode
                    inner join product_category_s d on c.prod_cate_code_s = d.code and d.pc_use = '1'
                    [add_left_join]
                where 
{$code_where} and c.p_use = 1 and a.hidden<>1 {$where} ";
    }

    
$sql_cnt str_replace("[add_left_join]","",$sql);
    
$sql_cnt str_replace("[field_list]","count(*) as cnt",$sql_cnt); // 총 갯수 구함
    
$row sql_fetch($sql_cnt,$j3['connect_j3']);

    
$total_count $row['cnt'];
    
$list_num $rowcnt*$colcnt;
    
$total_page  ceil($total_count $list_num);  // 전체 페이지 계산
    
$from_record = ($page 1) * $list_num// 시작 열을 구함
    
$limit_add " limit {$from_record},{$list_num}";

    if(
$orderby=='sale desc'){ // 판매 많은순 일 경우
        
$sql str_replace("[add_left_join]","left join (select b.pcode, sum(qty) as sale_qty from sale_m a left join sale_d b on a.midx = b.midx where a.ocode = '{$configshop['office_code']}' group by b.pcode) bbb on a.code = bbb.pcode",$sql);
        
$orderby "sale_qty desc, p_sort ";
    } else {
        
$sql str_replace("[add_left_join]","",$sql);
    }

    
$sql str_replace("[field_list]","a.*, b.*, c.*, d.code2",$sql)." order by {$orderby} {$limit_add}";
    
//echo $sql;
    
$prod_array prod_list_get($sql);
    
$prod_array[0]['total_page'] = $total_page;
    
$prod_array[0]['list_num'] = $list_num;
    
$prod_array[0]['total_count'] = $total_count;
    return 
$prod_array;
}

function 
product_search_list($where$orderby$page$rowcnt$colcnt){ // 통합 검색 상품 리스트
    
Global $j3$configshop$jego_get_table_sql$Global_Where$soldout_pcode_list;

    Global 
$Global_Where;
    
$where .= $Global_Where;
    
    if(
$configshop['soldout_hidden']=='1'){ // 품절 숨김일 경우
        
$sql "select [field_list] 
                from 
                    product_m a 
                    inner join product_d b on a.code = b.pcode and b.ocode = '
{$configshop['office_code']}
                    inner join product_s c on a.code = c.pcode
                    inner join product_category_s d on c.prod_cate_code_s = d.code and d.pc_use = '1'
                    [add_left_join]
                where c.p_use = 1 and a.hidden<>1 and p_soldout <> 1 and a.code not in (
{$soldout_pcode_list}{$where} ";
    } else {
        
$sql "select [field_list] 
                from 
                    product_m a 
                    inner join product_d b on a.code = b.pcode and b.ocode = '
{$configshop['office_code']}
                    inner join product_s c on a.code = c.pcode
                    inner join product_category_s d on c.prod_cate_code_s = d.code and d.pc_use = '1'
                    [add_left_join]
                where c.p_use = 1 and a.hidden<>1 
{$where} ";
    }

    
$sql_cnt str_replace("[add_left_join]","",$sql);
    
$sql_cnt str_replace("[field_list]","count(*) as cnt",$sql_cnt); // 총 갯수 구함
    
$row sql_fetch($sql_cnt,$j3['connect_j3']);

    
$total_count $row['cnt'];
    
$list_num $rowcnt*$colcnt;
    
$total_page  ceil($total_count $list_num);  // 전체 페이지 계산
    
$from_record = ($page 1) * $list_num// 시작 열을 구함
    
$limit_add " limit {$from_record},{$list_num}";

    if(
$orderby=='sale desc'){ // 판매 많은순 일 경우
        
$sql str_replace("[add_left_join]","left join (select b.pcode, sum(qty) as sale_qty from sale_m a left join sale_d b on a.midx = b.midx where a.ocode = '{$configshop['office_code']}' group by b.pcode) bbb on a.code = bbb.pcode",$sql);
        
$orderby "sale_qty desc, p_sort ";
    } else {
        
$sql str_replace("[add_left_join]","",$sql);
    }

    
$sql_rtn str_replace("[field_list]","a.code, c.prod_cate_code_s",$sql)." order by {$orderby}"// 상품검색에서 카테고리별 분류를 처리하기위해서 임시로 SQL문 빼놓는다.
    
$sql str_replace("[field_list]","a.*, b.*, c.*, d.name as cate_name",$sql)." order by {$orderby} {$limit_add}";

    
//_pr($sql_rtn);
    //_pr($sql);

    
$prod_array prod_list_get($sql);
    
$prod_array[0]['total_page'] = $total_page;
    
$prod_array[0]['list_num'] = $list_num;
    
$prod_array[0]['total_count'] = $total_count;
    
$prod_array[0]['sql_rtn'] = $sql_rtn;
    return 
$prod_array;
}

function 
prod_list_get($sql$ev_code=""){ // sql 조건으로 상품 리스트 가져온다. 검색조건등 여러개를 한개의 모듈로 리턴하기위해서
    
Global $j3$configshop$id_ccode;
    Global 
$configshop$cinfo;

    
$tmp_id_ccode $id_ccode// prod_multi_price_get 통해서 $id_ccode가 변조되므로 임시 $id_ccode를 저장함

    //_pr($sql);
    
$res mysql_query($sql,$j3['connect_j3']);
    
$pcode_list "";
    while(
$info=mysql_fetch_array($res)){
        
/*$sql = "select sale_dcrate from customers where code = '{$id_ccode}' "; // 다중단가용 거래처할인율 가져오기
        $cinfo = sql_fetch($sql,$j3['connect_j3']);*/

        
$info['ori_saleprice'] = $info['saleprice'];
        
$info['saleprice'] = prod_multi_price_get($info['saleprice'], $info['code'], $cinfo['sale_dcrate'],$info['prod_cate_code']);
        if(
$configshop['price_level']<=$cinfo['mb_lv']){  // 가격표시권한이 있을경우만
            
$info['marketprice'] = number_format($info['marketprice']);
            
$info['saleprice'] = number_format($info['saleprice']);
        } else {
            
$info['marketprice'] = "";
            
$info['saleprice'] = "";
        }
        
$info['href'] = "{$j3['j3_shop_url']}/item.php?code={$info['code1']}&ev_code={$ev_code}";

        if(
$configshop['bigo_view_type']=='0'){ $info['remarks'] = ""; } // 옵션에따라서 표시할 비고를 처리
        
else if($configshop['bigo_view_type']=='2'){ $info['remarks'] = $info['p_bigo']; }

        
//$info['jego'] = product_jego_get($info['code']); 
        
$pcode_list .= $info['code'].","// 개별 제고 가져오는 방식 대신에 한꺼번에 재고 가져와서 넣는방식으로 변경

        
if($configshop['ev_cart_saleprice']=='1' && $info['ev_saleprice']>&& $ev_code!=''){ // 이벤트 전용단가일경우
            
$info['saleprice'] = $info['ev_saleprice'];
        }

        if(
$info['p_price_tel']=='1'){
            
$info['saleprice'] = "전화문의";
        }

        if(
$configshop['gust_price_view']=='1' && ($tmp_id_ccode=='0' || $tmp_id_ccode=="")){ // 비회원 가격문구기능
            
$info['saleprice'] = $configshop['gust_price_text'];
        }

        
$prod_array[] = $info;
    }

    
$pcode_list substr($pcode_list,0,strlen($pcode_list)-1);
    
$jego_array product_jego_list_get($pcode_list); // 개별 제고 가져오는 방식 대신에 한꺼번에 재고 가져와서 넣는방식으로 변경
    
foreach($prod_array as $key=>$pinfo){
        
$pcode $pinfo['code'];
        
$jego $jego_array[$pcode]['jego'];

        if(
$pinfo['set_yn']=='0'){
            
$prod_array[$key]['jego'] = $jego;
        } else if(
$pinfo['set_yn']=='2'){
            
$sql "select box_qty as jego from ({$jego_get_box_sql}) bbb where bbb.parent_pcode = '{$pcode}' ";
            
$jego_info sql_fetch($sql,$j3['connect_j3']);
            
$prod_array[$key]['jego'] = $jego_info['jego'];
        } else if(
$pinfo['set_yn']=='1'){
            
$prod_array[$key]['jego'] = get_set_jego($pcode);
        } else {
            
$prod_array[$key]['jego'] = 9999;
        }        
    }
    return 
$prod_array;
}

function 
prod_is_soldout($code){
    Global 
$j3$configshop$id_ccode;

    
$is_soldout false$not_soldout_cnt 0;
    
$sql "select pcode as code, opt_yn,p_soldout from product_s where pcode = '{$code}' ";
    
$pinfo sql_fetch($sql,$j3['connect_j3']);
    
$pinfo['jego'] = product_jego_get($code);

    if(
$pinfo['opt_yn']==1){ // 옵션 상품 일 경우
        
$opt_array prod_opt_get($pinfo['code'], "" ,""); // 상품옵션 가져옴

        
foreach($opt_array as $key=>$val){
            if(
$val['jego']<='0' || $val['p_soldout']=='1'){ // 품절 체크

            
} else {
                
$not_soldout_cnt++;
            }
        }
        if(
$not_soldout_cnt==0){ $is_soldout true; }
    } else {
        if(
$pinfo['jego']<='0' || $pinfo['p_soldout']=='1'){ // 품절 체크
            
$is_soldout true;
        }
    }
    return 
$is_soldout;
}

function 
prod_multi_price_get($price$pcode$sale_dcrate,$prod_cate_code){ // 행사단가, 특별단가, 다중단가, 할인등 처리
    
Global $j3$configshop$options$id_ccode,$price_rtn;
    
$price_ori $price;
    if(
$id_ccode=='0' && $configshop['guest_buy']=='1'){
        
$id_ccode $configshop['guest_ccode'];
    }

    
//$configshop['event_price_use'] = '1';
    
if($configshop['event_price_use']=='1'){ // 천년3 행사단가 처리 : 옵션은 차후에 필요하면 만들면 바로 적용됨
        
$sql "select a.name, p.price from event_price a
                    inner join event_x_customer c on a.nidx = c.nidx and c.ccode = '
{$id_ccode}'
                    inner join event_x_product p on a.nidx = p.nidx and p.pcode = '
{$pcode}'
                where a.start_date <= '"
.date("Y-m-d",time())."' and a.end_date >= '".date("Y-m-d",time())."'    and a.ocode = '{$configshop['office_code']}'
                    order by a.nidx desc"
;
        
$info sql_fetch($sql,$j3['connect_j3']);
        if(
$info['price']!=''){
            
$price_rtn "행사단가:{$info['price']} / {$info['name']}";
            return 
$info['price'];
        }
    }

    if(
$configshop['special_price_use']=='1' && $options['특별단가사용'] = '1' && $id_ccode!=''){ // 천년 특별단가 및 쇼핑몰 특별단가 사용시
        
$sql "select price from special_price where biztype = '1' and pcode = '{$pcode}' and ccode = '{$id_ccode}' and ifnull(start_date,'1977-01-01')<='".date("Y-m-d",time())."' 
                    and ifnull(end_date,'9999-12-31')>='"
.date("Y-m-d",time())."' ";
        
$info sql_fetch($sql,$j3['connect_j3']);
        if(
$info['price']!=''){ 
            
$price_rtn "특별단가:{$info['price']} / {$info['name']}";
            
$spprice $info['price'];
        }
    }

    
//$options['shop_basic_multi_price_no'] = '3';
    
$pr_type "";
    if(
$configshop['multi_price_use']=='1' && $spprice==""){ // 쇼핑몰 다중단가 사용시
        //_pr($id_ccode);
        
if($id_ccode!=''){
            
$sql "select a.*, if('{$options['다중단가계산기준Sale']}'='0',b.buyprice,if('{$options['다중단가계산기준Sale']}'='1',b.saleprice,if('{$options['다중단가계산기준Sale']}'='2',b.baseprice,b.buyprice))) as rprice
                        from multi_price a
                        left join product_d b on a.pcode = b.pcode and b.ocode = '
{$configshop['office_code']}'
                        where a.biztype = '1' and a.pcode = '
{$pcode}' and a.ocode = '{$configshop['office_code']}' and a.seq = (select sale_price_no from customers where code = '{$id_ccode}')
            "
;
            
$info sql_fetch($sql,$j3['connect_j3']);
            
$pr_type "거래처다중단가:";
        }
        
//_pr($sql);

        
if(($id_ccode=='' || $info['price_type']=='') && (int)$options['shop_basic_multi_price_no']>0){
            
$sql "select a.*, if('{$options['다중단가계산기준Sale']}'='0',b.buyprice,if('{$options['다중단가계산기준Sale']}'='1',b.saleprice,if('{$options['다중단가계산기준Sale']}'='2',b.baseprice,b.buyprice))) as rprice
                        from multi_price a
                        left join product_d b on a.pcode = b.pcode and b.ocode = '
{$configshop['office_code']}'
                        where a.biztype = '1' and a.pcode = '
{$pcode}' and a.ocode = '{$configshop['office_code']}' and a.seq = {$options['shop_basic_multi_price_no']}
            "
;
            
//_pr($sql);
            
$info sql_fetch($sql,$j3['connect_j3']);
            
$pr_type "쇼핑몰기본다중단가:";
        }
        if(
$info['price_type']=='0'){ 
            
$multiprice $info['price']; 
            
$price_rtn "{$pr_type}{$multiprice} / {$info['seq']}";
        } else if(
$info['price_type']=='1'){
            
$multiprice $info['rprice']+$info['price'];
            
$price_rtn "{$pr_type}{$multiprice} / {$info['seq']}";
        } else if(
$info['price_type']=='2'){

            if(
$options['원단위자리수']=='0' || $options['원단위자리수']==''){ $ce "10"$rce = -1; }
            if(
$options['원단위자리수'] == "1"){     $ce "100"$rce = -2; }
            if(
$options['원단위자리수'] == "2"){     $ce "1000"$rce = -3; }
            if(
$options['원단위자리수'] == "3"){     $ce "10000"$rce = -4; }

            
$v $info['rprice']*$info['price']/100
            if(
$options['원단위처리']=='0' || $options['원단위처리']==''){
                
$multiprice round($v); // 쇼핑몰은 소수점 안되므로 그대로 라운드 처리
            
} else if($options['원단위처리']=='1'){
                
$multiprice round($v,$rce);
            } else if(
$options['원단위처리']=='2'){
                
$multiprice ceil($v/$ce)*$ce;
            } else if(
$options['원단위처리']=='3'){
                
$multiprice floor($v/$ce)*$ce;
            }
            
$price_rtn "{$pr_type}{$multiprice} / {$info['seq']}";
        }
    }

    if(
$spprice!=""){ 
        
$new_price $spprice
    } else if(
$multiprice!=""){ 
        
$new_price $multiprice
    } else { 
        
$new_price $price_ori
    }

    if(
$options['특별DC사용']=='1' && $id_ccode!='' && $configshop['spdc_price_use']=='1'){ // 천년특별DC 사용 및 쇼핑몰특별DC사용일 경우
        
$sql "select dc from special_dc where biztype = '1' and pcode = '{$pcode}' and ccode = '{$id_ccode}' and ifnull(start_date,'1977-01-01')<='".date("Y-m-d",time())."' and ifnull(end_date,'9999-12-31')>='".date("Y-m-d",time())."' ";
        
$sp_dc sql_fetch($sql,$j3['connect_j3']);
        
$spdc$sp_dc['dc'];
        if(
$spdc!=""){ // 특별DC 있을경우 특별DC 적용
            
$cinfo customer_info_get($id_ccode); // 고객 정보
            
if($cinfo['vattype']=='2'){
                
$v $new_price*1.1;
                
$vv $v-$spdc;
                
$vvv $vv/1.1;
                if(
$options['부가세반올림처리']=='1'){ // 반올림
                    
$new_price round($vvv);
                } else if(
$options['부가세반올림처리']=='2'){
                    
$new_price ceil($vvv);
                } else {
                    
$new_price floor($vvv);
                }
            } else {
                
$new_price $new_price-$spdc;
            }
            
$price_rtn .= " / 특별DC:{$new_price}";
        }
    }
    if(
$spdc=='' || $spdc=='0') { // 특별DC없을경우 거래처/소분류할인 적용
        
if($sale_dcrate>&& $configshop['cusdc_price_use']=='1'){ // 거래처할인이 있고 쇼핑몰 거래처할인 사용일경우
            
if(($spprice!='' && $options['특별단가거래처할인']=='1') || $spprice==''){ // 특별단가이면서 특별단가거래처할인이 있을경우나 특별단가가 아닌경우
                
$cust_dc = (round($new_price*$sale_dcrate/100));
                
$new_price $new_price-$cust_dc;
                
$price_rtn .= " / 특별단가거래처할인:{$new_price}";
            }
        }
        if((
$cust_dc=="0" || $cust_dc=='') && $configshop['catedc_price_use']=='1'){ // 쇼핑몰 소분류할인 사용 이면서 거래처할인이 없을경우 거래처소분류별 할인 체크
            
$sql "select * from product_category_dc where ccode = '{$id_ccode}' and prod_cate_code = '{$prod_cate_code}' ";
            
$cate_dc sql_fetch($sql,$j3['connect_j3']);
            if(
$cate_dc['dc']!="" && $cate_dc['dc']>&& (($spprice!='' && $options['특별단가거래처할인']=='1') || $spprice=='')){ // 소분류별 할인이 있고, 특별단가 이면서 특별단가거래처할인이 있을경우나 특별단가가 아닌경우
                
$cate_dc = (round($new_price*$cate_dc['dc']/100));
                
$new_price $new_price-$cate_dc;
                
$price_rtn .= " / 소분류할인:{$new_price}";
            }
        }
    }

    if(
$new_price!=''){
        return 
$new_price;
    } else {
        return 
$price_ori;
    }
}

function 
prod_event_price_get($ev_code$pcode){ // 이벤트 전용상품의 가격 가져옴
    
Global $j3$configshop;

    
$sql "select ev_saleprice from shop_event_prod a where a.ev_idx = '{$ev_code}' and a.pcode = '{$pcode}' ";
    
$info sql_fetch($sql,$j3['connect_j3']);
    if(
$info['ev_saleprice']>0){
        return 
$info['ev_saleprice'];
    } else {
        return 
"";
    }
}

function 
prod_qa_list_get($pcode$where2$page$list_num){ // 상품문의 리스트 함수
    
Global $j3$configshop;

    if(
$pcode!=''){    $where " and a.pcode = '{$pcode}' ";    } else { $where ""; }
    
$orderby " iq_time desc, idx desc ";

    
$sql "select [field_list] from shop_prod_qa a
                left join product_m b on a.pcode = b.code
                [add_left_join]
                where 1=1 
{$where} {$where2} ";

    
$sql_cnt str_replace("[add_left_join]","",$sql);
    
$sql_cnt str_replace("[field_list]","count(*) as cnt",$sql_cnt); // 총 갯수 구함
    
$row sql_fetch($sql_cnt,$j3['connect_j3']);
    
$total_count $row['cnt'];
    if(
$list_num==''){ $list_num 15; }
    
$total_page  ceil($total_count $list_num);  // 전체 페이지 계산
    
$from_record = ($page 1) * $list_num// 시작 열을 구함
    
$limit_add " limit {$from_record},{$list_num}";

    
$sql str_replace("[add_left_join]","",$sql);
    
$sql str_replace("[field_list]","a.*, b.name, b.pic1, b.code1",$sql)." order by {$orderby} {$limit_add}";
    
$res mysql_query($sql,$j3['connect_j3']);
    while(
$info=mysql_fetch_array($res)){
        
$qa_array[] = $info;
    }
    
$qa_array[0]['total_page'] = $total_page;
    
$qa_array[0]['list_num'] = $list_num;
    
$qa_array[0]['total_count'] = $total_count;
    return 
$qa_array;
}

function 
prod_use_list_get($pcode$where2$page$list_num){ // 상품후기 리스트 함수
    
Global $j3$configshop$is_admin$admin_page;

    if(
$pcode!=''){    $where " and a.pcode = '{$pcode}' ";    } else { $where ""; }
    if(
$admin_page!='Y'){ // 관리자가 아닐경우
        
if($configshop['item_use_type']=='0'){ return; } // 후기 사용안하면 가져오지 않음
        
if($configshop['item_use_type']=='2'){ $where .= " and iu_view = '1' "; } // 관리자 승인만 보이기 일경우
    
}

    
$orderby " iu_time desc, idx desc ";

    
$sql "select [field_list] from shop_prod_use a
                left join product_m b on a.pcode = b.code
                [add_left_join]
                where 1=1 
{$where} {$where2} ";

    
$sql_cnt str_replace("[add_left_join]","",$sql);
    
$sql_cnt str_replace("[field_list]","count(*) as cnt",$sql_cnt); // 총 갯수 구함
    
$row sql_fetch($sql_cnt,$j3['connect_j3']);
    
$total_count $row['cnt'];
    if(
$list_num==''){ $list_num 15; }
    
$total_page  ceil($total_count $list_num);  // 전체 페이지 계산
    
$from_record = ($page 1) * $list_num// 시작 열을 구함
    
$limit_add " limit {$from_record},{$list_num}";

    
$sql str_replace("[add_left_join]","",$sql);
    
$sql str_replace("[field_list]","a.*, b.name, b.pic1, b.code1",$sql)." order by {$orderby} {$limit_add}";
    
$res mysql_query($sql,$j3['connect_j3']);
    while(
$info=mysql_fetch_array($res)){
        
$use_array[] = $info;
    }
    
$use_array[0]['total_page'] = $total_page;
    
$use_array[0]['list_num'] = $list_num;
    
$use_array[0]['total_count'] = $total_count;
    return 
$use_array;
}

function 
prod_cart_list_get($ccode$where2$page$list_num){ // 장바구니 리스트 함수
    
Global $j3$configshop$_SESSION;

    if(
$ccode=='0'){
        if(
table_field_ck("shop_cart""sess_id")){
            
$where " and a.sess_id = '{$_SESSION['sess_id']}' and a.ccode = '{$ccode}' ";
        } else {
            
$where " and a.ccode = '{$ccode}' ";
        }
    } else {
        if(
$ccode!=''){    $where " and a.ccode = '{$ccode}' ";    } else { $where ""; }
    }
    
$orderby " od_id desc, pcode, ev_code, if(a.opt_mode='','1',if(a.opt_mode='opt','2','3')) asc, ct_time ";

    
$sql "select [field_list]
                from shop_cart a
                inner join product_m b on a.pcode = b.code
                left join customers c on a.ccode = c.code
                left join product_d d on a.pcode = d.pcode and d.ocode = '
{$configshop['office_code']}'
                left join product_s e on a.pcode = e.pcode
                [add_left_join]
                where 1=1 and b.hidden<>1 
{$where} {$where2}    ";

    
$sql_cnt str_replace("[add_left_join]","",$sql);
    
$sql_cnt str_replace("[field_list]","count(*) as cnt",$sql_cnt); // 총 갯수 구함
    
$row sql_fetch($sql_cnt,$j3['connect_j3']);
    
$total_count $row['cnt'];
    if(
$list_num==''){ $list_num 15; }
    
$total_page  ceil($total_count $list_num);  // 전체 페이지 계산
    
$from_record = ($page 1) * $list_num// 시작 열을 구함
    
$limit_add " limit {$from_record},{$list_num}";

    
$sql str_replace("[add_left_join]","",$sql);
    
$sql str_replace("[field_list]","a.*, b.name, b.norm, b.pic1, b.code1, c.login_id, c.comp_name, e.p_min_buy, e.p_max_buy, e.p_pack_buy",$sql)." order by {$orderby} {$limit_add}";
    
$res mysql_query($sql,$j3['connect_j3']);
    
//_pr($sql);
    
while($info=mysql_fetch_array($res)){
        if(
$configshop['prod_danga_view']=='1'){
            
$info['ct_tot_amt'] = $info['ct_amt'];
        }
        
$ct_array[] = $info;
    }

    
$tot_deli_price cart_deli_price_get($ct_array); // 전체 배송비 구함

    
$ct_array[0]['total_page'] = $total_page;
    
$ct_array[0]['list_num'] = $list_num;
    
$ct_array[0]['total_count'] = $total_count;
    
$ct_array[0]['tot_deli_price'] = $tot_deli_price;
    return 
$ct_array;
}

function 
prod_cart_rank_get($ct_state$where2$page$list_num){ // 상품 판매 랭킹 리스트 함수
    
Global $j3$configshop;

    if(
$ccode!=''){    $where " and a.ccode = '{$ccode}' ";    } else { $where ""; }
    
$orderby " c.cart_cnt desc ";

    
$sql "select [field_list]
                from product_m a 
                inner join product_s b on a.code = b.pcode
                inner join (select opt_pcode,sum(ct_qty) as cart_cnt from shop_cart where ct_state = 
{$ct_state} group by opt_pcode) c on a.code = c.opt_pcode
            where 1 
{$where2} ";

    
$sql_cnt str_replace("[add_left_join]","",$sql);
    
$sql_cnt str_replace("[field_list]","count(*) as cnt",$sql_cnt); // 총 갯수 구함
    
$row sql_fetch($sql_cnt,$j3['connect_j3']);
    
$total_count $row['cnt'];
    if(
$list_num==''){ $list_num 15; }
    
$total_page  ceil($total_count $list_num);  // 전체 페이지 계산
    
$from_record = ($page 1) * $list_num// 시작 열을 구함
    
$limit_add " limit {$from_record},{$list_num}";

    
$sql str_replace("[add_left_join]","",$sql);
    
$sql str_replace("[field_list]","a.code1, b.pcode, a.pic1, a.name, c.cart_cnt",$sql)." order by {$orderby} {$limit_add}";
    
$res mysql_query($sql,$j3['connect_j3']);
    
//_pr($sql);
    
while($info=mysql_fetch_array($res)){
        if(
$configshop['prod_danga_view']=='1'){
            
$info['ct_tot_amt'] = $info['ct_amt'];
        }
        
$ct_array[] = $info;
    }

    
$ct_array[0]['total_page'] = $total_page;
    
$ct_array[0]['list_num'] = $list_num;
    
$ct_array[0]['total_count'] = $total_count;
    
$ct_array[0]['tot_deli_price'] = $tot_deli_price;
    return 
$ct_array;
}

function 
cart_deli_price_get($list_array){
    Global 
$j3$configshop$ct_box;
    
$deli_price 0;
    
$deli_amount 0;
    
    foreach(
$list_array as $key=>$ct){
        
$ct_deli 0;
        if(
$ct['ct_deli_type']=='1' || ($ct['ct_deli_type']=='0' && $configshop['deli_type']=='f')){ // 무료배송일경우
            
$ct_deli 0;
        } else if(
$ct['ct_deli_type']=='0'){ // 쇼핑몰 기본설정일 경우
            
$deli_amount $deli_amount $ct['ct_tot_amt'];
        } else if(
$ct['ct_deli_type']=='2'){ // 상품조건별 무료배송일경우
            
if($ct['ct_tot_amt']<$ct['ct_deli_mm']){
                
$ct_deli $ct['ct_deli_price']; 
                
$ct_box++;
            }
        } else if(
$ct['ct_deli_type']=='3'){ // 유료배송일 경우
            
$ct_deli $ct['ct_deli_price']; 
            
$ct_box++;
        } else if(
$ct['ct_deli_type']=='4'){ // 수량별 부과일경우
            
$it_box ceil((int)$ct['ct_qty']/(int)$ct['ct_deli_mm']);
            
$ct_deli $ct['ct_deli_price']*$it_box
            
$ct_box $ct_box $it_box;
        } else if(
$ct['ct_deli_type']=='5'){ // 수량 초과별  부과일경우
            
$it_box ceil((int)$ct['ct_qty']/(int)$ct['ct_deli_mm']);
            if(
$it_box==1){
                
$deli_amount $deli_amount $ct['ct_tot_amt'];
            } else {
                
$ct_deli $ct['ct_deli_price']*($it_box-1);
                
$ct_box $ct_box + ($it_box-1);
                
//echo $ct['ct_tot_amt']." ".($ct['ct_price']*((int)$ct['ct_deli_mm']*($it_box-1)));
                
$deli_amount $ct['ct_tot_amt']-($ct['ct_price']*((int)$ct['ct_deli_mm']*($it_box-1)));
            }
        }
        
$deli_price $deli_price $ct_deli;

    }

    
//_pr($deli_amount." ".$configshop['deli_type']);

    
if($deli_amount>&& $configshop['deli_type']=='p'){ // 쇼핑몰 기본설정에 해당되는 금액이 있을경우
        
if($configshop['deli_amount']>$deli_amount){
            
$deli_price $deli_price $configshop['deli_price'];
        }
        
$ct_box++;
    } else if(
$deli_amount>&& $configshop['deli_type']=='r'){ // 지정금액마다 배송비 책정
        
$mod floor($deli_amount/$configshop['deli_amount'])+1;
        
$deli_price $deli_price + ($mod*$configshop['deli_price']);
        
$ct_box++;
    }
    if(
$deli_amount==&& $deli_price==0){
        
$ct_box++;
    }
    return 
$deli_price;
}

function 
get_deli_price($code){
    Global 
$j3$configshop$cinfo;

    
$sql "select * from product_s where pcode = '{$code}' ";
    
$pinfo sql_fetch($sql,$j3['connect_j3']);

    
$deli_price 0;
    if(
$pinfo['p_deli_type']=='1'){ $deli_price 0; }
    else if(
$pinfo['p_deli_type']>'2'){ $deli_price pinfo['p_deli_price']; }
    else if(
$pinfo['p_deli_type']=='0'){ $deli_price $configshop['deli_price']; }
    return 
$deli_price;

}

function 
prod_wish_list_get($ccode$where2$page$list_num){ // 위시 리스트 함수
    
Global $j3$configshop$cinfo;

    if(
$ccode!=''){ // 거래처가 있으면 거래처할인율 가져오기
        /*$sql = "select sale_dcrate from customers where code = '{$ccode}' "; // 다중단가용 거래처할인율 가져오기
        $cinfo = sql_fetch($sql,$j3['connect_j3']);*/
    
} else {
        
$cinfo['sale_dcrate'] = 0;
    }

    if(
$ccode!=''){    $where " and a.ccode = '{$ccode}' ";    } else { $where ""; }
    if(
$ccode!=''){
        
$orderby " ws_seq, idx desc, if(a.opt_mode='','1',if(a.opt_mode='opt','2','3')) asc ";
    } else {
        
$orderby " idx desc, if(a.opt_mode='','1',if(a.opt_mode='opt','2','3')) asc ";
    }

    Global 
$Global_Where;
    
$where .= $Global_Where;

    
$sql "select [field_list]
                from shop_wish a
                left join product_m b on a.pcode = b.code
                left join product_d bb on b.code = bb.pcode and bb.ocode = '
{$configshop['office_code']}'
                left join customers c on a.ccode = c.code
                left join product_m d on a.opt_pcode = d.code and a.opt_mode<>''
                left join product_d dd on d.code = dd.pcode and dd.ocode = '
{$configshop['office_code']}'
                [add_left_join]
                where 1=1 
{$where} {$where2}    ";

    
$sql_cnt str_replace("[add_left_join]","",$sql);
    
$sql_cnt str_replace("[field_list]","count(*) as cnt",$sql_cnt); // 총 갯수 구함
    
$row sql_fetch($sql_cnt,$j3['connect_j3']);
    
$total_count $row['cnt'];
    if(
$list_num==''){ $list_num 15; }
    
$total_page  ceil($total_count $list_num);  // 전체 페이지 계산
    
$from_record = ($page 1) * $list_num// 시작 열을 구함
    
$limit_add " limit {$from_record},{$list_num}";

    
$sql str_replace("[add_left_join]","",$sql);
    
$sql str_replace("[field_list]","distinct a.*, b.name, b.pic1, b.code1, c.login_id, c.comp_name, b.name as pname, b.norm, d.name as opt_name, bb.saleprice, dd.saleprice as optprice, b.prod_cate_code, d.prod_cate_code as opt_cate_code",$sql)." order by {$orderby} {$limit_add}";
    
$res mysql_query($sql,$j3['connect_j3']);
    
//echo $sql;
    
while($info=mysql_fetch_array($res)){
        if(
$ccode!=''){ // 거래처가 있을경우만 매출가 계산
            
$info['saleprice'] = prod_multi_price_get($info['saleprice'], $info['pcode'], $cinfo['sale_dcrate'],$info['prod_cate_code']);
            if(
$info['opt_mode']!=''){
                
$info['optprice'] = prod_multi_price_get($info['optprice'], $info['opt_pcode'], $cinfo['sale_dcrate'],$info['opt_cate_code']);
            } else {
                
$info['optprice'] = 0;
            }
        }
        
        
$ct_array[] = $info;
    }
    
$ct_array[0]['total_page'] = $total_page;
    
$ct_array[0]['list_num'] = $list_num;
    
$ct_array[0]['total_count'] = $total_count;
    return 
$ct_array;
}

function 
qa_list_get($ccode$where2$page$list_num){ // 1:1문의 리스트 함수
    
Global $j3$configshop;

    if(
$ccode!=''){    $where " and a.ccode = '{$ccode}' ";    } else { $where ""; }
    
$orderby " idx desc ";

    
$sql "select [field_list] from shop_qa a 
                [add_left_join]
                WHERE 1=1 
{$where} {$where2}";

    
$sql_cnt str_replace("[add_left_join]","",$sql);
    
$sql_cnt str_replace("[field_list]","count(*) as cnt",$sql_cnt); // 총 갯수 구함
    
$row sql_fetch($sql_cnt,$j3['connect_j3']);
    
$total_count $row['cnt'];
    if(
$list_num==''){ $list_num 15; }
    
$total_page  ceil($total_count $list_num);  // 전체 페이지 계산
    
$from_record = ($page 1) * $list_num// 시작 열을 구함
    
$limit_add " limit {$from_record},{$list_num}";

    
$sql str_replace("[add_left_join]","",$sql);
    
$sql str_replace("[field_list]","*, ifnull(rep_date,'') as rep_date",$sql)." order by {$orderby} {$limit_add}";
    
$res mysql_query($sql,$j3['connect_j3']);
    while(
$info=mysql_fetch_array($res)){
        
$qa_array[] = $info;
    }
    
$qa_array[0]['total_page'] = $total_page;
    
$qa_array[0]['list_num'] = $list_num;
    
$qa_array[0]['total_count'] = $total_count;
    return 
$qa_array;
}

function 
faq_list_get($faq_idx$where2$page$list_num){ // FAQ 리스트 함수
    
Global $j3$configshop;

    if(
$faq_idx!=''){    $where " and a.faq_idx = '{$faq_idx}' ";    } else { $where ""; }
    
$orderby " faq_seq, idx desc ";

    
$sql "select [field_list] from shop_faq a 
                left join shop_faq_list b on a.faq_idx = b.idx
                [add_left_join]
                WHERE 1=1 
{$where} {$where2}";

    
$sql_cnt str_replace("[add_left_join]","",$sql);
    
$sql_cnt str_replace("[field_list]","count(*) as cnt",$sql_cnt); // 총 갯수 구함
    
$row sql_fetch($sql_cnt,$j3['connect_j3']);
    
$total_count $row['cnt'];
    if(
$list_num==''){ $list_num 15; }
    
$total_page  ceil($total_count $list_num);  // 전체 페이지 계산
    
$from_record = ($page 1) * $list_num// 시작 열을 구함
    
$limit_add " limit {$from_record},{$list_num}";

    
$sql str_replace("[add_left_join]","",$sql);
    
$sql str_replace("[field_list]","a.*, b.faq_cate",$sql)." order by {$orderby} {$limit_add}";
    
$res mysql_query($sql,$j3['connect_j3']);
    while(
$info=mysql_fetch_array($res)){
        
$qa_array[] = $info;
    }
    
$qa_array[0]['total_page'] = $total_page;
    
$qa_array[0]['list_num'] = $list_num;
    
$qa_array[0]['total_count'] = $total_count;
    return 
$qa_array;
}

function 
faq_cate_list_get($idx$where2$page$list_num){ // FAQ 카테고리 리스트 함수
    
Global $j3$configshop;

    
$orderby " faq_order, idx desc ";

    
$sql "select [field_list] from shop_faq_list a 
                [add_left_join]
                WHERE 1=1 
{$where} {$where2}";

    
$sql_cnt str_replace("[add_left_join]","",$sql);
    
$sql_cnt str_replace("[field_list]","count(*) as cnt",$sql_cnt); // 총 갯수 구함
    
$row sql_fetch($sql_cnt,$j3['connect_j3']);
    
$total_count $row['cnt'];
    if(
$list_num==''){ $list_num 15; }
    
$total_page  ceil($total_count $list_num);  // 전체 페이지 계산
    
$from_record = ($page 1) * $list_num// 시작 열을 구함
    
$limit_add " limit {$from_record},{$list_num}";

    
$sql str_replace("[add_left_join]","",$sql);
    
$sql str_replace("[field_list]","a.*",$sql)." order by {$orderby} {$limit_add}";
    
$res mysql_query($sql,$j3['connect_j3']);
    while(
$info=mysql_fetch_array($res)){
        
$qa_array[] = $info;
    }
    
$qa_array[0]['total_page'] = $total_page;
    
$qa_array[0]['list_num'] = $list_num;
    
$qa_array[0]['total_count'] = $total_count;
    return 
$qa_array;
}

function 
qa_info_get($idx){ // 1:1문의 정보 가져옴
    
Global $j3$configshop$id_ccode;

    
$sql "select * from shop_qa where idx = '{$idx}' and ccode = '{$id_ccode}' ";
    
$info sql_fetch($sql,$j3['connect_j3']);
    return 
$info;
}

function 
all_prod_use_list_get($cnt){ // 메인에서 사용할 전체 사용후기리스트 가져오기
    
Global $j3;

    if(
$cnt==""){ $cnt 5; }

    
$sql "select a.*, b.name, b.pic1, b.code1, ifnull(c.score,0) as score  from shop_prod_use a 
                left join product_m b on a.pcode = b.code
                left join (select pcode, round(avg(iu_score),1) as score from shop_prod_use group by pcode) c on a.pcode = c.pcode
                where 1 and iu_view = 1 order by idx desc limit 
{$cnt}";
    
$res mysql_query($sql,$j3['connect_j3']);
    while(
$info=mysql_fetch_array($res)){
        
$pu_array[] = $info;
    }
    return 
$pu_array;
}

function 
bbs_lv_option($lv){
    
$rtn  "";
    echo 
$lv;
    for(
$i=1;$i<=5;$i++){
        if(
$lv==$i){ $std "selected"; } else { $std ""; }
        
$rtn  .= "<option value='{$i}{$std}>{$i}</option>";
    }
    return 
$rtn;
}

function 
board_last_w_num($table_name){ // 게시판 마지막 w_num값 가져옴
    
Global $j3;
    
$sql "select ifnull(min(w_num),0) as l_w_num from {$table_name}";
    
$info sql_fetch($sql,$j3['connect_j3']);
    return 
$info['l_w_num']-1;
}

function 
bbs_info($b_table){ // 게시판 정보 가져오기
    
Global $j3,$_SESSION;
    
    
$sql "select * from shop_bbs where b_table = '{$b_table}' ";
    
$info sql_fetch($sql,$j3['connect_j3']);
    return 
$info;
}

function 
board_info_get($bbsinfo,$idx){ // 게시글 정보 가져옴
    
Global $j3$configshop$id_ccode;

    
$b_table $bbsinfo['b_table'];
    if(
$b_table=='' || $idx==''){ return; }
    
$table_name "shop_write_".$b_table;

    
$sql "select * from {$table_name} where idx = '{$idx}' ";
    
$binfo sql_fetch($sql,$j3['connect_j3']);
    
$sql "select * from shop_bbs_file where b_table = '{$b_table}' and b_idx = '{$idx}' "
    
$res mysql_query($sql,$j3['connect_j3']);
    while(
$info mysql_fetch_array($res)){ // 게시글 파일 정보 가져옴
        
$info["download_url"] = "<a href='{$j3['j3_adm_url']}/board_download.php?b_table={$b_table}&idx={$idx}&b_no={$info['b_no']}'>{$info['b_oriname']}</a>";
        
$b_file_array[$info['b_no']] = $info;
    }
    
$binfo['file_array'] = $b_file_array;
    return 
$binfo;
}

function 
board_list($bbsinfo$qstr$w_notice){ // 게시판의 게시글 리스트 가져옴
    
Global $j3,$page,$total_page,$list_num,$_SESSION$total_count;

    
$b_table $bbsinfo['b_table'];
    if(
$b_table==''){ return; }

    
$table_name "shop_write_".$b_table;
    
$where " 1=1 and w_comment = 0 and w_notice = '{$w_notice}' ";
    
$order_key " w_num, w_reply";

    
$qstr_l explode("&",$qstr);
    foreach(
$qstr_l as $key=>$val){
        
$vv explode("=",$val);
        if(
$vv[0]=='sti'){ $sti $vv[1]; }
        if(
$vv[0]=='cate' && $vv[1]!='' && $vv[1]!='all'){ // 분류검색시
            
$vv[1] = urldecode($vv[1]);
            
$where .= " and w_cate = '{$vv[1]}' ";
        }
        if(
$vv[0]=='stx' && $vv[1]!=''){ // 검색시
            
$where .= " and {$sti } like '%{$vv[1]}%' ";
        }
    }

    
$sql "select count(*) as cnt from {$table_name} where {$where} ";
    
$cntinfo sql_fetch($sql,$j3['connect_j3']); 
    
$total_count $cntinfo['cnt'];

    
$list_num $bbsinfo['b_list_row'];
    
$total_page  ceil($total_count $list_num);  // 전체 페이지 계산
    
if ($page 1) { $page 1; } // 페이지가 없으면 첫 페이지 (1 페이지)
    
$from_record = ($page 1) * $list_num// 시작 열을 구함

    
$sql "select * from {$table_name} a WHERE {$where} order by $order_key limit $from_record$list_num";
    
//_pr($sql);
    
$res mysql_query($sql,$j3['connect_j3']);
    
$k=0;
    while(
$info=mysql_fetch_array($res)){
        
$num $total_count - ($page 1) * $list_num;

        
$sql "select count(*) as cnt from {$table_name} where w_parent = '{$info['w_parent']}' and w_comment > 0"// 댓글 갯수 가져옴
        
$comm_info =sql_fetch($sql,$j3['connect_j3']);
        if(
$comm_info['cnt']>0){
            
$info['comm_cnt'] = "&nbsp;<span class='strong'>[{$comm_info['cnt']}]</span>";
        } else {
            
$info['comm_cnt'] = "";
        }

        if(
$info['w_file']>0){
            
$info['w_file_icon'] = "<img src='{$j3['j3_img_url']}/icon_file.gif' style='margin-left:5px;margin-right:3px;'>";
        } else {
            
$info['w_file_icon'] = "";
        }

        
$info['num'] = $num-$k;
        if(
$info['w_reply']!=''){ // 답변글 처리
            
$rep_len strlen($info['w_reply'])*10;
            
$info['w_rep_icon'] = "<img src='{$j3['j3_img_url']}/icon_reply.gif' style='margin-left:{$rep_len}px;margin-right:3px;'>";
        } else {
            
$info['w_rep_icon'] = "";
        }
        if(
$bbsinfo['b_subj_size']>0){ // 게시판 제목길이 제한이 있으면 처리
            
$info['w_subject'] = cut_str($info['w_subject'],$bbsinfo['b_subj_size']);
        }
        
$list[] = $info;
        
$k++;
    }
    return 
$list;
}

function 
board_hit_add($bbsinfo,$idx){ // 게시글 조회수 추가
    
Global $j3;

    
$b_table $bbsinfo['b_table'];
    if(
$b_table==''){ return; }

    
$table_name "shop_write_".$b_table;

    
$sql "update {$table_name} set w_hit = w_hit + 1 where idx = '{$idx}' ";
    
mysql_query($sql,$j3['connect_j3']);    
}

function 
prod_type_rep_txt($type){ // 상품유형 텍스트 문구 처리
    
Global $configshop$type_default_txt;
    if(
$configshop['type'.$type.'_rep_txt']!=''){ return $configshop['type'.$type.'_rep_txt']; }
    else { return 
$type_default_txt[$type]; }
}

function 
skin_module_list($sk_pos$pos='pc'){ // 특정 위치의 스킨 모듈리스트를 불러온다.
    
Global $j3$configshop;

    
$sql "select * from shop_skin where sk_pos = '$sk_pos' and pos = '$pos' order by sk_type, idx ";
    
$res mysql_query($sql,$j3['connect_j3']);
    while(
$info=mysql_fetch_array($res)){
        
$sk[] = $info;
    }

    return 
$sk;
}

function 
skin_module_show($sk_pos,$sample_idx=""){ // 특정 위치의 스킨 모듈을 표시한다.
    
Global $j3$config$configshop$code,$_GET,$qstr,$qstr_order,$orderkey_array,$is_admin$_SESSION$is_mobile;
    @
extract($j3);
    @
extract($_GET);
    @
extract($_SESSION);
    if(
$is_mobile){ $where " and pos = 'mobile' "; } else { $where " and pos = 'pc' "; }
    if(
$sample_idx!=''){  // 샘플뷰일경우 
        
$sql "select idx from shop_skin where sk_pos = '{$sk_pos}' and idx = '{$sample_idx}' ";
        
$info sql_fetch($sql,$j3['connect_j3']);
        
$sk skin_module_get($info['idx']);
        
$skin_css $sk['skin_css'];
        include(
$sk['skin_file']);
        return;
    }

    
$sql "select * from shop_skin_show where sk_pos = '$sk_pos{$where} and sk_use = '1' order by sk_seq, idx ";
    
$res mysql_query($sql,$j3['connect_j3']);
    while(
$info=mysql_fetch_array($res)){
        
$sk_idx $info['sk_idx'];
        
$sk skin_module_get($sk_idx);
        
$skin_css $sk['skin_css'];
        include(
$sk['skin_file']);
    }
}

function 
skin_module_get($idx){ // 스킨 정보를 가져온다
    
Global $j3$configshop$is_mobile;

    
$sql "select * from shop_skin where idx = '{$idx}' ";
    
$info sql_fetch($sql,$j3['connect_j3']);
    if(
$is_mobile){
        
$rtn['skin_file'] = "{$j3['j3_skinm_path']}/{$info['sk_pos']}/{$info['sk_filename']}";
    } else {
        
$rtn['skin_file'] = "{$j3['j3_skin_path']}/{$info['sk_pos']}/{$info['sk_filename']}";
    }
    
$rtn['skin_css'] = stripslashes($info['sk_css']);
    
$rtn['sk_pos'] = $info['sk_pos'];
    
$rtn['sk_type'] = $info['sk_type'];
    
    
$v explode(".",$info['sk_filename']);
    
$rtn['sk_img_path'] = $v[0];

    
$rtn['sk_name'] = $info['sk_name'];
    
$rtn['sk_title'] = $info['sk_title'];
    
$rtn['sk_desc'] = $info['sk_desc'];
    
$rtn['sk_line_cnt'] = $info['sk_line_cnt'];
    
$rtn['sk_max_cnt'] = $info['sk_max_cnt'];
    
$rtn['sk_box_width'] = $info['sk_box_width'];
    
$rtn['sk_img_width'] = $info['sk_img_width'];
    
$rtn['sk_img_height'] = $info['sk_img_height'];
    
$rtn['sk_bn_pos'] = $info['sk_bn_pos'];
    
$rtn['sk_ev_code'] = $info['sk_ev_code'];

    return 
$rtn;
}

function 
bankbook_get(){
    Global 
$j3$configshop$shop_bank;

    if(
$shop_bank=="1"){
        
$sql "select a.*, b.bankalias as bk_name from bankbook a left join bank b on a.bankcode = b.code where a.hidden = 0 and ocode = '{$configshop['office_code']}' and a.shopyn = '{$shop_bank}' ";
    } else {
        
$sql "select a.*, b.bankalias as bk_name from bankbook a left join bank b on a.bankcode = b.code where a.hidden = 0 and ocode = '{$configshop['office_code']}' ";
    }
    
$res mysql_query($sql,$j3['connect_j3']);
    while(
$info=mysql_fetch_array($res)){
        
$bank[] = $info;
    }
    return 
$bank;
}

function 
bank_list_get(){ // 은행코드정보 받아온다.
    
Global $j3$configshop;

    
$sql "select * from bank where 1=1 and hidden = 0 ";
    
$res mysql_query($sql,$j3['connect_j3']);
    while(
$info=mysql_fetch_array($res)){
        
$bank_array[] = $info;
    }    
    return 
$bank_array;
}

function 
bankbook_list_get(){ // 계좌정보를 받아온다.
    
Global $j3$configshop$shop_bank;

    
$bank_array bank_list_get();

    if(
$shop_bank=="1"){
        
$sql "select * from bankbook where 1=1 and hidden = 0 and ocode = '{$configshop['office_code']}' and shopyn = '{$shop_bank}' order by nidx"// 통장 정보를 가져옴
    
} else {
        
$sql "select * from bankbook where 1=1 and hidden = 0 and ocode = '{$configshop['office_code']}' order by nidx"// 통장 정보를 가져옴
    
}
    
$res mysql_query($sql,$j3['connect_j3']);
    while(
$info=mysql_fetch_array($res)){
        foreach(
$bank_array as $key=>$val){
            if(
$val['code']==$info['bankcode']){ $info['bank_name'] = $val['bankalias']; }
        }
        
$account_array[] = $info;
    }    
    return 
$account_array;
}

function 
notice_simple_get($limit=1){
    Global 
$j3$configshop;

    
$b_table "notice";
    
$sql "select * from shop_write_{$b_table} where w_comment = 0 and w_reply = '' order by idx desc limit {$limit} ";
    
$res mysql_query($sql,$j3['connect_j3']);
    while(
$info=mysql_fetch_array($res)){
        
$info['reg_date2'] = str_replace("-",".",substr($info['w_regdate'],0,10));
        
$info['href'] = "{$j3['j3_shop_url']}/board.php?b_table={$b_table}&idx={$info['idx']}";
        
$notice[] = $info;
    }
    return 
$notice;
}

function 
captcha_str_ch($v){ // 세선파일 디렉토리 설정시 캇차 이미지 처리 안되어서 그냥 텍스트로 하되 해킹프로그램 긁기로 최대한 처리안되게 해주는 역활
    
$c_array = array('gray','red','blue','green','pink','purple');
    
$v_cnt strlen($v);
    
$rtn "";
    for(
$i=0;$i<$v_cnt;$i++){
        
$rtn .= "<span style='color:{$c_array[$i]}'>{$v[$i]}&nbsp;</span>";
    }
    return 
$rtn;
}

function 
prod_wish_heart($code){ // 현재 상품을 위시리스트 담았는가 체크
    
Global $j3$configshop$id_ccode;

    
//$sql = "select count(*) as cnt from shop_wish where pcode = '{$code}' and ccode = '{$id_ccode}' ";
    
$sql "select count(*) as cnt 
                from shop_wish a 
                inner join product_s b on a.pcode = b.pcode
                where a.pcode = '
{$code}' and a.ccode = '{$id_ccode}' and b.opt_yn = '0'"// 옵션상품일경우 하트가 온되어서 다른 옵션을 위시로 못담게 하는것 방지... 옵션은 무조건 off로 처리
    
$cnt_info sql_fetch($sql,$j3['connect_j3']);
    return 
$cnt_info['cnt'];
}

function 
get_uniqid(){ // 유니크 주문번호 가져온다.
    
global $j3;

    
mysql_query(" LOCK TABLE shop_uniq WRITE ",$j3['connect_j3']);
    while (
1) {
        
// 년월일시분초에 100분의 1초 두자리를 추가함 (1/100 초 앞에 자리가 모자르면 0으로 채움)
        
$key date('YmdHis'time()) . str_pad((int)(microtime()*100), 2"0"STR_PAD_LEFT);

        
$result mysql_query(" insert into shop_uniq set uq_id = '$key', uq_ip = '{$_SERVER['REMOTE_ADDR']}' ",$j3['connect_j3']);
        if (
$result) break; // 쿼리가 정상이면 빠진다.

        // insert 하지 못했으면 일정시간 쉰다음 다시 유일키를 만든다.
        
usleep(10000); // 100분의 1초를 쉰다
    
}
    
mysql_query(" UNLOCK TABLES ",$j3['connect_j3']);

    return 
$key;
}

function 
get_od_id($mode=""){
    Global 
$j3$configshop$id_ccode,$ss_od_id$_SESSION;

    if(
$mode!='cart'){
        if(
$ss_od_id!=''){ return $ss_od_id; }
    }
    
$ss_od_id get_uniqid();
    
$_SESSION['ss_od_id'] = $ss_od_id;

    if(
$id_ccode=='0' && table_field_ck("shop_cart""sess_id")){
        
$sql "select idx from shop_cart where ccode = '0' and sess_id = '{$_SESSION['sess_id']}' and ct_state in (0,1) ";
        
$res mysql_query($sql,$j3['connect_j3']);
        while(
$info mysql_fetch_array($res)){
            
$sql "update shop_cart set od_id = '{$ss_od_id}' , ct_state = '0' where idx = '{$info['idx']}' ";
            @
mysql_query($sql,$j3['connect_j3']);        
        }
    } else {
        
$sql "select idx from shop_cart where ccode = '{$id_ccode}' and ct_state in (0,1) ";
        
$res mysql_query($sql,$j3['connect_j3']);
        while(
$info mysql_fetch_array($res)){
            
$sql "update shop_cart set od_id = '{$ss_od_id}' , ct_state = '0' where idx = '{$info['idx']}' ";
            @
mysql_query($sql,$j3['connect_j3']);        
        }
    }

    return 
$ss_od_id;
}

function 
init_cart($od_id){
    Global 
$j3$id_ccode$_SESSION;

    
//if($id_ccode>0 && table_field_ck("shop_cart", "sess_id")){
    
if($id_ccode>&& table_field_ck("shop_cart""sess_id")){
        
$sql "update shop_cart set ct_state = '0', od_id = '{$od_id}', ccode = '{$id_ccode}' where (ccode = '{$id_ccode}' or sess_id = '{$_SESSION['sess_id']}') and ct_state in (0,1)";
    } else if(
table_field_ck("shop_cart""sess_id")){
        
$sql "update shop_cart set ct_state = '0', od_id = '{$od_id}' where ccode = '{$id_ccode}' and sess_id = '{$_SESSION['sess_id']}' and ct_state in (0,1)";
    } else {
        
$sql "update shop_cart set ct_state = '0', od_id = '{$od_id}' where ccode = '{$id_ccode}' and ct_state in (0,1)";
    }
    
//_pr($sql);
    
mysql_query($sql,$j3['connect_j3']);
}

function 
prod_cart_has_ck($od_id$pcode$opt_pcode$opt_mode){ // 해당 장바구니에 이미 해당 상품이 들어 있는지 체크
    
Global $j3$configshop$ev_code$ct$ev_add_set$ev_add_where,$id_ccode$_SESSION;

    if(
table_field_ck("shop_cart""ev_code") && $configshop['ev_cart_saleprice']=='1'){
        
//$sql = "select ct_qty from shop_cart where od_id = '{$od_id}' and pcode = '{$pcode}' and opt_pcode = '{$opt_pcode}' and opt_mode = '{$opt_mode}' and ev_code = '{$ev_code}' ";
        
if($configshop['guest_buy']=='1' && $id_ccode=='0' && table_field_ck("shop_cart""sess_id")){ // 비회원 구매일 경우
            
$sql "select ct_qty,ev_code from shop_cart where sess_id = '{$_SESSION['sess_id']}' and pcode = '{$pcode}' and opt_pcode = '{$opt_pcode}' and opt_mode = '{$opt_mode}' and ct_price = '{$ct['ct_price']}' and opt_price = '{$ct['opt_price']}' "// 이벤트단가 상관없이 ev코드가
        
} else {
            
$sql "select ct_qty,ev_code from shop_cart where od_id = '{$od_id}' and pcode = '{$pcode}' and opt_pcode = '{$opt_pcode}' and opt_mode = '{$opt_mode}' and ct_price = '{$ct['ct_price']}' and opt_price = '{$ct['opt_price']}' "// 이벤트단가 상관없이 ev코드가
        
}
    } else {
        if(
$configshop['guest_buy']=='1' && $id_ccode=='0' && table_field_ck("shop_cart""sess_id")){ // 비회원 구매일 경우
            
$sql "select ct_qty, ev_code from shop_cart where sess_id = '{$_SESSION['sess_id']}' and pcode = '{$pcode}' and opt_pcode = '{$opt_pcode}' and opt_mode = '{$opt_mode}' ";
        } else {
            
$sql "select ct_qty, ev_code from shop_cart where od_id = '{$od_id}' and pcode = '{$pcode}' and opt_pcode = '{$opt_pcode}' and opt_mode = '{$opt_mode}' ";
        }
    }
    
//_pr($sql);
    
$info sql_fetch($sql,$j3['connect_j3']);
    if(
$info['ct_qty']==''){ 
        
$info['ct_qty'] = 0
    } else {
        
$ev_add_where " and ev_code = '{$info['ev_code']}' ";
        
$ev_add_set " , ev_code = '{$info['ev_code']}' ";
    }
    
    return 
$info['ct_qty'];
}

function 
qstr_except($qstr,$ext_var){ // qstr에서 특정 파라메터만 제거함
    
$qstr_l explode("&",$qstr);
    
$rtn_qstr "";
    foreach(
$qstr_l as $key=>$val){
        
$v explode("=",$val);
        if(
$v[0]!=$ext_var){
            
$rtn_qstr .= "{$v[0]}={$v[1]}&";
        }
    }
    return 
substr($rtn_qstr,0,strlen($rtn_qstr)-1);;
}

function 
repeat_reg_exp(){ // 중복 저장 방지용. 1분에 한번씩 글이나 댓글 가능...
    
Global $_SESSION$config$mode;

    if(
$config['bbs_reg_time']==''){ $config['bbs_reg_time'] = 60; }

    if(
$_SESSION['bbs_time']+$config['bbs_reg_time']>time()){
        if(
$mode=='comment'){
            echo 
"<?php xml version='1.0' encoding='utf-8'?><output>";
            echo 
"<mode>error</mode>";
            echo 
"<mode_ok>N</mode_ok>";
            echo 
"<msg>너무빠른 댓글입니다. {$config['bbs_reg_time']}초에 한번씩 작성 가능합니다.</msg>";
            echo 
"</output>";
            exit;
        } else {
            
alert("너무빠른 글입니다. {$config['bbs_reg_time']}초에 한번씩 작성 가능합니다.");
        }
    }
}

function 
order_info_get($idx){ // 주문정보 가져오기
    
Global $j3$configshop$id_ccode$od_state_tit$admin_page$_SESSION;

    
    if(
$admin_page!='Y'){ 
        if(
$id_ccode=='0'){
            
$where " and b.order_id = 'GUEST' and b.s_name = '{$_SESSION['ss_s_name']}' and (b.s_email = '{$_SESSION['ss_s_email']}' or b.s_hpno = '{$_SESSION['ss_s_email']}') ";
        } else {
            
$where " and a.ccode = '{$id_ccode}' "
        }
    }

    
$sql "select a.*, b.*, (b.cart_price+b.deli_price+b.deli_price2-b.dc_price-b.use_point-b.deposit_price) as wdeposit_price, 
                (b.cart_price+b.deli_price+b.deli_price2) as tot_sale_price, 
                (b.cart_price+b.deli_price+b.deli_price2-b.dc_price-b.use_point) as tot_pay_price, 
                c.login_id from sale_ord_m a
                inner join customers c on a.ccode = c.code
                left join sale_ord_s b on a.midx = b.midx
                where a.midx = '
{$idx}{$where}
            "
;
    
$info sql_fetch($sql,$j3['connect_j3']);
    if(
$info['ord_cancel']=='1'){
        
$od_state $od_state_tit['9'];
    } else if(
$info['ordstate']>0){
        
$od_state $od_state_tit[$info['ordstate']];
    } else if(
$info['deposit']=='1'){
        
$od_state $od_state_tit['01'];
    } else {
        
$od_state $od_state_tit['00'];
    }
    
$info['od_state'] = $od_state;
    if(
$info['midx']!=''){
        
$sql "select ev_code, b.code1, c.pcode as sc_pcode, c.opt_mode, c.ct_name, c.ct_tot_amt, c.ct_price, c.opt_price, c.idx as ct_idx, a.*, b.pic1, ifnull(e.idx,0) as use_idx, c.opt_pcode, c.opt_name, b.norm, a.out_tot_qty
                    from sale_ord_d a 
                    left join shop_cart c on a.remarks = c.idx
                    left join product_m b on c.pcode = b.code 
                    left join shop_prod_use e on c.idx = e.ct_idx
                where a.midx = '
{$idx}'
                order by c.od_id desc, ev_code, sc_pcode, if(c.opt_mode='','1',if(c.opt_mode='opt','2','3')) asc "
;
        
//echo $sql;
        
$res mysql_query($sql,$j3['connect_j3']);
        
$tmp_cart_price 0;
        while(
$row=mysql_fetch_array($res)){
            if(
$configshop['prod_danga_view']=='1'){
                
$row['tot_amt'] = $row['price']*$row['qty'];
                if(
$row['ct_idx']!=''){ // 배송비나 기타부분 제외하기위해서
                    
$tmp_cart_price += $row['tot_amt'];
                }
            }
            
$info['row'][] = $row;
        }
        if(
$configshop['prod_danga_view']=='1'){
            
$info['wdeposit_price'] = $info['wdeposit_price']-$info['cart_price']+$tmp_cart_price;
            
$info['tot_sale_price'] = $info['tot_sale_price']-$info['cart_price']+$tmp_cart_price;
            
$info['tot_pay_price'] = $info['tot_pay_price']-$info['cart_price']+$tmp_cart_price;
            
$info['cart_price'] = $tmp_cart_price;
        }
    }
    
//_pr($info);

    
return $info;    
}

function 
order_info_get_od_id($od_id){ // od_id 기반으로 주문정보 가져오기
    
Global $j3$configshop$id_ccode$od_state_tit$admin_page;

    if(
$admin_page!='Y'){ $where " and a.ccode = '{$id_ccode}' "; }

    
$sql "select a.*, b.*, (b.cart_price+b.deli_price+b.deli_price2-b.dc_price-b.use_point-b.deposit_price) as wdeposit_price,
                    (b.cart_price+b.deli_price+b.deli_price2) as tot_sale_price, 
                    (b.cart_price+b.deli_price+b.deli_price2-b.dc_price-b.use_point) as tot_pay_price
                from sale_ord_m a
                left join sale_ord_s b on a.midx = b.midx
                where b.od_id = '
{$od_id}
            "
// od_id 기반으로 가져올때는 ccode 검증을 하지 않는다 note_url처리등을 위해서
    //echo $sql;
    
$info sql_fetch($sql,$j3['connect_j3']);
    if(
$info['ord_cancel']=='1'){
        
$od_state $od_state_tit['9'];
    } else if(
$info['ordstate']>0){
        
$od_state $od_state_tit[$info['ordstate']];
    } else if(
$info['deposit']=='1'){
        
$od_state $od_state_tit['01'];
    } else {
        
$od_state $od_state_tit['00'];
    }
    
$info['od_state'] = $od_state;
    if(
$info['midx']!=''){
        
$sql "select b.code1, c.pcode as sc_pcode, c.opt_mode, c.ct_name, c.ct_tot_amt, c.ct_price, c.opt_price, c.idx as ct_idx, a.*, b.pic1, ifnull(e.idx,0) as use_idx, a.out_tot_qty
                    from sale_ord_d a 
                    left join shop_cart c on a.remarks = c.idx
                    left join product_m b on c.pcode = b.code 
                    left join shop_prod_use e on c.idx = e.ct_idx
                where a.midx = '
{$info['midx']}'
                order by c.od_id desc, pcode, if(c.opt_mode='','1',if(c.opt_mode='opt','2','3')) asc "
;
        
//echo $sql;
        
$res mysql_query($sql,$j3['connect_j3']);
        while(
$row=mysql_fetch_array($res)){
            
$info['row'][] = $row;
        }
    }

    return 
$info;    
}

function 
order_sha2_get($enckey){
    Global 
$j3$admin_page$idx;
    
$sql "select midx from sale_ord_s where sha2(concat(od_id,'§',s_name),256) = '{$enckey}'";
    
$info sql_fetch($sql,$j3['connect_j3']);
    if(
$info['midx']!=''){
        
$admin_page "Y";
        
$idx $info['midx'];
    }
}

function 
enckey_get($concat){
    Global 
$j3;
    
$sql "select sha2('{$concat}',256);";
    
$info sql_fetch($sql,$j3['connect_j3']);
    return 
$info[0];

}

function 
order_product_qty($idx){ // 주문정보의 상품의 갯수 가져오기
    
Global $j3$configshop$id_ccode;

    
$sql "select sum(qty) as sum_qty from sale_ord_d where midx = '{$idx}' ";
    
$info sql_fetch($sql,$j3['connect_j3']);
    return 
$info['sum_qty'];
}

function 
sale_ord_d_cancel_process($oinfo$midx$seq$cancel_qty){ // 주무정보 상품 개별 취소 처리하기 (이건 나중에 필요시 사용하기로함)
    
Global $j3$configshop$id_ccode;

    return;

    if(
$oinfo['ordstate']==&& $oinfo['deposit']==&& $cancel_qty>0){
        
$sql "update sale_ord_d set out_tot_qty = out_tot_qty + {$cancel_qty}, cancel_qty = cancel_qty + {$cancel_qty} where midx = '{$midx}' and seq = '{$seq}' ";
        
mysql_query($sql,$j3['connect_j3']);

        
// 수주 납품처리 데이터 추가하기
        
$sql "select ifnull(max(subseq),0) as max_cnt from sale_ord_sd where midx = '{$midx}' and seq = '{$seq}' ";
        
$info sql_fetch($sql,$j3['connect_j3'] );
        
$subseq $info['max_cnt']+1;

        
$sql "insert into sale_ord_sd set
                    midx = '
{$midx}', seq = '{$seq}', subseq = '{$subseq}', dealdate = '".date("Y-m-d")."', 
                    dealtype = '1', dealqty = '
{$cancel_qty}', 
                    remarks = '쇼핑몰관리자 취소처리', data_created = '"
.date("Y-m-d H:i:s")."', data_creator = '0', data_updated = '".date("Y-m-d H:i:s")."', 
                    data_updater = '0'
        "
;
        
mysql_query($sql,$j3['connect_j3']);

        
// 로그 히스토리 남기기
        
$pname $oinfo['row'][$seq]['pname']."/".$oinfo['row'][$seq]['opt_name'];
        
$his date("Ymd His",time())." 상품개별취소 -> {$pname} {$cancel_qty}개 취소처리\n";
        
$sql "update sale_ord_s set
                         s_order_his = concat(s_order_his,'
{$his}') 
                    where midx = '
{$midx}' ";
        
mysql_query($sql,$j3['connect_j3']);

        
//취소금액 제외 장바구니금액 재 계산
    
}
}

function 
sale_ord_qty_change($oinfo$midx$seq$ch_qty){ // 주문수량 변경 처리
    
Global $j3$configshop$id_ccode$user_mode;

    if(
$oinfo['ordstate']==&& $oinfo['deposit']==&& $ch_qty>0){
        
$sql "select count(*) as cnt from sale_ord_sd where midx = '{$midx}' and seq = '{$seq}' ";
        
$info sql_fetch($sql,$j3['connect_j3'] );

        if(
$info['cnt']>0){ 
            return 
"이미 납품하거나 취소된적이 있는 주문상품은 수량수정 불가능합니다."
        } else {

            
$ct_idx $old_qty $old_price $old_sup_amt $old_vat $old_tot_amt $pname "";
            foreach(
$oinfo['row'] as $key=>$val){
                if(
$val['seq']==$seq){
                    
$ct_idx  $val['ct_idx'];
                    
$old_qty $val['qty']*1;
                    
$old_price $val['price']*1;
                    
$old_sup_amt $val['sup_amt']*1;
                    
$old_vat $val['vat']*1;
                    
$old_tot_amt $val['tot_amt']*1;
                    
$pname $val['pname']."/".$val['opt_name'];
                    
$pcode $val['pcode'];
                    break;
                }
            }

            
$jego product_jego_get($pcode);
            
$add_qty $ch_qty-$old_qty;
            if(
$jego-$add_qty<0){ // 변경된 수량이 재고 오버시
                
return "재고가 부족합니다. 재고수량:{$jego} 추가된수량:{$add_qty}";
            }

            
$ch_qty $ch_qty 1;
            if(
$old_vat=='0'){
                
$new_sup_amt $ch_qty*$old_price;
                
$new_vat 0;
                
$new_tot_amt $new_sup_amt;
            } else if(
$old_sup_amt+$old_vat==($old_qty*$old_price)){
                
$new_tot_amt $ch_qty*$old_price;
                
$new_vat round($new_tot_amt/11);
                
$new_sup_amt $new_tot_amt-$new_vat;
            } else if((
$old_sup_amt+$old_vat)>($old_qty*$old_price)){
                
$new_sup_amt $ch_qty*$old_price;
                
$new_vat $new_sup_amt*0.1;
                
$new_tot_amt $new_sup_amt+$new_vat;
            } else { 
// 혹시나 이럴일은 없지만 아래와같이 처리되면 오류기 때문에 vat를 1로줘서 시그니쳐 남김
                
$new_sup_amt $ch_qty*$old_price;
                
$new_vat 1;
                
$new_tot_amt $new_sup_amt;
            }

            
$sql "update sale_ord_d set qty = '{$ch_qty}', sup_amt = '{$new_sup_amt}', vat = '{$new_vat}', tot_amt = {$new_tot_amt} where midx = '{$midx}' and seq = '{$seq}'";
            
mysql_query($sql,$j3['connect_j3']);
            
update_del_log("sale_ord_d""midx = '{$midx}' and seq = '{$seq}'""","where"); // 업데이트 로그 처리

            
if($ct_idx!=""){ // 장바구니는 남겨놓기로함
                /*$sql = "update shop_cart set ct_qty = '{$ch_qty}', ct_tot_amt = '{$new_tot_amt}' where idx = '{$ct_idx}' ";
                mysql_query($sql,$j3['connect_j3']);
                update_del_log("shop_cart", "idx", $ct_idx,""); // 업데이트 로그 처리*/
            
}

            
cart_price_recal($oinfo$midx$seq);

            
// 로그 히스토리 남기기
            
if($user_mode=="Y"){ $add_msg "사용자($id_ccode)"; }
            
$his date("Ymd His",time()).{$add_msg} 상품수량변경 -> {$pname} {$old_qty}에서 {$ch_qty}개로 변경처리\n";
            
$sql "update sale_ord_s set
                             s_order_his = concat(s_order_his,'
{$his}') 
                        where midx = '
{$midx}' ";
            
mysql_query($sql,$j3['connect_j3']);

        }
    } else {
        return 
"주문상태값이 정상적이지 않습니다."
    }
}

function 
sale_ord_del_change($oinfo$midx$seq$pcode){
    Global 
$j3$configshop$id_ccode$user_mode;

    if(
$oinfo['ordstate']==&& $oinfo['deposit']==0){
        
$sql "select count(*) as cnt from sale_ord_sd where midx = '{$midx}' and seq = '{$seq}' ";
        
$info sql_fetch($sql,$j3['connect_j3'] );

        if(
$info['cnt']>0){ 
            return 
"이미 납품하거나 취소된적이 있는 주문상품은 삭제 불가능합니다."
        } else {
            
update_del_log("sale_ord_d""midx = '{$midx}' and seq = '{$seq}'""","where_del"); // 삭제 로그 처리
            
$sql "delete from  sale_ord_d where midx = '{$midx}' and seq = '{$seq}'";
            
mysql_query($sql,$j3['connect_j3']);

            
$ct_idx $old_qty $old_price $old_sup_amt $old_vat $old_tot_amt $pname "";
            foreach(
$oinfo['row'] as $key=>$val){
                if(
$val['seq']==$seq){
                    
$ct_idx  $val['ct_idx'];
                    
$old_qty $val['qty']*1;
                    
$pname $val['pname']."/".$val['opt_name'];
                    break;
                }
            }

            if(
$ct_idx!=""){ // 장바구니는 남겨놓기로함
                /*update_del_log("shop_cart", "idx", $ct_idx,"del"); // 삭제 로그 처리
                $sql = "delete from  shop_cart where idx = '{$ct_idx}' ";
                mysql_query($sql,$j3['connect_j3']);*/
            
}

            
cart_price_recal($oinfo$midx$seq);
    
            
// 로그 히스토리 남기기
            
if($user_mode=="Y"){ $add_msg "사용자($id_ccode)"; }
            
$his date("Ymd His",time()).{$add_msg} 상품삭제변경 -> {$pname} 상품코드({$pcode}{$old_qty}개를 삭제처리\n";
            
$sql "update sale_ord_s set
                             s_order_his = concat(s_order_his,'
{$his}') 
                        where midx = '
{$midx}' ";
            
mysql_query($sql,$j3['connect_j3']);
        }
    }
}

function 
cart_price_recal($oinfo$midx$seq){
    Global 
$j3$configshop$id_ccode;

    
$sql "update sale_ord_s 
                set cart_price = (select ifnull(sum(tot_amt-dc),0) as sum_tot from sale_ord_d where midx = '
{$midx}' and not (pcode = 1 and pname like '%배송%')) 
                    , deli_price = (select ifnull(sum(tot_amt-dc),0) as sum_tot from sale_ord_d where midx = '
{$midx}' and (pcode = 1 and pname like '%배송%')) 
                where midx = '
{$midx}'
                
            "
// 장바구니 합계 재계산
    
mysql_query($sql,$j3['connect_j3']);
}

function 
payment_log($mode$cont$sql){ // 걸제 로그 처리
    
Global $j3$configshop$id_ccode$id_cust;

    
$yearmonth date("Ymd",time());
    
$dateinfo date("Y-m-d H:i:s",time());
    
$content "";
    
$content .= 
"{$dateinfo} / {$id_ccode} / $id_cust} / {$mode}
{$cont} / {$sql}
"
.chr(10).chr(10);

    
$fp fopen($j3['j3_data_path']."/paylog/{$id_cust}_payment.txt",'a');
    
fwrite($fp,$content);
    
fclose($fp);
}

function 
payment_deposit_do($od_id$pay_type$s_tno$s_app_no$s_app_info$s_escrow$deposit_time$deposit_price$res_array){ // 입금처리 작업
    
Global $j3$configshop$id_ccode$id_cust;

    if(
$pay_type=='가상계좌'){ $deposit "0"; } else { $deposit "1"; }
    
$s_order_his date("Ymd His").$pay_type $deposit_price 결제완료됨\n"// 필드로그
    
$sql "update sale_ord_s set 
                    deposit = '
{$deposit}', s_pg ='{$configshop['pg_service']}', pay_type = '{$pay_type}', s_tno = '{$s_tno}', s_app_no = '{$s_app_no}', s_app_info = '{$s_app_info}', 
                    s_escrow = '
{$s_escrow}', deposit_price = '{$deposit_price}', deposit_time = '{$deposit_time}', s_order_his = concat(s_order_his,'{$s_order_his}')
                where od_id = '
{$od_id}' ";
    
mysql_query($sql,$j3['connect_j3']);
    
insert_log("sale_ord_s"$od_id$sql); // SQL 업데이트 로그

    
$cont json_encode($res_array);
    
payment_log("lg_payres_ok"$cont""); // 결제시 로그 저장

    
$sql "select deposit from sale_ord_s where od_id = '{$od_id}' ";
    
$info sql_fetch($sql,$j3['connect_j3']);
    if(
$info['deposit']=='1'){ return "ok"; } else { return "fail"; }

}

function 
payment_noteurl_do($mode,$od_id$deposit,$s_app_info$s_escrow$pay_date$deposit_price){ // 가상계좌 처리 작업
    
Global $j3$configshop$id_ccode$id_cust;
    
    if(
$mode=="bank_set"){ // 통장정보 입력
        
$s_order_his date("Ymd His").$s_app_info 가상계좌 설정됨\n"// 필드로그
        
$sql "update sale_ord_s set
                    s_app_info = '
{$s_app_info}', s_escrow = '{$s_escrow}', s_order_his = concat(s_order_his,'{$s_order_his}')
                where od_id = '
{$od_id}' ";
        
mysql_query($sql,$j3['connect_j3']);
        
insert_log("sale_ord_s"$od_id$sql); // SQL 업데이트 로그

        
return "ok";
    }
    if(
$mode=="income_set"){ // 입금처리
        
$s_order_his date("Ymd His")." 가상계좌 $deposit_price 입금완료됨\n"// 필드로그
        
$sql "update sale_ord_s set
                    deposit = '
{$deposit}', s_escrow = '{$s_escrow}', deposit_price = '{$deposit_price}', deposit_time = '{$pay_date}', s_order_his = concat(s_order_his,'{$s_order_his}')
                where od_id = '
{$od_id}' ";
        
mysql_query($sql,$j3['connect_j3']);
        
insert_log("sale_ord_s"$od_id$sql); // SQL 업데이트 로그

        
return "ok";
    }
    if(
$mode=="cancel_set"){ // 취소처리
        
$s_order_his date("Ymd His")." 가상계좌 $deposit_price 입금취소됨\n"// 필드로그
        
$sql "update sale_ord_s set
                    deposit = '
{$deposit}', s_escrow = '{$s_escrow}', deposit_time = '{$pay_date}', s_order_his = concat(s_order_his,'{$s_order_his}')
                where od_id = '
{$od_id}' ";
        
mysql_query($sql,$j3['connect_j3']);
        
insert_log("sale_ord_s"$od_id$sql); // SQL 업데이트 로그

        
return "ok";
    }

}

function 
sms_send_msg_conv($type$info){ // SMS보내기 메시지 변환처리
    
Global $j3$config;
    if(
$type=='1'){ // 회원가입시 일경우
        
$msg $config['shop_sms_cont'.$type];
        
$msg str_replace("{고객명}",$info['comp_name'],$msg);
        
$msg str_replace("{회원아이디}",$info['login_id'],$msg);
    }
    if(
$type=='2'){ // 주문시 회원에게 일경우
        
$msg $config['shop_sms_cont'.$type];
        
$msg str_replace("{고객명}",$info['s_name'],$msg);
        
$msg str_replace("{받는분}",$info['consignee_name'],$msg);
        
$msg str_replace("{주문번호}",$info['od_id'],$msg);
        
$msg str_replace("{주문금액}",$info['wdeposit_price'],$msg);
        
$msg str_replace("{주문내용}",$info['sms_msg'],$msg);
    }
    if(
$type=='3'){ // 주문시 관리자에게 일경우
        
$msg $config['shop_sms_cont'.$type];
        
$msg str_replace("{고객명}",$info['s_name'],$msg);
        
$msg str_replace("{받는분}",$info['consignee_name'],$msg);
        
$msg str_replace("{주문번호}",$info['od_id'],$msg);
        
$msg str_replace("{주문금액}",$info['wdeposit_price'],$msg);
        
$msg str_replace("{주문내용}",$info['sms_msg'],$msg);
    }
    if(
$type=='4'){ // 입금시 회원에게 일경우
        
$msg $config['shop_sms_cont'.$type];
        
$msg str_replace("{고객명}",$info['s_name'],$msg);
        
$msg str_replace("{입금액}",$info['deposit_price'],$msg);
        
$msg str_replace("{주문번호}",$info['od_id'],$msg);
    }
    if(
$type=='5'){ // 배송시 회원에게 일경우
        
$msg $config['shop_sms_cont'.$type];
        
$msg str_replace("{고객명}",$info['s_name'],$msg);
        
$msg str_replace("{택배회사}",$info['deli_company'],$msg);
        
$msg str_replace("{운송장번호}",$info['tracking_number'],$msg);
        
$msg str_replace("{주문번호}",$info['od_id'],$msg);
    }

    return 
$msg;
}

function 
call_sms_send($sms_totel$sms_fromtel$sms_msg){ // SMS 보내기
    
Global $j3$config$configshop$id_ccode$id_cust;

    
$sms_totel preg_replace("/[^0-9]/"""$sms_totel);
    
$sms_fromtel preg_replace("/[^0-9]/"""$sms_fromtel);

    if(
$config['sms_use']=='mjsoft'){
        
$sms_userid $config['sms_id'];
        
$sms_pswd $config['sms_pw'];
        
$cttime date("YmdHis",time());
        
$usign sha1($cttime.sha1($sms_pswd));

        
$loginUrl "http://psms.mjsoft.co/api/sms_send.php";
        
$login_data "&uid={$sms_userid}&ctime={$cttime}&usign={$usign}&senddate=&phone={$sms_totel}&callback={$sms_fromtel}&msg={$sms_msg}&appcode=17";
        
$result curl_call($loginUrl,$login_data);
        
$json_data json_decode($result);

        
sms_send_log($id_cust."_".$sms_totel,$loginUrl.$login_data,$result); // 로그 남김

        
return $json_data;
    }
}

function 
call_lms_send($sms_totel$sms_fromtel$sms_msg){ // LMS 보내기
    
Global $j3$config$configshop$id_ccode$id_cust;

    
$sms_totel preg_replace("/[^0-9]/"""$sms_totel);
    
$sms_fromtel preg_replace("/[^0-9]/"""$sms_fromtel);

    if(
$config['sms_use']=='mjsoft'){
        
$sms_userid $config['sms_id'];
        
$sms_pswd $config['sms_pw'];
        
$cttime date("YmdHis",time());
        
$usign sha1($cttime.sha1($sms_pswd));

        
$loginUrl "http://psms.mjsoft.co/api/lms_send.php";
        
$login_data "&uid={$sms_userid}&ctime={$cttime}&usign={$usign}&senddate=&phone={$sms_totel}&callback={$sms_fromtel}&msg={$sms_msg}&title=&appcode=17";
        
$result curl_call($loginUrl,$login_data);
        
$json_data json_decode($result);

        
sms_send_log($id_cust."_".$sms_totel,$loginUrl.$login_data,$result); // 로그 남김

        
return $json_data;
    }
}

function 
call_kakako_send($kakao_totel$kakao_sender$oinfo$tno){ // 알림톡 보내기
    
Global $j3$config$configshop$id_ccode$id_cust$j3_url$app_id;
    if(
$app_id=='salmonhouses'){ // 만약 대문자를 사용한 업체가 있을경우 처리루틴
        //$v = explode(":/",$j3_url);
        //$j3_url = $v[0].":/".strtoupper($v[1]);
    
}

    if(
$config['kakako_use']=='orange'){
        if(
$config['kakao_tn_'.$tno]!='' && $kakao_totel!='' && $kakao_sender!=''){
            
$tmp_number    $config['kakao_tn_'.$tno] ;    // 오렌지메세지 사이트에서 템플릿번호를 확인하시고 입력해주세요.
            
$kakao_sender    $kakao_sender ;    // 오렌지메세지 사이트에서 등록하신 발신번호를 넣어주세요. ( 하이픈까지 일치해야 합니다 )
            
$kakao_name    $oinfo['s_name'] ;    // 받으시는 분의 고객명
            
$kakao_phone    $kakao_totel ;    // 받으시는 분 휴대폰번호

            
if($config['kakako_sms_080']==''){ $config['kakako_sms_080'] = 'Y'; }
            
$kakao_080    $config['kakako_sms_080'] ;    // 대체문자발송시 080 무료수신거부를 사용하시는 경우에는 Y
            
$kakao_res    "" ;    // 예약발송인 경우에는 Y
            
$kakao_res_date    "" ;    // 예약인 경우에만 필요, 예) 2017-12-24 07:08:09
            
$TRAN_REPLACE_TYPE    $config['kakako_sms_send'];  // 알림톡 실패시 대체문자 발송 ( 공백:미발송, S : SMS로 발송, L : LMS로 발송 )

            
$kka["add".$config['kakao_preset_0']] = $oinfo['s_name'];
            
$kka["add".$config['kakao_preset_1']] = $oinfo['login_id'];
            
$kka["add".$config['kakao_preset_2']] = $oinfo['consignee_name'];
            
$kka["add".$config['kakao_preset_3']] = $oinfo['od_id'];
            
$kka["add".$config['kakao_preset_4']] = $oinfo['wdeposit_price'];
            
$kka["add".$config['kakao_preset_5']] = $oinfo['deposit_price'];
            
$kka["add".$config['kakao_preset_6']] = $oinfo['deli_company'];
            
$kka["add".$config['kakao_preset_7']] = $oinfo['tracking_number'];

            
// 추가정보 1~10 에 대한 값이 필요하신 경우 값을 넣어주세요
            
$kakao_add1     $kka['add1'];
            
$kakao_add2     $kka['add2'];
            
$kakao_add3     $kka['add3'];
            
$kakao_add4     $kka['add4'];
            
$kakao_add5     $kka['add5'];
            
$kakao_add6     $kka['add6'];
            
$kakao_add7     $kka['add7'];
            
$kakao_add8     "" ;
            
$kakao_add9     "" ;
            
$kakao_add10    "" ;

            if(
$tno>=&& $tno<=4){
                
$enckey enckey_get($oinfo['od_id']."§".$oinfo['s_name']);
                
$kakao_url1_1 "{$j3_url}/shopm/orderview.php?enckey={$enckey}"
                
$kakao_url1_2 "{$j3_url}/shop/orderview.php?enckey={$enckey}"
            }

            
$headers = array(
                    
"Content-Type: application/json; charset=utf-8",
                    
"Authorization: {$config['kakao_api']}"
            
);

            
$parameters = array(
                    
"tmp_number" => $tmp_number,
                    
"kakao_url" => $kakao_url,
                    
"kakao_sender" => $kakao_sender,
                    
"kakao_name" => $kakao_name,
                    
"kakao_phone" => $kakao_phone,
                    
"kakao_add1" => $kakao_add1,
                    
"kakao_add2" => $kakao_add2,
                    
"kakao_add3" => $kakao_add3,
                    
"kakao_add4" => $kakao_add4,
                    
"kakao_add5" => $kakao_add5,
                    
"kakao_add6" => $kakao_add6,
                    
"kakao_add7" => $kakao_add7,
                    
"kakao_add8" => $kakao_add8,
                    
"kakao_add9" => $kakao_add9,
                    
"kakao_add10" => $kakao_add10,

                    
"kakao_080" => $kakao_080,
                    
"kakao_res" => $kakao_res,
                    
"kakao_res_date" => $kakao_res_date,
                    
"TRAN_REPLACE_TYPE" => $TRAN_REPLACE_TYPE,

                    
"kakao_url1_1" => $kakao_url1_1,
                    
"kakao_url1_2" => $kakao_url1_2,

                    
"kakao_url2_1" => $kakao_url2_1,
                    
"kakao_url2_2" => $kakao_url2_2,

                    
"kakao_url3_1" => $kakao_url3_1,
                    
"kakao_url3_2" => $kakao_url3_2,

                    
"kakao_url4_1" => $kakao_url4_1,
                    
"kakao_url4_2" => $kakao_url4_2,

                    
"kakao_url5_1" => $kakao_url5_1,
                    
"kakao_url5_2" => $kakao_url5_2
            
);


            
$curl curl_init();

            
curl_setopt($curlCURLOPT_URL"http://www.apiorange.com/api/send/notice.do");
            
curl_setopt($curlCURLOPT_HTTPHEADER$headers);
            
curl_setopt($curlCURLOPT_POSTFIELDSjson_encode($parameters));
            
curl_setopt($curlCURLOPT_POSTtrue);
            
curl_setopt($curlCURLOPT_NOSIGNALtrue);
            
curl_setopt($curlCURLOPT_VERBOSEfalse);
            
curl_setopt($curlCURLOPT_FOLLOWLOCATIONtrue);
            
curl_setopt($curlCURLOPT_SSL_VERIFYHOSTfalse);
            
curl_setopt($curlCURLOPT_SSL_VERIFYPEERfalse);
            
curl_setopt($curlCURLOPT_RETURNTRANSFERtrue); 

            
$result curl_exec($curl);

            
kakao_send_log($id_cust."_".$kakao_totel,$kakao_sender."/tno:".$tno,$parameters,$result); // 로그 남김
            
return $result;
        }
    }
}

function 
content_info_get($code){ // 내용 정보 가져온다.
    
Global $j3$config$configshop;

    
$sql "select * from shop_content a where 1=1 and idx = '{$code}'";
    
$res mysql_query($sql,$j3['connect_j3']);
    
$info mysql_fetch_array($res);

    return 
$info;
}

function 
content_info_get_by_id($co_id){ // 내용 정보 아이디 기반으로 가져온다.
    
Global $j3$config$configshop;

    
$sql "select * from shop_content a where 1=1 and co_id = '{$co_id}'";
    
$res mysql_query($sql,$j3['connect_j3']);
    
$info mysql_fetch_array($res);

    return 
$info;
}

function 
content_list_get(){ // 내용 정보 리스트 가져온다.
    
Global $j3$config$configshop;

    
$sql "select * from shop_content a where 1=1";
    
$res mysql_query($sql,$j3['connect_j3']);
    while(
$info mysql_fetch_array($res)){
        
$list_array[] = $info;
    }
    return 
$list_array;
}

function 
add_search_keyword($v){ // 전체검색시 검색어 로그를 처리한다.
    
Global $j3$config$configshop$id_ccode$_SESSION;

    
$sql "insert into shop_keyword set k_word = '{$v}', k_date = '".date("Y-m-d"time())."', k_ip = '{$_SERVER['REMOTE_ADDR']}', k_ccode = '{$id_ccode}' ";
    
mysql_query($sql,$j3['connect_j3']);

    
$_SESSION['search_keyword'][] = $v;
}

function 
add_search_list_get($limit=3){ // 메인에서 검색어 많은순서대로 리스트 가져온다.
    
Global $j3$config$configshop$id_ccode;

    
$sql "select k_word, count(*) as cnt from shop_keyword where 1=1 group by k_word order by cnt desc limit $limit";
    
$res mysql_query($sql,$j3['connect_j3']);
    while(
$info=mysql_fetch_array($res)){
        
$kword_list[] = $info;
    }
    return 
$kword_list;
}

function 
deli_comp_auto(){ // 자동 배송완료 처리 작업
    
Global $j3$config$configshop$id_ccode,$_SESSION$od_state_tit;

    
$key_minute substr(date("i",time()),1,1);

    if(
$key_minute == '1' && $configshop['deli_comp_day']!=''){ // 10분마다 1분일경우 처리된다.
        
$deli_com_date date("Y-m-d H:i:s",time()-(60*60*24*$configshop['deli_comp_day']));
        
$sql "select a.midx, a.ccode, a.ordstate, b.deli_time from sale_ord_m a left join sale_ord_s b on a.midx = b.midx where 1=1 and a.ordstate = '2' and b.deli_time < '{$deli_com_date}'";
        
$res mysql_query($sql,$j3['connect_j3']);

        
insert_log("sale_ord_m"$midx$sql);
        while(
$info=mysql_fetch_array($res)){
            
$order_list[] = $info;
        }
        foreach(
$order_list as $key=>$info){
            
$idx $info['midx'];
            
$sql "update sale_ord_m set ordstate = '3' where midx = '{$idx}' "// 주문상태 배송완료 처리
            
mysql_query($sql,$j3['connect_j3']);
            
$_SESSION['where_update'] = "ordstate = '3'";
            
update_del_log("sale_ord_m""midx"$idx,""); // 업데이트 로그 처리
            
$_SESSION['where_update'] = "";

            
$his date("Ymd His",time())." 자동 수령완료처리 -> 배송후 {$configshop['deli_comp_day']}일 \n";
            
$sql "update sale_ord_s set s_order_his = concat(s_order_his,'{$his}') where midx = '{$idx}' ";
            
mysql_query($sql,$j3['connect_j3']);
            
$_SESSION['where_update'] = "s_order_his = concat(s_order_his,'{$his}')";
            
update_del_log("sale_ord_s""midx"$idx,""); // 업데이트 로그 처리
            
$_SESSION['where_update'] = "";
        }
    }
}

function 
vat_price_get($vattype$tax_yn$tot_price){ // 거래처별 상품별 부가세 처리
    
Global $options;
    if(
$tax_yn=='1'){ // 과세일경우 계산
        
if($vattype=='0'){ // 면세
            
$ct_amt $tot_price$ct_vat 0;
        } else if(
$vattype=='1'){ // 포함
            
if($options['부가세반올림처리']=='1'){ // 반올림
                
$ct_vat round($tot_price/11);
            } else if(
$options['부가세반올림처리']=='2'){ // 올림
                
$ct_vat ceil($tot_price/11);
            } else { 
// 버림(기본값)
                
$ct_vat floor($tot_price/11);
            }
            
$ct_amt $tot_price-$ct_vat;
        } else if(
$vattype=='2'){ // 별도
            
if($options['부가세반올림처리']=='1'){ // 반올림
                
$ct_vat round($tot_price*0.1);
            } else if(
$options['부가세반올림처리']=='2'){ // 올림
                
$ct_vat ceil($tot_price*0.1);
            } else { 
// 버림(기본값)
                
$ct_vat floor($tot_price*0.1);
            }
            
$ct_amt $tot_price;
        } else if(
$vattype=='3'){ // 영세율
            
$ct_vat 0;
            
$ct_amt $tot_price;
        }
    } else { 
// 면세,영세일 경우 계산
        
$ct_amt =$tot_price$ct_vat 0;
    }
    
$v['ct_amt'] = $ct_amt;
    
$v['ct_vat'] = $ct_vat;
    
$v['ct_tot_amt'] = $ct_amt+$ct_vat;

    return 
$v;
}

function 
cs3_jego_cal($pcode){ // CS3기반의 재고를 계산해서 적용한다.
    
Global $j3$configshop$cs3_jego_get_table_sql;

    
$ocode $configshop['office_code'];

    
$sql str_replace("[pcode]","$pcode",$cs3_jego_get_table_sql);
    
$info sql_fetch($sql,$j3['connect_j3']);
    if(
$info['pcode']!=''){
        
$sql "select count(*) as cnt from stock_current where pcode = '{$pcode}' and ocode = '{$ocode}' ";
        
$row sql_fetch($sql,$j3['connect_j3']);
        if(
$row['cnt']>'0'){
            
$sql "update stock_current set qty = '{$info['jego']}', data_updated = '".date("Y-m-d H:i:s",time())."' where pcode = '{$pcode}' and ocode = '{$ocode}' and scode = '1' ";
        } else {
            
$sql "insert into stock_current set qty = '{$info['jego']}', data_updated = '".date("Y-m-d H:i:s",time())."', pcode = '{$pcode}', ocode = '{$ocode}', scode = '1' ";
        }
        
mysql_query($sql,$j3['connect_j3']);
    }
    
}

function 
sellbuy_per($buyprice,$saleprice){ // 매익율 계산
    
Global $options;
    if(
$options['이익률계산방식']=='0' || $options['이익률계산방식']==''){ //(매출가 - 매입가) / 매출가 * 100
        
if($saleprice==0){ 
            
$rtn 0
        } else {
            
$rtn = ($saleprice-$buyprice)/$saleprice*100;
        }
    } else if(
$options['이익률계산방식']=='1'){ //(매출가 - 매입가) / 매입가 * 100
        
if($buyprice==0){ 
            
$rtn 0
        } else {
            
$rtn = ($saleprice-$buyprice)/$buyprice*100;
        }
    } else if(
$options['이익률계산방식']=='2'){ //매출가 / 매입가 * 100
        
if($buyprice==0){ 
            
$rtn 0
        } else {
            
$rtn $saleprice/$buyprice*100;
        }
    } else if(
$options['이익률계산방식']=='3'){ //매입가 / 매출가 * 100
        
if($saleprice==0){ 
            
$rtn 0
        } else {
            
$rtn $buyprice/$saleprice*100;
        }
    }
    return 
round($rtn,1);
}

function 
office_array_get(){ // 사업장 코드 명칭 가져오기
    
Global $j3;

    
$sql "select code, comp_name from offices where 1=1 ";
    
$res mysql_query($sql$j3['connect_j3']);
    while(
$info=mysql_fetch_array($res)){
        
$office_array[$info['code']] = $info['comp_name'];
    }

    return 
$office_array;
}

function 
get_multi_price_name($ccode){
    Global 
$j3;

    if(
$ccode==''){ 
        return 
"";
    } else {
        
$sql "select a.sale_price_no, if(a.sale_price_no=0,'',ifnull(b.pricename,concat('고객단가',a.sale_price_no))) as cus_grade
                    from customers a
                    left join multi_price_name b on a.sale_price_no = b.seq and b.biztype = '1'
                    where a.code = 
{$ccode}; ";
        
$info sql_fetch($sql$j3['connect_j3']);
        return 
$info['cus_grade'];
    }
}

function 
ftp_server_size(){
    Global 
$ftp_conn$j3_img_server_dir;
    
    
$ftp_total_size 0;
    
$dir_array ftp_nlist ($ftp_conn$j3_img_server_dir);
    foreach(
$dir_array as $key=>$dir){
        
$sub_dir ftp_nlist ($ftp_conn$dir);
        foreach(
$sub_dir as $key2=>$file){
            
$ftp_size ftp_size($ftp_conn$file);
            
$ftp_total_size += $ftp_size;
        }
    }

    return 
round($ftp_total_size/1024);
}

function 
company_no_check($n) { //사업자등록번호 체크
    
$CHECKNUMS "137137135";
    
$checkSum 0;
    
$lastNumber 0;
    
$no str_replace("-"""$n);

    for(
$i=0$i<9$i++) {
        
$tmp = ($CHECKNUMS[$i] * $no[$i]);
        if(
$i 8) {
            
$checkSum += $tmp;
        }
        else { 
// 9번째 곱셈의 결과를 각 자리수를 더함 ( ex: 8*5=45 => 4 + 5 = 9
            
$tmp2 = (string)$tmp;
            
$checkSum += (int)$tmp2[0] + (int)$tmp2[1];
            
$lastNumber = (10 - ($checkSum 10)) % 10// (10 - (체크섬 % 10)) % 10
        
}
    }
    if( 
$no[9] == $lastNumber ) { // 마지막숫자가 같으면 OK
        
return true;
    }
    else {
        return 
false;
    }
}

function 
nl2br2($string) { 
    
$string str_replace(array("\r\n""\r""\n"), "<br />"$string); 
    return 
$string


function 
br2nl($string)
{
    return 
preg_replace('/\<br(\s*)?\/?\>/i'"\n"$string);
}

function 
get_brow($agent)
{
    
$agent strtolower($agent);

    
//echo $agent; echo "<br/>";

    
if (preg_match("/msie ([1-9][0-9]\.[0-9]+)/"$agent$m)) { $s 'MSIE '.$m[1]; }
    else if(
preg_match("/firefox/"$agent))            { $s "FireFox"; }
    else if(
preg_match("/chrome/"$agent))             { $s "Chrome"; }
    else if(
preg_match("/x11/"$agent))                { $s "Netscape"; }
    else if(
preg_match("/opera/"$agent))              { $s "Opera"; }
    else if(
preg_match("/gec/"$agent))                { $s "Gecko"; }
    else if(
preg_match("/bot|slurp/"$agent))          { $s "Robot"; }
    else if(
preg_match("/internet explorer/"$agent))  { $s "IE"; }
    else if(
preg_match("/mozilla/"$agent))            { $s "Mozilla"; }
    else { 
$s "기타"; }

    return 
$s;
}

function 
get_os($agent)
{
    
$agent strtolower($agent);

    
//echo $agent; echo "<br/>";

    
if (preg_match("/windows 98/"$agent))                 { $s "98"; }
    else if(
preg_match("/windows 95/"$agent))             { $s "95"; }
    else if(
preg_match("/windows nt 4\.[0-9]*/"$agent))   { $s "NT"; }
    else if(
preg_match("/windows nt 5\.0/"$agent))        { $s "2000"; }
    else if(
preg_match("/windows nt 5\.1/"$agent))        { $s "XP"; }
    else if(
preg_match("/windows nt 5\.2/"$agent))        { $s "2003"; }
    else if(
preg_match("/windows nt 6\.0/"$agent))        { $s "Vista"; }
    else if(
preg_match("/windows nt 6\.1/"$agent))        { $s "Windows7"; }
    else if(
preg_match("/windows nt 6\.2/"$agent))        { $s "Windows8"; }
    else if(
preg_match("/windows 9x/"$agent))             { $s "ME"; }
    else if(
preg_match("/windows ce/"$agent))             { $s "CE"; }
    else if(
preg_match("/mac/"$agent))                    { $s "MAC"; }
    else if(
preg_match("/linux/"$agent))                  { $s "Linux"; }
    else if(
preg_match("/sunos/"$agent))                  { $s "sunOS"; }
    else if(
preg_match("/irix/"$agent))                   { $s "IRIX"; }
    else if(
preg_match("/phone/"$agent))                  { $s "Phone"; }
    else if(
preg_match("/bot|slurp/"$agent))              { $s "Robot"; }
    else if(
preg_match("/internet explorer/"$agent))      { $s "IE"; }
    else if(
preg_match("/mozilla/"$agent))                { $s "Mozilla"; }
    else { 
$s "기타"; }

    return 
$s;
}

function 
table_field_ck($table$field){ //특정 테이블에 필드가 있는지 체크
    
Global $j3;

    
$sql "show columns from {$table} like '{$field}';";
    
$res mysql_query($sql,$j3['connect_j3']);
    while(
$info=mysql_fetch_array($res)){
        return 
1;
    }
    return 
0;
}

function 
filesize_unit_rtn($file_size){
    if(
$file_size 1024){
        return 
number_format($file_size 1.024).'b';
    }else if((
$file_size 1024) && ($file_size 1024000)){
        return 
number_format($file_size 0.001024).'Kb';
    }else if(
$file_size 1024000){
        return 
number_format($file_size 0.000001024,2).'Mb';
    }
}

$tax_yn_name[0] = "면세";
$tax_yn_name[1] = "과세";
$tax_yn_name[2] = "영세";

$sk_pos_array['menu'] = "메뉴";
$sk_pos_array['header'] = "상단";
$sk_pos_array['main'] = "메인";
$sk_pos_array['footer'] = "하단";
$sk_pos_array['list'] = "상품리스트";
$sk_pos_array['item'] = "상품상세";
$sk_pos_array['cart'] = "장바구니";
$sk_pos_array['orderform'] = "주문하기";
$sk_pos_array['ordercomp'] = "주문완료";
$sk_pos_array['orderlist'] = "주문리스트";
$sk_pos_array['orderview'] = "주문상세";
$sk_pos_array['wish'] = "위시리스트";
$sk_pos_array['mypage'] = "마이페이지";
$sk_pos_array['listtype'] = "상품유형";
$sk_pos_array['event'] = "이벤트";
$sk_pos_array['search'] = "상품검색";

$sk_type_array['menu']['menu'] = "상품메뉴";
$sk_type_array['header']['hd_gnb'] = "회원메뉴";
$sk_type_array['header']['hd_snb'] = "검색메뉴";
$sk_type_array['header']['hd_lnb'] = "상단메뉴";
$sk_type_array['header']['hd_float'] = "플롯메뉴";
$sk_type_array['main']['banner'] = "배너";
$sk_type_array['main']['evbanner'] = "이벤트배너";
$sk_type_array['main']['type1'] = "상품유형1";
$sk_type_array['main']['type2'] = "상품유형2";
$sk_type_array['main']['type3'] = "상품유형3";
$sk_type_array['main']['type4'] = "상품유형4";
$sk_type_array['main']['event'] = "이벤트";
$sk_type_array['main']['cate'] = "분류상품";
$sk_type_array['main']['tail'] = "메인하단";
$sk_type_array['footer']['footer'] = "하단";
$sk_type_array['list']['lhead'] = "상품리스트상단";
$sk_type_array['list']['list'] = "상품리스트";
$sk_type_array['item']['ihead'] = "상품상세 상단";
$sk_type_array['item']['iform'] = "상품상세 구매";
$sk_type_array['item']['iinfo'] = "상품상세 정보";
$sk_type_array['cart']['hcart'] = "장바구니 상단";
$sk_type_array['cart']['cart'] = "장바구니";
$sk_type_array['orderform']['horderform'] = "주문하기 상단";
$sk_type_array['orderform']['orderform'] = "주문하기";
$sk_type_array['ordercomp']['hordercomp'] = "주문완료 상단";
$sk_type_array['ordercomp']['ordercomp'] = "주문완료";
$sk_type_array['orderlist']['horderlist'] = "주문리스트 상단";
$sk_type_array['orderlist']['orderlist'] = "주문완료";
$sk_type_array['orderview']['horderview'] = "주문상세 상단";
$sk_type_array['orderview']['orderview'] = "주문상세";
$sk_type_array['wish']['hwish'] = "위시리스트 상단";
$sk_type_array['wish']['wish'] = "위시리스트";
$sk_type_array['mypage']['hmypage'] = "마이페이지 상단";
$sk_type_array['mypage']['mypage'] = "마이페이지";
$sk_type_array['listtype']['hlisttype'] = "상품유형 상단";
$sk_type_array['listtype']['listtype'] = "상품유형";
$sk_type_array['event']['hevent'] = "이벤트상품 상단";
$sk_type_array['event']['event'] = "이벤트상품";
$sk_type_array['search']['hsearch'] = "상품검색 상단";
$sk_type_array['search']['search'] = "상품검색";

$sk_pos_array2['login'] = "로그인";
$sk_pos_array2['regjoin'] = "회원가입동의";
$sk_pos_array2['regist'] = "회원가입";
$sk_pos_array2['regcomp'] = "회원가입완료";
$sk_pos_array2['board'] = "게시판";
$sk_pos_array2['content'] = "내용페이지";
$sk_pos_array2['qa'] = "1:1문의";
$sk_pos_array2['faq'] = "자주하는질문";
$sk_pos_array2['intro'] = "인트로";
$sk_pos_array2['orderform2'] = "주문하기(커스텀)";

$sk_type_array2['login']['hlogin'] = "로그인상단";
$sk_type_array2['login']['login'] = "로그인";
$sk_type_array2['regjoin']['hregjoin'] = "회원가입동의상단";
$sk_type_array2['regjoin']['regjoin'] = "회원가입동의";
$sk_type_array2['regist']['hregist'] = "회원가입상단";
$sk_type_array2['regist']['regist'] = "회원가입";
$sk_type_array2['regcomp']['hregcomp'] = "회원가입완료상단";
$sk_type_array2['regcomp']['regcomp'] = "회원가입완료";
$sk_type_array2['board']['hboard'] = "게시판상단";
$sk_type_array2['board']['board'] = "게시판";
$sk_type_array2['content']['hcontent'] = "내용페이지상단";
$sk_type_array2['content']['content'] = "내용페이지";
$sk_type_array2['qa']['hqa'] = "1:1문의상단";
$sk_type_array2['qa']['qa'] = "1:1문의";
$sk_type_array2['faq']['hfaq'] = "자주하는질문상단";
$sk_type_array2['faq']['faq'] = "자주하는질문";
$sk_type_array2['intro']['itr_top'] = "인트로 상단";
$sk_type_array2['intro']['itr_login'] = "인트로 로그인";
$sk_type_array2['orderform2']['horderform2'] = "주문하기상단(커스텀)";
$sk_type_array2['orderform2']['orderform2'] = "주문하기(커스텀)";

$sk_type_arraym2['login']['hlogin'] = "로그인상단(m)";
$sk_type_arraym2['login']['login'] = "로그인(m)";
$sk_type_arraym2['regjoin']['hregjoin'] = "회원가입동의상단(m)";
$sk_type_arraym2['regjoin']['regjoin'] = "회원가입동의(m)";
$sk_type_arraym2['regist']['hregist'] = "회원가입상단(m)";
$sk_type_arraym2['regist']['regist'] = "회원가입(m)";
$sk_type_arraym2['regcomp']['hregcomp'] = "회원가입완료상단(m)";
$sk_type_arraym2['regcomp']['regcomp'] = "회원가입완료(m)";
$sk_type_arraym2['board']['hboard'] = "게시판상단(m)";
$sk_type_arraym2['board']['board'] = "게시판(m)";
$sk_type_arraym2['content']['hcontent'] = "내용페이지상단(m)";
$sk_type_arraym2['content']['content'] = "내용페이지(m)";
$sk_type_arraym2['qa']['hqa'] = "1:1문의상단(m)";
$sk_type_arraym2['qa']['qa'] = "1:1문의(m)";
$sk_type_arraym2['faq']['hfaq'] = "자주하는질문상단(m)";
$sk_type_arraym2['faq']['faq'] = "자주하는질문(m)";
$sk_type_arraym2['intro']['itr_top'] = "인트로 상단(m)";
$sk_type_arraym2['intro']['itr_login'] = "인트로 로그인(m)";
$sk_type_arraym2['orderform2']['orderform2'] = "주문하기(커스텀)(m)";

$sk_pos_arraym['menu'] = "메뉴(m)";
$sk_pos_arraym['header'] = "상단(m)";
$sk_pos_arraym['main'] = "메인(m)";
$sk_pos_arraym['footer'] = "하단(m)";
$sk_pos_arraym['list'] = "상품리스트(m)";
$sk_pos_arraym['item'] = "상품상세(m)";
$sk_pos_arraym['cart'] = "장바구니(m)";
$sk_pos_arraym['orderform'] = "주문하기(m)";
$sk_pos_arraym['ordercomp'] = "주문완료(m)";
$sk_pos_arraym['orderlist'] = "주문리스트(m)";
$sk_pos_arraym['orderview'] = "주문상세(m)";
$sk_pos_arraym['wish'] = "위시리스트(m)";
$sk_pos_arraym['mypage'] = "마이페이지(m)";
$sk_pos_arraym['listtype'] = "상품유형(m)";
$sk_pos_arraym['event'] = "이벤트(m)";
$sk_pos_arraym['search'] = "상품검색(m)";

$sk_type_arraym['menu']['menu'] = "상품메뉴(m)";
$sk_type_arraym['header']['hd_gnb'] = "회원메뉴(m)";
$sk_type_arraym['header']['hd_snb'] = "검색메뉴(m)";
$sk_type_arraym['header']['hd_lnb'] = "상단메뉴(m)";
$sk_type_arraym['main']['banner'] = "배너(m)";
$sk_type_arraym['main']['evbanner'] = "이벤트배너(m)";
$sk_type_arraym['main']['type1'] = "상품유형1(m)";
$sk_type_arraym['main']['type2'] = "상품유형2(m)";
$sk_type_arraym['main']['type3'] = "상품유형3(m)";
$sk_type_arraym['main']['type4'] = "상품유형4(m)";
$sk_type_arraym['main']['event'] = "이벤트(m)";
$sk_type_arraym['main']['cate'] = "분류상품(m)";
$sk_type_arraym['main']['tail'] = "메인하단(m)";
$sk_type_arraym['footer']['footer1'] = "하단정보(m)";
$sk_type_arraym['footer']['footer2'] = "하단카피라이트(m)";
$sk_type_arraym['footer']['float'] = "우측장바구니(m)";
$sk_type_arraym['list']['lhead'] = "상품리스트상단(m)";
$sk_type_arraym['list']['list'] = "상품리스트(m)";
$sk_type_arraym['item']['ihead'] = "상품상세 상단(m)";
$sk_type_arraym['item']['iform'] = "상품상세 구매(m)";
$sk_type_arraym['item']['iinfo'] = "상품상세 정보(m)";
$sk_type_arraym['cart']['hcart'] = "장바구니 상단(m)";
$sk_type_arraym['cart']['cart'] = "장바구니(m)";
$sk_type_arraym['orderform']['horderform'] = "주문하기 상단(m)";
$sk_type_arraym['orderform']['orderform'] = "주문하기(m)";
$sk_type_arraym['ordercomp']['hordercomp'] = "주문완료 상단(m)";
$sk_type_arraym['ordercomp']['ordercomp'] = "주문완료(m)";
$sk_type_arraym['orderlist']['horderlist'] = "주문리스트 상단(m)";
$sk_type_arraym['orderlist']['orderlist'] = "주문완료(m)";
$sk_type_arraym['orderview']['horderview'] = "주문상세 상단(m)";
$sk_type_arraym['orderview']['orderview'] = "주문상세(m)";
$sk_type_arraym['wish']['hwish'] = "위시리스트 상단(m)";
$sk_type_arraym['wish']['wish'] = "위시리스트(m)";
$sk_type_arraym['mypage']['hmypage'] = "마이페이지 상단(m)";
$sk_type_arraym['mypage']['mypage'] = "마이페이지(m)";
$sk_type_arraym['listtype']['hlisttype'] = "상품유형 상단(m)";
$sk_type_arraym['listtype']['listtype'] = "상품유형(m)";
$sk_type_arraym['event']['hevent'] = "이벤트상품 상단(m)";
$sk_type_arraym['event']['event'] = "이벤트상품(m)";
$sk_type_arraym['search']['hsearch'] = "상품검색 상단(m)";
$sk_type_arraym['search']['search'] = "상품검색(m)";

$sk_pos_arraym2['login'] = "로그인(m)";
//$sk_pos_arraym2['regjoin'] = "회원가입동의(m)";
$sk_pos_arraym2['regist'] = "회원가입(m)";
$sk_pos_arraym2['regcomp'] = "회원가입완료(m)";
$sk_pos_arraym2['board'] = "게시판(m)";
$sk_pos_arraym2['content'] = "내용페이지(m)";
$sk_pos_arraym2['qa'] = "1:1문의(m)";
$sk_pos_arraym2['faq'] = "자주하는질문(m)";
$sk_pos_arraym2['intro'] = "인트로(m)";
$sk_pos_arraym2['orderform2'] = "주문하기(커스텀)(m)";

$bn_pos_array[] = "메인";
$bn_pos_array[] = "메인(m)";
$bn_pos_array[] = "우측상단";
$bn_pos_array[] = "우측상단(m)";
$bn_pos_array[] = "이벤트";
$bn_pos_array[] = "이벤트(m)";
$bn_pos_array[] = "가운데1";
$bn_pos_array[] = "가운데2";
$bn_pos_array[] = "가운데3";
$bn_pos_array[] = "가운데1(m)";
$bn_pos_array[] = "가운데2(m)";
$bn_pos_array[] = "가운데3(m)";
$bn_pos_array[] = "로그인";
$bn_pos_array[] = "로그인(m)";
$bn_pos_array[] = "좌측플롯1";
$bn_pos_array[] = "우측플롯1";
$bn_pos_array[] = "기타1";
$bn_pos_array[] = "기타2";
$bn_pos_array[] = "기타3";
$bn_pos_array[] = "기타4";
$bn_pos_array[] = "기타5";
$bn_pos_array[] = "기타6";
$bn_pos_array[] = "기타7";
$bn_pos_array[] = "기타8";
$bn_pos_array[] = "기타9";

$type_default_txt[1] = "히트";
$type_default_txt[2] = "베스트";
$type_default_txt[3] = "신상품";
$type_default_txt[4] = "인기";

$orderkey_array['code desc'] = "최근등록순";
$orderkey_array['saleprice asc'] = "낮은가격순";
$orderkey_array['saleprice desc'] = "높은가격순";
$orderkey_array['sale desc'] = "판매많은순";

$prod_set_type[0] = "일반";
$prod_set_type[1] = "<span style='color:blue'>옵션</span>";
/*$prod_set_type[2] = "박스";
$prod_set_type[5] = "옵션";*/

$ct_state_list[0] = "장바구니담기";
$ct_state_list[1] = "주문시";
$ct_state_list[2] = "주문완료";
$ct_state_list[3] = "취소";

$od_state_tit['00'] = "미입금";
$od_state_tit['01'] = "입금완료";
$od_state_tit['1'] = "배송준비중";
$od_state_tit['2'] = "배송중";
$od_state_tit['3'] = "배송완료";
$od_state_tit['9'] = "취소";

$per_biz_type_tit['0'] = '개인';
$per_biz_type_tit['1'] = '기업';

$pay_type_list[] = "무통장";
$pay_type_list[] = "카드";
$pay_type_list[] = "계좌이체";
$pay_type_list[] = "가상계좌";

/* shop.custom.lib.php 에 있는 목록

$customer_menu_list

*/

if(table_field_ck("bankbook""shopyn")){ // 쇼핑몰 전용 계좌 처리용 필드 있는지 확인
    
$shop_bank "1";
} else {
    
$shop_bank "0";
}

?>