Advertisement
Guest User

Untitled

a guest
Mar 27th, 2018
217
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 108.23 KB | None | 0 0
  1. <?php
  2. $servername = "localhost";
  3. $username = "algolhos_unisitc";
  4. $password = "Un1s1t_commerce";
  5. $dbname = "algolhos_unisitc";
  6.  
  7. // Create connection
  8. $conn = new mysqli($servername, $username, $password, $dbname);
  9. // Check connection
  10. if ($conn->connect_error) {
  11.     die("Connection failed: " . $conn->connect_error);
  12. }
  13.  
  14. $sql = "SELECT codice_target FROM customer";
  15. $result = $conn->query($sql);
  16. $rtoclass = array();
  17.  
  18. if ($result->num_rows > 0) {
  19.     // output data of each row
  20.     while($row = $result->fetch_assoc()) {
  21.         //echo "id: " . $row["id_customer"]. " - Codice target: " . $row["codice_target"]."<br>";
  22.         $rtoclass[] = $row;
  23.     }
  24. } else {
  25.     echo "0 results";
  26. }
  27.  
  28. $obj = new AdvancedExport();
  29. $obj->set_arr_needed( $rtoclass );
  30.  
  31.  
  32.  
  33. $conn->close();
  34.  
  35. if (!defined('_PS_VERSION_'))
  36.     exit;
  37.  
  38. class AdvancedExport extends Module
  39. {
  40.     public $hasAttr;
  41.     public $lastElement;
  42.     public $rowsNumber;
  43.     public $link;
  44.     private $selected_cat;
  45.     private $export_types =  array('products', 'orders', 'categories', 'manufacturers', 'newsletters', 'suppliers', 'customers' ), $counter = null; // put it here
  46.     public $products = array(
  47.         array('name' => 'Product Id','field' =>  'id_product', 'database' => 'products', 'alias' => 'p'),
  48.         array('name' => 'Product Reference','field' =>  'reference', 'database' => 'products', 'alias' => 'p', 'attribute' => true),
  49.         array('name' => 'Name','field' =>  'name', 'database' => 'products_lang', 'alias' => 'pl'),
  50.         array('name' => 'Short Description','field' =>  'description_short', 'database' => 'products_lang', 'alias' => 'pl'),
  51.         array('name' => 'Long Description','field' =>  'description', 'database' => 'products_lang', 'alias' => 'pl'),
  52.         array('name' => 'Quantity','field' =>  'quantity', 'database' => 'other', 'attribute' => true),
  53.         array('name' => 'Price','field' =>  'price', 'database' => 'products', 'alias' => 'p', 'attribute' => true),
  54.         array('name' => 'Price Catalogue TTC','field' =>  'price_tax_nodiscount', 'database' => 'other', 'attribute' => true),
  55.         array('name' => 'Price Tax','field' =>  'price_tax', 'database' => 'other', 'attribute' => true),
  56.         array('name' => 'Wholesale Price','field' =>  'wholesale_price', 'database' => 'products', 'alias' => 'p', 'attribute' => true),
  57.         array('name' => 'Supplier Id (default)','field' =>  'id_supplier', 'database' => 'products', 'alias' => 'p'),
  58.         array('name' => 'Suppliers Ids','field' =>  'id_supplier_all', 'database' => 'other', 'attribute' => true),
  59.         array('name' => 'Supplier Name (default)','field' =>  'supplier_name', 'as' => true, 'database' => 'supplier', 'alias' => 's'),
  60.         array('name' => 'Supplier Names','field' =>  'supplier_name_all', 'database' => 'other', 'attribute' => true),
  61.         array('name' => 'Manufacturer Id','field' =>  'id_manufacturer', 'database' => 'products', 'alias' => 'p'),
  62.         array('name' => 'Manufacturer Name','field' =>  'manufacturer_name', 'database' => 'other'),
  63.         array('name' => 'Tax Id Rules Group','field' =>  'id_tax_rules_group', 'database' => 'products', 'alias' => 'p'),
  64.         array('name' => 'Tax Rate','field' =>  'tax_rate', 'database' => 'other'),
  65.         array('name' => 'Default Category Id','field' =>  'id_category_default', 'database' => 'products', 'alias' => 'p'),
  66.         array('name' => 'Default Category Name','field' =>  'nameCategoryDefault', 'database' => 'other'),
  67.         array('name' => 'Categories Names','field' =>  'categories_names', 'database' => 'other'),
  68.         array('name' => 'Categories Ids','field' =>  'categories_ids', 'database' => 'other'),
  69.         array('name' => 'On Sale','field' =>  'on_sale', 'database' => 'products', 'alias' => 'p'),
  70.         array('name' => 'EAN 13','field' =>  'ean13', 'database' => 'products', 'alias' => 'p', 'attribute' => true),
  71.         array('name' => 'Supplier Reference','field' =>  'supplier_reference', 'database' => 'products', 'alias' => 'p', 'attribute' => true),
  72.         array('name' => 'Date Added','field' =>  'date_add', 'database' => 'products', 'alias' => 'p'),
  73.         array('name' => 'Date Update','field' =>  'date_upd', 'database' => 'products', 'alias' => 'p'),
  74.         array('name' => 'Active','field' =>  'active', 'database' => 'products', 'alias' => 'p'),
  75.         array('name' => 'Meta Title','field' =>  'meta_title', 'database' => 'products_lang', 'alias' => 'pl'),
  76.         array('name' => 'Meta Description','field' =>  'meta_description', 'database' => 'products_lang', 'alias' => 'pl'),
  77.         array('name' => 'Meta Keywords','field' =>  'meta_keywords', 'database' => 'products_lang', 'alias' => 'pl'),
  78.         array('name' => 'Available Now','field' =>  'available_now', 'database' => 'products_lang', 'alias' => 'pl'),
  79.         array('name' => 'Available Later','field' =>  'available_later', 'database' => 'products_lang', 'alias' => 'pl'),      
  80.         array('name' => 'Tags','field' =>  'tags', 'database' => 'other'),
  81.         array('name' => 'Accessories','field' =>  'accessories', 'database' => 'other'),
  82.         array('name' => 'Images','field' =>  'images', 'database' => 'other', 'attribute' => true),
  83.         array('name' => 'Online only','field' =>  'online_only', 'database' => 'products', 'alias' => 'p'),
  84.         array('name' => 'Upc','field' =>  'upc', 'database' => 'products', 'alias' => 'p', 'attribute' => true),
  85.         array('name' => 'Ecotax','field' =>  'ecotax', 'database' => 'products', 'alias' => 'p', 'attribute' => true),
  86.         array('name' => 'Unity','field' =>  'unity', 'database' => 'products', 'alias' => 'p'),
  87.         array('name' => 'Unit Price Ratio','field' =>  'unit_price_ratio', 'database' => 'products', 'alias' => 'p'),
  88.         array('name' => 'Minimal Quantity','field' =>  'minimal_quantity', 'database' => 'products', 'alias' => 'p', 'attribute' => true),
  89.         array('name' => 'Additional Shipping Cost','field' =>  'additional_shipping_cost', 'database' => 'products', 'alias' => 'p'),
  90.         array('name' => 'Location','field' =>  'location', 'database' => 'products', 'alias' => 'p', 'attribute' => true),
  91.         array('name' => 'Width','field' =>  'width', 'database' => 'products', 'alias' => 'p'),
  92.         array('name' => 'Height','field' =>  'height', 'database' => 'products', 'alias' => 'p'),
  93.         array('name' => 'Depth','field' =>  'depth', 'database' => 'products', 'alias' => 'p'),
  94.         array('name' => 'Weight','field' =>  'weight', 'database' => 'products', 'alias' => 'p', 'attribute' => true),
  95.         array('name' => 'Out Of Stock','field' =>  'out_of_stock', 'database' => 'products', 'alias' => 'p'),
  96.         array('name' => 'Quantity Discount','field' =>  'quantity_discount', 'database' => 'products', 'alias' => 'p'),
  97.         array('name' => 'Customizable','field' =>  'customizable', 'database' => 'products', 'alias' => 'p'),
  98.         array('name' => 'Uploadable Files','field' =>  'uploadable_files', 'database' => 'products', 'alias' => 'p'),
  99.         array('name' => 'Text Fields','field' =>  'text_fields', 'database' => 'products', 'alias' => 'p'),
  100.         array('name' => 'Available For Order','field' =>  'available_for_order', 'database' => 'products', 'alias' => 'p'),
  101.         array('name' => 'Condition','field' =>  'condition', 'database' => 'products', 'alias' => 'p'),
  102.         array('name' => 'Show Price','field' =>  'show_price', 'database' => 'products', 'alias' => 'p'),
  103.         array('name' => 'Indexed','field' =>  'indexed', 'database' => 'products', 'alias' => 'p'),
  104.         array('name' => 'Cache Is Pack','field' =>  'cache_is_pack', 'database' => 'products', 'alias' => 'p'),
  105.         array('name' => 'Cache Has Attachments','field' =>  'cache_has_attachments', 'database' => 'products', 'alias' => 'p'),
  106.         array('name' => 'Cache Default Attribute','field' =>  'cache_default_attribute', 'database' => 'products', 'alias' => 'p'),
  107.         array('name' => 'Link Rewrite','field' =>  'link_rewrite', 'database' => 'products_lang', 'alias' => 'pl'),
  108.         array('name' => 'Url Product','field' =>  'url_product', 'database' => 'other'),
  109.         array('name' => 'Features','field' =>  'features', 'database' => 'other'),
  110.         array('name' => 'Attributes','field' =>  'attributes_name', 'database' => 'other', 'attribute' => true)
  111.     );
  112.     public $orders = array(
  113.         //PS_ORDER
  114.         array('name' => 'Order No', 'field' => 'id_order', 'database' => 'orders', "alias" => "o"),
  115.         array('name' => 'Reference', 'field' => 'reference', 'database' => 'orders', "alias" => "o", 'attribute' => true),
  116.         array('name' => 'Code (voucher)', 'field' => 'code', 'database' => 'other'),
  117.         //SHOP
  118.         array('name' => 'Payment module', 'field' => 'module', 'database' => 'orders',  "alias" => "o"),
  119.         array('name' => 'Payment', 'field' => 'payment', 'database' => 'orders',  "alias" => "o"),
  120.         array('name' => 'Total paid', 'field' => 'total_paid', 'database' => 'orders',  "alias" => "o"),
  121.         array('name' => 'Total paid tax incl', 'field' => 'total_paid_tax_incl', 'database' => 'orders', "alias" => "o"),
  122.         array('name' => 'Total paid tax excl', 'field' => 'total_paid_tax_excl', 'database' => 'orders', "alias" => "o"),
  123.         array('name' => 'Total products with tax', 'field' => 'total_products_wt', 'database' => 'orders', "alias" => "o"),
  124.         array('name' => 'Total paid real', 'field' => 'total_paid_real', 'database' => 'orders', "alias" => "o"),
  125.         array('name' => 'Total products', 'field' => 'total_products', 'database' => 'orders', "alias" => "o"),
  126.         array('name' => 'Total shipping', 'field' => 'total_shipping', 'database' => 'orders', "alias" => "o"),
  127.         array('name' => 'Total wrapping', 'field' => 'total_wrapping', 'database' => 'orders', "alias" => "o"),
  128.         array('name' => 'Shipping number', 'field' => 'shipping_number', 'database' => 'orders', "alias" => "o"),
  129.         array('name' => 'Delivery number', 'field' => 'delivery_number', 'database' => 'orders', "alias" => "o"),
  130.         array('name' => 'Invoice number', 'field' => 'invoice_number', 'database' => 'orders', "alias" => "o"),
  131.         array('name' => 'Invoice date', 'field' => 'invoice_date', 'database' => 'orders', "alias" => "o"),
  132.         array('name' => 'Delivery date', 'field' => 'delivery_date', 'database' => 'orders', "alias" => "o"),
  133.         array('name' => 'Date added', 'field' => 'date_add', 'database' => 'orders', "alias" => "o"),
  134.         array('name' => 'Date updated', 'field' => 'date_upd', 'database' => 'orders', "alias" => "o"),
  135.         array('name' => 'Total discounts', 'field' => 'total_discounts', 'database' => 'orders', "alias" => "o"),
  136.         array('name' => 'Gift message', 'field' => 'gift_message', 'database' => 'orders', "alias" => "o"),
  137.         array('name' => 'Valid', 'field' => 'valid', 'database' => 'orders', "alias" => "o"),
  138.         array('name' => 'Carrier id', 'field' => 'id_carrier', 'database' => 'orders', "alias" => "o"),
  139.         array('name' => 'Customer id', 'field' => 'id_customer', 'database' => 'orders', "alias" => "o"),
  140.         array('name' => 'Recycled packaging', 'field' => 'recyclable', 'database' => 'orders', "alias" => "o"),
  141.         array('name' => 'Gift wrapping', 'field' => 'gift', 'database' => 'orders', "alias" => "o"),
  142.         array('name' => 'Customization', 'field' => 'customization', 'database' => 'other', "alias" => "o"),
  143.         //PS_CUSTOMER
  144.         array('name' => 'Customer Firstname', 'field' => 'firstname', 'database' => 'customer', "alias" => "cu"),
  145.         array('name' => 'Customer Lastname', 'field' => 'lastname', 'database' => 'customer', "alias" => "cu"),
  146.         array('name' => 'Customer Email', 'field' => 'email', 'database' => 'customer', "alias" => "cu"),
  147.         array('name' => 'Customer id language', 'field' => 'id_lang', 'database' => 'customer', "alias" => "cu"),
  148.         //array("name" => "codice target", "field" => "codice_target", "database" => "customer", "alias" => "cu"), //aggiunto codice target
  149.         //PS_ADRESS
  150.         array('name' => 'Delivery Gender', 'field' => 'delivery_name', 'as' => true, 'database' => 'gender', "alias" => "gl"),
  151.         array('name' => 'Delivery Company Name', 'field' => 'company', 'database' => 'address', "alias" => "a"),
  152.         array('name' => 'Delivery Firstname', 'field' => 'delivery_firstname', 'as' => true, 'database' => 'address', "alias" => "a"),
  153.         array('name' => 'Delivery Lastname', 'field' => 'delivery_lastname', 'as' => true, 'database' => 'address', "alias" => "a"),
  154.         array('name' => 'Delivery address line 1', 'field' => 'delivery_address1', 'as' => true, 'database' => 'address', "alias" => "a"),
  155.         array('name' => 'Delivery address line 2', 'field' => 'delivery_address2', 'as' => true, 'database' => 'address', "alias" => "a"),
  156.         array('name' => 'Delivery postcode', 'field' => 'delivery_postcode', 'as' => true, 'database' => 'address', "alias" => "a"),
  157.         array('name' => 'Delivery city', 'field' => 'delivery_city', 'as' => true, 'database' => 'address', "alias" => "a"),
  158.         array('name' => 'Delivery phone', 'field' => 'delivery_phone', 'as' => true, 'database' => 'address', "alias" => "a"),
  159.         array('name' => 'Delivery phone(mobile)', 'field' => 'delivery_phone_mobile', 'as' => true, 'database' => 'address', "alias" => "a"),
  160.         array('name' => 'Delivery VAT', 'field' => 'delivery_vat_number', 'as' => true, 'database' => 'address', "alias" => "a"),
  161.         array('name' => 'Delivery DNI', 'field' => 'delivery_dni', 'as' => true, 'database' => 'address', "alias" => "a"),
  162.         //PS_STATE
  163.         array('name' => 'Delivery country iso code', 'field' => 'iso_code', 'database' => 'country', 'alias' => 'co'),
  164.         array('name' => 'Delivery state', 'field' => 'state_name', 'as' => true, 'database' => 'state', 'alias' => 's'),
  165.         //PS_COUNTRY_LANG
  166.         array('name' => 'Delivery country', 'field' => 'country_name', 'as' => true, 'database' => 'country_lang', 'alias' => 'cl'),
  167.         //PS_ADRESS
  168.         array('name' => 'Invoice address line 1', 'field' => 'invoice_address1', 'as' => true, 'database' => 'address', 'alias' => 'inv_a'),
  169.         array('name' => 'Invoice address line 2', 'field' => 'invoice_address2', 'as' => true, 'database' => 'address', 'alias' => 'inv_a'),
  170.         array('name' => 'Invoice postcode', 'field' => 'invoice_postcode', 'as' => true, 'database' => 'address', 'alias' => 'inv_a'),
  171.         array('name' => 'Invoice city', 'field' => 'invoice_city', 'as' => true, 'database' => 'address', 'alias' => 'inv_a'),
  172.         array('name' => 'Invoice phone', 'field' => 'invoice_phone', 'as' => true, 'database' => 'address', 'alias' => 'inv_a'),
  173.         array('name' => 'Invoice phone (mobile)', 'field' => 'invoice_phone_mobile', 'as' => true, 'database' => 'address', 'alias' => 'inv_a'),
  174.         array('name' => 'Invoice gender', 'field' => 'invoice_name', 'as' => true, 'database' => 'gender', "alias" => "inv_gl"),
  175.         array('name' => 'Invoice firstname', 'field' => 'invoice_firstname', 'as' => true, 'database' => 'address', 'alias' => 'inv_a'),
  176.         array('name' => 'Invoice lastname', 'field' => 'invoice_lastname', 'as' => true, 'database' => 'address', 'alias' => 'inv_a'),
  177.         array('name' => 'Invoice company name', 'field' => 'invoice_company', 'as' => true, 'database' => 'address', 'alias' => 'inv_a'),
  178.         //ORDER_PAYMENT
  179.         array('name' => 'Transaction Id', 'field' => 'transaction_id', 'database' => 'order_payment', "alias" => "op"),
  180.         //PS_CARRIER
  181.         array('name' => 'Name carrier', 'field' => 'carrier_name', 'as' => true, 'database' => 'carrier', "alias" => "ca"),
  182.         //PS_ORDER_DETAIL
  183.         array('name' => 'Product ID', 'field' => 'product_id', 'database' => 'order_detail', "alias" => "od"),
  184.         array('name' => 'Product Ref', 'field' => 'product_reference', 'database' => 'order_detail', "alias" => "od"),
  185.         array('name' => 'Product Name', 'field' => 'product_name', 'database' => 'order_detail', "alias" => "od"),
  186.         array('name' => 'Product Price', 'field' => 'product_price', 'database' => 'order_detail', "alias" => "od"),
  187.         array('name' => 'Product Quantity', 'field' => 'product_quantity', 'database' => 'order_detail', "alias" => "od"),
  188.         array('name' => 'Shop name', 'field' => 'shop_name', 'database' => 'shop', 'as' => true, 'alias' => 'sh'),
  189.  
  190.         array('name' => 'Message', 'field' => 'message', 'database' => 'message', 'alias' => 'm'),
  191.         array('name' => 'Order currency', 'field' => 'currency_iso_code', 'database' => 'currency', 'as' => true, 'alias' => 'cur'),
  192.     );
  193.     public $categories = array(
  194.         array("name" => "Id category", "field" => "id_category", "database" => "category", "alias" => "c"),
  195.         array("name" => "Id parent", "field" => "id_parent", "database" => "category", "alias" => "c"),
  196.         array("name" => "Id shop default", "field" => "id_shop_default", "database" => "category", "alias" => "c"),
  197.         array("name" => "Level depth", "field" => "level_depth", "database" => "category", "alias" => "c"),
  198.         array("name" => "nleft", "field" => "nleft", "database" => "category", "alias" => "c"),
  199.         array("name" => "nright", "field" => "nright", "database" => "category", "alias" => "c"),
  200.         array("name" => "active", "field" => "active", "database" => "category", "alias" => "c"),
  201.         array("name" => "Is root category", "field" => "is_root_category", "database" => "category", "alias" => "c"),
  202.         array("name" => "Id group", "field" => "id_group", "database" => "other"),
  203.         array("name" => "Id shop", "field" => "id_shop", "database" => "category_lang", "alias" => "cl"),
  204.         array("name" => "Name", "field" => "name", "database" => "category_lang", "alias" => "cl"),
  205.         array("name" => "Description", "field" => "description", "database" => "category_lang", "alias" => "cl"),
  206.         array("name" => "Link rewrite", "field" => "link_rewrite", "database" => "category_lang", "alias" => "cl"),
  207.         array("name" => "Meta title", "field" => "meta_title", "database" => "category_lang", "alias" => "cl"),
  208.         array("name" => "Meta keywords", "field" => "meta_keywords", "database" => "category_lang", "alias" => "cl"),
  209.         array("name" => "Meta description", "field" => "meta_description", "database" => "category_lang", "alias" => "cl"),
  210.         array("name" => "Position", "field" => "position", "database" => "category_shop", "alias" => "category_shop")
  211.     );
  212.     public $manufacturers = array(
  213.         array("name" =>"id manufacturer", "field" => "id_manufacturer", "database" => "manufacturer", "alias" => "m"),
  214.         array("name" =>"name", "field" => "name", "database" => "manufacturer", "alias" => "m"),
  215.         array("name" =>"active", "field" => "active", "database" => "manufacturer", "alias" => "m"),
  216.         array("name" =>"description", "field" => "description", "database" => "manufacturer", "alias" => "ml"),
  217.         array("name" =>"short description", "field" => "short_description", "database" => "manufacturer", "alias" => "ml"),
  218.         array("name" =>"meta title", "field" => "meta_title", "database" => "manufacturer", "alias" => "ml"),
  219.         array("name" =>"meta keywords", "field" => "meta_keywords", "database" => "manufacturer", "alias" => "ml"),
  220.         array("name" =>"meta description", "field" => "meta_description", "database" => "manufacturer", "alias" => "ml"),
  221.         array("name" =>"id shop", "field" => "id_shop", "database" => "manufacturer", "alias" => "manufacturer_shop"),
  222.         );
  223.     public $suppliers = array(
  224.         array("name" =>"id supplier", "field" => "id_supplier", "database" => "supplier", "alias" => "s"),
  225.         array("name" =>"name", "field" => "name", "database" => "supplier", "alias" => "s"),
  226.         array("name" =>"active", "field" => "active", "database" => "supplier", "alias" => "s"),
  227.         array("name" =>"description", "field" => "description", "database" => "supplier", "alias" => "sl"),
  228.         array("name" =>"meta title", "field" => "meta_title", "database" => "supplier", "alias" => "sl"),
  229.         array("name" =>"meta keywords", "field" => "meta_keywords", "database" => "supplier", "alias" => "sl"),
  230.         array("name" =>"meta description", "field" => "meta_description", "database" => "supplier", "alias" => "sl"),
  231.         array("name" =>"id shop", "field" => "id_shop", "database" => "supplier", "alias" => "supplier_shop"),
  232.         );
  233.     public $customers = array(
  234.         array("name" => "id customer", "field" => "id_customer", "database" => "customer", "alias" => "c"),
  235.         array("name" => "codice_target", "field" => "codice_target", "database" => "customer", "alias" => "c"), //aggiunto codice target
  236.         array("name" => "id gender", "field" => "id_gender", "database" => "customer", "alias" => "c"),
  237.         array("name" => "company", "field" => "company", "database" => "customer", "alias" => "c"),
  238.         array("name" => "siret", "field" => "siret", "database" => "customer", "alias" => "c"),
  239.         array("name" => "ape", "field" => "ape", "database" => "customer", "alias" => "c"),
  240.         array("name" => "firstname", "field" => "firstname", "database" => "customer", "alias" => "c"),
  241.         array("name" => "lastname", "field" => "lastname", "database" => "customer", "alias" => "c"),
  242.         array("name" => "email", "field" => "email", "database" => "customer", "alias" => "c"),
  243.         array("name" => "birthday", "field" => "birthday", "database" => "customer", "alias" => "c"),
  244.         array("name" => "newsletter", "field" => "newsletter", "database" => "customer", "alias" => "c"),
  245.         array("name" => "website", "field" => "website", "database" => "customer", "alias" => "c"),
  246.         array("name" => "password", "field" => "passwd", "database" => "customer", "alias" => "c"),
  247.  
  248.         array("name" => "address company", "field" => "address_company", "database" => "address", 'as' => true, "alias" => "a"),
  249.         array("name" => "address firstname", "field" => "address_firstname", "database" => "address", 'as' => true, "alias" => "a"),
  250.         array("name" => "address lastname", "field" => "address_lastname", "database" => "address", 'as' => true, "alias" => "a"),
  251.         array("name" => "address address1", "field" => "address1", "database" => "address", "alias" => "a"),
  252.         array("name" => "address address2", "field" => "address2", "database" => "address", "alias" => "a"),
  253.         array("name" => "address postcode", "field" => "postcode", "database" => "address", "alias" => "a"),
  254.         array("name" => "address city", "field" => "city", "database" => "address", "alias" => "a"),
  255.         array("name" => "address other", "field" => "other", "database" => "address", "alias" => "a"),
  256.         array("name" => "address phone", "field" => "phone", "database" => "address", "alias" => "a"),
  257.         array("name" => "address phone_mobile", "field" => "phone_mobile", "database" => "address", "alias" => "a"),
  258.         array("name" => "address vat_number", "field" => "vat_number", "database" => "address", "alias" => "a"),
  259.         array("name" => "address dni", "field" => "dni", "database" => "address", "alias" => "a"),
  260.         array("name" => "address active", "field" => "active", "database" => "address", "alias" => "a"),
  261.         );
  262.     public $newsletters = array(
  263.         array("name" => "Email", "field" => "email", "database" => "newsletter"),
  264.         array("name" => "Date add", "field" => "newsletter_date_add", "database" => "newsletter"),
  265.         array("name" => "Ip", "field" => "ip_registration_newsletter", "database" => "newsletter"),
  266.         array("name" => "Referer", "field" => "http_referer", "database" => "newsletter"),
  267.         array("name" => "Active", "field" => "active", "database" => "newsletter")
  268.     );
  269.     public $switch;
  270.     public $showTimeAndMemory;
  271.  
  272.     public function __construct()
  273.     {
  274.         $this->name = "advancedexport";
  275.         $this->tab = "administration";
  276.         $this->bootstrap  = true;
  277.         $this->author = "Algol Consulting";
  278.         $this->version = "4.2.0";
  279.         $this->displayName = $this->l('Esportazione Avanzata');
  280.         $this->description = $this->l('Strumento esportazione avanzata');
  281.         $this->module_key = "a3895af3e1e55fa47a756b6e973e77fe";
  282.         $this->link = new Link();
  283.         $this->showTimeAndMemory = false;
  284.         $this->switch = (_PS_VERSION_ >= 1.6 ? "switch": "radio");
  285.         parent::__construct();
  286.  
  287.         $path = dirname(__FILE__);
  288.  
  289.         if (strpos(__FILE__, 'Module.php') !== false)
  290.             $path .= '/../modules/'.$this->name;
  291.  
  292.         include_once($path.'/classes/AdvancedExportClass.php');
  293.     }
  294.  
  295.     public function install()
  296.     {
  297.          if(!$this->CreateTables()
  298.             || !Configuration::updateGlobalValue("AdvancedExport_CURRENT", 0)
  299.              || !Configuration::updateGlobalValue("AdvancedExport_TOTAL", 0)
  300.             || !Configuration::updateGlobalValue("ADVANCEDEXPORT_SECURE_KEY", Tools::strtoupper(Tools::passwdGen(16))))
  301.             return false;
  302.  
  303.          if (!parent::install())
  304.             return false;
  305.  
  306.          return true;
  307.     }
  308.  
  309.     public function CreateTables()
  310.     {
  311.         //for test create tmp table
  312.         $table_name =  _DB_PREFIX_ . "advancedexport";
  313.  
  314.         $query = "CREATE TABLE IF NOT EXISTS `".$table_name."` (
  315.             `id_advancedexport` int(10) unsigned NOT NULL auto_increment,
  316.             `type` varchar(200) NOT NULL,
  317.             `name` varchar(200) NOT NULL,
  318.             `delimiter` varchar(255) NOT NULL,
  319.             `separator` varchar(255) NOT NULL,
  320.             `id_lang` int(10) NOT NULL,
  321.             `charset` varchar(255) NOT NULL,
  322.             `add_header` BOOL NOT NULL DEFAULT 0,
  323.             `decimal_separator` varchar(10) NOT NULL,
  324.             `decimal_round` int(10) NOT NULL,
  325.             `strip_tags` BOOL NOT NULL DEFAULT 0,
  326.             `only_new` BOOL NOT NULL DEFAULT 0,
  327.             `date_from` varchar(255) NOT NULL,
  328.             `date_to` varchar(255) NOT NULL,
  329.            `last_exported_id` int(10) NOT NULL DEFAULT 0,
  330.            `start_id` int(10) NOT NULL DEFAULT 0,
  331.             `end_id` int(10) NOT NULL DEFAULT 0,
  332.             `save_type` int(10) NOT NULL DEFAULT 0,
  333.             `filename` varchar(255) NOT NULL,
  334.             `image_type` varchar(255) NOT NULL,
  335.             `email` varchar(255) NOT NULL,
  336.             `ftp_hostname` varchar(255) NOT NULL,
  337.             `ftp_user_name` varchar(255) NOT NULL,
  338.             `ftp_user_pass` varchar(255) NOT NULL,
  339.             `fields` text  NOT NULL,
  340.             PRIMARY KEY  (`id_advancedexport`)
  341.             ) ENGINE="._MYSQL_ENGINE_." DEFAULT CHARSET=utf8";
  342.  
  343.         if(!$this->DbExecute($query))
  344.             return false;
  345.  
  346.         return true;
  347.     }
  348.  
  349.     public function DbExecute($query)
  350.     {
  351.         return Db::getInstance()->Execute($query);
  352.     }
  353.  
  354.     public function uninstall()
  355.     {
  356.         if(!$this->RemoveTables()
  357.             || !Configuration::deleteByName("AdvancedExport_CURRENT")
  358.             || !Configuration::deleteByName("AdvancedExport_TOTAL"))  //install tables
  359.             return false;
  360.  
  361.         if (!parent::uninstall())
  362.             return false;
  363.  
  364.         return true;
  365.     }
  366.  
  367.     public function RemoveTables()
  368.     {
  369.         //remove main table
  370.         if(!$this->DbExecute("DROP TABLE IF EXISTS `"._DB_PREFIX_."advancedexport`"))
  371.             return false;
  372.         return true;
  373.     }
  374.  
  375.     public function getContent()
  376.     {
  377.         $this->_html = '';
  378.         $this->_postProcess();
  379.  
  380.         if ($this->getValue('add_model') || Tools::isSubmit('updateadvancedexport')  || Tools::isSubmit('btnSubmit'))
  381.         {
  382.             $this->_html .= $this->displayAddModelForm($helper = new HelperForm());
  383.         }
  384.         else
  385.             $this->_html .= $this->displayIndexForm();
  386.  
  387.         $this->addHeader();
  388.         return $this->_html;
  389.     }
  390.  
  391.     public function addHeader()
  392.     {
  393.         $this->addCSS($this->_path.'views/css/admin.css');
  394.         $this->addCSS($this->_path.'views/css/jquery.percentageloader-0.1.css');
  395.  
  396.         if(_PS_VERSION_ >= 1.6) {
  397.             $this->addJS(_PS_JS_DIR_ . 'jquery/ui/jquery.ui.sortable.min.js');
  398.             $this->addJS($this->_path.'views/js/admin.js');
  399.         } else {
  400.             $this->addJS($this->_path.'views/js/jquery-ui-1.10.4.custom.min.js');
  401.             $this->addJS($this->_path.'views/js/admin15.js');
  402.         }
  403.  
  404.         $this->addJS($this->_path.'views/js/jquery.percentageloader-0.1.min.js');
  405.         $this->addJS($this->_path.'views/js/jquery.bsmselect.js');
  406.         $this->addJS($this->_path.'views/js/jquery.bsmselect.compatibility.js');
  407.         $this->addJS($this->_path.'views/js/jquery.bsmselect.sortable.js');
  408.  
  409.         $this->addJS($this->_path.'views/js/jquery.cooki-plugin.js');
  410.     }
  411.  
  412.     public function _postProcess()
  413.     {
  414.         if($this->getValue("ajax"))
  415.             $this->hookAjaxCall();
  416.  
  417.         if ($this->_postValidation() == false)
  418.             return false;
  419.  
  420.         $errors = '';
  421.  
  422.         if (Tools::isSubmit('btnSubmit') )
  423.         {
  424.             if($this->saveModel())
  425.                 $this->redirect('saveModelConfirmation');
  426.         }
  427.         else if(Tools::isSubmit('deleteadvancedexport'))
  428.         {
  429.             if(!$this->deleteModel())
  430.                 $this->redirect('deleteModelConfirmation');
  431.         }
  432.         elseif ($this->isSubmit('duplicateadvancedexport') && $this->getValue('id_advancedexport'))
  433.         {
  434.             $time_start = microtime(true);  //debug
  435.  
  436.             $this->getExportType($this->getValue('id_advancedexport'));
  437.  
  438.             if($this->showTimeAndMemory) // debug
  439.                 $this->showTimeAndMemoryUsage($time_start); // debug
  440.             else
  441.                 $this->redirect('exportConfirmation');
  442.         }
  443.         elseif ($this->isSubmit('viewfiles') && $this->getValue('url'))
  444.         {
  445.             $this->getFile($this->getValue('url'));
  446.         }
  447.         elseif ($this->isSubmit('deletefiles') && $url = $this->getValue('url'))
  448.         {
  449.             $this->deleteFile($url);
  450.             $this->redirect('deleteFileConfirmation');
  451.         }
  452.         elseif (Tools::isSubmit('saveModelConfirmation'))
  453.             $this->_html .= $this->displayConfirmation($this->l('Model save successfully.'));
  454.         elseif (Tools::isSubmit('deleteModelConfirmation'))
  455.             $this->_html .= $this->displayConfirmation($this->l('Model delete successfully.'));
  456.         elseif (Tools::isSubmit('deleteFileConfirmation'))
  457.             $this->_html .= $this->displayConfirmation($this->l('File delete successfully.'));
  458.         elseif (Tools::isSubmit('exportConfirmation'))
  459.             $this->_html .= $this->displayConfirmation($this->l('Export finish successfully.'));
  460.  
  461.         if ($errors)
  462.             $this->_html .= $this->displayError($errors);
  463.     }
  464.  
  465.     protected function _postValidation()
  466.     {
  467.         $this->_errors = array();
  468.  
  469.         if (Tools::isSubmit('btnSubmit') )
  470.         {
  471.             $fields = Tools::getValue('fields');
  472.             if (!is_array($fields))
  473.                       $this->_errors[] = $this->l('You must choose at least one field.');
  474.             if (!Validate::isName(Tools::getValue('name')) || Tools::getValue('name') == '')
  475.                       $this->_errors[] = $this->l('Invalid or empty name.');
  476.             if (Tools::getValue('filename') != '' && !Validate::isName(Tools::getValue('filename')))
  477.                       $this->_errors[] = $this->l('Invalid file name.');
  478.             if (Tools::getValue('date_from') != '' && !Validate::isDate(Tools::getValue('date_from')))
  479.                       $this->_errors[] = $this->l('Invalid date from.');
  480.             if (Tools::getValue('date_to') != '' && !Validate::isDate(Tools::getValue('date_to')))
  481.                       $this->_errors[] = $this->l('Invalid date to.');
  482.             if (Tools::getValue('start_id') != '' && !Validate::isInt(Tools::getValue('start_id')))
  483.                       $this->_errors[] = $this->l('Invalid begin id field.');
  484.             if (Tools::getValue('end_id') != '' && !Validate::isInt(Tools::getValue('end_id')))
  485.                       $this->_errors[] = $this->l('Invalid finish id field.');
  486.         }
  487.  
  488.         if (count($this->_errors))
  489.         {
  490.             foreach ($this->_errors as $err)
  491.             $this->_html .= '<div class="alert alert-danger">'.$err.'</div>';
  492.  
  493.             return false;
  494.         }
  495.  
  496.         return true;
  497.     }
  498.  
  499.     public function saveModel()
  500.     {
  501.         $functionName = ($this->getValue('type') ? $this->getValue('type')  : '').'FormFields';
  502.         $specific = $this->$functionName();
  503.  
  504.         $to_serialize = null;
  505.         foreach ($specific as $key => $value) {
  506.             $trimmed = str_replace('[]', '', $value['name']);
  507.             if($this->getValue($trimmed) != "")
  508.                 $to_serialize[$value['name']] = $this->getValue($trimmed);
  509.         }
  510.  
  511.         $AdvancedExport = new AdvancedExportClass($this->getValue('id_advancedexport'));
  512.         $AdvancedExport->copyFromPost();
  513.         $AdvancedExport->fields = Tools::jsonEncode($to_serialize);
  514.         $AdvancedExport->save();
  515.  
  516.         return true;
  517.     }
  518.  
  519.     public function getValue($value)
  520.     {
  521.         return Tools::getValue($value);
  522.     }
  523.  
  524.     public function redirect($action)
  525.     {
  526.         Tools::redirectAdmin(AdminController::$currentIndex.'&configure='.$this->name.'&token='.Tools::getAdminTokenLite('AdminModules').'&'.$action);
  527.     }
  528.  
  529.     public function deleteModel()
  530.     {
  531.         $AdvancedExport = new AdvancedExportClass($this->getValue('id_advancedexport'));
  532.         $AdvancedExport->delete();
  533.  
  534.         return true;
  535.     }
  536.  
  537.     public function addCSS($path)
  538.     {
  539.         return $this->context->controller->addCSS($path);
  540.     }
  541.  
  542.     public function addJS($path)
  543.     {
  544.         return $this->context->controller->addJS($path);
  545.     }
  546.  
  547.     public function displayAddModelForm($helper)
  548.     {
  549.         $type = null;
  550.         if($id = Tools::getValue("id_advancedexport"))
  551.         {
  552.             $aec = new AdvancedExportClass($id);
  553.             if(is_object($aec))
  554.                 $type = $aec->type;
  555.         }
  556.         else
  557.         {
  558.             $type = Tools::getValue("type");
  559.         }
  560.  
  561.         $helper->module = $this;
  562.         $helper->show_toolbar = true;
  563.         $helper->table = 'advancedexport';
  564.         $helper->id = (int)$id;
  565.         $helper->default_form_language = (int)Configuration::get("PS_LANG_DEFAULT");
  566.         $helper->allow_employee_form_lang = (int)Configuration::get("PS_LANG_DEFAULT");
  567.         $helper->submit_action = 'btnSubmit';
  568.         $helper->token = $this->getValue('token');
  569.         $helper->currentIndex = $this->getAdminLink().'&configure='.$this->name.'&tab_module='.$this->tab.'&module_name='.$this->name;
  570.         $helper->fields_value = $this->getModelFieldsValues($type);
  571.  
  572.         return $helper->generateForm( $this->ModelFormFields($type) );
  573.     }
  574.  
  575.     public function getAdminLink()
  576.     {
  577.         return $this->context->link->getAdminLink('AdminModules', false);
  578.     }
  579.  
  580.     public function getModelFieldsValues($type)
  581.     {
  582.         $fields = array('id_advancedexport', 'type', 'name', 'delimiter', 'separator', 'id_lang', 'charset', 'add_header', 'decimal_separator', 'decimal_round', 'strip_tags', 'file_type', 'only_new', 'save_type', 'shops', 'image_type', 'filename', 'email', 'ftp_hostname', 'ftp_user_pass', 'ftp_user_name', 'date_from', 'date_to', 'start_id', 'end_id');
  583.         $fields_specific = null;
  584.         $fields_value = null;
  585.  
  586.         if($this->getValue('id_advancedexport'))
  587.         {
  588.             $ae = new AdvancedExportClass($this->getValue('id_advancedexport'));
  589.             $fields_specific = Tools::jsonDecode($ae->fields, true);
  590.         }
  591.         foreach ($fields as $field)
  592.         {
  593.             if (Tools::getValue($field))
  594.                 $fields_value[$field] = Tools::getValue($field);
  595.             else if (isset($ae) && isset($ae->$field))
  596.                 $fields_value[$field] = $ae->$field;
  597.             else
  598.                 $fields_value[$field] = '';
  599.           }
  600.  
  601.           $functionName = ($type ? $type : 'products').'FormFields';
  602.           $specific = $this->$functionName();
  603.  
  604.           foreach ($specific as $value)
  605.           {
  606.             if(isset($fields_specific[$value['name']]))
  607.             {
  608.                 $fields_value[$value['name']] = $fields_specific[$value['name']];
  609.             }
  610.             else
  611.             {
  612.                 $fields_value[$value['name']] = null;
  613.              }
  614.           }
  615.  
  616.         if(isset($fields_specific["categories"])) {
  617.             $this->selected_cat = $fields_specific["categories"];
  618.         }
  619.  
  620.           return $fields_value;
  621.     }
  622.  
  623.     public function ModelFormFields($type)
  624.     {
  625.         $functionName = ($type ? $type : 'products').'FormFields';
  626.         $result = null;
  627.  
  628.         $result[0] = array(
  629.             'form' => array(
  630.                 'legend' => array(
  631.                     'title' => $this->l('Settings Form'),
  632.                     'icon' => 'icon-envelope'
  633.                 ),
  634.                 'input' => array(
  635.                 array(
  636.                     'type' => 'hidden',
  637.                     'name' => 'id_advancedexport'
  638.                 ),
  639.                 array(
  640.                     'type' => 'hidden',
  641.                     'name' => 'type'
  642.                 ),
  643.                 array(
  644.                     'type' => 'text',
  645.                     'label' => $this->l('Name'),
  646.                     'name' => 'name',
  647.                     'required' => true,
  648.                     'desc' =>$this->l('Settings insternal name')
  649.                 ),
  650.                 array(
  651.                     'type' => 'text',
  652.                     'label' => $this->l('File name'),
  653.                     'name' => 'filename',
  654.                     'desc' =>$this->l('You can set name for file or leave blank name will be given by system.')
  655.                 ),
  656.                 array(
  657.                     'type' => 'select',
  658.                     'label' => $this->l('Delimiter'),
  659.                     'name' => 'delimiter',
  660.                     'options' => array(
  661.                         'query' => array(
  662.                             array(
  663.                                 'value' => ",",
  664.                                 'name' => "[,] ".$this->l("comma")
  665.                             ),
  666.                             array(
  667.                                 'value' => ";",
  668.                                 'name' => "[;] ". $this->l("semi-colons")
  669.                             ),
  670.                             array(
  671.                                 'value' => ":",
  672.                                 'name' => "[:] ". $this->l("colons")
  673.                             ),
  674.                             array(
  675.                                 'value' => "|",
  676.                                 'name' => "[|] ". $this->l("pipes")
  677.                             ),
  678.                             array(
  679.                                 'value' => "~",
  680.                                 'name' => "[~] ". $this->l("tilde")
  681.                             )
  682.                         ),
  683.                         'id' => 'value',
  684.                         'name' => 'name'
  685.                     ),
  686.                     'desc' =>$this->l('Separrator for each line in csv file')
  687.                 ),
  688.                 array(
  689.                     'type' => 'select',
  690.                     'label' => $this->l('Separator'),
  691.                     'name' => 'separator',
  692.                     'options' => array(
  693.                         'query' => array(
  694.                             array(
  695.                                 'value' => '&#34;',
  696.                                 'name' => '["] '.$this->l("quotation marks")
  697.                             ),
  698.                             array(
  699.                                 'value' => "'",
  700.                                 'name' => "['] ". $this->l("single quotation marks")
  701.                             )
  702.                         ),
  703.                         'id' => 'value',
  704.                         'name' => 'name'
  705.                     ),
  706.                     'desc' =>$this->l('Separrator for each value in csv file')
  707.                 ),
  708.                 array(
  709.                     'type' => 'select',
  710.                     'label' => $this->l('Language'),
  711.                     'name' => 'id_lang',
  712.                     'col' => '4',
  713.                     'options' => array(
  714.                         'query' => Language::getLanguages(),
  715.                         'id' => 'id_lang',
  716.                         'name' => 'name'
  717.                     ),
  718.                     'desc' =>$this->l('Default utf-8.')
  719.  
  720.                 ),
  721.                 array(
  722.                     'type' => 'select',
  723.                     'label' => $this->l('Encoding type'),
  724.                     'name' => 'charset',
  725.                     'col' => '4',
  726.                     'options' => array(
  727.                         'query' => $this->getCharsets(),
  728.                         'id' => 'name',
  729.                         'name' => 'name'
  730.                     ),
  731.                     'desc' =>$this->l('Default utf-8.')
  732.  
  733.                 ),
  734.                 array(
  735.                     'type' => 'select',
  736.                     'label' => $this->l('Decimal separator'),
  737.                     'name' => 'decimal_separator',
  738.                     'options' => array(
  739.                         'query' => array(
  740.                             array(
  741.                                 'value' => ',',
  742.                                 'name' => '[,] '.$this->l("comma")
  743.                             ),
  744.                             array(
  745.                                 'value' => ".",
  746.                                 'name' => "[.] ". $this->l("dot")
  747.                             )
  748.                         ),
  749.                         'default' => array(
  750.                             'label' => $this->l('default'),
  751.                             'value' => -1
  752.                         ),
  753.                         'id' => 'value',
  754.                         'name' => 'name'
  755.                     )
  756.                 ),
  757.                 array(
  758.                     'type' => 'select',
  759.                     'label' => $this->l('Round values'),
  760.                     'name' => 'decimal_round',
  761.                     'options' => array(
  762.                         'default' => array(
  763.                             'label' => $this->l('default'),
  764.                             'value' => '-1'
  765.                         ),
  766.                         'query' => array(
  767.                             array(
  768.                                 'value' => '0',
  769.                                 'label' => '0'
  770.                             ),
  771.                             array(
  772.                                 'value' => '1',
  773.                                 'label' => '1'
  774.                             ),
  775.                             array(
  776.                                 'value' => '2',
  777.                                 'label' => '2'
  778.                             ),
  779.                             array(
  780.                                 'value' => '3',
  781.                                 'label' => '3'
  782.                             ),
  783.                             array(
  784.                                 'value' => '4',
  785.                                 'label' => '4'
  786.                             ),
  787.                             array(
  788.                                 'value' => '5',
  789.                                 'label' => '5'
  790.                             ),
  791.                             array(
  792.                                 'value' => '6',
  793.                                 'label' => '6'
  794.                             )
  795.                         ),
  796.                         'id' => 'value',
  797.                         'name' => 'label'
  798.                     )
  799.                 ),
  800.                 array(
  801.                     'type' => 'select',
  802.                     'label' => $this->l('Save type'),
  803.                     'name' => 'save_type',
  804.                     'default' => '0',
  805.                     'options' => array(
  806.                         'query' => $this->getSaveTypes(),
  807.                         'id' => 'id',
  808.                         'name' => 'name'
  809.                     ),
  810.                     'desc' =>$this->l('Save your file, sent to server or email.')
  811.  
  812.                 ),
  813.                 array(
  814.                     'type' => 'text',
  815.                     'label' => $this->l('Email'),
  816.                     'name' => 'email',
  817.                     'class' => 'process2'
  818.                 ),
  819.                 array(
  820.                     'type' => 'text',
  821.                     'label' => $this->l('Hostname'),
  822.                     'name' => 'ftp_hostname',
  823.                     'class' => 'process1'
  824.                 ),
  825.                 array(
  826.                     'type' => 'text',
  827.                     'label' => $this->l('Username'),
  828.                     'name' => 'ftp_user_name',
  829.                     'class' => 'process1'
  830.                 ),
  831.                 array(
  832.                     'type' => 'text',
  833.                     'label' => $this->l('Password'),
  834.                     'name' => 'ftp_user_pass',
  835.                     'class' => 'process1'
  836.                 ),
  837.                 array(
  838.                     'type' => $this->switch,
  839.                     'label' => $this->l('Display labels'),
  840.                     'name' => 'add_header',
  841.                     'class' => 't',
  842.                     'is_bool' => true,
  843.                     'values' => array(
  844.                         array(
  845.                             'id' => 'active_on',
  846.                             'value' => 1,
  847.                             'label' => $this->l('Yes')
  848.                         ),
  849.                         array(
  850.                             'id' => 'active_off',
  851.                             'value' => 0,
  852.                             'label' => $this->l('No')
  853.                         )
  854.                     ),
  855.                 ),
  856.                 array(
  857.                     'type' => $this->switch,
  858.                     'label' => $this->l('Strip tags'),
  859.                     'name' => 'strip_tags',
  860.                     'class' => 't',
  861.                     'is_bool' => true,
  862.                     'values' => array(
  863.                         array(
  864.                             'id' => 'active_on',
  865.                             'value' => 1,
  866.                             'label' => $this->l('Yes')
  867.                         ),
  868.                         array(
  869.                             'id' => 'active_off',
  870.                             'value' => 0,
  871.                             'label' => $this->l('No')
  872.                         )
  873.                     ),
  874.                 ),
  875.                 array(
  876.                     'type' => $this->switch,
  877.                     'label' => $this->l('Export not exported'),
  878.                     'name' => 'only_new',
  879.                     'class' => 't',
  880.                     'is_bool' => true,
  881.                     'desc' =>$this->l('Export not exported yet.'),
  882.                     'values' => array(
  883.                         array(
  884.                             'id' => 'active_on',
  885.                             'value' => 1,
  886.                             'label' => $this->l('Yes')
  887.                          ),
  888.                         array(
  889.                             'id' => 'active_off',
  890.                             'value' => 0,
  891.                             'label' => $this->l('No')
  892.                          )
  893.                     ),
  894.                 ),
  895.                 array(
  896.                     'type' => 'text',
  897.                     'label' => $this->l('Begin id'),
  898.                     'name' => 'start_id',
  899.                     'desc' =>$this->l('You can specyify start id number.')
  900.                 ),
  901.                 array(
  902.                     'type' => 'text',
  903.                     'label' => $this->l('Finish id'),
  904.                     'name' => 'end_id',
  905.                     'desc' =>$this->l('You can specify end id number.')
  906.                 ),
  907.                 array(
  908.                     'type' => (_PS_VERSION_ >= 1.6 ? 'datetime' : 'date'),
  909.                     'label' => $this->l('From'),
  910.                     'name' => 'date_from',
  911.                     'size' => 10,
  912.                     'maxlength' => 10,
  913.                     'desc' =>$this->l('Format: 2011-12-31 HH-MM-SS(inclusive).')
  914.                 ),
  915.                 array(
  916.                     'type' => (_PS_VERSION_ >= 1.6 ? 'datetime' : 'date'),
  917.                     'label' => $this->l('To'),
  918.                     'name' => 'date_to',
  919.                     'size' => 10,
  920.                     'maxlength' => 10,
  921.                     'desc' =>$this->l('Format: 2012-12-31 HH-MM-SS(inclusive).')
  922.                 )
  923.             ),
  924.             'submit' => array(
  925.                 'title' => $this->l('Save'),
  926.              ),
  927.             'buttons' => array(
  928.                     'cancelBlock' => array(
  929.                         'title' => $this->l('Cancel'),
  930.                         'href' => $this->getAdminUrl(),
  931.                         'icon' => 'process-icon-cancel'
  932.                     )
  933.                 )
  934.             ),
  935.          );
  936.  
  937.         if($type != "orders" && $type != "newsletters" && $type != "customers") {
  938.             $result[0]['form']['input'][] = array(
  939.                 'type' => 'select',
  940.                 'label' => $this->l('Image type'),
  941.                 'name' => 'image_type',
  942.                 'col' => '4',
  943.                 'options' => array(
  944.                     'query' => ImageType::getImagesTypes($type),
  945.                     'id' => 'name',
  946.                     'name' => 'name'
  947.                 ),
  948.             );
  949.         }
  950.  
  951.         $specific = $this->$functionName();
  952.         $result[0]['form']['input'] = array_merge( $result[0]['form']['input'], $specific);
  953.  
  954.         return $result;
  955.     }
  956.  
  957.     public function getCharsets()
  958.     {
  959.         return array(
  960.             array('id' => 1, 'name' => "UTF-8"),
  961.             array('id' => 2, 'name' => "ISO-8859-1"),
  962.             array('id' => 3, 'name' => "GB2312"),
  963.             array('id' => 4, 'name' => "Windows-1251"),
  964.             array('id' => 5, 'name' => "Windows-1252"),
  965.             array('id' => 6, 'name' => "Shift JIS"),
  966.             array('id' => 7, 'name' => "GBK"),
  967.             array('id' => 8, 'name' => "Windows-1256"),
  968.             array('id' => 9, 'name' => "ISO-8859-2"),
  969.             array('id' => 10, 'name' => "EUC-JP"),
  970.             array('id' => 11, 'name' => "ISO-8859-15"),
  971.             array('id' => 12, 'name' => "ISO-8859-9"),
  972.             array('id' => 13, 'name' => "Windows-1250"),
  973.             array('id' => 14, 'name' => "Windows-1254"),
  974.             array('id' => 15, 'name' => "EUC-KR"),
  975.             array('id' => 16, 'name' => "Big5"),
  976.             array('id' => 17, 'name' => "Windows-874"),
  977.             array('id' => 18, 'name' => "US-ASCII"),
  978.             array('id' => 19, 'name' => "TIS-620"),
  979.             array('id' => 20, 'name' => "ISO-8859-7"),
  980.             array('id' => 21, 'name' => "Windows-1255"),
  981.         );
  982.     }
  983.  
  984.     public function getSaveTypes()
  985.     {
  986.         return array(
  987.             array('id' => 0, 'name' => $this->l("Save to disc"), 'short_name' => $this->l("disc")),
  988.             array('id' => 1, 'name' => $this->l("Save to server"), 'short_name' => $this->l("ftp")),
  989.             array('id' => 2, 'name' => $this->l("Sent to emal"), 'short_name' => $this->l("email"))
  990.         );
  991.     }
  992.  
  993.     public function getFileTypes()
  994.     {
  995.         return array(
  996.             array('id' => 1, 'name' => "csv"),
  997.             array('id' => 2, 'name' => "xml")
  998.         );
  999.     }
  1000.  
  1001.     public function getAdminUrl()
  1002.     {
  1003.         return AdminController::$currentIndex.'&configure='.$this->name.'&token='.Tools::getAdminTokenLite('AdminModules');
  1004.     }
  1005.  
  1006.     public  function isFeatureActive()
  1007.     {
  1008.         return Shop::isFeatureActive();
  1009.     }
  1010.  
  1011.     public function isSubmit($value)
  1012.     {
  1013.         return Tools::isSubmit($value);
  1014.     }
  1015.  
  1016.     public function getExportType($id_advancedexport)
  1017.     {
  1018.         Configuration::updateGlobalValue("AdvancedExport_CURRENT", 0);
  1019.  
  1020.         $ae = new AdvancedExportClass($id_advancedexport);
  1021.         $this->createExportFile($ae);
  1022.     }
  1023.  
  1024.     public function showTimeAndMemoryUsage($time_start)
  1025.     {
  1026.         echo "</br></br></br></br></br></br></br><b>Using <span style='font-size:20px;'>". memory_get_peak_usage(1). "</span> bytes of ram.</b>";
  1027.         $time_end = microtime(true);
  1028.         //dividing with 60 will give the execution time in minutes other wise seconds
  1029.         $execution_time = ($time_end - $time_start)/60;
  1030.         //execution time of the script
  1031.         echo '</br><b>Total Execution Time: <span style="font-size:20px;"> '.$execution_time.'</span> Mins</b>';
  1032.     }
  1033.  
  1034.     public function createExportFile($ae)
  1035.     {
  1036.         ini_set('memory_limit','725M');
  1037.         $ae->fields = Tools::jsonDecode($ae->fields, true);
  1038.         $sorted_fields = $this->getLabelsAndFields($ae->type, $ae->fields);
  1039.  
  1040.         $functionName = $ae->type.'Query';
  1041.         $elements = $this->$functionName($ae, $sorted_fields);
  1042.         //total number for progress bar
  1043.         Configuration::updateGlobalValue("AdvancedExport_TOTAL", DB::getInstance()->numRows());
  1044.  
  1045.         $url = $this->writeToFile($ae, $sorted_fields, $elements);
  1046.  
  1047.         $this->saveLastId($ae, $this->lastElement);
  1048.  
  1049.         $this->processFile($ae->save_type, $url, $ae);
  1050.     }
  1051.  
  1052.     public function getLabelsAndFields($type, $fields)
  1053.     {
  1054.         if($fields)
  1055.         {
  1056.             set_time_limit(0);
  1057.  
  1058.             foreach ($fields['fields[]'] as $key => $field)
  1059.             {
  1060.                 $fields['allexportfields'][] = $this->{$type}[$field]['field'];
  1061.                 $fields['labels'][] = $this->{$type}[$field]['name'];
  1062.  
  1063.                 if($this->{$type}[$field]['database'] == 'other')
  1064.                 {
  1065.                     $fields['otherfields'][$this->{$type}[$field]['field']] = $this->{$type}[$field]['field'];
  1066.                 }
  1067.                 else
  1068.                 {
  1069.                     //JeÅ›li jest podany alias w array
  1070.                     //to użyj ten alias jako prefix w nazwie tabeli
  1071.                     //wraz z kropkÄ….
  1072.                     $alias = (isset($this->{$type}[$field]['alias']) ?  $this->{$type}[$field]['alias'].'.' : '');
  1073.  
  1074.                     //jeÅ›li wartość as jest false
  1075.                     //to utwórz polecenie as
  1076.                     //wymagane przy nazwach pól które siÄ™powtarzajÄ…
  1077.                     if (isset($this->{$type}[$field]['as']) && $this->{$type}[$field]['as']) {
  1078.                         $fields['sqlfields'][] = $alias."`".Tools::substr(strstr($this->{$type}[$field]['field'], '_'), Tools::strlen('_'))."` as " .$this->{$type}[$field]['field']."";
  1079.                     }else {
  1080.                         $fields['sqlfields'][] = $alias . "`" . $this->{$type}[$field]['field'] . "`";
  1081.                     }
  1082.                 }
  1083.  
  1084.                 if(isset($this->{$type}[$field]['attribute']) && $this->{$type}[$field]['attribute'] == true)
  1085.                 {
  1086.                     $fields['attribute_fields'][] = $this->{$type}[$field]['field'];
  1087.                 }
  1088.  
  1089.                 if($this->{$type}[$field]['database'] == "order_detail")
  1090.                 {
  1091.                     $fields['order_detail'] = true;
  1092.                     $fields['sqlfields'][] = "od.`product_id`";
  1093.                     $fields['sqlfields'][] = "od.`product_attribute_id`";
  1094.                     $fields['sqlfields'][] = "o.`id_cart`";
  1095.                 }
  1096.             }
  1097.         }
  1098.  
  1099.         return $fields;
  1100.     }
  1101.  
  1102.     //manufacturer name
  1103.  
  1104.     public function writeToFile($ae, $sorted_fields, $elements)
  1105.     {
  1106.         $url = $this->getFileUrl($ae->filename, $ae->type);
  1107.  
  1108.         $file = @fopen( $url, 'w' );
  1109.         //add labels for export data ==== Nascosto da Dario
  1110.         //if($ae->add_header)
  1111.           //$this->filewrite($ae, $sorted_fields, $file);
  1112.  
  1113.         $i = 0;
  1114.         while ($element = $this->nextRow($elements))
  1115.         {
  1116.             if ($i == $this->rowsNumber - 1)
  1117.             {
  1118.                 $this->lastElement = $element;
  1119.             }
  1120.  
  1121.             Configuration::updateGlobalValue("AdvancedExport_CURRENT", (string)$i);
  1122.             //progress bar
  1123.             $this->getDataFromObject($element, $file, $sorted_fields, $ae);
  1124.             $i++; //progress bar
  1125.         }
  1126.  
  1127.         //close file
  1128.         if($file)
  1129.             fclose($file);
  1130.  
  1131.         return $url;
  1132.     }
  1133.  
  1134.     public function nextRow ($elements)
  1135.     {
  1136.         return Db::getInstance(_PS_USE_SQL_SLAVE_)->nextRow($elements);
  1137.     }
  1138.  
  1139.     public function hookAjaxCall()
  1140.     {
  1141.         header("Cache-Control: no-cache, must-revalidate");
  1142.         header("Expires: 0");
  1143.  
  1144.         $action = Tools::getValue('action');
  1145.  
  1146.         switch ($action) {
  1147.             case "getCurrentIndex":
  1148.                 $response = array(
  1149.                     'total' => (int)Configuration::get("AdvancedExport_TOTAL"),
  1150.                     'current' => (int)Configuration::get("AdvancedExport_CURRENT")
  1151.                 );
  1152.                 echo Tools::jsonEncode($response);
  1153.                 break;
  1154.         }
  1155.     }
  1156.  
  1157.     public function getFileUrl($filename, $type)
  1158.     {
  1159.         //open file for write
  1160.         if($filename == null || $filename == "")
  1161.             $filename = $type.date('Y-m-d_His').".csv";
  1162.         else
  1163.             $filename = $filename.".csv";
  1164.  
  1165.         $url = _PS_ROOT_DIR_.'/modules/advancedexport/csv/'.$type;
  1166.         if (!is_dir($url)) {
  1167.             mkdir($url);
  1168.         }
  1169.  
  1170.         return $url.'/'.$filename;
  1171.     }
  1172.  
  1173.     public function getDataFromObject($element, $file, $sorted_fields, $ae)
  1174.     {
  1175.         $id_object = $element[$this->getId($ae->type)];
  1176.         //instance od product object
  1177.         $obj = $this->getObject($id_object, $ae->type);
  1178.         //has attributes clean varible
  1179.         $this->hasAttr = 0;
  1180.         if(isset($sorted_fields['otherfields']))
  1181.         {
  1182.             foreach ($sorted_fields['otherfields'] as $key => $value) {
  1183.                 $run = $ae->type.'_'.$value;
  1184.                 $element[$value] = $this->$run($obj, $ae, $element);
  1185.             }
  1186.         }
  1187.  
  1188.         if($ae->type == "products" && $ae->fields['attributes'] && isset($sorted_fields['attribute_fields']))
  1189.             $this->processWithAttributes($obj, $element, $file, $sorted_fields, $ae);
  1190.  
  1191.         if($this->hasAttr == 0)
  1192.             $this->fputToFile($file, $sorted_fields['allexportfields'], $element, $ae);
  1193.     }
  1194.  
  1195.     //get default category name
  1196.  
  1197.     public function getObject($id_object, $type, $full = false)
  1198.     {
  1199.         switch ($type) {
  1200.             case 'categories':
  1201.                 $type = new Category($id_object);
  1202.                 break;
  1203.             case 'manufacturers':
  1204.                 $type = new Manufacturer($id_object);
  1205.                 break;
  1206.             case 'newsletters':
  1207.                 $type = null;
  1208.                 break;
  1209.             case 'orders':
  1210.                 $type = new Order($id_object);
  1211.                 break;
  1212.             case 'products':
  1213.                 $type = new Product($id_object, $full);
  1214.                 break;
  1215.             case 'suppliers':
  1216.                 $type = new Supplier($id_object);
  1217.                 break;
  1218.             default:
  1219.                 $type = null;
  1220.                 break;
  1221.         }
  1222.  
  1223.         return $type;
  1224.     }
  1225.  
  1226.     //get images url
  1227.  
  1228.     public function processWithAttributes($obj, $element, $file, $sorted_fields, $ae)
  1229.     {
  1230.         $combArray = null;
  1231.         $combArray = $this->getProductCombination($obj, $ae);
  1232.        
  1233.         if (isset($combArray)){
  1234.             $this->hasAttr = 1;
  1235.             foreach ($combArray AS $id_products_attribute => $products_attribute) {
  1236.                 $list = null;
  1237.                 $elementCopy = null;
  1238.                 $elementCopy = $element;
  1239.  
  1240.                 foreach ($sorted_fields['attribute_fields'] as $key => $value) {
  1241.                     $run = 'combination_' . $value;
  1242.                     $elementCopy[$value] = $this->$run($obj, $products_attribute, $ae);
  1243.                 }
  1244.  
  1245.                 $this->fputToFile($file, $sorted_fields['allexportfields'], $elementCopy, $ae);
  1246.             }
  1247.         }
  1248.     }
  1249.  
  1250.     //tags
  1251.  
  1252.     //$dati_csv = $readyForExport[$value];
  1253.     //echo " <script type=\"text/javascript\">alert('$dati_csv')</script>";
  1254.  
  1255.  
  1256. private $count = null; // put this within class
  1257.  
  1258.         private $arr_needed = array();
  1259.  
  1260.         public function set_arr_needed( $arr ) {    
  1261.             $this->arr_needed = $arr;
  1262.         }
  1263.  
  1264.         public function get_arr_needed() {  
  1265.             return $this->arr_needed;
  1266.         }
  1267.  
  1268.  
  1269.         public function fputToFile($file, $allexportfields, $object, $ae)
  1270.         {
  1271.  
  1272.         $arr_needed_in = $this->get_arr_needed(); // array needed already inside
  1273.  
  1274.             if($allexportfields && $file && $object && $ae)
  1275.             {
  1276.                 //one ready for export product
  1277.                 $readyForExport = array();
  1278.  
  1279.  
  1280.                 //put in correct sort order
  1281.                 foreach ($allexportfields as $value)
  1282.                 {
  1283.                     $object = $this->processDecimalSettings($object, $ae, $value);
  1284.                     $readyForExport[$value] = iconv("UTF-8", $ae->charset, $object[$value]);
  1285.  
  1286.                 }
  1287.  
  1288.                 $readyForExport['codice_target'] = $arr_needed_in[0]['codice_target'];
  1289.  
  1290.                 echo '<pre>' . var_dump($readyForExport) . '</pre>';
  1291.  
  1292.                 $this->counter[$readyForExport['id_order']] = (!empty($this->counter[$readyForExport['id_order']])) ? ++$this->counter[$readyForExport['id_order']] : 1; // try here
  1293.                 $readyForExport['orderLine'] = $this->counter[$readyForExport['id_order']]; // and try here
  1294.                
  1295.                 //print_r('The id_order is added: ' . $readyForExport['orderLine']); // see if it is added
  1296.  
  1297.                 //echo '<pre>' . var_dump($readyForExport) . '</pre>';
  1298.  
  1299.                 // modifiche === Dario === prezzo
  1300.                 $newPrice = substr($readyForExport['product_price'], 0, strpos($readyForExport['product_price'], "."));
  1301.                 $readyForExport['product_price'] = $newPrice;
  1302.  
  1303.                 // === data
  1304.  
  1305.                 $newDateAdd = new DateTime($readyForExport['date_add']);
  1306.                 $readyForExport['date_add'] = $newDateAdd->format('d/m/Y');
  1307.  
  1308.  
  1309.                 // aggiungo 21 giorni - 3 settimane - alla data di acquisto
  1310.                 $date_mod = clone $newDateAdd;
  1311.                 $date_mod->add(new DateInterval('P21D'));
  1312.                 $readyForExport['delivery_date'] = $date_mod->format('d/m/Y');
  1313.  
  1314.                 // === data invoice
  1315.                 $newDateInvoice = clone $newDateAdd;
  1316.                 $readyForExport['invoice_date'] = $newDateAdd->format('d/m/Y');
  1317.  
  1318.                 //scambio l'id customer con il codice_target
  1319.  
  1320.                 //$readyForExport['codice_target'] = 8989;
  1321.  
  1322.                 $textTarget = (string)$readyForExport['codice_target'];
  1323.  
  1324.                 $readyForExport['id_customer'] = $textTarget;
  1325.  
  1326.                 // aggiungo gli zeri davanti al customer id
  1327.                 $id_count = strlen($readyForExport['id_customer']);            
  1328.                 if ($id_count == 1) {
  1329.                    
  1330.                     $newCustomer = "0000000".$readyForExport['id_customer'];
  1331.                     $readyForExport['id_customer'] = $newCustomer;
  1332.                    
  1333.                 }elseif ($id_count == 2) {
  1334.                    
  1335.                     $newCustomer = "000000".$readyForExport['id_customer'];
  1336.                     $readyForExport['id_customer'] = $newCustomer;
  1337.                    
  1338.                 }elseif ($id_count == 3) {
  1339.                    
  1340.                     $newCustomer = "00000".$readyForExport['id_customer'];
  1341.                     $readyForExport['id_customer'] = $newCustomer;
  1342.                    
  1343.                 }elseif ($id_count == 4) {
  1344.                     $newCustomer = "0000".$readyForExport['id_customer'];
  1345.                     $readyForExport['id_customer'] = $newCustomer;
  1346.                    
  1347.                 }elseif ($id_count == 5) {
  1348.                     $newCustomer = "000".$readyForExport['id_customer'];
  1349.                     $readyForExport['id_customer'] = $newCustomer;
  1350.                    
  1351.                 }elseif ($id_count == 6) {
  1352.                     $newCustomer = "00".$readyForExport['id_customer'];
  1353.                     $readyForExport['id_customer'] = $newCustomer;
  1354.                    
  1355.                 }
  1356.  
  1357.                 // elaboro lo SKU
  1358.  
  1359.                 $textSku = (string)$readyForExport['product_name'];
  1360.                
  1361.                 $newSku_1 = $readyForExport['product_name'];
  1362.  
  1363.                 $newSku_1 = substr($newSku_1,0,4);
  1364.                 $newSku_2 = "/".substr($textSku,-4,4);
  1365.  
  1366.                 $newSku_tot = $newSku_1.$newSku_2;
  1367.                
  1368.                 $newSku_tot = str_replace(' ', '', $newSku_tot);
  1369.                 $newSku_tot = str_replace('-', '', $newSku_tot);
  1370.                 $newSku_tot = str_replace('co', '', $newSku_tot);
  1371.                
  1372.                 $newSku_tot = str_replace('e', '', $newSku_tot);
  1373.                 $newSku_tot = str_replace('r', '', $newSku_tot);
  1374.  
  1375.                 $readyForExport['product_name'] = $newSku_tot;
  1376.  
  1377.  
  1378.  
  1379.                 // aggiungo un campo fisso
  1380.                 $readyForExport['causale'] = "NR";
  1381.  
  1382.                 // aggiungo un campo fisso
  1383.                 $readyForExport['ORCL'] = "ORCL";
  1384.            
  1385.                 //$readyForExport['G'] = "";
  1386.                 $readyForExport['J'] = "";
  1387.                 $readyForExport['K'] = "";
  1388.                 $readyForExport['L'] = "";
  1389.                 $readyForExport['M'] = "";
  1390.                 $readyForExport['N'] = "";
  1391.                 $readyForExport['P'] = "";
  1392.                 $readyForExport['Q'] = "";
  1393.                 $readyForExport['R'] = "30";
  1394.  
  1395.                 $index_arr=array("id_customer","date_add","ORCL","product_name","causale","product_quantity","product_price","delivery_date","id_order","J","K","L","M","N","orderLine","P","Q","R");
  1396.  
  1397.                 //riordino i campi in base a come li dispongo nella variabile $index_arr
  1398.                 $arr_t=array();
  1399.                 foreach($index_arr as $i=>$v) {
  1400.                     foreach($readyForExport as $k=>$b) {
  1401.                         if ($k==$v) $arr_t[$k]=$b;
  1402.                     }
  1403.                 }
  1404.                 $readyForExport=$arr_t;
  1405.  
  1406.                 //write into csv line by line
  1407.                 fputcsv($file, $readyForExport, $ae->delimiter, $ae->separator);
  1408.             }
  1409.         }
  1410.  
  1411.     //tags
  1412.  
  1413.     public function saveLastId($ae, $myLastElement)
  1414.     {
  1415.         if($ae->only_new && isset($myLastElement[$this->getId($ae->type)]))
  1416.         {
  1417.             $ae->last_exported_id = $myLastElement[$this->getId($ae->type)];
  1418.             $ae->fields = Tools::jsonEncode($ae->fields);
  1419.             $ae->save();
  1420.         }
  1421.  
  1422.         return $ae;
  1423.     }
  1424.  
  1425.     public function getId ($type)
  1426.     {
  1427.         $id = '';
  1428.         switch ($type) {
  1429.             case "categories":
  1430.                 $id = "id_category";
  1431.                 break;
  1432.             case "customers":
  1433.                 $id = "id_customer";
  1434.                 break;
  1435.             case "manufacturers":
  1436.                 $id = "id_manufacturer";
  1437.                 break;
  1438.             case "newsletters":
  1439.                 $id = "id";
  1440.                 break;
  1441.             case "orders":
  1442.                 $id = "id_order";
  1443.                 break;
  1444.             case "products":
  1445.                 $id = "id_product";
  1446.                 break;
  1447.             case "suppliers":
  1448.                 $id = "id_supplier";
  1449.                 break;
  1450.         }
  1451.         return $id;
  1452.     }
  1453.  
  1454.  
  1455.     public function processFile($process, $url, $ae)
  1456.     {
  1457.         switch ($process)
  1458.         {
  1459.             case 0:
  1460.             break;
  1461.             case 1:
  1462.                 $this->ftpFile($ae->ftp_hostname, $ae->ftp_user_name, $ae->ftp_user_pass, $url);
  1463.             break;
  1464.             case 2:
  1465.                 $this->sentFile($url, $ae->email);
  1466.             break;
  1467.             default:
  1468.             break;
  1469.         }
  1470.     }
  1471.  
  1472.     public function ftpFile($ftp_hostname, $ftp_user_name, $ftp_user_pass, $export_file )
  1473.     {
  1474.         // open some file for reading
  1475.         $file = basename($export_file);
  1476.         $fp = fopen($export_file, 'r');
  1477.  
  1478.         // set up basic connection
  1479.         $conn = ftp_connect($ftp_hostname);
  1480.  
  1481.         // login with username and password
  1482.         $login_result = ftp_login($conn, $ftp_user_name, $ftp_user_pass);
  1483.  
  1484.         // try to upload $file
  1485.         if (ftp_fput($conn, $file, $fp, FTP_BINARY))
  1486.             echo "Successfully uploaded $file\n";
  1487.         else
  1488.             echo "There was a problem while uploading $file\n";
  1489.  
  1490.         // close the connection and the file handler
  1491.         ftp_close($conn);
  1492.         fclose($fp);
  1493.     }
  1494.  
  1495.             public function sentFile($export_file, $email)
  1496.             {
  1497.                 $file_attachement = null;
  1498.                 $file_attachement['content'] = Tools::file_get_contents($export_file);
  1499.                 $file_attachement['name'] = "export file";
  1500.                 $file_attachement['mime'] = 'text/csv';
  1501.  
  1502.                 $id_lang = $this->getConfiguration("PS_LANG_DEFAULT");
  1503.                 Mail::Send($id_lang, 'index', 'index', null, $email, null, null, "advanced export", $file_attachement, null, dirname(__FILE__).'/mails/');
  1504.             }
  1505.  
  1506.     public function getConfiguration($value)
  1507.     {
  1508.         return (int)Configuration::get($value);
  1509.     }
  1510.  
  1511.     public function displayIndexForm()
  1512.     {
  1513.         $html = '<script type="text/javascript">
  1514.            var urlJson = "index.php?controller=AdminModules&configure=advancedexport&module_name=advancedexport&token='.Tools::getAdminTokenLite("AdminModules").'";
  1515.        </script>';
  1516.         $html .= '<div class="row">';
  1517.             $html .= '<div class="col-lg-12">';
  1518.                 $html .= '<div id="loader-container">';
  1519.                     $html .= '<div id="topLoader"> </div>';
  1520.                 $html .= '</div>';
  1521.                 $html .= '<div class="row">';
  1522.                     $html .= '<div class="col-lg-2 col-md-3">';
  1523.                         $html .= '<div class="list-group">';
  1524.                             foreach ($this->export_types as $key => $value)
  1525.                             {
  1526.                                 $html .= '<a href="#" id="'.$value.'" class="list-group-item">'.$value.'</a>';
  1527.                             }
  1528.                         $html .= '</div>';
  1529.                     $html .= '</div>';
  1530.                     $html .= '<div class="form-horizontal col-lg-10">';
  1531.                         $html .= '<div class="list-group">';
  1532.  
  1533.                             foreach ($this->export_types as $key => $value)
  1534.                             {
  1535.                                 $html .= "<div class='product-tab-content hide' alt='$value'>";
  1536.                                 $html .= $this->displayModelListForm($helper = new HelperList(), $value);
  1537.                                 $html .= $this->displayFilesForm($helper = new HelperList(), $value);
  1538.                                 $html .= '</div>';
  1539.                             }
  1540.                         $html .= '</div>';
  1541.                     $html .= '</div>';
  1542.                 $html .= '</div>';
  1543.             $html .= '</div>';
  1544.         $html .= '</div>';
  1545.  
  1546.         return $html;
  1547.  
  1548.  
  1549.  
  1550.     }
  1551.  
  1552.     public function displayModelListForm($helper, $type)
  1553.     {
  1554.         $this->fields_list = $this->listFieldsForm();
  1555.         $links = $this->getLinks($type);
  1556.         $this->_display = 'index';
  1557.         $helper->module = $this;
  1558.         $helper->identifier = 'id_advancedexport';
  1559.         $helper->actions = array('edit', 'duplicate', 'delete');
  1560.         $helper->show_toolbar = true;
  1561.         //$helper->simple_header = true;
  1562.         $helper->shopLinkType = '';
  1563.         $helper->listTotal = count($links);
  1564.         $helper->toolbar_btn = $this->initToolbar($type);
  1565.         $helper->title = $type." models";
  1566.         $helper->table = 'advancedexport';
  1567.         $helper->token = Tools::getAdminTokenLite('AdminModules');
  1568.         $helper->currentIndex = AdminController::$currentIndex.'&configure='.$this->name;
  1569.         $helper->tpl_vars['version'] = false;
  1570.         return $helper->generateList($links, $this->fields_list);
  1571.     }
  1572.  
  1573.     public function listFieldsForm()
  1574.     {
  1575.         return array(
  1576.             'id_advancedexport' => array(
  1577.                 'title' => $this->l('ID'),
  1578.                 'width' => 20
  1579.             ),
  1580.             'name' => array(
  1581.                 'title' => $this->l('Name'),
  1582.                 'width' => 100
  1583.             ),
  1584.             'cron_url' => array(
  1585.                 'title' => $this->l('Cron url'),
  1586.                 'type' => 'html'
  1587.             ),
  1588.             'save_type' => array(
  1589.                 'title' => $this->l('Save Type'),
  1590.                 'width' => 30
  1591.             ),
  1592.             'only_new' => array(
  1593.                 'title' => $this->l('New entries'),
  1594.                 'active' => 'only_new',
  1595.                 'type' => 'bool',
  1596.                 'align' => 'center',
  1597.                 'width' => 30,
  1598.                 'orderby' => false
  1599.             )
  1600.         );
  1601.     }
  1602.  
  1603.     //get features
  1604.  
  1605.     public function DbExecuteS($query)
  1606.     {
  1607.         return Db::getInstance()->ExecuteS( $query );
  1608.     }
  1609.  
  1610.  
  1611.     //price tax
  1612.  
  1613.     public function initToolbar($type)
  1614.     {
  1615.         $current_index = AdminController::$currentIndex;
  1616.         $token = Tools::getAdminTokenLite('AdminModules');
  1617.  
  1618.         $back = Tools::safeOutput(Tools::getValue('back', ''));
  1619.  
  1620.         if (!isset($back) || empty($back))
  1621.             $back = $current_index.'&configure='.$this->name.'&token='.$token;
  1622.  
  1623.         switch ($this->_display)
  1624.         {
  1625.             case 'add':
  1626.                 $this->toolbar_btn['cancel'] = array(
  1627.                 'href' => $back,
  1628.                 'desc' => $this->l('Cancel')
  1629.             );
  1630.             break;
  1631.             case 'edit':
  1632.                 $this->toolbar_btn['cancel'] = array(
  1633.                 'href' => $back,
  1634.                 'desc' => $this->l('Cancel')
  1635.             );
  1636.             break;
  1637.             case 'index':
  1638.                 $this->toolbar_btn['new'] = array(
  1639.                     'href' => $current_index.'&configure='.$this->name.'&token='.$token.'&add_model=1&type='.$type,
  1640.                     'desc' => $this->l('Add new')
  1641.                                            );
  1642.              break;
  1643.              default:
  1644.             break;
  1645.         }
  1646.  
  1647.         return $this->toolbar_btn;
  1648.     }
  1649.  
  1650.     //price tax without discount
  1651.  
  1652.     public function displayFilesForm($helper, $type)
  1653.     {
  1654.         $this->fields_list = $this->filesFieldsForm();
  1655.         $files = $this->getFiles($type);
  1656.         $this->_display = 'index';
  1657.         $helper->module = $this;
  1658.         $helper->identifier = 'url';
  1659.         $helper->simple_header = true;
  1660.         $helper->actions = array('view', 'delete');
  1661.         $helper->show_toolbar = true;
  1662.         $helper->shopLinkType = '';
  1663.         $helper->listTotal = count($files);
  1664.         $helper->title = $type.' files ';
  1665.         $helper->table = 'files';
  1666.         $helper->token = Tools::getAdminTokenLite('AdminModules');
  1667.         $helper->currentIndex = AdminController::$currentIndex.'&configure='.$this->name;
  1668.  
  1669.         return $helper->generateList($files, $this->fields_list);
  1670.     }
  1671.  
  1672.     public function format_size($size) {
  1673.         $sizes = array(" Bytes", " KB", " MB", " GB", " TB", " PB", " EB", " ZB", " YB");
  1674.         if ($size == 0) { return('n/a'); } else {
  1675.             return (round($size/pow(1024, ($i = floor(log($size, 1024)))), 2) . $sizes[$i]); }
  1676.     }
  1677.  
  1678.     public function filesFieldsForm()
  1679.     {
  1680.         return array(
  1681.             'id_file' => array(
  1682.                 'title' => $this->l('ID'),
  1683.                 'width' => 25
  1684.             ),
  1685.             'name' => array(
  1686.                 'title' => $this->l('Name'),
  1687.                 'width' => 100
  1688.             ),
  1689.             'filesize' => array(
  1690.                 'title' => $this->l('File size'),
  1691.                 'width' => 100
  1692.             )
  1693.         );
  1694.      }
  1695.  
  1696.     //wholesale_price
  1697.  
  1698.     public function getFiles($type)
  1699.     {
  1700.         $dirname = _PS_ROOT_DIR_.'/modules/advancedexport/csv/'.$type.'/';
  1701.         $files = glob($dirname.'*.{csv}', GLOB_BRACE);
  1702.  
  1703.         $result = array();
  1704.         $lp = 1;
  1705.  
  1706.         if($files){
  1707.             foreach ($files as $key => $value)
  1708.             {
  1709.                 $result[] = array(
  1710.                     'id_file' => $lp,
  1711.                     'name' => basename($value),
  1712.                     'filesize' => $this->format_size(filesize($value)),
  1713.                     'url' => urlencode($type.'/'.basename($value))
  1714.                 );
  1715.                 $lp++;
  1716.             }
  1717.         }
  1718.         return $result;
  1719.     }
  1720.  
  1721.  
  1722.     public function getFile($url)
  1723.     {
  1724.         $dir = (string)realpath(dirname(__FILE__).'/csv/'.$url);
  1725.         if(file_exists($dir))
  1726.         {
  1727.             header('Content-Description: File Transfer');
  1728.             header('Content-Type: application/csv');
  1729.             header('Content-Disposition: attachment; filename='.basename($dir));
  1730.             header('Content-Transfer-Encoding: binary');
  1731.             header('Expires: 0');
  1732.             header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
  1733.             header('Pragma: public');
  1734.             header('Content-Length: ' . filesize($dir));
  1735.             ob_clean();
  1736.             flush();
  1737.             readfile($dir);
  1738.             exit;
  1739.         }
  1740.     }
  1741.  
  1742.     public function cronTask()
  1743.     {
  1744.         Context::getContext()->link = new Link();
  1745.         $id = Tools::getValue('id');
  1746.         $this->getExportType($id);
  1747.     }
  1748.  
  1749.     public function deleteFile($url)
  1750.     {
  1751.         $dir = (string)realpath(dirname(__FILE__).'/csv/'.$url);
  1752.         if(file_exists($dir))
  1753.             unlink($dir);
  1754.     }
  1755.  
  1756.     public function productsFormFields()
  1757.     {
  1758.         $fields = array(
  1759.             array(
  1760.                 'type'  => 'bsmselect',
  1761.                 'label' => $this->l('Products fields'),
  1762.                 'name'  => 'fields[]',
  1763.                 'id'  => 'fields',
  1764.                 'class' => 'sminit, ds-select',
  1765.                 'multiple' => true,
  1766.                 'options' => array(
  1767.                     'query' => $this->addToFieldId($this->products),
  1768.                     'id' => 'id',
  1769.                     'name' => 'name'
  1770.                 )
  1771.             ),
  1772.             array(
  1773.                 'type' => $this->switch,
  1774.                 'label' => $this->l('Active products only'),
  1775.                 'name' => 'active',
  1776.                 'class' => 't',
  1777.                 'is_bool' => true,
  1778.                 'values' => array(
  1779.                     array(
  1780.                         'id' => 'active_on',
  1781.                         'value' => 1,
  1782.                         'label' => $this->l('Yes')
  1783.                      ),
  1784.                     array(
  1785.                         'id' => 'active_off',
  1786.                         'value' => 0,
  1787.                         'label' => $this->l('No')
  1788.                      )
  1789.                 ),
  1790.             ),
  1791.             array(
  1792.                 'type' => $this->switch,
  1793.                 'label' => $this->l('Products out of stock'),
  1794.                 'name' => 'out_of_stock',
  1795.                 'class' => 't',
  1796.                 'is_bool' => true,
  1797.                 'values' => array(
  1798.                     array(
  1799.                         'id' => 'active_on',
  1800.                         'value' => 1,
  1801.                         'label' => $this->l('Yes')
  1802.                      ),
  1803.                     array(
  1804.                         'id' => 'active_off',
  1805.                         'value' => 0,
  1806.                         'label' => $this->l('No')
  1807.                      )
  1808.                 ),
  1809.             ),
  1810.             array(
  1811.                 'type' => $this->switch,
  1812.                 'label' => $this->l('Products with ean13'),
  1813.                 'name' => 'ean',
  1814.                 'class' => 't',
  1815.                 'is_bool' => true,
  1816.                 'values' => array(
  1817.                     array(
  1818.                         'id' => 'active_on',
  1819.                         'value' => 1,
  1820.                         'label' => $this->l('Yes')
  1821.                      ),
  1822.                     array(
  1823.                         'id' => 'active_off',
  1824.                         'value' => 0,
  1825.                         'label' => $this->l('No')
  1826.                      )
  1827.                 ),
  1828.             ),
  1829.             array(
  1830.                 'type' => $this->switch,
  1831.                 'label' => $this->l('Export attributes'),
  1832.                 'name' => 'attributes',
  1833.                 'is_bool' => true,
  1834.                 'class' => 't',
  1835.                 'desc' =>$this->l('Each combination will be exported in new line and specific values will be overwrite'),
  1836.                 'values' => array(
  1837.                     array(
  1838.                         'id' => 'active_on',
  1839.                         'value' => 1,
  1840.                         'label' => $this->l('Yes')
  1841.                      ),
  1842.                     array(
  1843.                         'id' => 'active_off',
  1844.                         'value' => 0,
  1845.                         'label' => $this->l('No')
  1846.                     )
  1847.                 ),
  1848.             ),
  1849.             array(
  1850.                 'type'  => 'select',
  1851.                 'label' => $this->l('Suppliers'),
  1852.                 'name'  => 'suppliers[]',
  1853.                 'id'  => 'suppliers',
  1854.                 'class' => 'ds-select',
  1855.                 'multiple' => true,
  1856.                 'desc' =>$this->l('If you want all leave blank. All are exported by default.'),
  1857.                 'options' => array(
  1858.                     'query' => Supplier::getSuppliers(false, $this->getConfiguration('PS_LANG_DEFAULT')),
  1859.                     'id' => 'id_supplier',
  1860.                     'name' => 'name'
  1861.                 )
  1862.             ),
  1863.             array(
  1864.                 'type'  => 'select',
  1865.                 'label' => $this->l('Manufacturers'),
  1866.                 'name'  => 'manufacturers[]',
  1867.                 'id'  => 'manufacturers',
  1868.                 'class' => 'ds-select',
  1869.                 'desc' =>$this->l('If you want all leave blank. All are exported by default.'),
  1870.                 'multiple' => true,
  1871.                 'options' => array(
  1872.                     'query' => Manufacturer::getManufacturers(false, $this->getConfiguration('PS_LANG_DEFAULT')),
  1873.                     'id' => 'id_manufacturer',
  1874.                     'name' => 'name'
  1875.                 )
  1876.             )
  1877.         );
  1878.         if(_PS_VERSION_ >= 1.6) {
  1879.             $fields[] = array(
  1880.                 'type' => 'categories',
  1881.                 'label' => $this->l('Categories'),
  1882.                 'name' => 'categories',
  1883.                 'desc' =>$this->l('If you want all leave blank. All are exported by default.'),
  1884.                 'tree' => array(
  1885.                     'id' => 'categories-tree',
  1886.                     'selected_categories' => $this->selected_cat,
  1887.                     'use_search' => true,
  1888.                     'use_checkbox' => true
  1889.                 )
  1890.             );
  1891.         }
  1892.         else
  1893.         {
  1894.             $root_category = Category::getRootCategory();
  1895.             $root_category = array('id_category' => $root_category->id, 'name' => $root_category->name);
  1896.  
  1897.             $fields[] = array(
  1898.                 'type' => 'categories',
  1899.                 'label' => $this->l('Parent category:'),
  1900.                 'name' => 'categories',
  1901.                 'values' => array(
  1902.                     'trads' => array(
  1903.                         'Root' => $root_category,
  1904.                         'selected' => $this->l('Selected'),
  1905.                         'Collapse All' => $this->l('Collapse All'),
  1906.                         'Expand All' => $this->l('Expand All'),
  1907.                         'Check All' => $this->l('Check All'),
  1908.                         'Uncheck All' => $this->l('Uncheck All'),
  1909.                     ),
  1910.                     'selected_cat' => ($this->selected_cat ? $this->selected_cat : array()),
  1911.                     'input_name' => 'categories[]',
  1912.                     'disabled_categories' => array(),
  1913.                     'use_checkbox' => true,
  1914.                     'use_radio' => false,
  1915.                     'use_search' => false,
  1916.                     'top_category' => Category::getTopCategory(),
  1917.                     'use_context' => true,
  1918.                 )
  1919.             );
  1920.         }
  1921.  
  1922.         return $fields;
  1923.     }
  1924.  
  1925.     public function addToFieldId($fields)
  1926.     {
  1927.         for ($i = 0; $i < count($fields); $i++) {
  1928.             //add id
  1929.             $fields[$i]['id'] = $i;
  1930.         }
  1931.  
  1932.         return $fields;
  1933.     }
  1934.  
  1935.     public function productsQuery($ae, $set)
  1936.     {
  1937.         $sql = 'SELECT p.`id_product` '.(empty($set['sqlfields']) ? "" : ', '.implode(', ', $set['sqlfields'])).
  1938.             ' FROM '._DB_PREFIX_.'product as p'.
  1939.             Shop::addSqlAssociation('product', 'p').'
  1940.            LEFT JOIN `'._DB_PREFIX_.'product_lang` pl ON (p.`id_product` = pl.`id_product` '.Shop::addSqlRestrictionOnLang('pl').')
  1941.            LEFT JOIN `'._DB_PREFIX_.'supplier` s ON (p.`id_supplier` = s.`id_supplier`)
  1942.            LEFT JOIN `'._DB_PREFIX_.'manufacturer` m ON (m.`id_manufacturer` = p.`id_manufacturer`)'.
  1943.             (isset($set['categories']) && $set['categories']   ? ' LEFT JOIN `'._DB_PREFIX_.'category_product` c ON (c.`id_product` = p.`id_product`)' : '').'
  1944.             WHERE pl.`id_lang` = '.(int)$ae->id_lang.
  1945.             (isset($ae->only_new) && $ae->only_new && $ae->last_exported_id ? ' AND p.`id_product` > '.$ae->last_exported_id : '').
  1946.             ($ae->only_new == false && $ae->start_id ? ' AND p.`id_product` >= '.$ae->start_id : '').
  1947.             ($ae->only_new == false && $ae->end_id ? ' AND p.`id_product` <= '.$ae->end_id : '').
  1948.             (isset($set['categories']) && $set['categories']  ? ' AND c.`id_category` IN ('.implode(",", $set['categories'] ).')' : '').
  1949.             (isset($set['suppliers[]'] ) && $set['suppliers[]']     ? ' AND p.`id_supplier` IN ('.implode(",", $set['suppliers[]']).')' : '').
  1950.             (isset($set['manufacturers[]']) && $set['manufacturers[]']  ? ' AND p.`id_manufacturer` IN ('.implode(",",$set['manufacturers[]']).')' : '').
  1951.             (isset($set['active']) && $set['active']  ? ' AND product_shop.`active` = 1' : '').
  1952.             (isset($set['out_of_stock']) && $set['out_of_stock']  ? ' AND p.`quantity` <= 0' : '').
  1953.             (isset($set['ean13']) && $set['ean13']  ? ' AND p.`ean13` != ""' : '').
  1954.             (isset($ae->date_from) && $ae->date_from &&  !$ae->only_new ? ' AND p.`date_add` >= "'.($ae->date_from).'"' : '').
  1955.             (isset($ae->date_to) && $ae->date_to &&  !$ae->only_new ? ' AND p.`date_add` <= "'.($ae->date_to).'"' : '').
  1956.             ' GROUP BY p.`id_product`';
  1957.  
  1958.         $result = $this->query($sql);
  1959.         $this->rowsNumber = $this->query("SELECT FOUND_ROWS()")->fetchColumn();
  1960.         return $result;
  1961.     }
  1962.  
  1963.     public function ExecuteS($sql)
  1964.     {
  1965.         return Db::getInstance()->ExecuteS($sql);
  1966.     }
  1967.  
  1968.     public function Execute($sql)
  1969.     {
  1970.         return Db::getInstance()->Execute($sql);
  1971.     }
  1972.  
  1973.     public function query($sql_query)
  1974.     {
  1975.         return Db::getInstance(_PS_USE_SQL_SLAVE_)->query($sql_query);
  1976.     }
  1977.  
  1978.     public function products_attributes_name($obj)
  1979.     {
  1980.         return null;
  1981.     }
  1982.  
  1983.     public function products_supplier_name_all($obj)
  1984.     {
  1985.         $sups = $this->executeS('
  1986.         SELECT DISTINCT(s.`name`)
  1987.         FROM `'._DB_PREFIX_.'product_supplier` ps
  1988.         LEFT JOIN `'._DB_PREFIX_.'supplier` s ON (ps.`id_supplier`= s.`id_supplier`)
  1989.         LEFT JOIN `'._DB_PREFIX_.'product` p ON (ps.`id_product`= p.`id_product`)
  1990.         WHERE ps.`id_product` = '.$obj->id);
  1991.         $suppliers = array();
  1992.         foreach($sups as $sup) {
  1993.             $suppliers[] = $sup['name'];
  1994.         }
  1995.  
  1996.         return implode(',', $suppliers);
  1997.     }
  1998.  
  1999.     public function products_id_supplier_all($obj)
  2000.     {
  2001.         $sups = $this->executeS('
  2002.         SELECT DISTINCT(ps.`id_supplier`)
  2003.         FROM `'._DB_PREFIX_.'product_supplier` ps
  2004.         JOIN `'._DB_PREFIX_.'product` p ON (ps.`id_product`= p.`id_product`)
  2005.         WHERE ps.`id_product` = '.$obj->id);
  2006.         $suppliers = array();
  2007.         foreach($sups as $sup) {
  2008.             $suppliers[] = $sup['id_supplier'];
  2009.         }
  2010.         return implode(',', $suppliers);
  2011.     }
  2012.  
  2013.     public function products_features($obj, $ae)
  2014.     {
  2015.         $features = $obj->getFrontFeaturesStatic($ae->id_lang, $obj->id);
  2016.         $feats = array();
  2017.         foreach($features as $feature) {
  2018.             $feats[] = $feature['name'] .'-'. $feature['value'];
  2019.         }
  2020.         return implode(",", $feats);
  2021.     }
  2022.  
  2023.     public function products_price_tax($obj)
  2024.     {
  2025.         return $obj->getPrice(true);
  2026.     }
  2027.  
  2028.     public function products_tax_rate($obj)
  2029.     {
  2030.         return $obj->getTaxesRate();
  2031.     }
  2032.  
  2033.     public function products_quantity($obj)
  2034.     {
  2035.         return Product::getQuantity((int)$obj->id);
  2036.     }
  2037.  
  2038.     public function products_price_tax_nodiscount($obj)
  2039.     {
  2040.         return $obj->getPrice(true, null, 6, null, false, false);
  2041.     }
  2042.  
  2043.     public function products_url_product($obj, $ae)
  2044.     {
  2045.         $category = Category::getLinkRewrite((int)$obj->id_category_default, (int)$ae->id_lang);
  2046.         return $this->context->link->getProductLink((int)$obj->id, $obj->link_rewrite[$ae->id_lang], $category);
  2047.     }
  2048.  
  2049.     public function products_manufacturer_name($obj)
  2050.     {
  2051.         return $obj->getWsManufacturerName();
  2052.     }
  2053.  
  2054.     public function products_categories_names($obj, $ae)
  2055.     {
  2056.         $categories = $obj->getCategories();
  2057.         $cats = array();
  2058.         foreach($categories as $cat) {
  2059.             $category = new Category($cat, $ae->id_lang);
  2060.             $cats[] = $category->name;
  2061.         }
  2062.         return implode(",", $cats);
  2063.     }
  2064.  
  2065.     public function products_categories_ids($obj, $ae)
  2066.     {
  2067.         $categories = $obj->getCategories();
  2068.         $cats = array();
  2069.         foreach($categories as $cat) {
  2070.             $category = new Category($cat, $ae->id_lang);
  2071.             $cats[] = $category->id;
  2072.         }
  2073.         return implode(",", $cats);
  2074.     }
  2075.  
  2076.     public function products_nameCategoryDefault($obj, $ae)
  2077.     {
  2078.         $category = new Category($obj->id_category_default, $ae->id_lang);
  2079.         return $category->name;
  2080.     }
  2081.  
  2082.     public function products_images($obj, $ae)
  2083.     {
  2084.         $imagelinks = array();
  2085.         $images = $obj->getImages($obj->id);
  2086.         foreach($images as $image) {
  2087.             $imagelinks[] = $this->link->getImageLink($obj->link_rewrite[$ae->id_lang], $obj->id .'-'. $image['id_image'], $ae->image_type);
  2088.         }
  2089.         return implode(",", $imagelinks);
  2090.     }
  2091.  
  2092.     public function products_tags($obj)
  2093.     {
  2094.         return $obj->getTags(1);
  2095.     }
  2096.  
  2097.     public function products_accessories($obj, $ae)
  2098.     {
  2099.         if($accessories = $obj->getAccessories($ae->id_lang, false)) {
  2100.             foreach($accessories as $value)
  2101.             {
  2102.                 $accessories[] = $value['reference'];
  2103.             }
  2104.             return implode(',', $accessories);
  2105.         } else {
  2106.             return '';
  2107.         }
  2108.     }
  2109.  
  2110.     public function getProductCombination($obj, $ae)
  2111.     {
  2112.         $combArray = null;
  2113.         $groups = null;
  2114.  
  2115.         $combinaisons = $obj->getAttributeCombinations((int)($ae->id_lang));
  2116.         if (is_array($combinaisons))
  2117.         {
  2118.             $combinationImages = $obj->getCombinationImages((int)($ae->id_lang));
  2119.  
  2120.             foreach ($combinaisons AS $k => $combinaison)
  2121.             {
  2122.                 $combArray[$combinaison['id_product_attribute']]['wholesale_price'] = $combinaison['wholesale_price'];
  2123.                 $combArray[$combinaison['id_product_attribute']]['price'] = $combinaison['price'];
  2124.                 $combArray[$combinaison['id_product_attribute']]['weight'] = $combinaison['weight'];
  2125.                 $combArray[$combinaison['id_product_attribute']]['unit_impact'] = $combinaison['unit_price_impact'];
  2126.                 $combArray[$combinaison['id_product_attribute']]['reference'] = $combinaison['reference'];
  2127.                 $combArray[$combinaison['id_product_attribute']]['supplier_reference'] = $combinaison['supplier_reference'];
  2128.                 $combArray[$combinaison['id_product_attribute']]['ean13'] = $combinaison['ean13'];
  2129.                 $combArray[$combinaison['id_product_attribute']]['upc'] = $combinaison['upc'];
  2130.                 $combArray[$combinaison['id_product_attribute']]['minimal_quantity'] = $combinaison['minimal_quantity'];
  2131.                 $combArray[$combinaison['id_product_attribute']]['location'] = $combinaison['location'];
  2132.                 $combArray[$combinaison['id_product_attribute']]['quantity'] = $combinaison['quantity'];
  2133.                 $combArray[$combinaison['id_product_attribute']]['id_image'] = isset($combinationImages[$combinaison['id_product_attribute']][0]['id_image']) ? $combinationImages[$combinaison['id_product_attribute']][0]['id_image'] : 0;
  2134.                 //$combArray[$combinaison['id_products_attribute']]['default_on'] = $combinaison['default_on'];
  2135.                 $combArray[$combinaison['id_product_attribute']]['ecotax'] = $combinaison['ecotax'];
  2136.                 $combArray[$combinaison['id_product_attribute']]['id_product_attribute'] = $combinaison['id_product_attribute'];
  2137.                 $combArray[$combinaison['id_product_attribute']]['attributes'][] = array($combinaison['group_name'], $combinaison['attribute_name'], $combinaison['id_attribute']);
  2138.                 if ($combinaison['is_color_group'])
  2139.                     $groups[$combinaison['id_attribute_group']] = $combinaison['group_name'];
  2140.             }
  2141.         }
  2142.         return $combArray;
  2143.     }
  2144.  
  2145.     public function combination_supplier_name_all($obj, $product_attribute, $ae)
  2146.     {
  2147.         $sups = $this->executeS('
  2148.            SELECT DISTINCT(s.`name`)
  2149.            FROM `'._DB_PREFIX_.'product_supplier` ps
  2150.            LEFT JOIN `'._DB_PREFIX_.'supplier` s ON (ps.`id_supplier`= s.`id_supplier`)
  2151.            LEFT JOIN `'._DB_PREFIX_.'product` p ON (ps.`id_product`= p.`id_product`)
  2152.            WHERE ps.`id_product` = '.$obj->id.' AND ps.id_product_attribute='.(int)$product_attribute['id_product_attribute']);
  2153.         $suppliers = array();
  2154.         foreach($sups as $sup) {
  2155.             $suppliers[] = $sup['name'];
  2156.         }
  2157.         return implode(',', $suppliers);
  2158.     }
  2159.  
  2160.     public function combination_id_supplier_all($obj, $product_attribute)
  2161.     {
  2162.         $sups = $this->executeS('
  2163.             SELECT DISTINCT(ps.`id_supplier`)
  2164.             FROM `'._DB_PREFIX_.'product_supplier` ps
  2165.             JOIN `'._DB_PREFIX_.'product` p ON (ps.`id_product`= p.`id_product`)
  2166.             WHERE ps.`id_product` = '.$obj->id.' AND ps.id_product_attribute='.(int)$product_attribute['id_product_attribute']);
  2167.  
  2168.         $suppliers = array();
  2169.         foreach($sups as $sup)
  2170.             $suppliers[] = $sup['id_supplier'];
  2171.  
  2172.         return implode(',', $suppliers);
  2173.     }
  2174.  
  2175.     public function combination_attributes_name($obj, $products_attribute)
  2176.     {
  2177.         $name = null;
  2178.         foreach ($products_attribute['attributes'] AS $attribute)
  2179.         {
  2180.             $name .= addslashes(htmlspecialchars($attribute[0])).': '.addslashes(htmlspecialchars($attribute[1])).' ';
  2181.         }
  2182.         return Tools::stripslashes($name);
  2183.     }
  2184.  
  2185.     public function combination_wholesale_price($obj, $product_attribute)
  2186.     {
  2187.         return $product_attribute['wholesale_price'];
  2188.     }
  2189.  
  2190.     public function combination_price($obj, $product_attribute)
  2191.     {
  2192.         return Product::getPriceStatic((int)$obj->id, false, (int)$product_attribute['id_product_attribute']);
  2193.     }
  2194.  
  2195.     public function combination_weight($obj, $product_attribute)
  2196.     {
  2197.         return $product_attribute['weight'];
  2198.     }
  2199.  
  2200.     public function combination_price_tax($obj, $product_attribute)
  2201.     {
  2202.         return $obj->getPrice(true, (int)$product_attribute['id_product_attribute']);
  2203.     }
  2204.  
  2205.     public function combination_price_tax_nodiscount($obj, $product_attribute)
  2206.     {
  2207.         return $obj->getPrice(true, (int)$product_attribute['id_product_attribute'], 2, null, false, false);
  2208.     }
  2209.  
  2210.     public function combination_unit_impact($obj, $products_attribute)
  2211.     {
  2212.         return $products_attribute['unit_impact'];
  2213.     }
  2214.  
  2215.     public function combination_reference($obj, $products_attribute)
  2216.     {
  2217.         return $products_attribute['reference'];
  2218.     }
  2219.  
  2220.     public function combination_supplier_reference($obj, $products_attribute)
  2221.     {
  2222.         return $products_attribute['supplier_reference'];
  2223.     }
  2224.  
  2225.     public function combination_ean13($obj, $products_attribute)
  2226.     {
  2227.         return $products_attribute['ean13'];
  2228.     }
  2229.  
  2230.     public function combination_upc($obj, $products_attribute)
  2231.     {
  2232.         return $products_attribute['upc'];
  2233.     }
  2234.  
  2235.     public function combination_minimal_quantity($obj, $products_attribute)
  2236.     {
  2237.         return $products_attribute['minimal_quantity'];
  2238.     }
  2239.  
  2240.     public function combination_location($obj, $products_attribute)
  2241.     {
  2242.         return $products_attribute['location'];
  2243.     }
  2244.  
  2245.     public function combination_quantity($obj, $products_attribute)
  2246.     {
  2247.         return $products_attribute['quantity'];
  2248.     }
  2249.  
  2250.     public function combination_ecotax($obj, $products_attribute)
  2251.     {
  2252.         return $products_attribute['ecotax'];
  2253.     }
  2254.  
  2255.     public function combination_images($obj, $product_attribute, $ae)
  2256.     {
  2257.         $attrImage = ($product_attribute['id_image'] ? new Image($product_attribute['id_image']) : null);
  2258.         if($attrImage){
  2259.             return $this->link->getImageLink($obj->link_rewrite[$ae->id_lang], $obj->id .'-'. $attrImage->id, $ae->image_type);
  2260.         }
  2261.     }
  2262.  
  2263.     public function ordersFormFields()
  2264.     {
  2265.         $fields = array(
  2266.             array(
  2267.                 'type'  => 'bsmselect',
  2268.                 'label' => $this->l('Orders fields'),
  2269.                 'name'  => 'fields[]',
  2270.                 'id'  => 'fields',
  2271.                 'class' => 'ds-select',
  2272.                 'multiple' => true,
  2273.                 'options' => array(
  2274.                     'query' => $this->addToFieldId($this->orders),
  2275.                     'id' => 'id',
  2276.                     'name' => 'name'
  2277.                 )
  2278.             ),
  2279.             array(
  2280.                 'type'  => 'select',
  2281.                 'label' => $this->l('Customers groups'),
  2282.                 'name'  => 'groups[]',
  2283.                 'id' => 'groups',
  2284.                 'class' => 'ds-select',
  2285.                 'desc' =>$this->l('If you want all leave blank. All are exported by default.'),
  2286.                 'multiple' => true,
  2287.                 'options' => array(
  2288.                     'query' => Group::getGroups($this->getConfiguration('PS_LANG_DEFAULT')),
  2289.                     'id' => 'id_group',
  2290.                     'name' => 'name'
  2291.                 )
  2292.             ),
  2293.             array(
  2294.                 'type'  => 'select',
  2295.                 'label' => $this->l('Payments'),
  2296.                 'name'  => 'payments[]',
  2297.                 'id'  => 'payments',
  2298.                 'class' => 'ds-select',
  2299.                 'desc' =>$this->l('If you want all leave blank. All are exported by default.'),
  2300.                 'multiple' => true,
  2301.                 'options' => array(
  2302.                     'query' => PaymentModule::getInstalledPaymentModules(),
  2303.                     'id' => 'name',
  2304.                     'name' => 'name'
  2305.                 )
  2306.             ),
  2307.             array(
  2308.                 'type'  => 'select',
  2309.                 'label' => $this->l('Carrier type'),
  2310.                 'name'  => 'carriers[]',
  2311.                 'id' => 'carriers',
  2312.                 'class' => 'ds-select',
  2313.                 'desc' =>$this->l('If you want all leave blank. All are exported by default.'),
  2314.                 'multiple' => true,
  2315.                 'options' => array(
  2316.                     'query' => Carrier::getCarriers($this->getConfiguration('PS_LANG_DEFAULT')),
  2317.                     'id' => 'id_carrier',
  2318.                     'name' => 'name'
  2319.                 )
  2320.             ),
  2321.             array(
  2322.                 'type'  => 'select',
  2323.                 'label' => $this->l('Order state'),
  2324.                 'name'  => 'state[]',
  2325.                 'id' => 'state',
  2326.                 'class' => 'ds-select',
  2327.                 'desc' =>$this->l('If you want all leave blank. All are exported by default.'),
  2328.                 'multiple' => true,
  2329.                 'options' => array(
  2330.                     'query' => OrderState::getOrderStates($this->getConfiguration('PS_LANG_DEFAULT')),
  2331.                     'id' => 'id_order_state',
  2332.                     'name' => 'name'
  2333.                 )
  2334.             )
  2335.         );
  2336.  
  2337.         return $fields;
  2338.     }
  2339.  
  2340.     public function ordersQuery($ae, $sorted_fields)
  2341.     {
  2342.         $sql = 'SELECT o.`id_order` '.(empty($sorted_fields['sqlfields']) ? "" : ', '.implode(', ', $sorted_fields['sqlfields'])).'
  2343.                FROM '._DB_PREFIX_.'orders o
  2344.                LEFT JOIN `'._DB_PREFIX_.'order_detail` od ON ( od.`id_order` = o.`id_order` )
  2345.                LEFT JOIN `'._DB_PREFIX_.'shop` sh ON ( o.`id_shop` = sh.`id_shop` )
  2346.                LEFT JOIN `'._DB_PREFIX_.'customer` cu ON ( o.`id_customer` = cu.`id_customer` )
  2347.                LEFT JOIN `'._DB_PREFIX_.'gender_lang` gl ON ( cu.`id_gender` = gl.`id_gender` AND gl.`id_lang` = 1)
  2348.                LEFT JOIN `'._DB_PREFIX_.'gender_lang` inv_gl ON ( cu.`id_gender` = inv_gl.`id_gender` AND inv_gl.`id_lang` = 1)
  2349.                LEFT JOIN `'._DB_PREFIX_.'address` a ON ( a.`id_address` = o.`id_address_delivery` )
  2350.                LEFT JOIN `'._DB_PREFIX_.'address` inv_a ON ( inv_a.`id_address` = o.`id_address_invoice` )
  2351.                LEFT JOIN `'._DB_PREFIX_.'state` s ON ( s.`id_state` = a.`id_state` )
  2352.                LEFT JOIN `'._DB_PREFIX_.'country` co ON ( co.`id_country` = a.`id_country` )
  2353.                LEFT JOIN `'._DB_PREFIX_.'country_lang` cl ON ( cl.`id_country` = co.`id_country` )
  2354.                LEFT JOIN `'._DB_PREFIX_.'carrier` ca ON ( ca.`id_carrier` = o.`id_carrier` )
  2355.                LEFT JOIN `'._DB_PREFIX_.'order_payment` op ON ( op.`order_reference` = o.`reference` )
  2356.                LEFT JOIN `'._DB_PREFIX_.'message` m ON ( m.`id_order` = o.`id_order` )
  2357.                LEFT JOIN `'._DB_PREFIX_.'currency` cur ON ( o.`id_currency` = cur.`id_currency` )
  2358.                WHERE cl.`id_lang`= '.$ae->id_lang.
  2359.                 (isset($ae->only_new) && $ae->only_new ? ' AND o.`id_order` > '.$ae->last_exported_id : '').
  2360.                 ($ae->only_new == false && $ae->start_id ? ' AND o.`id_order` >= '.$ae->start_id : '').
  2361.                 ($ae->only_new == false && $ae->end_id ? ' AND o.`id_order` <= '.$ae->end_id : '').
  2362.                 (isset($sorted_fields['groups[]']) && $sorted_fields['groups[]'] ? ' AND cu.`id_default_group` IN ('.implode(', ', $sorted_fields['groups[]']).')' : '').
  2363.                 (isset($sorted_fields['payments[]']) && $sorted_fields['payments[]'] ? ' AND o.`module` IN ("'.implode('", "', $sorted_fields['payments[]']).'")' : '').
  2364.                 (isset($sorted_fields['carriers[]']) && $sorted_fields['carriers[]'] ? ' AND o.`id_carrier` IN ('.implode(', ', $sorted_fields['carriers[]']).')' : '').
  2365.                 (isset($sorted_fields['state[]']) && $sorted_fields['state[]'] ? ' AND o.`current_state` IN ('.implode(', ', $sorted_fields['state[]']).')' : '').
  2366.                 (isset($ae->date_from) && $ae->date_from &&  !$ae->only_new ? ' AND o.`date_add` >= "'.($ae->date_from).'"' : '').
  2367.                 (isset($ae->date_to) && $ae->date_to &&  !$ae->only_new ? ' AND o.`date_add` <= "'.($ae->date_to).'"' : '')
  2368.                              .Shop::addSqlRestriction(false, 'o').
  2369.                 ' GROUP BY '.(isset($sorted_fields['order_detail']) && $sorted_fields['order_detail']  ? 'od.`id_order_detail`' : 'o.`id_order`');
  2370.  
  2371.         $result = $this->query($sql);
  2372.         $this->rowsNumber = $this->query("SELECT FOUND_ROWS()")->fetchColumn();
  2373.         return $result;
  2374.     }
  2375.  
  2376.     public function orders_code($obj)
  2377.     {
  2378.         $result = $obj->getCartRules();
  2379.         $codes = array();
  2380.         foreach($result as $res) {
  2381.             $codes[] = $res['name'];
  2382.         }
  2383.         return implode(',', $codes);
  2384.     }
  2385.  
  2386.     public function orders_customization($obj,$ae, $element)
  2387.     {
  2388.         $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS('
  2389.                 SELECT cud.`value`, cu.`quantity`
  2390.                 FROM `'._DB_PREFIX_.'customization` cu
  2391.                 INNER JOIN `'._DB_PREFIX_.'customized_data` cud ON (cud.`id_customization` = cu.`id_customization`)
  2392.                 WHERE cu.`id_product` = '.(int)($element['product_id']).' AND cu.`id_product_attribute` = '.(int)($element['product_attribute_id']).'  AND cu.`id_cart` = '.(int)($element['id_cart']) );
  2393.         $cud = array();
  2394.         foreach($result as $res)
  2395.             $cud[] = 'value:'.$res['value'] . ' ' . 'quantity:' . $res['quantity'];
  2396.  
  2397.         return implode(',', $cud);
  2398.     }
  2399.  
  2400.     public function categoriesQuery($ae, $sorted_fields)
  2401.     {
  2402.         $sql = 'SELECT c.`id_category` '.(empty($sorted_fields['sqlfields']) ? "" : ', '.implode(', ', $sorted_fields['sqlfields'])).'
  2403.            FROM `'._DB_PREFIX_.'category` c
  2404.             '.Shop::addSqlAssociation('category', 'c').'
  2405.             LEFT JOIN `'._DB_PREFIX_.'category_lang` cl ON c.`id_category` = cl.`id_category`'.Shop::addSqlRestrictionOnLang('cl').'
  2406.             WHERE 1'.($ae->id_lang ? ' AND `id_lang` = '.(int)$ae->id_lang : '').
  2407.             (isset($ae->only_new) && $ae->only_new ? ' AND c.`id_category` > '.$ae->last_exported_id : '').
  2408.             ($ae->only_new == false && $ae->start_id ? ' AND c.`id_category` >= '.$ae->start_id : '').
  2409.             ($ae->only_new == false && $ae->end_id ? ' AND c.`id_category` <= '.$ae->end_id : '').
  2410.             (isset($sorted_fields['active']) && $sorted_fields['active'] ? ' AND c.`active` = 1' : '').
  2411.             (isset($ae->date_from) && $ae->date_from &&  !$ae->only_new ? ' AND c.`date_add` >= "'.($ae->date_from).'"' : '').
  2412.             (isset($ae->date_to) && $ae->date_to &&  !$ae->only_new ? ' AND c.`date_add` <= "'.($ae->date_to).'"' : '').'
  2413.             GROUP BY c.id_category
  2414.             ORDER BY c.`level_depth` ASC, category_shop.`position` ASC';
  2415.         $result = $this->query($sql);
  2416.         $this->rowsNumber = $this->query("SELECT FOUND_ROWS()")->fetchColumn();
  2417.         return $result;
  2418.     }
  2419.  
  2420.     public function categories_id_group($obj)
  2421.     {
  2422.         $result = $this->executeS('
  2423.             SELECT cg.`id_group`
  2424.             FROM '._DB_PREFIX_.'category_group cg
  2425.             WHERE cg.`id_category` = '.(int)$obj->id);
  2426.         $groups = null;
  2427.         foreach ($result as $group)
  2428.             $groups = $group['id_group'];
  2429.  
  2430.         return $groups;
  2431.     }
  2432.  
  2433.     public function categoriesFormFields()
  2434.     {
  2435.         $fields = array(
  2436.             array(
  2437.                 'type'  => 'bsmselect',
  2438.                 'label' => $this->l('Orders fields'),
  2439.                 'name'  => 'fields[]',
  2440.                 'id'  => 'fields',
  2441.                 'class' => 'sminit, ds-select',
  2442.                 'multiple' => true,
  2443.                 'options' => array(
  2444.                     'query' => $this->addToFieldId($this->categories),
  2445.                     'id' => 'id',
  2446.                     'name' => 'name'
  2447.                 )
  2448.             ),
  2449.             array(
  2450.                 'type' => $this->switch,
  2451.                 'label' => $this->l('Only active'),
  2452.                 'name' => 'active',
  2453.                 'class' => 't',
  2454.                 'is_bool' => true,
  2455.                 'values' => array(
  2456.                     array(
  2457.                         'id' => 'active_on',
  2458.                         'value' => 1,
  2459.                         'label' => $this->l('Yes')
  2460.                     ),
  2461.                     array(
  2462.                         'id' => 'active_off',
  2463.                         'value' => 0,
  2464.                         'label' => $this->l('No')
  2465.                     )
  2466.                 ),
  2467.             )
  2468.         );
  2469.  
  2470.         return $fields;
  2471.     }
  2472.  
  2473.     public function manufacturersQuery($ae, $sorted_fields)
  2474.     {
  2475.         $sql = 'SELECT m.`id_manufacturer` '.(empty($sorted_fields['sqlfields']) ? "" : ', '.implode(', ', $sorted_fields['sqlfields'])).'
  2476.         FROM `'._DB_PREFIX_.'manufacturer` m
  2477.         '.Shop::addSqlAssociation('manufacturer', 'm').'
  2478.         INNER JOIN `'._DB_PREFIX_.'manufacturer_lang` ml ON (m.`id_manufacturer` = ml.`id_manufacturer` AND ml.`id_lang` = '.(int)$ae->id_lang.')'.'
  2479.            WHERE 1'.(isset($sorted_fields['active']) && $sorted_fields['active'] ? ' AND m.`active` = 1' : '').
  2480.             (isset($ae->only_new) && $ae->only_new ? ' AND m.`id_manufacturer` > '.$ae->last_exported_id : '').
  2481.             ($ae->only_new == false && $ae->start_id ? ' AND m.`id_manufacturer` >= '.$ae->start_id : '').
  2482.             ($ae->only_new == false && $ae->end_id ? ' AND m.`id_manufacturer` <= '.$ae->end_id : '').
  2483.             (isset($ae->date_from) && $ae->date_from &&  !$ae->only_new ? ' AND m.`date_add` >= "'.($ae->date_from).'"' : '').
  2484.             (isset($ae->date_to) && $ae->date_to &&  !$ae->only_new ? ' AND m.`date_add` <= "'.($ae->date_to).'"' : '');
  2485.         $result = $this->query($sql);
  2486.         $this->rowsNumber = $this->query("SELECT FOUND_ROWS()")->fetchColumn();
  2487.         return $result;
  2488.     }
  2489.  
  2490.     public function manufacturersFormFields()
  2491.     {
  2492.         $fields = array(
  2493.             array(
  2494.                 'type' => 'bsmselect',
  2495.                 'label' => $this->l('Manufacturers fields'),
  2496.                 'name' => 'fields[]',
  2497.                 'id' => 'fields',
  2498.                 'class' => 'ds-select',
  2499.                 'multiple' => true,
  2500.                 'options' => array(
  2501.                     'query' => $this->addToFieldId($this->manufacturers),
  2502.                     'id' => 'id',
  2503.                     'name' => 'name'
  2504.                 )
  2505.             ),
  2506.             array(
  2507.                 'type' => $this->switch,
  2508.                 'label' => $this->l('Only active'),
  2509.                 'name' => 'active',
  2510.                 'class' => 't',
  2511.                 'is_bool' => true,
  2512.                 'values' => array(
  2513.                     array(
  2514.                         'id' => 'active_on',
  2515.                         'value' => 1,
  2516.                         'label' => $this->l('Yes')
  2517.                     ),
  2518.                     array(
  2519.                         'id' => 'active_off',
  2520.                         'value' => 0,
  2521.                         'label' => $this->l('No')
  2522.                     )
  2523.                 ),
  2524.             )
  2525.         );
  2526.  
  2527.         return $fields;
  2528.     }
  2529.  
  2530.     public function suppliersQuery($ae, $sorted_fields)
  2531.     {
  2532.         $sql = 'SELECT s.`id_supplier` '.(empty($sorted_fields['sqlfields']) ? "" : ', '.implode(', ', $sorted_fields['sqlfields'])).'
  2533.         FROM `'._DB_PREFIX_.'supplier` s
  2534.         '.Shop::addSqlAssociation('supplier', 's').'
  2535.         INNER JOIN `'._DB_PREFIX_.'supplier_lang` sl ON (s.`id_supplier` = sl.`id_supplier` AND sl.`id_lang` = '.(int)$ae->id_lang.')'.'
  2536.            WHERE 1'.(isset($sorted_fields['active']) && $sorted_fields['active'] ? ' AND s.`active` = 1' : '').
  2537.             (isset($ae->only_new) && $ae->only_new ? ' AND s.`id_supplier` > '.$ae->last_exported_id : '').
  2538.             ($ae->only_new == false && $ae->start_id ? ' AND s.`id_supplier` >= '.$ae->start_id : '').
  2539.             ($ae->only_new == false && $ae->end_id ? ' AND s.`id_supplier` <= '.$ae->end_id : '').
  2540.             (isset($ae->date_from) && $ae->date_from &&  !$ae->only_new ? ' AND s.`date_add` >= "'.($ae->date_from).'"' : '').
  2541.             (isset($ae->date_to) && $ae->date_to &&  !$ae->only_new ? ' AND s.`date_add` <= "'.($ae->date_to).'"' : '');
  2542.         $result = $this->query($sql);
  2543.         $this->rowsNumber = $this->query("SELECT FOUND_ROWS()")->fetchColumn();
  2544.         return $result;
  2545.     }
  2546.  
  2547.     public function suppliersFormFields()
  2548.     {
  2549.         $fields = array(
  2550.             array(
  2551.                 'type' => 'bsmselect',
  2552.                 'label' => $this->l('Orders fields'),
  2553.                 'name' => 'fields[]',
  2554.                 'id' => 'fields',
  2555.                 'class' => 'sminit, ds-select',
  2556.                 'multiple' => true,
  2557.                 'options' => array(
  2558.                     'query' => $this->addToFieldId($this->suppliers),
  2559.                     'id' => 'id',
  2560.                     'name' => 'name'
  2561.                 )
  2562.             ),
  2563.             array(
  2564.                 'type' => $this->switch,
  2565.                 'label' => $this->l('Only active'),
  2566.                 'name' => 'active',
  2567.                 'class' => 't',
  2568.                 'is_bool' => true,
  2569.                 'values' => array(
  2570.                     array(
  2571.                         'id' => 'active_on',
  2572.                         'value' => 1,
  2573.                         'label' => $this->l('Yes')
  2574.                     ),
  2575.                     array(
  2576.                         'id' => 'active_off',
  2577.                         'value' => 0,
  2578.                         'label' => $this->l('No')
  2579.                     )
  2580.                 ),
  2581.             )
  2582.         );
  2583.  
  2584.         return $fields;
  2585.     }
  2586.  
  2587.     public function customersFormFields()
  2588.     {
  2589.         $fields = array(
  2590.             array(
  2591.                 'type' => 'bsmselect',
  2592.                 'label' => $this->l('Customers fields'),
  2593.                 'name' => 'fields[]',
  2594.                 'id' => 'fields',
  2595.                 'class' => 'sminit, ds-select',
  2596.                 'multiple' => true,
  2597.                 'options' => array(
  2598.                     'query' => $this->addToFieldId($this->customers),
  2599.                     'id' => 'id',
  2600.                     'name' => 'name'
  2601.                 )
  2602.  
  2603.             ),
  2604.             array(
  2605.                 'type' => $this->switch,
  2606.                 'label' => $this->l('Only active'),
  2607.                 'name' => 'active',
  2608.                 'class' => 't',
  2609.                 'is_bool' => true,
  2610.                 'values' => array(
  2611.                     array(
  2612.                         'id' => 'active_on',
  2613.                         'value' => 1,
  2614.                         'label' => $this->l('Yes')
  2615.                     ),
  2616.                     array(
  2617.                         'id' => 'active_off',
  2618.                         'value' => 0,
  2619.                         'label' => $this->l('No')
  2620.                     )
  2621.                 ),
  2622.             )
  2623.         );
  2624.  
  2625.         return $fields;
  2626.     }
  2627.  
  2628.     public function customersQuery($ae, $sorted_fields)
  2629.     {
  2630.         $sql = 'SELECT c.`id_customer` '.(empty($sorted_fields['sqlfields']) ? "" : ', '.implode(', ', $sorted_fields['sqlfields'])).'  
  2631.                 FROM '._DB_PREFIX_.'customer c
  2632.                LEFT JOIN `'._DB_PREFIX_.'address` a ON ( a.`id_customer` = c.`id_customer` )
  2633.                 WHERE 1'.Shop::addSqlRestriction(Shop::SHARE_CUSTOMER).
  2634.             (isset($sorted_fields['active']) && $sorted_fields['active'] ? ' AND c.`active` = 1' : '').
  2635.             (isset($ae->only_new) && $ae->only_new ? ' AND c.`id_customer` > '.$ae->last_exported_id : '').
  2636.             ($ae->only_new == false && $ae->start_id ? ' AND c.`id_customer` >= '.$ae->start_id : '').
  2637.             ($ae->only_new == false && $ae->end_id ? ' AND c.`id_customer` <= '.$ae->end_id : '').
  2638.             (isset($sorted_fields['active']) && $sorted_fields['active'] ? ' AND c.`active` = 1' : '').
  2639.             (isset($ae->date_from) && $ae->date_from &&  !$ae->only_new ? ' AND c.`date_add` >= "'.($ae->date_from).'"' : '').
  2640.             (isset($ae->date_to) && $ae->date_to &&  !$ae->only_new ? ' AND c.`date_add` <= "'.($ae->date_to).'"' : '');
  2641.         $result = $this->query($sql);
  2642.         $this->rowsNumber = $this->query("SELECT FOUND_ROWS()")->fetchColumn();
  2643.         return $result;
  2644.     }
  2645.  
  2646.  
  2647.     public function newslettersQuery($ae, $sorted_fields)
  2648.     {
  2649.         $sql = 'SELECT n.`id` '.(empty($sorted_fields['sqlfields']) ? "" : ', '.implode(', ', $sorted_fields['sqlfields'])).'
  2650.                 FROM '._DB_PREFIX_.'newsletter as n
  2651.                 WHERE 1'.(isset($sorted_fields['active']) && $sorted_fields['active'] ? ' AND n.`active` = 1' : '').
  2652.                 (isset($ae->only_new) && $ae->only_new ? ' AND n.`id` > '.$ae->last_exported_id : '').
  2653.                 ($ae->only_new == false && $ae->start_id ? ' AND n.`id` >= '.$ae->start_id : '').
  2654.                 ($ae->only_new == false && $ae->end_id ? ' AND n.`id` <= '.$ae->end_id : '').
  2655.                 (isset($ae->date_from) && $ae->date_from &&  !$ae->only_new ? ' AND n.`newsletter_date_add` >= "'.($ae->date_from).'"' : '').
  2656.                 (isset($ae->date_to) && $ae->date_to &&  !$ae->only_new ? ' AND n.`newsletter_date_add` <= "'.($ae->date_to).'"' : '').'
  2657.                 AND n.`id_shop` = '.$this->context->shop->id;
  2658.         $result = $this->query($sql);
  2659.         $this->rowsNumber = $this->query("SELECT FOUND_ROWS()")->fetchColumn();
  2660.         return $result;
  2661.     }
  2662.  
  2663.     public function newslettersFormFields()
  2664.     {
  2665.         $fields = array(
  2666.             array(
  2667.                 'type' => 'bsmselect',
  2668.                 'label' => $this->l('Newsletters fields'),
  2669.                 'name' => 'fields[]',
  2670.                 'id' => 'fields',
  2671.                 'class' => 'sminit, ds-select',
  2672.                 'multiple' => true,
  2673.                 'options' => array(
  2674.                     'query' => $this->addToFieldId($this->newsletters),
  2675.                     'id' => 'id',
  2676.                     'name' => 'name'
  2677.                 )
  2678.             ),
  2679.             array(
  2680.                 'type' => $this->switch,
  2681.                 'label' => $this->l('Only active'),
  2682.                 'class' => 't',
  2683.                 'name' => 'active',
  2684.                 'is_bool' => true,
  2685.                 'values' => array(
  2686.                     array(
  2687.                         'id' => 'active_on',
  2688.                         'value' => 1,
  2689.                         'label' => $this->l('Yes')
  2690.                     ),
  2691.                     array(
  2692.                         'id' => 'active_off',
  2693.                         'value' => 0,
  2694.                         'label' => $this->l('No')
  2695.                     )
  2696.                 ),
  2697.             )
  2698.         );
  2699.  
  2700.         return $fields;
  2701.     }
  2702.  
  2703.     public function getLanguages()
  2704.     {
  2705.         return Language::getLanguages();
  2706.     }
  2707.  
  2708.     /**
  2709.      * Add key to array element as id
  2710.      * for select control
  2711.      * @param array $array
  2712.      * @return array $array
  2713.      */
  2714.     public function addKeyAsArrayElementId($array)
  2715.     {
  2716.         for ($i=0; $i < count($array); $i++) {
  2717.             $array[$i]['id'] = $i;
  2718.         }
  2719.  
  2720.         return $array;
  2721.     }
  2722.  
  2723.     /**
  2724.      * @param $object
  2725.      * @param $ae
  2726.      * @param $value
  2727.      * @return mixed
  2728.      */
  2729.     public function processDecimalSettings($object, $ae, $value)
  2730.     {
  2731.         if ($this->is_decimal($object[$value]))
  2732.         {
  2733.             //this have to be first becasue if we change separator
  2734.             //the value is not recognise
  2735.             if($ae->decimal_round != -1 && $ae->decimal_round != "-1")
  2736.                 $object[$value] = Tools::ps_round((float)$object[$value], $ae->decimal_round);
  2737.  
  2738.             if($ae->decimal_separator != -1 && $ae->decimal_separator != "-1")
  2739.             {
  2740.                 $object[$value] = str_replace(',', $ae->decimal_separator, $object[$value]);
  2741.                 $object[$value] = str_replace('.', $ae->decimal_separator, $object[$value]);
  2742.             }
  2743.         }
  2744.         if ($ae->strip_tags)
  2745.             $object[$value] = strip_tags($object[$value]);
  2746.         return $object;
  2747.     }
  2748.  
  2749.     public function is_decimal( $val )
  2750.     {
  2751.         return is_numeric( $val ) && strpos( $val, "." ) !== false;
  2752.     }
  2753.  
  2754.     /**
  2755.      * @param $type
  2756.      * @return array
  2757.      */
  2758.     public function getLinks($type)
  2759.     {
  2760.         $links = $this->DbExecuteS("select * from " . _DB_PREFIX_ . "advancedexport where type = '$type'");
  2761.         for ($i = 0; $i < count($links); $i++) {
  2762.             $links[$i]['cron_url'] = "<span class='cron_url'>http://" . $_SERVER['HTTP_HOST'] . __PS_BASE_URI__ . "modules/advancedexport/cron.php?secure_key=".Configuration::get('ADVANCEDEXPORT_SECURE_KEY')."&id=" . $links[$i]['id_advancedexport']."   </span><span class='cron_button'>copy to clipboard</span>";
  2763.             $type = $this->getSaveTypes();
  2764.             $links[$i]['save_type'] = $type[$links[$i]['save_type']]['short_name'];
  2765.         }
  2766.         return $links;
  2767.     }
  2768.  
  2769.     /**
  2770.      * @param $ae
  2771.      * @param $sorted_fields
  2772.      * @param $file
  2773.      */
  2774.     public function filewrite($ae, $sorted_fields, $file)
  2775.     {
  2776.         fwrite($file, implode($ae->delimiter, $sorted_fields['labels']) . "\r\n");
  2777.     }
  2778. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement