catalogs.class_.php 81.6 KB
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
<?php
class Catalogs{
 var $db = null;
 var $tpl = null;
 var $error = null;
 var $photo_id = null;


 function Catalogs(&$db,&$tpl,&$error){
  $this->db = &$db;
  $this->tpl = &$tpl;
  $this->error = &$error;
 }


 function trim(&$data){
  foreach($data as $key=>$value){
   if(is_array($value))$this->trim($value);
   else $data[$key] = stripslashes(trim($value));
  }
 }
 

 function valid($data,$upload = null){

  if(isset($data['name'])){
   if( !preg_match("/.{1,100}/i",$data['name']) ) $this->error[] = "Îøèáêà ââîäà ïîëÿ Íàçâàíèÿ.";
  }
  
  if(isset($data['about_min'])){
   if( !preg_match("/.+/is",$data['about_min']) ) $this->error[] = "Îøèáêà ââîäà ïîëÿ Êðàòêîå îïèñàíèå.";
  }
 /*
  if(isset($data['text'])){
   if( !preg_match("/.+/is",$data['text']) ) $this->error[] = "Îøèáêà ââîäà ïîëÿ Ïîëíîå îïèñàíèå.";
  } */
/*
  if(isset($data['cine'])){
   if( !preg_match("/[0-9]+/",$data['cine']) ) $this->error[] = "Îøèáêà ââîäà ïîëÿ Öåíà, òîëüêî öèôðû.";
  } */
  
  if(isset($upload['pic']['name']) && $upload['pic']['tmp_name']){
   $type = substr(strrchr($upload['pic']['name'],"."),1);
   if( !preg_match("/^(jpeg|jpg|gif|png|bmp)$/i",$type) ) $this->error[] = "Îøèáêà ââîäà ïîëÿ Èçîáðàæåíèÿ, òîëüêî jpg,png,gif.";
  }
  
  if(isset($upload['file']['name'])){
   if( !preg_match("/\.csv$/i",$upload['file']['name']) ) $this->error[] = "Îøèáêà ââîäà ïîëÿ CSV ôàéë, òîëüêî csv.";
  }
  

  if(isset($data['order_name'])){
   if( !preg_match("/.{1,100}/i",$data['order_name']) ) $this->error[] = "Îøèáêà ââîäà ïîëÿ Èìÿ (Ìàêñèìóì 100 ñèìâîëîâ).";
  }
  
  if(isset($data['order_adress'])){
   if( !preg_match("/.{1,200}/i",$data['order_adress']) ) $this->error[] = "Îøèáêà ââîäà ïîëÿ Àäðåñ (Ìàêñèìóì 200 ñèìâîëîâ).";
  }
  
  if(isset($data['order_phone2'])&& strlen($data['order_phone2'])>0){
   if( !preg_match("/.{1,20}/i",$data['order_phone2']) ) $this->error[] = "Îøèáêà ââîäà ïîëÿ Òåëåôîí (Ìàêñèìóì 70 ñèìâîëîâ).";
  }

  if(isset($data['order_phone'])){
if( trim($data['order_phone']) == "" ) $this->error[] = "Îøèáêà ââîäà ïîëÿ Ìîáèëüíûé òåëåôîí (ôîðìàò: (0XX) XXX-XXXX).";
  }
  
  if(isset($data['delivery']) && $data['delivery']==0){
        $this->error[] = "Îøèáêà ââîäà ïîëÿ Äîñòàâêà.";
  }  
  
  if(isset($data['user_name'])){
   if( !preg_match("/.{1,100}/i",$data['user_name']) ) $this->error[] = "Îøèáêà ââîäà ïîëÿ Èìÿ (Ìàêñèìóì 100 ñèìâîëîâ).";
  }
  
  if(isset($data['user_email'])){
   if( !preg_match("/.{1,80}/i",$data['user_email']) ) $this->error[] = "Îøèáêà ââîäà ïîëÿ Âàø e-mail (Ìàêñèìóì 80 ñèìâîëîâ).";
  }
  
  if(isset($data['user_login'])){
   if( !preg_match("/.{1,100}/i",$data['user_login']) ) $this->error[] = "Îøèáêà ââîäà ïîëÿ Âàø ëîãèí (Ìàêñèìóì 100 ñèìâîëîâ).";
   elseif( $this->isLoginUser($data['user_login']) ) $this->error[] = "Îøèáêà òàêîé Ëîãèí óæå åñòü!";
  }
  
  if(isset($data['you_login'])){
   if( !$this->isLoginUser($data['you_login']) ) $this->error[] = "Òàêîãî ËÎÃÈÍÀ íåò â áàçå äàííûõ ñàéòà!";
  }
  
  if(isset($data['user_psw'])){
   if( !preg_match("/.{1,100}/i",$data['user_psw']) ) $this->error[] = "Îøèáêà ââîäà ïîëÿ Âàø ïàðîëü (Ìàêñèìóì 100 ñèìâîëîâ).";
  }

 return ( count($this->error) ) ? true : false;
 }
 
 function deleteRubric($id,$field="id"){
  $sql = "select pic,id,parent_id from catalogs_rubrics where $field=?";
  $res = $this->db->getAll($sql,array($id),DB_FETCHMODE_ASSOC);
  foreach($res as $row){
  @unlink("{$_SERVER['DOCUMENT_ROOT']}/uploaded/pic/catalogs/rubrics/{$row['pic']}");
  $sql = "delete from catalogs_rubrics where id=?";
  $this->db->query($sql,array($row['id']));
  $this->deleteFiltersRubric_id($row['id']);
  $this->deleteYearsRubric_id($row['id']);
  $this->deleteProductsRubric($row['id']);
  $this->deleteRubric($row['id'],"parent_id");
  }
 }
 
 function deleteProductPics($id,$pics = array('pic_big','pic')){
  $sql = "select pic_big,pic from catalogs_products where id=?";
  $row = $this->db->getRow($sql,array($id),DB_FETCHMODE_ASSOC);
 // if(in_array('pic_big',$pics))@unlink("{$_SERVER['DOCUMENT_ROOT']}/uploaded/pic/catalogs/products/big/{$row['pic_big']}");
  if(in_array('pic',$pics))@unlink("{$_SERVER['DOCUMENT_ROOT']}/uploaded/pic/catalogs/products/{$row['pic']}");
 }
 
 function deleteProduct($id){
  $this->deleteProductPics($id);
  $sql = "delete from catalogs_products where id=?";
  $this->db->query($sql,array($id));
  $this->delete_keysProductsFilters($id);
  $this->delete_keysProductsAkcii($id);
  $this->delete_keysProductsYears($id);
  $this->delete_keysProductsCities($id);
  $this->deleteProductModifications($id);
 }
 
 function deleteProductsRubric($id){
  $res = $this->db->getAll("select id from catalogs_products where rubric_id=?",array($id),DB_FETCHMODE_ASSOC);
  foreach($res as $row){
   $this->deleteProduct($row['id']);
  }
 }


 function PhotosCheck($id_s,$check_s = array()){
  $sql = "UPDATE gallery SET active = ? WHERE id =?";

  foreach($id_s as $id){
  $this->db->query($sql,array(0,$id));
  }
 if(count($check_s)){
  foreach($check_s as $id){
  $this->db->query($sql,array(1,$id));
  }
 }
 }
 
 function viewRubrics($id = 0,$parent_id = 0){ // print $parent_id."<br />";
  global $rubrics;
  //$sql = "select a.*,(select b.id from catalogs_rubrics b where b.parent_id=a.id order by b.sort limit 1) as r_pid from catalogs_rubrics a where a.parent_id=? group by a.id order by a.sort asc";
$sql = "select a.*,(select b.translit from catalogs_rubrics b where b.parent_id=a.id order by b.sort limit 1) as r_pid2,(select b.id from catalogs_rubrics b where b.parent_id=a.id order by b.sort limit 1) as r_pid from catalogs_rubrics a where a.parent_id=? group by a.id order by a.sort asc";
    
$res = $this->db->query($sql,array($id));
  while ($res->fetchInto($row,DB_FETCHMODE_ASSOC)){
   $rubrics[] = $row;   //print $row['id']."<br />";

   if(in_array($row['id'],$this->getParentIdRubric($parent_id))){$this->viewRubrics($row['id']);}
  // if($row['level']==0){$this->viewRubrics($row['id']);}
  }
   $this->tpl->assign("rubrics",$rubrics);
 }
 
 function getParentIdRubric($id){
 //$ids = array();
 global $ids;
  if(!count($ids))$ids = array();
  while($id>0){
   $row = $this->db->getRow('select id,parent_id from catalogs_rubrics where id=?',array($id),DB_FETCHMODE_ASSOC);
   //if(isset($row['id']))
   $ids[] = $row['id'];
   $id = $row['parent_id'];
  }   //print_r($ids);
 // sort($ids);
  return $ids;
 }
 
 function viewRubricsAll($id = 0){
  global $rubrics;
  $sql = "select * from catalogs_rubrics where parent_id=? order by sort asc";
  $res = $this->db->query($sql,array($id));
  while ($res->fetchInto($row,DB_FETCHMODE_ASSOC)){
   $rubrics[] = $row;
   $this->viewRubricsAll($row['id']);
  }
   $this->tpl->assign("rubrics",$rubrics);
 }


 function viewRubrics_begin($item = 'parents'){
  $sql = "select a.*,(select b.id from catalogs_rubrics b where b.parent_id=a.id order by b.sort limit 1) as r_pid from catalogs_rubrics a where a.parent_id=? order by a.sort asc";
  $row = $this->db->getAll($sql,array(0),DB_FETCHMODE_ASSOC);
  foreach($row as $key=>$value){
   if($item=='parents'){
    $row[$key]['parents'] = $this->db->getAll("select * from catalogs_rubrics where parent_id=? order by sort asc",array($value['id']),DB_FETCHMODE_ASSOC);
   }elseif($item=='brends'){
    $row[$key]['brends'] = $this->db->getAll("select * from catalogs_brends where rubric_id in (select id from catalogs_rubrics where parent_id=? or id=?) group by name",array($value['id'],$value['id']),DB_FETCHMODE_ASSOC);
   }
  }
  $this->tpl->assign("catalogs_rubrics_begin",$row);
 }
 
 function viewRubrics_parent($parent_id = 0){
  $sql = "select * from catalogs_rubrics where parent_id=? order by sort asc";
  $row = $this->db->getAll($sql,array($parent_id),DB_FETCHMODE_ASSOC);
  $this->tpl->assign("catalogs_rubrics_parent",$row);
 }
 
 function viewRubrics_parent2($rub_id){
  $parent_id = $this->getRubricParent($rub_id);
  if($parent_id==0)$parent_id = $rub_id;
  $sql = "select * from catalogs_rubrics where parent_id=? order by sort asc";
  $row = $this->db->getAll($sql,array($parent_id),DB_FETCHMODE_ASSOC);
  $this->tpl->assign("catalogs_rubrics_parent2",$row);
 }
 
 function viewRubricOne($id,&$row){
  $sql = "select * from catalogs_rubrics where id=?";
  $row = $this->db->getRow($sql,array($id),DB_FETCHMODE_ASSOC);
  $this->tpl->assign('rubric',$row);
 }
 
 function getRubricName($id){
  $sql = "select name from catalogs_rubrics where id=?";
  return $this->db->getOne($sql,array($id));
 }
 
 function getRubricParent($id){
  $sql = "select parent_id from catalogs_rubrics where id=?";
  return $this->db->getOne($sql,array($id));
 }

 function SaveRubric($data,$upload){
 $table_name = "catalogs_rubrics";

if(trim($data['translit']) == '') $data['translit'] = translit($data['name']);

 $DB_AUTOQUERY = ($data['update_id']>0) ? DB_AUTOQUERY_UPDATE : DB_AUTOQUERY_INSERT;
 $parent_id = (isset($data['parent_id']) ? $data['parent_id'] : 0);
 $fields_values = array('parent_id' => $parent_id,"level"=>($this->getLevelRubric($parent_id)+1),'sort' => $data['sort'],'name' => $data['name'],'list_name' => $data['list_name'],'sort_cost' => $data['sort_cost'],'meta_title' => $data['meta_title'],'meta_description' => $data['meta_description'],'meta_keywords' => $data['meta_keywords'],'meta_about' => $data['meta_about'],'translit' => $data['translit']);
  /*
  if($upload['pic']['tmp_name']){
   $fields_values['pic'] = upload_ImageResize($upload['pic'],array('width'=>"180",'height'=>"180",'upload_path'=>"./uploaded/pic/catalogs/rubrics/"));
  } */
  
  if($upload['pic']['tmp_name']){
   if($data['update_id']>0)$this->deletePicRubric($data['update_id']);
   $uploadfile = "./uploaded/pic/catalogs/rubrics/";
   $type = substr(strrchr($upload['pic']['name'],"."),1);
   $uploadname = mktime() . "." . $type;
   if (!move_uploaded_file($_FILES['pic']['tmp_name'], $uploadfile . $uploadname))print"Îøèáêà ïðè çàêà÷êå ôàéëà!";
   $fields_values['pic'] = $uploadname;
  }
  $this->db->autoExecute($table_name,$fields_values,$DB_AUTOQUERY,"id={$data['update_id']}");
 }
 
 function deletePicRubric($id){
  $sql = "select pic from catalogs_rubrics where id=?";
  $rub = $this->db->getRow($sql,array($id),DB_FETCHMODE_ASSOC);
  @unlink("./uploaded/pic/catalogs/rubrics/{$rub['pic']}");
 }
 
 function getLevelRubric($id){
  $level = $this->db->getOne("select level from catalogs_rubrics where id=?",array($id));
  return ($level==null)? -1 : $level;
 }
 
 function saveUser($data){
  $table_name = "catalogs_users";
  $DB_AUTOQUERY = ($data['update_id']>0) ? DB_AUTOQUERY_UPDATE : DB_AUTOQUERY_INSERT;
  $fields_values = array('name' => $data['user_name'],'email' => $data['user_email'],'login' => $data['user_login'],'psw' => $data['user_psw'],'about' => $data['user_about'],'mktime'=>mktime());
  $this->db->autoExecute($table_name,$fields_values,$DB_AUTOQUERY,"id={$data['update_id']}");
 }
 
 function updateUser($data){
  $table_name = "catalogs_users";
  $DB_AUTOQUERY = DB_AUTOQUERY_UPDATE;
  $fields_values = array('name' => $data['user_name'],'email' => $data['user_email'],'login' => $data['user_login'],'psw' => $data['user_psw'],'about' => $data['user_about'],'discount'=>$data['user_discount']);
  $this->db->autoExecute($table_name,$fields_values,$DB_AUTOQUERY,"id={$data['update_id']}");
 }
 
 function updateUserID($data,$id){
  $table_name = "catalogs_users";
  $DB_AUTOQUERY = DB_AUTOQUERY_UPDATE;
  $fields_values = array('name' => $data['user_name'],'email' => $data['user_email'],'psw' => $data['user_psw'],'about' => $data['user_about'],'phone' => $data['user_phone'],'phonemob' => $data['user_phonemob'],'adress' => $data['user_adress']);
  $this->db->autoExecute($table_name,$fields_values,$DB_AUTOQUERY,"id={$id}");
 }
 
 function deleteUser($id){
  $this->db->query("delete from catalogs_users where id=?",array($id));
  $res_order_id = $this->db->getRow("select id from catalogs_orders where user_id=?",array($id),DB_FETCHMODE_ASSOC);
  if(count($res_order_id)){
  foreach($res_order_id as $_id){
   $this->db->query("delete from catalogs_orders where id=?",array($_id));
   $this->db->query("delete from catalogs_orders_products where order_id=?",array($_id));
  }}
 }
 
 function isLoginUser($login){
  return $this->db->getOne("select id from catalogs_users where login=?",array($login));
 }
 
 function sendLoginInfo($login){
  $user = $this->db->getRow("select * from catalogs_users where login=?",array($login),DB_FETCHMODE_ASSOC);
  $mail = new PHPMailer();
  $mail->CharSet = "windows-1251";
  $mail->From = "shop@eltrade.com.ua";
  $mail->FromName = "shop@eltrade.com.ua";
  $mail->AddAddress($user['email'], $user['name']);
  $mail->Subject = "Àêêàóíò ýêñòðèì";
  $msg = "";
   $msg .= "Çäðàâñòâóéòå: ".$user['name'];
   $msg .= "<br />";
   $msg .= "Âàø ëîãèí: ".$user['login'];
   $msg .= "<br>";
   $msg .= "Âàø ïàðîëü: ".$user['psw'];
   $msg .= "<br>";
   $msg .= "Ñ óâàæåíèåì, shop@eltrade.com.ua";

  $mail->MsgHTML($msg);

   if(!$mail->Send()){echo "There has been a mail error sending to <br>";return false;}
   $mail->ClearAddresses();
   $mail->ClearAttachments();
 }
 
 function isUser($login,$psw){
  $row = $this->db->getRow("select * from catalogs_users where login=? AND psw=?",array($login,$psw),DB_FETCHMODE_ASSOC);
  $this->tpl->assign('user_service',$row);
  return $row['id'];
 }
 
 function viewUser($id){
  $sql = "select * from catalogs_users where id=?";
  $row = $this->db->getRow($sql,array($id),DB_FETCHMODE_ASSOC);
  $this->tpl->assign('user',$row);
 }
 
 function getUserDiscount($id){
  return $this->db->getOne("select discount from catalogs_users where id=?",array($id));
 }
 
 function viewUsers(){
  $sql = "SELECT catalogs_users. *, COUNT(catalogs_orders.user_id) as count_orders
FROM catalogs_users LEFT JOIN catalogs_orders ON catalogs_orders.user_id=catalogs_users.id
GROUP BY catalogs_users.id
ORDER BY catalogs_users.mktime DESC";

  $pagerOptions = Array(
    'mode' => 'Sliding',
    'delta' => 6,
    'perPage' => 10,
    'linkClass'=>"link_class",
    'curPageLinkClassName'=>"link_class_active",
    'spacesBeforeSeparator' => 1,
    'spacesAfterSeparator' => 1
  );
  $res = Pager_Wrapper_DB($this->db, $sql, $pagerOptions, false, DB_FETCHMODE_ASSOC, array());

  $this->tpl->assign('usersData', $res);
 }
 
 function viewModifications($product_id){
  $sql = "select * from catalogs_modifications where product_id=? order by id desc";
  $row = $this->db->getAll($sql,array($product_id),DB_FETCHMODE_ASSOC);
  $this->tpl->assign('modifications', $row);
 }
 
 function viewModificationsProduct($product_id){
  $sql = "select * from catalogs_modifications where product_id=? and active>0 order by id desc";
 // $sql = "select m.* from catalogs_keys_products_cities k left join catalogs_modifications m on m.code=k.mod_code where k.product_id=? and k.count>0 order by k.mod_code desc";
  $row = $this->db->getAll($sql,array($product_id),DB_FETCHMODE_ASSOC);
  $this->tpl->assign('modifications', $row);
 }
 
 function viewModificationOne($id){
  $sql = "select * from catalogs_modifications where id=?";
  $row = $this->db->getRow($sql,array($id),DB_FETCHMODE_ASSOC);
  $this->tpl->assign('modification', $row);
 }
 
 function getModificationProduct_id($code){
  return $this->db->getOne("select product_id from catalogs_modifications where code=?",array($code));
 }
 
 function SaveModification($data,$upload){
 $table_name = "catalogs_modifications";
 $DB_AUTOQUERY = ($data['update_id']>0) ? DB_AUTOQUERY_UPDATE : DB_AUTOQUERY_INSERT;
 $fields_values = array('product_id'=>$data['product_id'],'code'=>$data['code'],'size' => $data['size'],'color' => $data['color'],'active' => $data['active']);
 if(isset($data['delete_pic'])){if($data['update_id']>0){$this->deleteModificationPics($data['update_id']);}$fields_values['pic']=null;$fields_values['pic_big']=null;}
  if($upload['pic']['tmp_name']){
   if($data['update_id']>0){
    $delete_pics = (isset($upload['pic']['big']) && $upload['pic']['big']==true)?array('pic'):array('pic','pic_big');
    $this->deleteModificationPics($data['update_id'],$delete_pics);
   }
   $fields_values['pic'] = upload_ImageResize($upload['pic'],array('width'=>"144",'height'=>"144",'upload_path'=>"./uploaded/pic/catalogs/modifications/"));
   $fields_values['pic_big'] = (isset($upload['pic']['big']) && $upload['pic']['big']==true)?$upload['pic']['name']:upload_ImageResize($upload['pic'],array('width'=>"500",'height'=>"500",'upload_path'=>"./uploaded/pic/catalogs/modifications/big/"));
  }

  $this->db->autoExecute($table_name,$fields_values,$DB_AUTOQUERY,"id='{$data['update_id']}'");
 return $id;
 }
 
 function deleteModification($id){
  $this->deleteModificationPics($id);
  $this->db->query("delete from catalogs_modifications where id=?",array($id));
 }
 
 function deleteProductModifications($product_id,$nopic = false){
  IF($nopic==false){
  $sql = "select * from catalogs_modifications where product_id=?";
  $res = $this->db->getAll($sql,array($product_id),DB_FETCHMODE_ASSOC);
  foreach($res as $row){
   $this->deleteModificationPics($row['id']);
  }
  }
  $this->db->query("delete from catalogs_modifications where product_id=?",array($product_id));
 }
 
 function deleteModificationPics($id,$pics = array('pic_big','pic')){
  $sql = "select pic,pic_big from catalogs_modifications where id=?";
  $row = $this->db->getRow($sql,array($id),DB_FETCHMODE_ASSOC);
  if(in_array('pic',$pics))@unlink("{$_SERVER['DOCUMENT_ROOT']}/uploaded/pic/catalogs/modifications/{$row['pic']}");
 // if(in_array('pic_big',$pics))@unlink("{$_SERVER['DOCUMENT_ROOT']}/uploaded/pic/catalogs/modifications/big/{$row['pic_big']}");
 }
 
 function ProductClick($id){
  $this->db->query("update catalogs_products set click=click+1 where id='$id'");
 }
 
 function SaveProduct($data,$upload){
 $table_name = "catalogs_products";

if(trim(@$data['translit'])=="") $data['translit'] = @totranslit($data['name']);

 $DB_AUTOQUERY = ($data['update_id']>0) ? DB_AUTOQUERY_UPDATE : DB_AUTOQUERY_INSERT;
 $id = ($data['update_id']>0) ? $data['update_id'] : $this->db->nextId('mySequence_'.$table_name);
 $fields_values = array('id'=>$id,'rubric_id'=>$data['rubric_id'],'rubric_parent_id'=>$this->getRubricParent($data['rubric_id']),'brend_id'=>$data['brend_id'],'name' => $data['name'],'about' => $data['about'],'text' => $data['text'],'strnumber' => $data['strnumber'],'cine'=>$data['cine'],'cine_last'=>$data['cine_last'],'sex'=>$data['sex'], 'mktime' => mktime(),'meta_title' => $data['meta_title'],'meta_description' => $data['meta_description'],'meta_keywords' => $data['meta_keywords'],'meta_about' => $data['meta_about'],'active' => $data['active'],'translit' => $data['translit']);
 if(isset($data['is_cost2']))$fields_values['is_cost2'] = 1;else $fields_values['is_cost2'] = 0;
 if(isset($data['cine2']))$fields_values['cine2'] = $data['cine2'];
 if(isset($data['params']))$fields_values['params'] = $data['params'];
 if(isset($data['doc']))$fields_values['doc'] = $data['doc'];
 if(isset($data['video_code']))$fields_values['video_code'] = $data['video_code'];
 if(isset($data['akcii_id']))$fields_values['akcii_id'] = $data['akcii_id'];

 if(isset($data['translit']))$fields_values['translit'] = $data['translit'];

  if($upload['pic']['tmp_name']){
   $delete_pics = (isset($upload['pic']['big']) && $upload['pic']['big']==true)?array('pic'):array('pic','pic_big');
   $this->deleteProductPics($id,$delete_pics);
   $fields_values['pic'] = upload_ImageResize($upload['pic'],array('width'=>"144",'height'=>"144",'upload_path'=>"./uploaded/pic/catalogs/products/"));
   $fields_values['pic_big'] = (isset($upload['pic']['big']) && $upload['pic']['big']==true)?$upload['pic']['name']:upload_ImageResize($upload['pic'],array('width'=>"500",'height'=>"500",'upload_path'=>"./uploaded/pic/catalogs/products/big/"));
  }

  $this->db->autoExecute($table_name,$fields_values,$DB_AUTOQUERY,"id='$id'");
  $this->save_keysProductsFilters($id,$data);
  $this->save_keysProductsYears($id,$data);
  //$this->save_keysProductsCities($id,$data);
  $this->save_keysProductsAkcii($id,$data);
 return $id;
 }
 
 function save_keysProductsFilters($id,$data){
  $this->delete_keysProductsFilters($id);
  if(!isset($data['filter']))return false;
  $table_name = "catalogs_keys_products_filters";
  foreach($data['filter'] as $filter_id){
   $this->db->autoExecute($table_name,array('product_id'=>$id,'filter_id'=>$filter_id,'rubric_id'=>$data['rubric_id']),DB_AUTOQUERY_INSERT);
  }
 }
 
 function delete_keysProductsFilters($id){
  $this->db->query("delete from catalogs_keys_products_filters where product_id=?",array($id));
 }
 
 function save_keysProductsYears($id,$data){
  $this->delete_keysProductsYears($id);
  if(!isset($data['years']))return false;
  $table_name = "catalogs_keys_products_years";
  foreach($data['years'] as $filter_id){
   $this->db->autoExecute($table_name,array('product_id'=>$id,'year_id'=>$filter_id,'rubric_id'=>$data['rubric_id']),DB_AUTOQUERY_INSERT);
  }
 }
 
 function delete_keysProductsYears($id){
  $this->db->query("delete from catalogs_keys_products_years where product_id=?",array($id));
 }
 
 function save_keysProductsCities($id,$data){
  $this->delete_keysProductsCities($id);
  if(!isset($data['city']))return false;
  $table_name = "catalogs_keys_products_cities";
  foreach($data['city'] as $city_id){
   $this->db->autoExecute($table_name,array('product_id'=>$id,'city_id'=>$city_id),DB_AUTOQUERY_INSERT);
  }
 }
 
 function delete_keysProductsAkcii($id){
  $this->db->query("delete from catalogs_keys_products_akcii where product_id=?",array($id));
 }

 function save_keysProductsAkcii($id,$data){
  $this->delete_keysProductsAkcii($id);
  if(!isset($data['akcii']))return false;
  $table_name = "catalogs_keys_products_akcii";
  foreach($data['akcii'] as $rubric_id){
   $this->db->autoExecute($table_name,array('product_id'=>$id,'rubric_id'=>$rubric_id),DB_AUTOQUERY_INSERT);
  }
 }
 
 function delete_keysProductsCities($id){
  $this->db->query("delete from catalogs_keys_products_cities where product_id=?",array($id));
 }

 
 function saveProductSizeCine($id,$data){
  $this->db->query("delete from catalogs_products_cine where product_id=?",array($id));
  foreach($data['size'] as $key=>$size){
   $this->db->autoExecute("catalogs_products_cine",array('product_id'=>$id,'size'=>$size,'cine'=>$data['cine'][$key],'metka'=>$data['size_metka'][$key],'n'=>$key),DB_AUTOQUERY_INSERT);
  }
 }
 

 function productsIsHits($products,$hits,$tops,$headers){
  $sql = "update catalogs_products set hit=?,top=?,header=? where id=?";
  foreach($products as $id){
   if(@in_array($id,$hits))$hit = true;
   else $hit = false;
   if(@in_array($id,$tops))$top = true;
   else $top = false;
   if(@in_array($id,$headers))$header = true;
   else $header = false;
   $this->db->query($sql,array($hit,$top,$header, $id));
  }
 }
 
 function productsIsHits2($data,$hits){
  $sql = "update catalogs_products set hit=?,hit_sort=? where id=?";
  foreach($data['product_id'] as $key=>$id){
   if(@in_array($id,$hits))$hit = true;
   else $hit = false;
   $this->db->query($sql,array($hit,$data['hit_sort'][$key],$id));
  }
 }
 
 function viewProductsRubrics($rubrics,$limit=20){
  $data = array();
  foreach($rubrics as $key=>$rubric_id){
   $data[$key]['rubric']['name'] = $this->getRubricName($rubric_id);
   $data[$key]['rubric']['id'] = $rubric_id;
   
   $count = $this->db->getOne("select count(*) from catalogs_products WHERE count_modifications>0 and rubric_id=?",array($rubric_id));
   $limit = 4; $round = ($count>$limit) ? rand(0,($count-$limit)) : $limit;
   $sql = "select * from catalogs_products where count_modifications>0 and rubric_id=? order by id " . ((rand(1,1000)%2) ? "asc" : "desc") . " limit $round,$limit";
   $data[$key]['products'] = $this->db->getAll($sql,array($rubric_id),DB_FETCHMODE_ASSOC);
  }
 /* print"<pre>";
  print_r($data);
  print"</pre>";   */
  $this->tpl->assign('products',$data);
 }
 
 function seralizeFilter($str){
  $array = explode(';',$str);
  $filter = array();
  foreach($array as $key=>$value){
   $filter[substr($value,0,1)][] = substr($value,1, strpos($value,"_")-1 );
  }
  return $filter;
 }
 
 function viewProducts($params,$rubricsP = false,$count_modf = true){
 	
 	
 	//exit;
 	
 	
  if(isset($params['filter']) && count($params['filter'])>0)$filter = $this->seralizeFilter($params['filter']);
  $search = array();
  if(isset($_GET['perPage']) && $_GET['perPage']>0 && $_GET['perPage']<=100)$perPage = $_GET['perPage'];else $perPage = 20;
  if(isset($params['search_str']) && strlen($params['search_str'])>0){
   $array_string = explode(" ",trim($params['search_str']));
   $search_string = array();
    $search_string[] = "catalogs_products.name like '%".mysql_real_escape_string($params['search_str'])."%'";
    $search_string[] = "catalogs_products.text like '%".mysql_real_escape_string($params['search_str'])."%'";
 /*  foreach($array_string as $str){
    $search_string[] = "catalogs_products.name like '$str'";
    $search_string[] = "catalogs_products.name like'% $str %'";
    $search_string[] = "catalogs_products.name like'%$str %'";
    $search_string[] = "catalogs_products.name like'% $str%'";

    $search_string[] = "catalogs_products.text like '$str'";
    $search_string[] = "catalogs_products.text like'% $str %'";
    $search_string[] = "catalogs_products.text like'%$str %'";
    $search_string[] = "catalogs_products.text like'% $str%'";
   } */
   $search[] = "((" . implode(" OR ",$search_string) . ") OR ". sprintf("catalogs_modifications.code='%s'", mysql_real_escape_string($params['search_str'])).")";
  }
      // print_r($params);
  if(isset($params['brendID']) && $params['brendID']>0)$search[] = sprintf("catalogs_products.brend_id='%d'",$params['brendID']);
  if(isset($params['akciiID']) && $params['akciiID']>0)$search[] = sprintf("catalogs_products.akcii_id='%d'",$params['akciiID']);
  if(isset($params['brend']) && strlen($params['brend'])>0)$search[] = "catalogs_products.brend_id in(".implode(",",$this->getBrendIDs_name($params['brend'])).")";
  if(isset($params['sex']) && strlen($params['sex'])>0){
  $sex = array('male'=>1,'female'=>2,'child'=>3,'unisex'=>4);
  $search[] = sprintf("catalogs_products.sex='%d'",$sex[$params['sex']]);

  }
  //if(isset($params['akcii']) && $params['akcii']>0)$search[] = sprintf("catalogs_products.hit='%d'",$params['akcii']);
  if($count_modf==true)$search[] = "catalogs_products.count_modifications>0";
  if(isset($params['rubID']) && $params['rubID']>0){
   $search[] = ($rubricsP==true)?sprintf("(catalogs_products.rubric_id='%d')",$params['rubID']):sprintf("
   (catalogs_products.rubric_parent_id='%d' || 
   catalogs_products.rubric_id='%d' || 
   catalogs_products.rubric_id=(SELECT id FROM catalogs_rubrics WHERE translit='%d') ||
   catalogs_products.rubric_parent_id=(SELECT id FROM catalogs_rubrics WHERE translit='%d'))",$params['rubID'],$params['rubID'],$params['rubID'],$params['rubID']);
  }
  
 /* if(isset($params['filterID'])){
   //$search[] = sprintf("catalogs_keys_products_filters.filter_id='%d'", $params['filterID']);
   $search[] = "catalogs_keys_products_filters.filter_id in (".implode(",",$params['filterID']).")";
  }*/
  if(isset($filter['f']) && count($filter['f'])>0){
   $search[] = "catalogs_keys_products_filters.filter_id in (".implode(",",$filter['f']).")";
  }
/*  if(isset($params['yearID']) && $params['yearID']>0){
   //$search[] = sprintf("catalogs_keys_products_years.year_id='%d'", $params['yearID']);
   $search[] = "catalogs_keys_products_years.year_id in (".implode(",",$params['yearID']).")";
  }*/
  if(isset($filter['y']) && $filter['y']>0){
   $search[] = "catalogs_keys_products_years.year_id in (".implode(",",$filter['y']).")";
  }
  $sql = "select catalogs_rubrics.translit as translit2,catalogs_products.*,catalogs_brends.name as brend_name,catalogs_rubrics.list_name from catalogs_products LEFT JOIN catalogs_brends ON catalogs_brends.id=catalogs_products.brend_id LEFT JOIN catalogs_rubrics ON catalogs_rubrics.id=catalogs_products.rubric_id ";
  if(isset($params['akcii']) && $params['akcii']>0)$sql .= "RIGHT JOIN catalogs_keys_products_akcii ON catalogs_keys_products_akcii.product_id=catalogs_products.id ";
  if(isset($filter['f']) && count($filter['f'])>0)$sql .= "LEFT JOIN catalogs_keys_products_filters ON catalogs_keys_products_filters.product_id=catalogs_products.id ";
 //if(isset($params['filterID']) && $params['filterID']>0)$sql .= "LEFT JOIN catalogs_keys_products_filters ON catalogs_keys_products_filters.product_id=catalogs_products.id ";
//  if(isset($params['yearID']) && $params['yearID']>0)$sql .= "LEFT JOIN catalogs_keys_products_years ON catalogs_keys_products_years.product_id=catalogs_products.id ";
  if(isset($filter['y']) && $filter['y']>0)$sql .= "LEFT JOIN catalogs_keys_products_years ON catalogs_keys_products_years.product_id=catalogs_products.id ";
  if(isset($params['search_str']) && strlen($params['search_str'])>0){$sql .= "LEFT JOIN catalogs_modifications ON catalogs_modifications.product_id=catalogs_products.id ";}
  $sql .= "WHERE 1=1 ";
  if(count($search))$sql .= "AND " . implode(" AND ",$search) . " ";
  if(isset($params['akcii']) && $params['akcii']>0){$sql .= " GROUP BY catalogs_keys_products_akcii.product_id ";}
  if(isset($params['search_str']) && strlen($params['search_str'])>0){$sql .= " GROUP BY catalogs_products.id ";}
  $sql .= "order by ";
  if(isset($params['sort'])){
   switch($params['sort']){
    case 'cine' : $sql .= " catalogs_products.cine " . (($_GET['order']=='asc')?"asc":"desc"); break;
    case 'click' : $sql .= " catalogs_products.click " . (($_GET['order']=='asc')?"asc":"desc"); break;
    case 'hit' : $sql .= " catalogs_products.hit_sort asc"; break;
    default : $sql .= " catalogs_products.mktime desc";
   }
  }else $sql .= " catalogs_products.cine desc";

  $pagerOptions = Array(
    'mode' => 'Sliding',
    'delta' => 5,
    'perPage' => $perPage,
    'linkClass'=>"link_class",
    'curPageLinkClassName'=>"link_class_active",
    'spacesBeforeSeparator' => 1,
    'spacesAfterSeparator' => 1
  );
  //echo $sql;
  //$sql="";
  $res = Pager_Wrapper_DB($this->db, $sql, $pagerOptions, false, DB_FETCHMODE_ASSOC, array());

if($_GET['test']=='1')
for($i=0;$i<count($res['data']);$i++){
	if( @$res['data'][$i]['rating'] ) $res['data'][$i]['rating'] = round( (@$res['data'][$i]['rating'] / @$res['data'][$i]['vote_num']), 0 );
	else $res['data'][$i]['rating'] = 0;
	$res['data'][$i]['rating'] = @$res['data'][$i]['rating'] * 17;
}

//if($_GET['test']=='1') print_r($res);

  $this->tpl->assign('productsData', $res);
  return $res;
 }
 
 function getCineCurs($type_curs,$cine){
  $curs = array();
  
     $uah = $this->db->getOne("select curs from catalogs_curs where type=?",array('uah'));
     $uah_bank = $this->db->getOne("select curs from catalogs_curs where type=?",array('uah_bank'));
     $usd = $this->db->getOne("select curs from catalogs_curs where type=?",array('usd'));
     
  switch($type_curs){
   case 'uah' :
    $curs['uah'] = round($cine,2);
    $curs['uah_bank'] = round(($cine/$usd)*$uah_bank,2);
    $curs['usd'] = round($cine/$usd,2);
   break;
   case 'uah_bank' :
    $curs['uah'] = round(($cine/$uah_bank)*$uah,2);
    $curs['uah_bank'] = round($cine,2);
    $curs['usd'] = round($cine/$uah_bank,2);
   break;
   case 'usd' :
    $curs['uah'] = round($cine*$uah,2);
    $curs['uah_bank'] = round($cine*$uah_bank,2);
    $curs['usd'] = round($cine,2);
   break;
  }
  return $curs;
 }
 
 function viewProductsAkcii($rubric_id){
  $sql = "select catalogs_products.* from catalogs_keys_products_akcii left join catalogs_products on catalogs_products.id=catalogs_keys_products_akcii.product_id where catalogs_keys_products_akcii.rubric_id=?";
  $res = $this->db->getAll($sql,array($rubric_id),DB_FETCHMODE_ASSOC);
  //print_r($res);
  $this->tpl->assign('products_akcii',$res);
 }

 function viewProductsHitsAll2(){
  if(isset($_GET['perPage']) && $_GET['perPage']>0 && $_GET['perPage']<=100)$perPage = $_GET['perPage'];else $perPage = 20;
  $sql = "select * from catalogs_products where hit=?";
  $pagerOptions = Array(
    'mode' => 'Sliding',
    'delta' => 6,
    'perPage' => $perPage,
    'linkClass'=>"link_class",
    'curPageLinkClassName'=>"link_class_active",
    'spacesBeforeSeparator' => 1,
    'spacesAfterSeparator' => 1
  );
  $res = Pager_Wrapper_DB($this->db, $sql, $pagerOptions, false, DB_FETCHMODE_ASSOC, array(true));

  $this->tpl->assign('productsData', $res);
 }
 
 function viewProductsHits($params,$limit = 4,$curs = null){
  $search = array();
  if(isset($params['rubID']) && $params['rubID']>0)$search[] = sprintf("rubric_parent_id=%d",$params['rubID']);
  $sql = "select catalogs_products.*,catalogs_brends.name as brend_name from catalogs_products LEFT JOIN catalogs_brends ON catalogs_brends.id=catalogs_products.brend_id WHERE catalogs_products.hit=? and catalogs_products.count_modifications>0 ";
  if(count($search))$sql .= "AND " . implode(" AND ",$search) . " ";
  $sql .= "order by catalogs_products.mktime desc";
  $res = $this->db->getAll($sql,array(true),DB_FETCHMODE_ASSOC);
  $this->tpl->assign('products_hits',$res);
 }
 
 function viewProductsTops($params,$limit = 4,$curs = null){
  $search = array();
  if(isset($params['rubID']) && $params['rubID']>0)$search[] = sprintf("rubric_parent_id=%d",$params['rubID']);
  $sql = "select catalogs_products.*,catalogs_brends.name as brend_name from catalogs_products LEFT JOIN catalogs_brends ON catalogs_brends.id=catalogs_products.brend_id WHERE catalogs_products.top=? and catalogs_products.count_modifications>0 ";
  if(count($search))$sql .= "AND " . implode(" AND ",$search) . " ";
  $sql .= "order by catalogs_products.mktime desc";
  $res = $this->db->getAll($sql,array(true),DB_FETCHMODE_ASSOC);
  $this->tpl->assign('products_top',$res);
 }

 function viewProductsTopOne(){
   $count = $this->db->getOne("select count(*) from catalogs_products WHERE catalogs_products.header=?",array(true));
   $limit = 1; $round = rand(0,($count-$limit));
   $res = $this->db->getRow("select * from catalogs_products WHERE catalogs_products.header=? order by id " . ((rand(1,1000)%2) ? "asc" : "desc") . " LIMIT $round,$limit",array(true),DB_FETCHMODE_ASSOC);
   $this->tpl->assign('products_top_one',$res);
 }

 function viewProductsLast($limit = 1){
  $search = array();
  $sql = "select catalogs_products.*,catalogs_brends.name as brend_name from catalogs_products LEFT JOIN catalogs_brends ON catalogs_brends.id=catalogs_products.brend_id WHERE catalogs_products.active=? ";
  $sql .= "order by catalogs_products.mktime desc LIMIT $limit";
  $res = $this->db->getAll($sql,array(true),DB_FETCHMODE_ASSOC);
  $this->tpl->assign('products_last',$res);
 }
 
 function viewProductsHitsAll($limit = 4){
  $sql = "select catalogs_products.*,catalogs_brends.name as brend_name from catalogs_products LEFT JOIN catalogs_brends ON catalogs_brends.id=catalogs_products.brend_id WHERE hit=? ";
  $sql .= "order by mktime desc LIMIT $limit";
  $products_hits = $this->db->getAll($sql,array(true),DB_FETCHMODE_ASSOC);
  $this->tpl->assign('products_hits_all',$products_hits);
 }
 
 function viewProductOne($id,&$row){
  $sql = "select p.*,b.name as brend_name,b.text as brend_text,b.pic_s as brend_pic_s from catalogs_products p left join catalogs_brends b ON b.id=p.brend_id where p.id=?";
  $row = $this->db->getRow($sql,array($id),DB_FETCHMODE_ASSOC);
  $this->tpl->assign('product',$row);
 }
 
 function deleteCompareProduct(&$compare,$id){
  foreach($compare as $key=>$_id){
   if($_id == $id)unset($compare[$key]);
  }
 }
 
 function viewCompareProducts($compare){
  $products = array();
  $i = 0;
  foreach($compare as $id){
   $sql = "select p.* from catalogs_products p where p.id=?";
   $products[$i] = $this->db->getRow($sql,array($id),DB_FETCHMODE_ASSOC);
   $products[$i]['params'] = $this->getProductParams($id);
   $i++;
  }  //print_r($products);
  $this->tpl->assign('products',$products);
 }
 
 function viewProductNembers($str_n){
  $arr_id = explode(",",$str_n);
  $products = array();
  foreach($arr_id as $id){
   $count = $this->db->getOne("select count(*) from catalogs_keys_products_filters where filter_id=?",array(trim($id)));
   $limit = 1; $round = rand(0,($count-$limit));                                                                                                                                                                                                                                                                                                                                           //" LIMIT 0,$limit"
   $sql = "select catalogs_rubrics.translit as translit2, catalogs_products.*,catalogs_keys_products_filters.filter_id as prd from catalogs_keys_products_filters Left Join catalogs_products ON catalogs_products.id=catalogs_keys_products_filters.product_id Left Join catalogs_rubrics ON catalogs_rubrics.id=catalogs_products.rubric_id where catalogs_keys_products_filters.filter_id=? and catalogs_products.count_modifications>0 order by catalogs_keys_products_filters.product_id " . ((rand(1,1000)%2) ? "asc" : "desc")  . " LIMIT $round,$limit";
   $row = $this->db->getRow($sql ,array(trim($id)),DB_FETCHMODE_ASSOC);
   if(count($row)>0)$products[] = $row;
  }

//  $products = $this->db->getAll("select catalogs_rubrics.translit as translit2,catalogs_products.*,catalogs_keys_products_filters.filter_id as prd from catalogs_keys_products_filters Left Join catalogs_products ON catalogs_products.id=catalogs_keys_products_filters.product_id Left Join catalogs_rubrics ON catalogs_rubrics.id=catalogs_products.rubric_id where catalogs_keys_products_filters.filter_id in(".implode(',',$arr_id).") and catalogs_products.count_modifications>0 Group By catalogs_keys_products_filters.filter_id order by catalogs_keys_products_filters.product_id " . ((rand(1,1000)%2) ? "asc" : "desc") ,array(),DB_FETCHMODE_ASSOC);
  $this->tpl->assign('products_parent',$products);
 }
 
 function getProductSizeCine($id,&$products){
  $res = $this->db->getAll("select * from catalogs_products_cine where product_id=?",array($id),DB_FETCHMODE_ASSOC);
  $i = 0;
  foreach($res as $row){
   $products['size_' . $row['n']] = $row['size'];
   $products['cine_' . $row['n']] = $row['cine'];
   $products['metka_' . $row['n']] = $row['metka'];
   $products['id_cine_' . $row['n']] = $row['id'];
  $i++;
  }  //print_r($products);
 }
 /*
 function getProductCine($id,$curs = null){
  $sql = "select cine from catalogs_products where id=?";
  $row = $this->db->getOne($sql,array($id));
  return $row;
 }*/
 
 function getProductCine($id){
  $sql = "select IF( catalogs_products.is_cost2 <1, catalogs_products.cine, catalogs_products.cine2 ) AS cine from catalogs_modifications left join catalogs_products on catalogs_products.id=catalogs_modifications.product_id where catalogs_modifications.id=?";
  return $this->db->getOne($sql,array($id));
 }
 
 function viewProductCine($id){
  $row = $this->db->getAll("select * from catalogs_products_cine where product_id=? and cine>0 Order By n ASC",array($id),DB_FETCHMODE_ASSOC);
  $this->tpl->assign('product_cines',$row);
 }
 
 function viewCatalogsCurs(){
  $uah = $this->db->getOne("select curs from catalogs_curs where type=?",array('uah'));
  $this->tpl->assign('curs_uah',$uah);
  $uah_bank = $this->db->getOne("select curs from catalogs_curs where type=?",array('uah_bank'));
  $this->tpl->assign('curs_uah_bank',$uah_bank);
  $usd = $this->db->getOne("select curs from catalogs_curs where type=?",array('usd'));
  $this->tpl->assign('curs_usd',$usd);
 }
 
 function saveCurs($data){
 $table_name = "catalogs_curs";
 $DB_AUTOQUERY = DB_AUTOQUERY_UPDATE;
 foreach($data as $key=>$value){
  $this->db->autoExecute($table_name,array('curs'=>$value),$DB_AUTOQUERY,"type='$key'");
 }
 }
 
 function viewVarCurs($curs){
  $this->tpl->assign('curs',$curs);
 }
 
 function viewBasketProducts($session_basket,$curs = null,$discount = 0){
  $products = array(); $i = 0; $cineAll = 0;
//  $sql = "select catalogs_products.* from catalogs_products where catalogs_products.id=?";
  $sql = "select catalogs_modifications.id,IF(catalogs_products.is_cost2<1,catalogs_products.cine,catalogs_products.cine2) as cine,catalogs_products.name,catalogs_modifications.code,catalogs_modifications.size,catalogs_modifications.color,catalogs_modifications.pic,catalogs_modifications.pic_big from catalogs_modifications Left Join catalogs_products On catalogs_products.id=catalogs_modifications.product_id where catalogs_modifications.id=?";

  foreach($session_basket as $id){
   $products_count = 1;
   if(count($products)){
   foreach($products as $key=>$value){
    if($value['id']==$id){$products_count=$products[$key]['products_count']+$products_count;$products[$key]['products_count']=$products_count;$products[$key]['products_cine_all']=$products[$key]['cine']*$products_count;$cineAll = $cineAll+$products[$key]['cine'];}
   }}
   if($products_count==1){
    $row = $this->db->getRow($sql,array($id),DB_FETCHMODE_ASSOC);
    $products[$i] = $row;
    $products[$i]['products_count']=$products_count;
    $products[$i]['products_cine_all']=$products[$i]['cine']*$products_count;
    $cineAll = $cineAll+$products[$i]['products_cine_all'];
    $i++;
   }

  }
  /*print"<pre>";
  print_r($products);
  print"</pre>";*/
  $this->tpl->assign('cineAll',$cineAll);
  $this->tpl->assign('cineAll_discount',$cineAll - (($cineAll*$discount)/100));
  $this->tpl->assign('basket_products',$products);   //print_r($products);
 }
 
 
 function BasketUpload(&$session_basket,$proructs_count){
 
 // ========== ZLODEYEV ============
 
    foreach($proructs_count as $key=>$value){ 
  
        // ==== îáíîâëÿåì ====
    
        // Âûáèðàåì èíôî î òîâàðå
        $sql4 = "SELECT * FROM catalogs_modifications as m
                LEFT JOIN catalogs_products as p
                ON p.id=m.product_id 
                WHERE m.id='".$key."' ";
        $result4 = mysql_query($sql4) or die(mysql_error());
        if (mysql_affected_rows()!=0) {	
            $item=mysql_fetch_assoc($result4);
        }    
        
        $f=0;
        
        if (isset($_SESSION['shopcart'])) {
        
            foreach ($_SESSION['shopcart'] as $i => $cart) {

                
                if ($cart['code']!='' && $cart['code']==$key) { 
                    $f=1;
                    $_SESSION['shopcart'][$i]['count']=$value;
                    $_SESSION['shopcart'][$i]['total']=$value*$_SESSION['shopcart'][$i]['price'];
                    if ($_SESSION['shopcart'][$i]['total']==0) {
                        unset($_SESSION['shopcart'][$i]);
                    }
                    break;
                }
            }
        } 
    }
 
  // ========== ZLODEYEV ============
 
 
  $session_basket = array();
  foreach($proructs_count as $key=>$value){
   for($i=0;$i<$value;$i++){
    $session_basket[] = $key;
   }
  }
 }
 
 function sendOrder($data){
  $mail = new PHPMailer();
  $mail->CharSet = "windows-1251";
  $mail->From = (strlen($data['order_email'])>0) ? $data['order_email'] : "shopextremstyle2@gmail.com";
  $mail->FromName = $data['order_name'];
  $mail->AddAddress("shop@eltrade.com.ua","shop");
  $mail->Subject = "Îôîðìèòü çàêàç ñ ÝêñòðèìÑòèëü";
  $title = Mail::str_rus("Îôîðìèòü çàêàç");
  $msg = "";
  foreach($data['product_id'] as $key=>$value){
   $msg .= "ID: ".$value." ";
   $msg .= "Íàçâàíèå: <b>".$data['product_name'][$key]."</b> ";
   $msg .= "Öåíà çà îäèí: ".$data['product_cine'][$key]." ";
   $msg .= "Êîëè÷åñòâî: ".$data['product_count'][$key]." ";
   $msg .= "Çà âåñü òîâàð: ".$data['product_cine_all'][$key]." ";
   $msg .= "<br>";
  }
   $msg .= "Îáùàÿ ñóìà: ".$data['cineAll'];
   $msg .= "<br>";
 /*  $msg .= "Ñêèäêà: ".$data['discount']." %";
   $msg .= "<br>";    */
   $msg .= "Èòîãî ê îïëàòå: ".$data['cineAll_discount'];
   $msg .= "<br><br><br>";
   $msg .= "Êîíòàêòíûå äàííûå:";
   $msg .= "<br>";
   $msg .= "Èìÿ: ".$data['order_name'];
   $msg .= "<br>";
   $msg .= "Àäðåñ: ".$data['order_adress'];
   $msg .= "<br>";
   $msg .= "E-mail: ".$data['order_email'];
   $msg .= "<br>";
   $msg .= "Êîíòàêòíûé òåëåôîí: ".$data['order_phone'];
//   $msg .= "<br>";
//   $msg .= "Ìîáèëüíûé òåëåôîí: ".$data['order_phonemob'];
   $msg .= "<br>";
   $msg .= "Êîììåíòàðèé: ".$data['order_comment'];
//   $order_email = (strlen($data['order_email'])>0) ? $data['order_email'] : "vapila@vapila.kiev.ua";
//   Mail::send("borisenko.pavel@gmail.com",$data['order_email'],$title,Mail::str_rus($msg));
  $mail->MsgHTML($msg);
  if(!$mail->Send()){echo "There has been a mail error sending to <br>";return false;}
  $mail->ClearAddresses();
  $mail->ClearAttachments();
  
  $this->sendOrderXML($data);
 }
 
 
 function sendOrderXML($data){



$data['order_phone'] = str_replace("-","",$data['order_phone']);
$data['order_phone'] = str_replace(")","",$data['order_phone']);
$data['order_phone'] = str_replace("(","",$data['order_phone']);
$data['order_phone'] = str_replace(" ","",$data['order_phone']);
$data['order_phone'] = "+38".$data['order_phone'];



  $mail = new PHPMailer();
  $mail->CharSet = "windows-1251";
  $mail->From = (strlen($data['order_email'])>0) ? $data['order_email'] : "shopextremstyle2@gmail.com";
  $mail->FromName = $data['order_name'];
  $mail->AddAddress("extremshop@portal.myoffice.biz.ua","extremshop");
  $mail->Subject = "xml çàêàç ñ ÝêñòðèìÑòèëü";
  $order_email = (strlen($data['order_email'])>0) ? $data['order_email'] : "shopextremstyle2@gmail.com";
  $xml = '<?xml version="1.0" encoding="windows-1251" ?>';
  $xml .= '<Order orderNum="'.mktime().'">';
  foreach($data['product_id'] as $key=>$value){
   $xml .= "<OrderItem ID='".$data['product_code'][$key]."'>";
   $xml .= "<ProductName>".$data['product_name2'][$key]."</ProductName>";
   $xml .= "<Size>".$data['product_size'][$key]."</Size>";
   $xml .= "<Color>".$data['product_color'][$key]."</Color>";
   $xml .= "<Price>".$data['product_price'][$key]."</Price>";
   $xml .= "<Count>".$data['product_count'][$key]."</Count>";
   $xml .= "</OrderItem>";
  }
   $xml .= '<CustomerInfo>';
   $xml .= '<Name>'.$data['order_name'].'</Name>';
   $xml .= '<Mobile>'.$data['order_phone'].'</Mobile>';
   $xml .= '<Email>'.$data['order_email'].'</Email>';
   $xml .= '</CustomerInfo>';
   $xml .= '<DeliveryInfo>';
   $xml .= '<City>Óêðàèíà</City>';
   $xml .= '<Address>'.$data['order_adress'].'</Address>';
   $xml .= '<DeliveryType>Äîñòàâêà</DeliveryType>';
   $xml .= '</DeliveryInfo>';
   $xml .= '<Comment>'.$data['order_comment'].'</Comment>';
   $xml .= '</Order>';
  $tmpfname = tempnam("tmp", "FOO");
  $handle = fopen($tmpfname, "w");
   fwrite($handle, $xml);
   $mail->AddAttachment($tmpfname, 'order.xml');
  if(!$mail->Send()){echo "There has been a mail error sending to <br>";return false;}
   fclose($handle);
   unlink($tmpfname);
  $mail->ClearAddresses();
  $mail->ClearAttachments();
 // Mail::send("borisenko.pavel@gmail.com",$order_email,"Order",Mail::str_rus($xml));
   // Mail::send("andrey.belyy@gmail.com",$order_email,"Order",Mail::str_rus($xml));
 }
 
 function saveOrder($data,$userID = 0){
 
  $table_name = "catalogs_orders";
  
  if(isset($data['update_id']) && $data['update_id']>0){
      $DB_AUTOQUERY = DB_AUTOQUERY_UPDATE;
      $id = $data['update_id']; 
      $where = sprintf("id='%d'",$id);
  } else {
    $DB_AUTOQUERY = DB_AUTOQUERY_INSERT;
    $id = $this->db->nextId('mySequence_'.$table_name);
    $where = null;
  }




    $fields_values = array(
        'id'=>$id,
        'user_id'=>$userID,
        'name' => $data['order_name'],
        'email' => $data['order_email'],
        'adress' => $data['order_adress'],
        //'phone' => phone_mobil($data['order_phone']),
	'phone' => $data['order_phone'],
        'comment' => $data['order_comment'],
        'delivery' => $data['delivery'],
        'total'=>$_SESSION['cart']['total'], 
        'status' => '1',
        'mktime'=>mktime()
    );
    $DB_AUTOQUERY;
 
    $this->db->autoExecute($table_name,$fields_values,$DB_AUTOQUERY,$where);

  if(isset($data['product_id'])){ $i=-1;
   foreach($data['product_id'] as $key=>$value){ $i++;
    $this->db->autoExecute("catalogs_orders_products",array(
    'order_id'=>$id,
    'product_id'=>$value,
    'product_cine_id'=>$_SESSION['cart'][$i]['price'],
    'count'=>$data['product_count'][$key])
    ,DB_AUTOQUERY_INSERT);
   }
  }
  
  
 }
 
 function deleteOrder($id){
  $this->db->query("delete from catalogs_orders where id=?",array($id));
  $this->db->query("delete from catalogs_orders_products where order_id=?",array($id));
 }
 
 function updateOrder($data){
  $table_name = "catalogs_orders";
  $fields_values = array('name' => $data['order_name'],'email' => $data['order_email'],'adress' => $data['order_adress'],'phone' => $data['order_phone'],'comment' => $data['order_comment'],'mktime'=>mktime());
  if(isset($data['order_active']))$fields_values['active'] = 1;
  else $fields_values['active'] = 0;
  $this->db->autoExecute($table_name,$fields_values,DB_AUTOQUERY_UPDATE,sprintf("id='%d'",$data['update_id']));
 }
 
 function updateOrderProducts($data){
   foreach($data['product_id'] as $key=>$value){
    if($data['product_count'][$value]<1){$this->db->query("delete from catalogs_orders_products where order_id='{$data['order_id']}' AND product_id='$value'");}
    else{$this->db->autoExecute("catalogs_orders_products",array('count'=>$data['product_count'][$value]),DB_AUTOQUERY_UPDATE,"order_id='{$data['order_id']}' AND product_id='$value'");}
   }
 }
 
 function viewOrder($id){
  $row = $this->db->getRow("select * from catalogs_orders where id=?",array($id),DB_FETCHMODE_ASSOC);
  $this->tpl->assign('order', $row);
 }
 
 function viewOrderProducts($order_id){
  $res = $this->db->getAll("select p.*,op.*,pr.name,pr.pic,pr.pic_big from catalogs_orders_products op Left join catalogs_products_cine p On p.id=op.product_id Left join catalogs_products pr On pr.id=p.product_id where order_id=?",array($order_id),DB_FETCHMODE_ASSOC);
   $sum = 0;
   foreach($res as $key=>$row){
    $sum = $sum + ($row['cine']*$row['count']);
    $res[$key]['cine_all'] = ($row['cine']*$row['count']);
   }
  $discount = $this->db->getOne('select catalogs_users.discount from catalogs_orders Left join catalogs_users on catalogs_users.id=user_id where catalogs_orders.id=?',array($order_id));
  $this->tpl->assign('cine', array('sum'=>$sum,'discount'=>$discount,'sum_discount'=>($sum - (($sum*$discount)/100)) ));
  $this->tpl->assign('basket_products', $res);
 }
 
 function viewOrders($params = array()){
  $search = array();
  if(isset($params['userID']) && $params['userID']>0)$search[] = sprintf("catalogs_orders.user_id='%d'",$params['userID']);
  $sql = "select catalogs_orders.*,catalogs_users.login as user_login,catalogs_users.discount from catalogs_orders Left join catalogs_users on catalogs_users.id=user_id WHERE 1=1 ";
  if(count($search))$sql .= "AND " . implode(" AND ",$search) . " ";
  $sql .= " order by mktime desc";
  $pagerOptions = Array(
    'mode' => 'Sliding',
    'delta' => 16,
    'perPage' => 50,
    'linkClass'=>"link_class",
    'curPageLinkClassName'=>"link_class_active",
    'spacesBeforeSeparator' => 1,
    'spacesAfterSeparator' => 1
  );
  $res = Pager_Wrapper_DB($this->db, $sql, $pagerOptions, false, DB_FETCHMODE_ASSOC, array());
  foreach($res['data'] as $key=>$value){
   $res['data'][$key]['sum'] = $this->getOrderProductsSum($value['id']);
   $res['data'][$key]['sum_discount'] = $res['data'][$key]['sum'] - (($res['data'][$key]['sum']*$value['discount'])/100);
  }
  $this->tpl->assign('ordersData', $res);
 }
 
 function getOrderProductsSum($order_id){
   $res = $this->db->getAll("select op.*,p.cine from catalogs_orders_products op Left join catalogs_products_cine p On p.id=op.product_id where op.order_id=?",array($order_id),DB_FETCHMODE_ASSOC);
  // print_r($res);
   $sum = 0;
   foreach($res as $row){
    $sum = $sum + ($row['cine']*$row['count']);
   }
   return $sum;
 }
 
 function SaveBrend($data,$upload){
  $table_name = "catalogs_brends";
  $DB_AUTOQUERY = ($data['update_id']>0) ? DB_AUTOQUERY_UPDATE : DB_AUTOQUERY_INSERT;
  $fields_values = array('rubric_id'=>$data['rubric_id'],'name'=>$data['brend'],'text'=>$data['text'],'youtube'=>$data['youtube'],'seo'=>$data['seo'],'sort'=>$data['sort'],'meta_title'=>$data['meta_title'],'meta_description'=>$data['meta_description'],'meta_keywords'=>$data['meta_keywords'],'active'=>$data['active'] ,'about'=>$data['about'],'link'=>$data['link'],'teh'=>$data['teh']);

  if(isset($data['delete_video']) && $data['delete_video']==1){
   $this->deleteBrendPic($data['update_id']);
   $fields_values['pic'] = null;
  }
  if($upload['pic']['tmp_name']){
   if($data['update_id']>0)$this->deleteBrendPic($data['update_id'],array('pic'));
   $name_pic = mktime() . "." . substr(strrchr($_FILES['pic']['name'],"."),1);
   $file_name = "{$_SERVER['DOCUMENT_ROOT']}/uploaded/pic/catalogs/brends/$name_pic";
   move_uploaded_file($_FILES["pic"]["tmp_name"], $file_name);
   chmod($file_name,"0777");
   $fields_values['pic'] = $name_pic;
  }

  if(isset($data['delete_pic_s']) && $data['delete_pic_s']==1){
   $this->deleteBrendPic($data['update_id'],array('pic_s'));
   $fields_values['pic_s'] = null;
  }
  if($upload['pic_s']['tmp_name']){
   if($data['update_id']>0)$this->deleteBrendPic($data['update_id'],array('pic_s'));
   $name_pic = mktime() . "." . substr(strrchr($_FILES['pic_s']['name'],"."),1);
   $file_name = "{$_SERVER['DOCUMENT_ROOT']}/uploaded/pic/catalogs/brends/s/$name_pic";
   move_uploaded_file($_FILES["pic_s"]["tmp_name"], $file_name);
   chmod($file_name,"0777");
   $fields_values['pic_s'] = $name_pic;
  }


  $this->db->autoExecute($table_name,$fields_values,$DB_AUTOQUERY,"id={$data['update_id']}");
 }
 
 function deleteBrendPic($id,$pics = array('pic','pic_s')){
  $sql = "select " . implode(',',$pics) . " from catalogs_brends where id=?";
  $row = $this->db->getRow($sql,array($id),DB_FETCHMODE_ASSOC);
  if(isset($row['pic'])){
   $file_name = "{$_SERVER['DOCUMENT_ROOT']}/uploaded/pic/catalogs/brends/{$row['pic']}";
   @unlink($file_name);
  }
  if(isset($row['pic_s'])){
   $file_name = "{$_SERVER['DOCUMENT_ROOT']}/uploaded/pic/catalogs/brends/s/{$row['pic_s']}";
   @unlink($file_name);
  }
 }

 function viewBrends($type = false){
  $sql = "select b.*,r.name as rubric from catalogs_brends b left join catalogs_rubrics r On r.id=b.rubric_id ";
  if($type!=false)$sql .= "where b.type='$type'";
  $sql .= " Order by b.name Asc";
  $row = $this->db->getAll($sql,array(),DB_FETCHMODE_ASSOC);
  $this->tpl->assign('brends',$row);
 }
 
 function viewBrendsGroup($params = array()){
  $sql = "select * from catalogs_brends  where 1=1 ";
  if(isset($params['rubID'])){
   $rubric_id = $params['rubID'];//$this->getRubricParent($params['rubID']);
   $rubric_id = ($rubric_id==0)?$params['rubID']:$rubric_id;
   $sql .= "and rubric_id='".$rubric_id."'";
  }
  $sql .= " Group by name Order by sort Asc";
  $row = $this->db->getAll($sql,array(),DB_FETCHMODE_ASSOC);
  $this->tpl->assign('brends',$row);
 }
 
 function viewBrendsActive(){
  $sql = "select * from catalogs_brends where active=1 ";
  $sql .= " Order by sort Asc";
  $row = $this->db->getAll($sql,array(),DB_FETCHMODE_ASSOC);
  $this->tpl->assign('brends_a',$row);
 }
 
 function SaveCity($data){
  $table_name = "catalogs_cities";
  $DB_AUTOQUERY = (isset($data['update_id']) && $data['update_id']>0) ? DB_AUTOQUERY_UPDATE : DB_AUTOQUERY_INSERT;
  $fields_values = array('name'=>$data['name']);
  $this->db->autoExecute($table_name,$fields_values,$DB_AUTOQUERY,"id={$data['update_id']}");
  return mysql_insert_id();
 }
 
 function is_city($name){
  return $this->db->getOne('select id from catalogs_cities where name=?',array($name));
 }
 
 function viewCityMod($code){
  $sql = "select c.name from catalogs_keys_products_cities k left join catalogs_cities c on c.id=k.city_id where k.mod_code=? and k.count>0";
  $row = $this->db->getCol($sql,"name",array($code));
  if(!count($row))return "";
  foreach($row as $key=>$value){if($value=="Èíòåðíåò ìàãàçèí" or $value=="Êèåâ(Îëèìïèéñêèé)")unset($row[$key]);}
  return implode(', ',$row);
 }
 
 function viewCitiesProductID($id){
  $sql = "select city_id from catalogs_keys_products_cities where product_id=?";
  $row = $this->db->getCol($sql,"city_id",array($id));
  $this->tpl->assign('product_cities',$row);
 }
 
 function viewCities($type = false){
  $sql = "select * from catalogs_cities ";
  $sql .= " Order by name Asc";
  $row = $this->db->getAll($sql,array(),DB_FETCHMODE_ASSOC);
  $this->tpl->assign('cities',$row);
 }
 
 function viewCitiesProduct($id){
  $sql = "select catalogs_cities.* from catalogs_keys_products_cities left join catalogs_cities on catalogs_cities.id=catalogs_keys_products_cities.city_id Where catalogs_keys_products_cities.product_id=? ";
  $row = $this->db->getAll($sql,array($id),DB_FETCHMODE_ASSOC);
  $this->tpl->assign('cities',$row);
 }
 
 function viewCity($id){
  $row = $this->db->getRow("select * from catalogs_cities where id=?",array($id),DB_FETCHMODE_ASSOC);
  $this->tpl->assign('city', $row);
 }
 
 function deleteCity($id){
  $this->db->query("delete from catalogs_cities where id=?",array($id));
  $this->delete_keysCitiesProduct($id);
 }
 
 function delete_keysCitiesProduct($id){
  $sql = "delete from catalogs_keys_products_cities where city_id=?";
  $this->db->query($sql,array($id));
 }
 
 function SaveYears($data){
  $table_name = "catalogs_years";
  foreach($data['filter'] as $key=>$name){
   if(strlen($name)>0){
     if(isset($data['update_id'][$key]) && $data['update_id'][$key]>0){$DB_AUTOQUERY = DB_AUTOQUERY_UPDATE;$where = "id='{$data['update_id'][$key]}'";}
     else{$DB_AUTOQUERY = DB_AUTOQUERY_INSERT;$where = "";}
    $this->db->autoExecute($table_name,array('name'=>$name,'rubric_id'=>$data['rubric_id']),$DB_AUTOQUERY,$where);
   }
  }
 }
 
 function viewYearsProductID($id){
  $sql = "select year_id from catalogs_keys_products_years where product_id=?";
  $row = $this->db->getCol($sql,"year_id",array($id));
  $this->tpl->assign('product_years',$row);
 }

 function viewYears($rubric_id){
  $row = $this->db->getAll("select * from catalogs_years where rubric_id=? order by name",array($rubric_id),DB_FETCHMODE_ASSOC);
  $this->tpl->assign('years', $row);
 }
 
 function getYearsName_IDs($ids){
  //$sql = "select name from catalogs_years where id in (".implode(",",$ids).") order by name";
  //$row = $this->db->getCol($sql,"name",array());
  //return implode(", ",$row);
  
  $name = array();
  foreach($ids as $id){
   $name[] = $this->db->getOne("select name from catalogs_years where id=?",array($id));
  }
  return implode(", ",$name);
 }
 
 function deleteYearsRubric_id($id){
  $this->db->query("delete from catalogs_years where rubric_id=?",array($id));
  $this->delete_keysYearsRubric($id);
 }
 
 function delete_keysYearsRubric($id){
  $sql = "delete from catalogs_keys_products_years where rubric_id=?";
  $this->db->query($sql,array($id));
 }
 
 function deleteYear($id){
  $this->db->query("delete from catalogs_years where id=?",array($id));
  $this->delete_keysYearsProduct($id);
 }
 
 function delete_keysYearsProduct($id){
  $sql = "delete from catalogs_keys_products_years where year_id=?";
  $this->db->query($sql,array($id));
 }
 
 function SaveFilters($data){
  $table_name = "catalogs_filters";
  foreach($data['filter'] as $key=>$name){
   if(strlen($name)>0){
     if(isset($data['update_id'][$key]) && $data['update_id'][$key]>0){$DB_AUTOQUERY = DB_AUTOQUERY_UPDATE;$where = "id='{$data['update_id'][$key]}'";}
     else{$DB_AUTOQUERY = DB_AUTOQUERY_INSERT;$where = "";}
     $active = (isset($data['active'][$key])) ? 1 : 0;
    $this->db->autoExecute($table_name,array('name'=>$name,'prefix'=>encodestring($name),'rubric_id'=>$data['rubric_id'],"sort"=>$data['sort'][$key],"active"=>$active),$DB_AUTOQUERY,$where);
   }
  }
 }

 function viewFilterProductID($id){
  $sql = "select filter_id from catalogs_keys_products_filters where product_id=?";
  $row = $this->db->getCol($sql,"filter_id",array($id));
  $this->tpl->assign('product_filters',$row);
 }
 
 function deleteFilter($id){
  $this->db->query("delete from catalogs_filters where id=?",array($id));
  $this->delete_keysFilterProduct($id);
 }
 
 function deleteFiltersRubric_id($rubric_id){
  $this->db->query("delete from catalogs_filters where rubric_id=?",array($rubric_id));
  $this->delete_keysFilterRubric($rubric_id);
 }
 
 function delete_keysFilterProduct($id){
  $sql = "delete from catalogs_keys_products_filters where filter_id=?";
  $this->db->query($sql,array($id));
 }
 
 function delete_keysFilterRubric($id){
  $sql = "delete from catalogs_keys_products_filters where rubric_id=?";
  $this->db->query($sql,array($id));
 }
 
 function viewFilters($rubric_id){
  $row = $this->db->getAll("select * from catalogs_filters where active='0' and rubric_id=? order by sort",array($rubric_id),DB_FETCHMODE_ASSOC);
  $this->tpl->assign('filters', $row);
 }
 
 function getFiltersName_IDs($ids){
  //$sql = "select name from catalogs_filters where id in (".implode(",",$ids).")";
  //$row = $this->db->getCol($sql,"name",array());
  $name = array();
  foreach($ids as $id){
   $name[] = $this->db->getOne("select name from catalogs_filters where id=?",array($id));
  }
  return implode(", ",$name);
 }
 
 function viewBrend($id){
  $row = $this->db->getRow("select * from catalogs_brends where id=?",array($id),DB_FETCHMODE_ASSOC);
  $this->tpl->assign('brend', $row);
 }
 
 function viewBrendName($name){
  $name = iconv("utf-8", "windows-1251", $name);
  $sql = "select * from catalogs_brends where name=? and active=1 limit 1";
  $row = $this->db->getRow($sql,array($name),DB_FETCHMODE_ASSOC);
  $this->tpl->assign('brend_seo', $row);
  return $row;
 }
 
 function getBrendIDs_name($name){
  //$name = iconv("utf-8", "windows-1251", $name);
  $sql = "select id from catalogs_brends where name=?";
  return $this->db->getCol($sql,"id",array($name));
 }
 
 function deleteBrend($id){
  $this->db->query("delete from catalogs_brends where id=?",array($id));
 }
 
 function viewAkciiProductID($id){
  $sql = "select rubric_id from catalogs_keys_products_akcii where product_id=?";
  $row = $this->db->getCol($sql,"rubric_id",array($id));
  $this->tpl->assign('product_akcii',$row);
 }
 
 function import_saveRubric($name,$parent_id){
  $id = $this->db->getOne("select id from catalogs_rubrics where name=? and parent_id=?",array($name,$parent_id));
  if( !$id ){
   $this->db->autoExecute("catalogs_rubrics",array('name'=>$name,'parent_id' => $parent_id,"level"=>($this->getLevelRubric($parent_id)+1)),DB_AUTOQUERY_INSERT);
   return mysql_insert_id();
  }
  return $id;
 }
 
 function import_saveBrend($name,$rubric_id){
  //getRubricParent();
  $id = $this->db->getOne("select id from catalogs_brends where name=? and rubric_id=?",array($name,$rubric_id));
  if( !$id ){
   $this->db->autoExecute("catalogs_brends",array('rubric_id'=>$rubric_id,'name'=>$name),DB_AUTOQUERY_INSERT);
   return mysql_insert_id();
  }
  return $id;
 }
 
 function import_saveFilters($rubric_id,$str){
  if(!$str)return array();
  $row_str = explode(",",trim($str));
  $arr_id = array();
  foreach($row_str as $str){
   $name = trim($str);
   $name_r = explode('=',$name);$name = $name_r[0];  $active = (isset($name_r[1])) ? 1 : 0;
   $id = $this->db->getOne("select id from catalogs_filters where rubric_id=? and name=?",array($rubric_id,$name));
   if( !$id ){
    $this->db->autoExecute("catalogs_filters",array('rubric_id'=>$rubric_id,'name'=>$name,'prefix'=>encodestring($name),'active'=>$active),DB_AUTOQUERY_INSERT);
    $id = mysql_insert_id();
   }else{ $this->db->autoExecute("catalogs_filters",array('rubric_id'=>$rubric_id,'name'=>$name,'prefix'=>encodestring($name),'active'=>$active),DB_AUTOQUERY_UPDATE,"id=$id");}
   $arr_id[] = $id;
  }
  return $arr_id;
 }
 
 function import_saveYear($rubric_id,$name){
  $id = $this->db->getOne("select id from catalogs_years where rubric_id=? and name=?",array($rubric_id,$name));
  if( !$id ){
   $this->db->autoExecute("catalogs_years",array('rubric_id'=>$rubric_id,'name'=>$name),DB_AUTOQUERY_INSERT);
   $id = mysql_insert_id();
  }
  return ($id)?array($id):array();
 }
 
 function import_updateProductCine($product_id,$row,$line='',$mktime = 0){  // print"<pre>";print_r($row);print"</pre>";

  IF($product_id>0){
  IF($row[3]>0){
   if($row[2]<1){$cine=$row[1];$cine_last=0;}
   else {$cine=$row[2];$cine_last=(($row[1]>0)?$row[1]:$row[2]);}
   $this->db->autoExecute("catalogs_products",array('cine'=>$cine,'cine_last'=>$cine_last),DB_AUTOQUERY_UPDATE,"id='$product_id'");
  }


  $city = trim($row[4]);
  if(!$city)$city = "Èíòåðíåò ìàãàçèí";
  //echo "OK(1) - <br/>";
  if(strlen($city)>0){    //print $city;
   $city_id = $this->is_city($city);
   //echo "OK(2) - <br/>";
   if(!$city_id){$city_id = $this->SaveCity(array('name'=>$city));}
     $this->db->query("delete from catalogs_keys_products_cities where product_id=? and mod_code=? and mktime<?", array($product_id,$row[0],$mktime));

     if($row[3]==0){

     }
     else{
   //  $this->db->query("delete from catalogs_keys_products_cities where product_id=? and mod_code=? and mktime<?", array($product_id,$row[0],$mktime));
   //echo "OK(3) - <br/>";
     if($this->getKeysModificationCity($row[0], $city_id)){$DB_AUTOQUERY = DB_AUTOQUERY_UPDATE;$where = "mod_code='".$row[0]."' and city_id='".$city_id."'";}
     else{$DB_AUTOQUERY = DB_AUTOQUERY_INSERT;$where = null;}

    // if($this->getKeysModificationCityMktime_count($row[0], $city_id, $mktime)>0){$row[3]=1;}
     //print $city_id .'--'.$where."<br>";
     $fields = array('count'=>$row[3],'product_id'=>$product_id,'mod_code'=>$row[0],'city_id'=>$city_id,'mktime'=>$mktime);
     $s = $this->db->autoExecute("catalogs_keys_products_cities",$fields,$DB_AUTOQUERY,$where);
     if (PEAR::isError($s)) die($s->getMessage());
  }}
  //echo "OK(4) - <br/>";
  $active = $this->db->getOne("select count(*) from catalogs_keys_products_cities where mod_code=? and count>0",array($row[0]));
  //$active = true;
  if($this->db->getOne("select count(*) from catalogs_modifications where code=?",array($row[0]))>0){
   $this->db->autoExecute("catalogs_modifications",array('active'=>$active,'is_update'=>1,'prefix'=>$row[4]),DB_AUTOQUERY_UPDATE,"code='".$row[0]."'");
   //echo "OK(5) - <br/>";
  }else{
	  //echo "OK(6) - <br/>";
   $this->saveCsvMod($line);
  }
  }
 }
 
 function saveCsvMod($line){
	 echo "OK1 - <br/>";
  $tmpfname = $_SERVER['DOCUMENT_ROOT'] . "/tmp/noDB_mod.csv";
  $handle = @fopen($tmpfname, "a");
//  $row = explode(";",$line);
//  File_FGetCSV::fputcsv($handle,$row,';');
	 echo "OK2 - <br/>";
	echo $line;
	 echo "OK3 - <br/>";
  fwrite($handle,$line);
  fclose($handle);
 }
 
 function getKeysModificationCity($code, $city_id){
  return $this->db->getOne("select count(*) from catalogs_keys_products_cities where mod_code=? and city_id=?", array($code, $city_id));
 }
 
 function getKeysModificationCity_count($code, $city_id){
  return $this->db->getOne("select count from catalogs_keys_products_cities where mod_code=? and city_id=?", array($code, $city_id));
 }
 
 function getKeysModificationCityMktime_count($code, $city_id, $mktime){
  $r = $this->db->getOne("select count from catalogs_keys_products_cities where mod_code=? and city_id=? and mktime=?", array($code, $city_id, $mktime));
 return $r;
 }
 
 function getProductID($name){
  $id = $this->db->getOne("select id from catalogs_products where name=?",array($name));
  return $id;
 }
 
 function getProductID_R($name,$rubric_parent_id){
  $id = $this->db->getOne("select id from catalogs_products where name=? and rubric_id=?",array($name,$rubric_parent_id));
  return $id;
 }
 
 function getModificationActive($code){
  return $this->db->getOne("select active from catalogs_modifications where code=?",array($code));
 }
 
 function updateProduct_countModification($product_id,$count){
  $this->db->autoExecute("catalogs_products",array('count_modifications'=>$count),DB_AUTOQUERY_UPDATE,"id='$product_id'");
 }
 
 function updateProductModificationCountPrefix($product_id,$prefix = "+"){
// print $product_id;
 $sql = "UPDATE catalogs_products SET count_modifications = count_modifications $prefix 1 WHERE id =?";
  $this->db->query($sql,array($product_id));
 }
 
 function exportCSV(){
  $tmpfname = "tmp/price.csv";
  $handle = fopen($tmpfname, "w");
  // fwrite($handle, $xml);
  $res = $this->db->getAll('select p.id,p.rubric_id,r2.name,r.name,b.name as brend,p.name,p.about,p.text,null,p.sex,null,p.cine,p.cine_last,p.akcii_id,p.strnumber,p.active,null,p.video_code,p.pic_big from catalogs_products p left join catalogs_rubrics r on r.id=p.rubric_id left join catalogs_rubrics r2 on r2.id=p.rubric_parent_id left join catalogs_brends b on b.id=p.brend_id',array());
  foreach($res as $key=>$row){
   $list = $row;
   $mod_res = $this->db->getAll('select code,size,color,pic_big,active from catalogs_modifications where product_id=?',array($row[0]));
   foreach($mod_res as $mod_row){$list[] = implode('=',$mod_row);}

   $f_row = $this->db->getCol("select f.name from catalogs_keys_products_filters k Left Join catalogs_filters f ON f.id=k.filter_id where k.product_id=?",'name',array($list[0]));
   $list[8]=implode(',',$f_row);

   switch($list[9]){
    case 1 : $list[9] = 'ìóæñêîé'; break;
    case 2 : $list[9] = 'æåíñêèé'; break;
    case 3 : $list[9] = 'äåòñêèé'; break;
    case 4 : $list[9] = 'óíèñåêñ'; break;
    default : $list[9] = 'ìóæñêîé'; break;
   }
   
   $y_row = $this->db->getCol("select y.name from catalogs_keys_products_years k Left Join catalogs_years y ON y.id=k.year_id where k.product_id=?",'name',array($list[0]));
   $list[10]=implode(',',$y_row);
   

   //print_r($list);exit;
   $p_res = $this->db->getAll("select name,size,metka from catalogs_products_params where product_id=?",array($list[0]));
   $param = array();
   foreach($p_res as $row_p){
    $param[] = implode('*',$row_p);
   }
   $list[15] = implode('=',$param);

   unset($list[0]);unset($list[1]);
   
   File_FGetCSV::fputcsv($handle,$list,';');



  }

     fclose($handle);

   $params = array(
      'file'                => $tmpfname,
      'contenttype'         => 'application/xls',
      'contentdisposition'  => array(HTTP_DOWNLOAD_ATTACHMENT, 'price.csv'),
      'cache'               => false
      );
      $error = HTTP_Download::staticSend($params, false); //îòäà¸ì ôàéë
      if ($error === true) {
           //åñëè ôàéë çàãðóæåí óñïåøíî, îáíîâëÿåì äàòó ïîñëåäíåé çàêà÷êè
      }
     
     unlink($tmpfname);
 }
 
 function exportModCSV(){
  $tmpfname = "tmp/price_mod.csv";
  $handle = fopen($tmpfname, "w");
  $res = $this->db->getAll('select m.code,p.cine,p.cine_last,m.active,null,m.prefix,m.is_update From catalogs_modifications m Left join catalogs_products p on p.id=m.product_id');
  foreach($res as $key=>$row){
   File_FGetCSV::fputcsv($handle,$row,';');
  }
  fclose($handle);
   $params = array(
      'file'                => $tmpfname,
      'contenttype'         => 'application/xls',
      'contentdisposition'  => array(HTTP_DOWNLOAD_ATTACHMENT, 'file_1.csv'),
      'cache'               => false
      );
      $error = HTTP_Download::staticSend($params, false); //îòäà¸ì ôàéë
      if ($error === true) {
           //åñëè ôàéë çàãðóæåí óñïåøíî, îáíîâëÿåì äàòó ïîñëåäíåé çàêà÷êè
      }

     unlink($tmpfname);
     $this->db->autoExecute("catalogs_modifications",array('is_update'=>0),DB_AUTOQUERY_UPDATE);
 }
 
 function exportOrdersCSV(){
  $tmpfname = "tmp/orders.csv";
  $handle = fopen($tmpfname, "w");
  $res = $this->db->getAll('select name,email,adress,phone From catalogs_orders order by id desc');
  foreach($res as $key=>$row){
   File_FGetCSV::fputcsv($handle,$row,';');
  }
  fclose($handle);
   $params = array(
      'file'                => $tmpfname,
      'contenttype'         => 'application/xls',
      'contentdisposition'  => array(HTTP_DOWNLOAD_ATTACHMENT, 'orders.csv'),
      'cache'               => false
      );
      $error = HTTP_Download::staticSend($params, false); //îòäà¸ì ôàéë
      if ($error === true) {
           //åñëè ôàéë çàãðóæåí óñïåøíî, îáíîâëÿåì äàòó ïîñëåäíåé çàêà÷êè
      }

     unlink($tmpfname);
 }
 
 function deleteProductParams($product_id){
  $sql = "delete from catalogs_products_params where product_id=?";
  $this->db->query($sql,array($product_id));
 }
 
 function saveProductParams($product_id,$pruduct_params){
  $this->deleteProductParams($product_id);
  $array_params = explode("=",$pruduct_params);
  foreach($array_params as $row){
   $arr = explode('*',$row);
   $this->db->autoExecute("catalogs_products_params",array('product_id'=>$product_id,'name'=>$arr[0],'size'=>$arr[1],'metka'=>$arr[2]),DB_AUTOQUERY_INSERT);
  }
 }
 
 function getProductParams($product_id){
  $sql = "select * from catalogs_products_params where product_id=? order by id";
  $row = $this->db->getAll($sql,array($product_id),DB_FETCHMODE_ASSOC);
  return $row;
 }

 function viewProductParams($product_id){
  $this->tpl->assign('params',$this->getProductParams($product_id));
 }
 
 function saveTmpProduct($row,$product_id){
  if($product_id>0){
   $this->db->autoExecute("catalogs_tmp_products",array('name'=>$row[3],'product_id'=>$product_id),DB_AUTOQUERY_INSERT);
   }
 }
 
 function clearTmpProduct(){
  $sql = "TRUNCATE TABLE catalogs_tmp_products";
  $this->db->query($sql,array());
 }
 
 function viewTmpProducts(){
  $sql = "SELECT count( name ) AS cn, name
FROM catalogs_tmp_products
GROUP BY name
ORDER BY name";
  $row = $this->db->getAll($sql,array(),DB_FETCHMODE_ASSOC);
  $this->tpl->assign('list',$row);
  $this->tpl->assign('list_total',$this->db->getOne("select count(*) from catalogs_tmp_products"));
 }
 
 function importCSV($upload){   error_reporting(0);
  if($upload['file']['name']=="file_1.csv"){print"Îøèáêà! Ôàéë öåí!";exit;}
  //$arr_line = file($upload['file']['tmp_name']);
  $f = fopen($upload['file']['tmp_name'], "r") or die("Îøèáêà!");
 // print"<pre>";
 $this->clearTmpProduct();
 for ($i=0; $row_line=File_FGetCSV::fgetcsv($f,15000000,";"); $i++) {
 // foreach($arr_line as $line){
   //$row_line = fgetcsv(";",$line);
   $rubric_id = $this->import_saveRubric($row_line[0],0);
   $rubric_parent_id = $this->import_saveRubric($row_line[1],$rubric_id);
   $brend_id = $this->import_saveBrend($row_line[2],$rubric_parent_id);
   $pruduct_name = trim($row_line[3]);
   $pruduct_about = trim($row_line[4]);
   $pruduct_text = trim($row_line[5]);
   switch($row_line[7]){
    case 'ìóæñêîé' : $pruduct_sex = 1; break;
    case 'æåíñêèé' : $pruduct_sex = 2; break;
    case 'äåòñêèé' : $pruduct_sex = 3; break;
    case 'óíèñåêñ' : $pruduct_sex = 4; break;
    default : $pruduct_sex = 0; break;
   }
   $pruduct_date = trim($row_line[8]);
   $pruduct_cine = trim($row_line[9]);
   $pruduct_cine_last = trim($row_line[10]);
   if($pruduct_cine<1){$pruduct_cine=$pruduct_cine_last;$pruduct_cine_last=0;}
   $pruduct_akcii_id = trim($row_line[11]);
   $pruduct_strnumber = trim($row_line[12]);
   $pruduct_active = trim($row_line[13]);
   $pruduct_params = trim($row_line[14]);
   $pruduct_pic_tmp = trim($row_line[16]);
   $pruduct_video = trim($row_line[15]);
   $pruduct_update_id = $this->getProductID_R($pruduct_name,$rubric_parent_id);
   $upload_pruduct = (strlen($pruduct_pic_tmp)>0 && is_file("./uploaded/pic/catalogs/products/big/$pruduct_pic_tmp"))?array('pic'=>array('tmp_name'=>"./uploaded/pic/catalogs/products/big/$pruduct_pic_tmp",'name'=>$pruduct_pic_tmp,'big'=>true)):null;
   $product_id = $this->saveProduct(
                        array('rubric_id'=>$rubric_parent_id,
                              'rubric_parent_id'=>$rubric_parent_id,
                              'brend_id'=>$brend_id,
                              'name'=>$pruduct_name,
                              'about'=>$pruduct_about,
                              'text'=>$pruduct_text,
                              'video_code'=>$pruduct_video,
                              'sex'=>$pruduct_sex,
                              'date'=>$pruduct_date,
                              'cine'=>$pruduct_cine,
                              'cine_last'=>$pruduct_cine_last,
                              'akcii_id'=>$pruduct_akcii_id,
                              'strnumber'=>$pruduct_strnumber,
                              'active'=>$pruduct_active,
                              'meta_title'=>$pruduct_name,
                              'meta_description'=>$pruduct_name,
                              'meta_keywords'=>$pruduct_name,
                              'meta_about'=>$pruduct_name,
                              'filter'=>$this->import_saveFilters($rubric_parent_id,$row_line[6]),
                              'years'=>$this->import_saveYear($rubric_parent_id,$pruduct_date),
                              'akcii'=>array(),
                              'update_id'=>$pruduct_update_id),
                              $upload_pruduct
                        );
                        //print $pruduct_update_id;exit;
   $this->saveProductParams($product_id,$pruduct_params);
   $this->deleteProductModifications($product_id,true);
   $m_i = 0;
   for($i=17;$i<count($row_line);$i++){
    $arr_mod = trim($row_line[$i]);
    if(strlen($arr_mod)>0){
     $row_mod = explode("=",$arr_mod);
     $upload_mod = (strlen($row_mod[3])>0 && is_file("./uploaded/pic/catalogs/modifications/big/".$row_mod[3]))?array('pic'=>array('tmp_name'=>"./uploaded/pic/catalogs/modifications/big/".$row_mod[3],'name'=>$row_mod[3],'big'=>true)):null;

     $this->SaveModification(
            array('product_id'=>$product_id,
                  'code'=>$row_mod[0],
                  'size'=>$row_mod[1],
                  'color'=>$row_mod[2],
                  'active'=>$row_mod[4]
                  ),$upload_mod
            );
    if($row_mod[4]>0)$m_i++;
    }
   }
   $this->updateProduct_countModification($product_id,$m_i);
   //$this->import_saveFilters($product_id,$rubric_parent_id,$row_line[6]);
   //$strnumber = $this->getProductID($row_line[3]);   $this->save_keysProductsFilters($id,$data);
   //print_r($row_line);
   $this->saveTmpProduct($row_line,$product_id);
   if(($i%30)==0)sleep(1);
  }
 // print"</pre>";

 }
 
 function importCSV_cine($upload){
   if($upload['file']['name']!="file_1.csv"){print"Îøèáêà! Òîëüêî file_1.csv";exit;}
  $arr_line = file($upload['file']['tmp_name']);
  //print"<pre>";
  $i = 0;
  $mktime = mktime();
  foreach($arr_line as $line){
     $row_line = explode(";",$line);
     $this->import_updateProductCine($this->getModificationProduct_id($row_line[0]),$row_line,$line,$mktime);
     if(($i%30)==0)sleep(1);
     $i++;
   //  print_r($row_line);
  }//print"</pre>";

 // $this->updateCountModificationProducts();
 }
 
 function loadCSV_cine($upload){
  if($upload['file']['name']!="file_1.csv"){print"Îøèáêà! Òîëüêî file_1.csv";exit;}
  $file = $_SERVER['DOCUMENT_ROOT'] . "/cron/file_1.csv";
  //echo $file;
  //exit;
  move_uploaded_file($upload['file']['tmp_name'], $file);
 }
 
 function is_loadCSV_cine(){
  $file = $_SERVER['DOCUMENT_ROOT'] . "/cron/file_1.csv";
  $is = is_file($file);
  $this->tpl->assign('is',$is);
 }
 
 function CronImportCSV_cine($upload){
   if($upload['file']['name']!="file_1.csv"){print"Îøèáêà! Òîëüêî file_1.csv";exit;}
  $arr_line = file($upload['file']['tmp_name']);
  //print"<pre>";
  $i = 0;
  $mktime = mktime();
  foreach($arr_line as $line){
     $row_line = explode(";",$line);
     $this->import_updateProductCine($this->getModificationProduct_id($row_line[0]),$row_line,$line,$mktime);
     if(($i%30)==0)sleep(1);
     $i++;
   //  print_r($row_line);
  }//print"</pre>";
  //$this->updateCountModificationProducts();
 }
 
 function updateCountModificationProducts(){   // print"test";
// $this->db->autoExecute("catalogs_products",array('count_modifications'=>0),DB_AUTOQUERY_UPDATE);
 $res = $this->db->getAll("select * from catalogs_products",array(),DB_FETCHMODE_ASSOC);
 $i = 0;
 foreach($res as $row){
  $count = $this->db->getOne("select count(*) from catalogs_modifications where product_id=? and active>0",array($row['id']));
  $this->db->autoExecute("catalogs_products",array('count_modifications'=>$count),DB_AUTOQUERY_UPDATE,"id='".$row['id']."'");
   //  if(($i%10)==0)sleep(10);
     $i++;
 }
 }
 
 function config_update($id,$value){
  $this->db->autoExecute("catalogs_config",array('value'=>$value),DB_AUTOQUERY_UPDATE,"id='".$id."'");
 }
 
 function view_config_value($id){
  $r = $this->db->getOne("select value from catalogs_config where id=?",$id);
  $this->tpl->assign("config",$r);
  return $r;
 }

 function displayCatalogsCurs(){
  $this->tpl->assign("tpl",'catalogs_curs.tpl');
 }
 
 function displayCatalogs(){
  $this->tpl->assign("tpl",'catalogs.tpl');
 }
 
 function displayProducts(){
  $this->tpl->assign("tpl",'catalogs_products.tpl');
 }
 
 function displayProductsTops(){
  $this->tpl->assign("tpl",'catalogs_products_tops.tpl');
 }
 
 function displayProductsHits(){
  $this->tpl->assign("tpl",'catalogs_products_hits.tpl');
 }
 
 function displayProductsHitsAll(){
  $this->tpl->assign("tpl",'catalogs_products_hits_all.tpl');
 }

 function displayBasket($count_products,$cine_products,$cine_products_discount,$discount){
  $this->tpl->assign("count_products",$count_products);
  $this->tpl->assign("cine_products",$cine_products);
  $this->tpl->assign("cine_products_discount",$cine_products_discount);
  $this->tpl->assign("discount",$discount);
  $this->tpl->display('basket.tpl');
 }
 
 function displayProduct(){
  $this->tpl->assign("tpl",'catalogs_product.tpl');
 }
 
 function displayProductBasket(){
  $this->tpl->assign("tpl",'catalogs_basket.tpl');
 }
 
 function displayBrends(){
  $this->tpl->assign("tpl",'catalogs_brends.tpl');
 }
 
 function displayBrend(){
  $this->tpl->assign("tpl",'catalogs_brend.tpl');
 }
 
 function displayCities(){
  $this->tpl->assign("tpl",'catalogs_cities.tpl');
 }

 function displayProductBasketSend(){
  $this->tpl->assign("tpl",'catalogs_basket_send.tpl');
 }
 
 function displayReg(){
  $this->tpl->assign("tpl",'catalogs_reg.tpl');
 }
 
 function displayEditUser(){
  $this->tpl->assign("tpl",'catalogs_user_edit.tpl');
 }
 
 function displayNoPsw(){
  $this->tpl->assign("tpl",'catalogs_nopsw.tpl');
 }
 
 function displayOrders(){
  $this->tpl->assign("tpl",'catalogs_orders.tpl');
 }
 
 function displayOrder(){
  $this->tpl->assign("tpl",'catalogs_order.tpl');
 }
 
 function displayUsers(){
  $this->tpl->assign("tpl",'catalogs_users.tpl');
 }
 
 function displayUser(){
  $this->tpl->assign("tpl",'catalogs_user.tpl');
 }
 
 function displayFilters(){
  $this->tpl->assign("tpl",'catalogs_filters.tpl');
 }
 
 function displayYears(){
  $this->tpl->assign("tpl",'catalogs_years.tpl');
 }
 
 function displayWinProducts(){
  $this->tpl->display('catalogs_win_products.tpl');
 }
 
 function displayModifications(){
  $this->tpl->assign("tpl",'catalogs_modifications.tpl');
 }
 
 function displayImport(){
  $this->tpl->assign("tpl",'catalogs_import.tpl');
 }
 
 function displayImportCine(){
  $this->tpl->assign("tpl",'catalogs_import_cine.tpl');
 }
 
 function displayAkcii(){
  $this->tpl->assign("tpl",'catalogs_akcii.tpl');
 }
 
 function displayCompare(){
  $this->tpl->assign("tpl",'catalogs_compare.tpl');
 }
 
 function displayTmpProducts(){
  $this->tpl->assign("tpl",'catalogs_tmp_products.tpl');
 }
 
}
?>