Advertisement
Guest User

Shop.php

a guest
Nov 26th, 2013
273
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 32.73 KB | None | 0 0
  1. <?php
  2. /*
  3. * 2007-2013 PrestaShop
  4. *
  5. * NOTICE OF LICENSE
  6. *
  7. * This source file is subject to the Open Software License (OSL 3.0)
  8. * that is bundled with this package in the file LICENSE.txt.
  9. * It is also available through the world-wide-web at this URL:
  10. * http://opensource.org/licenses/osl-3.0.php
  11. * If you did not receive a copy of the license and are unable to
  12. * obtain it through the world-wide-web, please send an email
  13. * to license@prestashop.com so we can send you a copy immediately.
  14. *
  15. * DISCLAIMER
  16. *
  17. * Do not edit or add to this file if you wish to upgrade PrestaShop to newer
  18. * versions in the future. If you wish to customize PrestaShop for your
  19. * needs please refer to http://www.prestashop.com for more information.
  20. *
  21. *  @author PrestaShop SA <contact@prestashop.com>
  22. *  @copyright  2007-2013 PrestaShop SA
  23. *  @license    http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
  24. *  International Registered Trademark & Property of PrestaShop SA
  25. */
  26.  
  27. /**
  28.  * @since 1.5.0
  29.  */
  30. class ShopCore extends ObjectModel
  31. {
  32.     /** @var int ID of shop group */
  33.     public  $id_shop_group;
  34.  
  35.     /** @var int ID of shop category */
  36.     public  $id_category;
  37.  
  38.     /** @var int ID of shop theme */
  39.     public  $id_theme;
  40.  
  41.     /** @var string Shop name */
  42.     public  $name;
  43.  
  44.     public  $active = true;
  45.     public  $deleted;
  46.  
  47.     /** @var string Shop theme name (read only) */
  48.     public $theme_name;
  49.  
  50.     /** @var string Shop theme directory (read only) */
  51.     public $theme_directory;
  52.  
  53.     /** @var string Physical uri of main url (read only) */
  54.     public $physical_uri;
  55.  
  56.     /** @var string Virtual uri of main url (read only) */
  57.     public $virtual_uri;
  58.  
  59.     /** @var string Domain of main url (read only) */
  60.     public $domain;
  61.  
  62.     /** @var string Domain SSL of main url (read only) */
  63.     public $domain_ssl;
  64.  
  65.     /** @var ShopGroup Shop group object */
  66.     protected $group;
  67.  
  68.     /**
  69.      * @see ObjectModel::$definition
  70.      */
  71.     public static $definition = array(
  72.         'table' => 'shop',
  73.         'primary' => 'id_shop',
  74.         'fields' => array(
  75.             'active' =>         array('type' => self::TYPE_BOOL, 'validate' => 'isBool'),
  76.             'deleted' =>        array('type' => self::TYPE_BOOL, 'validate' => 'isBool'),
  77.             'name' =>           array('type' => self::TYPE_STRING, 'validate' => 'isGenericName', 'required' => true, 'size' => 64),
  78.             'id_theme' =>       array('type' => self::TYPE_INT, 'required' => true),
  79.             'id_category' =>    array('type' => self::TYPE_INT, 'required' => true),
  80.             'id_shop_group' =>  array('type' => self::TYPE_INT, 'required' => true),
  81.         ),
  82.     );
  83.  
  84.     /** @var array List of shops cached */
  85.     protected static $shops;
  86.  
  87.     protected static $asso_tables = array();
  88.     protected static $id_shop_default_tables = array();
  89.     protected static $initialized = false;
  90.  
  91.     protected $webserviceParameters = array(
  92.         'fields' => array(
  93.             'id_shop_group' => array('xlink_resource' => 'shop_groups'),
  94.             'id_category' => array(),
  95.             'id_theme' => array(),
  96.         ),
  97.     );
  98.  
  99.     /** @var int Store the current context of shop (CONTEXT_ALL, CONTEXT_GROUP, CONTEXT_SHOP) */
  100.     protected static $context;
  101.  
  102.     /** @var int ID shop in the current context (will be empty if context is not CONTEXT_SHOP) */
  103.     protected static $context_id_shop;
  104.  
  105.     /** @var int ID shop group in the current context (will be empty if context is CONTEXT_ALL) */
  106.     protected static $context_id_shop_group;
  107.  
  108.     /**
  109.      * There are 3 kinds of shop context : shop, group shop and general
  110.      */
  111.     const CONTEXT_SHOP = 1;
  112.     const CONTEXT_GROUP = 2;
  113.     const CONTEXT_ALL = 4;
  114.  
  115.     /**
  116.      * Some data can be shared between shops, like customers or orders
  117.      */
  118.     const SHARE_CUSTOMER = 'share_customer';
  119.     const SHARE_ORDER = 'share_order';
  120.     const SHARE_STOCK = 'share_stock';
  121.  
  122.     /**
  123.      * On shop instance, get its theme and URL data too
  124.      *
  125.      * @param int $id
  126.      * @param int $id_lang
  127.      * @param int $id_shop
  128.      */
  129.     public function __construct($id = null, $id_lang = null, $id_shop = null)
  130.     {
  131.         parent::__construct($id, $id_lang, $id_shop);
  132.         if ($this->id)
  133.             $this->setUrl();
  134.     }
  135.    
  136.     /**
  137.      * Initialize an array with all the multistore associations in the database
  138.      */
  139.     protected static function init()
  140.     {
  141.         Shop::$id_shop_default_tables = array('product', 'category');
  142.        
  143.         $asso_tables = array(
  144.             'carrier' => array('type' => 'shop'),
  145.             'carrier_lang' => array('type' => 'fk_shop'),
  146.             'category' => array('type' => 'shop'),
  147.             'category_lang' => array('type' => 'fk_shop'),
  148.             'cms' => array('type' => 'shop'),
  149.             'contact' => array('type' => 'shop'),
  150.             'country' => array('type' => 'shop'),
  151.             'currency' => array('type' => 'shop'),
  152.             'employee' => array('type' => 'shop'),
  153.             'hook_module' => array('type' => 'fk_shop'),
  154.             'hook_module_exceptions' => array('type' => 'fk_shop', 'primary' => 'id_hook_module_exceptions'),
  155.             'image' => array('type' => 'shop'),
  156.             'lang' => array('type' => 'shop'),
  157.             'meta_lang' => array('type' => 'fk_shop'),
  158.             'module' => array('type' => 'shop'),
  159.             'module_currency' => array('type' => 'fk_shop'),
  160.             'module_country' => array('type' => 'fk_shop'),
  161.             'module_group' => array('type' => 'fk_shop'),
  162.             'product' => array('type' => 'shop'),
  163.             'product_attribute' => array('type' => 'shop'),
  164.             'product_lang' => array('type' => 'fk_shop'),
  165.             'referrer' => array('type' => 'shop'),
  166.             'scene' => array('type' => 'shop'),
  167.             'store' => array('type' => 'shop'),
  168.             'webservice_account' => array('type' => 'shop'),
  169.             'warehouse' => array('type' => 'shop'),
  170.             'stock_available' => array('type' => 'fk_shop'),
  171.             'carrier_tax_rules_group_shop' => array('type' => 'fk_shop'),
  172.             'attribute' => array('type' => 'shop'),
  173.             'feature' => array('type' => 'shop'),
  174.             'group' => array('type' => 'shop'),
  175.             'attribute_group' => array('type' => 'shop'),
  176.             'tax_rules_group' => array('type' => 'shop'),
  177.             'zone' => array('type' => 'shop'),
  178.             'manufacturer' => array('type' => 'shop'),
  179.             'supplier' => array('type' => 'shop'),
  180.         );
  181.        
  182.         foreach ($asso_tables as $table_name => $table_details)
  183.             Shop::addTableAssociation($table_name, $table_details);
  184.  
  185.         Shop::$initialized = true;
  186.     }
  187.  
  188.     public function setUrl()
  189.     {
  190.         $cache_id = 'Shop::setUrl_'.(int)$this->id;
  191.         if (!Cache::isStored($cache_id))
  192.         {
  193.             $row = Db::getInstance()->getRow('
  194.             SELECT su.physical_uri, su.virtual_uri, su.domain, su.domain_ssl, t.id_theme, t.name, t.directory
  195.             FROM '._DB_PREFIX_.'shop s
  196.             LEFT JOIN '._DB_PREFIX_.'shop_url su ON (s.id_shop = su.id_shop)
  197.             LEFT JOIN '._DB_PREFIX_.'theme t ON (t.id_theme = s.id_theme)
  198.             WHERE s.id_shop = '.(int)$this->id.'
  199.             AND s.active = 1 AND s.deleted = 0 AND su.main = 1');
  200.             Cache::store($cache_id, $row);
  201.         }
  202.         $row = Cache::retrieve($cache_id);
  203.         if (!$row)
  204.             return false;
  205.  
  206.         $this->theme_id = $row['id_theme'];
  207.         $this->theme_name = $row['name'];
  208.         $this->theme_directory = $row['directory'];
  209.         $this->physical_uri = $row['physical_uri'];
  210.         $this->virtual_uri = $row['virtual_uri'];
  211.         $this->domain = $row['domain'];
  212.         $this->domain_ssl = $row['domain_ssl'];
  213.  
  214.         return true;
  215.     }
  216.  
  217.     /**
  218.      * Add a shop, and clear the cache
  219.      *
  220.      * @param bool $autodate
  221.      * @param bool $null_values
  222.      * @return bool
  223.      */
  224.     public function add($autodate = true, $null_values = false)
  225.     {
  226.         $res = parent::add($autodate, $null_values);
  227.         Shop::cacheShops(true);
  228.         Db::getInstance()->Execute('INSERT INTO '._DB_PREFIX_.'employee_shop (id_employee, id_shop) (SELECT id_employee, '.(int)$this->id.' FROM '._DB_PREFIX_.'employee WHERE id_profile = '.(int)_PS_ADMIN_PROFILE_.')');
  229.         return $res;
  230.     }
  231.  
  232.     /**
  233.      * Remove a shop only if it has no dependencies, and remove its associations
  234.      *
  235.      * @return bool
  236.      */
  237.     public function delete()
  238.     {
  239.         if (Shop::hasDependency($this->id) || !$res = parent::delete())
  240.             return false;
  241.  
  242.         foreach (Shop::getAssoTables() as $table_name => $row)
  243.         {
  244.             $id = 'id_'.$row['type'];
  245.             if ($row['type'] == 'fk_shop')
  246.                 $id = 'id_shop';
  247.             else
  248.                 $table_name .= '_'.$row['type'];
  249.             $res &= Db::getInstance()->execute('
  250.                 DELETE FROM `'.bqSQL(_DB_PREFIX_.$table_name).'`
  251.                 WHERE `'.bqSQL($id).'`='.(int)$this->id
  252.             );
  253.         }
  254.  
  255.         // removes stock available
  256.         $res &= Db::getInstance()->delete('stock_available', 'id_shop = '.(int)$this->id);
  257.  
  258.         // Remove urls
  259.         $res &= Db::getInstance()->delete('shop_url', 'id_shop = '.(int)$this->id);
  260.  
  261.         Shop::cacheShops(true);
  262.  
  263.         return $res;
  264.     }
  265.  
  266.     /**
  267.      * Detect dependency with customer or orders
  268.      *
  269.      * @param int $id_shop
  270.      * @return bool
  271.      */
  272.     public static function hasDependency($id_shop)
  273.     {
  274.         $has_dependency = false;
  275.         $nbr_customer = (int)Db::getInstance()->getValue('
  276.             SELECT count(*)
  277.             FROM `'._DB_PREFIX_.'customer`
  278.             WHERE `id_shop`='.(int)$id_shop
  279.         );
  280.         if ($nbr_customer)
  281.             $has_dependency = true;
  282.         else
  283.         {
  284.             $nbr_order = (int)Db::getInstance()->getValue('
  285.                 SELECT count(*)
  286.                 FROM `'._DB_PREFIX_.'orders`
  287.                 WHERE `id_shop`='.(int)$id_shop
  288.             );
  289.             if ($nbr_order)
  290.                 $has_dependency = true;
  291.         }
  292.  
  293.         return $has_dependency;
  294.     }
  295.  
  296.     /**
  297.      * Find the shop from current domain / uri and get an instance of this shop
  298.      * if INSTALL_VERSION is defined, will return an empty shop object
  299.      *
  300.      * @return Shop
  301.      */
  302.     public static function initialize()
  303.     {
  304.         // Find current shop from URL
  305.         if (!($id_shop = Tools::getValue('id_shop')) || defined('_PS_ADMIN_DIR_'))
  306.         {
  307.             $host = pSQL(Tools::getHttpHost());
  308.             $sql = 'SELECT s.id_shop, CONCAT(su.physical_uri, su.virtual_uri) AS uri, su.domain, su.main
  309.                     FROM '._DB_PREFIX_.'shop_url su
  310.                     LEFT JOIN '._DB_PREFIX_.'shop s ON (s.id_shop = su.id_shop)
  311.                     WHERE (su.domain = \''.$host.'\' OR su.domain_ssl = \''.$host.'\')
  312.                         AND s.active = 1
  313.                         AND s.deleted = 0
  314.                     ORDER BY LENGTH(CONCAT(su.physical_uri, su.virtual_uri)) DESC';
  315.  
  316.             $id_shop = '';
  317.             $found_uri = '';
  318.             $request_uri = rawurldecode($_SERVER['REQUEST_URI']);
  319.             $is_main_uri = false;
  320.             if ($results = Db::getInstance()->executeS($sql))
  321.             {
  322.                 foreach ($results as $row)
  323.                 {
  324.                     // An URL matching current shop was found
  325.                     if (preg_match('#^'.preg_quote($row['uri'], '#').'#i', $request_uri))
  326.                     {
  327.                         $id_shop = $row['id_shop'];
  328.                         $found_uri = $row['uri'];
  329.                         if ($row['main'])
  330.                             $is_main_uri = true;
  331.                         break;
  332.                     }
  333.                 }
  334.             }
  335.  
  336.             // If an URL was found but is not the main URL, redirect to main URL
  337.             if ($id_shop && !$is_main_uri)
  338.             {
  339.                 foreach ($results as $row)
  340.                 {
  341.                     if ($row['id_shop'] == $id_shop && $row['main'])
  342.                     {
  343.                         // extract url parameters
  344.                         $request_uri = substr($request_uri, strlen($found_uri));
  345.                         $url = str_replace('//', '/', $row['domain'].$row['uri'].$request_uri);
  346.                         header('HTTP/1.1 301 Moved Permanently');
  347.                         header('Cache-Control: no-cache');
  348.                         header('location: http://'.$url);
  349.                         exit;
  350.                     }
  351.                 }
  352.             }
  353.         }
  354.  
  355.         if ((!$id_shop && defined('_PS_ADMIN_DIR_')) || Tools::isPHPCLI())
  356.         {
  357.             // If in admin, we can access to the shop without right URL
  358.             if ((!$id_shop && Tools::isPHPCLI()) || defined('_PS_ADMIN_DIR_'))
  359.                 $id_shop = (int)Configuration::get('PS_SHOP_DEFAULT');
  360.  
  361.             $shop = new Shop((int)$id_shop);
  362.             if (!Validate::isLoadedObject($shop))
  363.                 $shop = new Shop((int)Configuration::get('PS_SHOP_DEFAULT'));
  364.  
  365.             $shop->physical_uri = preg_replace('#/+#', '/', str_replace('\\', '/', dirname(dirname($_SERVER['SCRIPT_NAME']))).'/');
  366.             $shop->virtual_uri = '';
  367.            
  368.             // Define some $_SERVER variables like HTTP_HOST if PHP is launched with php-cli
  369.             if (Tools::isPHPCLI())
  370.             {
  371.                 if (!isset($_SERVER['HTTP_HOST']) || empty($_SERVER['HTTP_HOST']))
  372.                     $_SERVER['HTTP_HOST'] = $shop->domain;
  373.                 if (!isset($_SERVER['SERVER_NAME']) || empty($_SERVER['SERVER_NAME']))
  374.                     $_SERVER['SERVER_NAME'] = $shop->domain;
  375.                 if (!isset($_SERVER['REMOTE_ADDR']) || empty($_SERVER['REMOTE_ADDR']))
  376.                     $_SERVER['REMOTE_ADDR'] = '127.0.0.1';
  377.             }
  378.         }
  379.         else
  380.         {
  381.             $shop = new Shop($id_shop);
  382.             if (!Validate::isLoadedObject($shop) || !$shop->active || !$id_shop)
  383.             {
  384.                 // No shop found ... too bad, let's redirect to default shop
  385.                 $default_shop = new Shop(Configuration::get('PS_SHOP_DEFAULT'));
  386.  
  387.                 // Hmm there is something really bad in your Prestashop !
  388.                 if (!Validate::isLoadedObject($default_shop))
  389.                     throw new PrestaShopException('Shop not found');
  390.  
  391.                 $params = $_GET;
  392.                 unset($params['id_shop']);
  393.                 if (!Configuration::get('PS_REWRITING_SETTINGS'))
  394.                     $url = 'http://'.$default_shop->domain.$default_shop->getBaseURI().'index.php?'.http_build_query($params);
  395.                 else
  396.                 {
  397.                     // Catch url with subdomain "www"
  398.                     if (strpos($default_shop->domain, 'www.') === 0 && 'www.'.$_SERVER['HTTP_HOST'] === $default_shop->domain
  399.                         || $_SERVER['HTTP_HOST'] === 'www.'.$default_shop->domain)
  400.                         $uri = $default_shop->domain.$_SERVER['REQUEST_URI'];
  401.                     else
  402.                         $uri = $default_shop->domain.$default_shop->getBaseURI();
  403.                    
  404.                     if (count($params))
  405.                         $url = 'http://'.$uri.'?'.http_build_query($params);
  406.                     else
  407.                         $url = 'http://'.$uri;
  408.                 }
  409.                 header('location: '.$url);
  410.                 exit;
  411.             }
  412.         }
  413.  
  414.         self::$context_id_shop = $shop->id;
  415.         self::$context_id_shop_group = $shop->id_shop_group;
  416.         self::$context = self::CONTEXT_SHOP;
  417.  
  418.         return $shop;
  419.     }
  420.  
  421.     /**
  422.     * @return Address the current shop address
  423.     */
  424.     public function getAddress()
  425.     {
  426.         if (!isset($this->address))
  427.         {
  428.             $address = new Address();
  429.             $address->company = Configuration::get('PS_SHOP_NAME');
  430.             $address->id_country = Configuration::get('PS_SHOP_COUNTRY_ID') ? Configuration::get('PS_SHOP_COUNTRY_ID') : Configuration::get('PS_COUNTRY_DEFAULT');
  431.             $address->id_state = Configuration::get('PS_SHOP_STATE_ID');
  432.             $address->address1 = Configuration::get('PS_SHOP_ADDR1');
  433.             $address->address2 = Configuration::get('PS_SHOP_ADDR2');
  434.             $address->postcode = Configuration::get('PS_SHOP_CODE');
  435.             $address->city = Configuration::get('PS_SHOP_CITY');
  436.  
  437.             $this->address = $address;
  438.         }
  439.  
  440.         return $this->address;
  441.     }
  442.  
  443.     /**
  444.      * Get shop theme name
  445.      *
  446.      * @return string
  447.      */
  448.     public function getTheme()
  449.     {
  450.         return $this->theme_directory;
  451.     }
  452.  
  453.     /**
  454.      * Get shop URI
  455.      *
  456.      * @return string
  457.      */
  458.     public function getBaseURI()
  459.     {
  460.         return $this->physical_uri.$this->virtual_uri;
  461.     }
  462.  
  463.     /**
  464.      * Get shop URL
  465.      *
  466.      * @return string
  467.      */
  468.     public function getBaseURL()
  469.     {
  470.         if (!$this->domain)
  471.             return false;
  472.         return 'http://'.$this->domain.$this->getBaseURI();
  473.     }
  474.  
  475.     /**
  476.      * Get group of current shop
  477.      *
  478.      * @return ShopGroup
  479.      */
  480.     public function getGroup()
  481.     {
  482.         if (!$this->group)
  483.             $this->group = new ShopGroup($this->id_shop_group);
  484.         return $this->group;
  485.     }
  486.  
  487.     /**
  488.      * Get root category of current shop
  489.      *
  490.      * @return int
  491.      */
  492.     public function getCategory()
  493.     {
  494.         return ($this->id_category) ? $this->id_category : 1;
  495.     }
  496.  
  497.     /**
  498.      * Get list of shop's urls
  499.      *
  500.      * @return array
  501.      */
  502.     public function getUrls()
  503.     {
  504.         $sql = 'SELECT *
  505.                 FROM '._DB_PREFIX_.'shop_url
  506.                 WHERE active = 1
  507.                     AND id_shop = '.(int)$this->id;
  508.         return Db::getInstance()->executeS($sql);
  509.     }
  510.  
  511.     /**
  512.      * Check if current shop ID is the same as default shop in configuration
  513.      *
  514.      * @return bool
  515.      */
  516.     public function isDefaultShop()
  517.     {
  518.         return $this->id == Configuration::get('PS_SHOP_DEFAULT');
  519.     }
  520.  
  521.     /**
  522.      * Get the associated table if available
  523.      *
  524.      * @return array
  525.      */
  526.     public static function getAssoTable($table)
  527.     {
  528.         if (!Shop::$initialized)
  529.             Shop::init();
  530.         return (isset(Shop::$asso_tables[$table]) ? Shop::$asso_tables[$table] : false);
  531.     }
  532.    
  533.     /**
  534.      * check if the table has an id_shop_default
  535.      *
  536.      * @return boolean
  537.      */
  538.     public static function checkIdShopDefault($table)
  539.     {
  540.         if (!Shop::$initialized)
  541.             Shop::init();
  542.         return in_array($table, self::$id_shop_default_tables);
  543.     }
  544.  
  545.     /**
  546.      * Get list of associated tables to shop
  547.      *
  548.      * @return array
  549.      */
  550.     public static function getAssoTables()
  551.     {
  552.         if (!Shop::$initialized)
  553.             Shop::init();
  554.         return Shop::$asso_tables;
  555.     }
  556.    
  557.     /**
  558.      * Add table associated to shop
  559.      *
  560.      * @param string $table_name
  561.      * @param array $table_details
  562.      * @return bool
  563.      */
  564.     public static function addTableAssociation($table_name, $table_details)
  565.     {
  566.         if (!isset(Shop::$asso_tables[$table_name]))
  567.             Shop::$asso_tables[$table_name] = $table_details;
  568.         else
  569.             return false;
  570.         return true;
  571.     }
  572.    
  573.     /**
  574.      * Check if given table is associated to shop
  575.      *
  576.      * @param string $table
  577.      * @return bool
  578.      */
  579.     public static function isTableAssociated($table)
  580.     {
  581.         if (!Shop::$initialized)
  582.             Shop::init();
  583.         return isset(Shop::$asso_tables[$table]) && Shop::$asso_tables[$table]['type'] == 'shop';
  584.     }
  585.  
  586.     /**
  587.      * Load list of groups and shops, and cache it
  588.      *
  589.      * @param bool $refresh
  590.      */
  591.     public static function cacheShops($refresh = false)
  592.     {
  593.         if (!is_null(self::$shops) && !$refresh)
  594.             return;
  595.  
  596.         self::$shops = array();
  597.  
  598.         $from = '';
  599.         $where = '';
  600.  
  601.         $employee = Context::getContext()->employee;
  602.  
  603.         // If the profile isn't a superAdmin
  604.         if (Validate::isLoadedObject($employee) && $employee->id_profile != _PS_ADMIN_PROFILE_)
  605.         {
  606.             $from .= 'LEFT JOIN '._DB_PREFIX_.'employee_shop es ON es.id_shop = s.id_shop';
  607.             $where .= 'AND es.id_employee = '.(int)$employee->id;
  608.         }
  609.  
  610.         $sql = 'SELECT gs.*, s.*, gs.name AS group_name, s.name AS shop_name, s.active, su.domain, su.domain_ssl, su.physical_uri, su.virtual_uri
  611.                 FROM '._DB_PREFIX_.'shop_group gs
  612.                 LEFT JOIN '._DB_PREFIX_.'shop s
  613.                     ON s.id_shop_group = gs.id_shop_group
  614.                 LEFT JOIN '._DB_PREFIX_.'shop_url su
  615.                     ON s.id_shop = su.id_shop AND su.main = 1
  616.                 '.$from.'
  617.                 WHERE s.deleted = 0
  618.                     AND gs.deleted = 0
  619.                     '.$where.'
  620.                 ORDER BY gs.name, s.name';
  621.  
  622.         if ($results = Db::getInstance()->executeS($sql))
  623.         {
  624.             foreach ($results as $row)
  625.             {
  626.                 if (!isset(self::$shops[$row['id_shop_group']]))
  627.                     self::$shops[$row['id_shop_group']] = array(
  628.                         'id' =>             $row['id_shop_group'],
  629.                         'name' =>           $row['group_name'],
  630.                         'share_customer' => $row['share_customer'],
  631.                         'share_order' =>    $row['share_order'],
  632.                         'share_stock' => $row['share_stock'],
  633.                         'shops' =>          array(),
  634.                     );
  635.  
  636.                 self::$shops[$row['id_shop_group']]['shops'][$row['id_shop']] = array(
  637.                     'id_shop' =>        $row['id_shop'],
  638.                     'id_shop_group' =>  $row['id_shop_group'],
  639.                     'name' =>           $row['shop_name'],
  640.                     'id_theme' =>       $row['id_theme'],
  641.                     'id_category' =>    $row['id_category'],
  642.                     'domain' =>         $row['domain'],
  643.                     'domain_ssl' =>     $row['domain_ssl'],
  644.                     'uri' =>            $row['physical_uri'].$row['virtual_uri'],
  645.                     'active' =>         $row['active'],
  646.                 );
  647.             }
  648.         }
  649.     }
  650.  
  651.     public static function getCompleteListOfShopsID()
  652.     {
  653.         $list = array();
  654.         $sql = 'SELECT id_shop FROM '._DB_PREFIX_.'shop';
  655.         foreach (Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sql) as $row)
  656.             $list[] = $row['id_shop'];
  657.         return $list;
  658.     }
  659.  
  660.     /**
  661.      * Get shops list
  662.      *
  663.      * @param bool $active
  664.      * @param int $id_shop_group
  665.      * @param bool $get_as_list_id
  666.      * @return array
  667.      */
  668.     public static function getShops($active = true, $id_shop_group = null, $get_as_list_id = false)
  669.     {
  670.         Shop::cacheShops();
  671.  
  672.         $results = array();
  673.         foreach (self::$shops as $group_id => $group_data)
  674.             foreach ($group_data['shops'] as $id => $shop_data)
  675.                 if ((!$active || $shop_data['active']) && (!$id_shop_group || $id_shop_group == $group_id))
  676.                 {
  677.                     if ($get_as_list_id)
  678.                         $results[$id] = $id;
  679.                     else
  680.                         $results[$id] = $shop_data;
  681.                 }
  682.         return $results;
  683.     }
  684.    
  685.     public function getUrlsSharedCart()
  686.     {
  687.         if (!$this->getGroup()->share_order)
  688.             return false;
  689.        
  690.         $query = new DbQuery();
  691.         $query->select('domain');
  692.         $query->from('shop_url');
  693.         $query->where('main = 1');
  694.         $query->where('active = 1');
  695.         $query .= $this->addSqlRestriction(Shop::SHARE_ORDER);
  696.         $domains = array();
  697.         foreach (Db::getInstance()->executeS($query) as $row)
  698.             $domains[] = $row['domain'];
  699.  
  700.         return $domains;
  701.     }
  702.  
  703.     /**
  704.      * Get a collection of shops
  705.      *
  706.      * @param bool $active
  707.      * @param int $id_shop_group
  708.      * @return Collection
  709.      */
  710.     public static function getShopsCollection($active = true, $id_shop_group = null)
  711.     {
  712.         $shops = new Collection('Shop');
  713.         if ($active)
  714.             $shops->where('active', '=', 1);
  715.  
  716.         if ($id_shop_group)
  717.             $shops->where('id_shop_group', '=', (int)$id_shop_group);
  718.  
  719.         return $shops;
  720.     }
  721.  
  722.     /**
  723.      * Return some informations cached for one shop
  724.      *
  725.      * @param int $shop_id
  726.      * @return array
  727.      */
  728.     public static function getShop($shop_id)
  729.     {
  730.         Shop::cacheShops();
  731.         foreach (self::$shops as $group_id => $group_data)
  732.             if (array_key_exists($shop_id, $group_data['shops']))
  733.                 return $group_data['shops'][$shop_id];
  734.         return false;
  735.     }
  736.  
  737.     /**
  738.      * Return a shop ID from shop name
  739.      *
  740.      * @param string $name
  741.      * @return int
  742.      */
  743.     public static function getIdByName($name)
  744.     {
  745.         Shop::cacheShops();
  746.         foreach (self::$shops as $group_data)
  747.             foreach ($group_data['shops'] as $shop_id => $shop_data)
  748.                 if (Tools::strtolower($shop_data['name']) == Tools::strtolower($name))
  749.                     return $shop_id;
  750.         return false;
  751.     }
  752.  
  753.     /**
  754.      * @param bool $active
  755.      * @param int $id_shop_group
  756.      * @return int Total of shops
  757.      */
  758.     public static function getTotalShops($active = true, $id_shop_group = null)
  759.     {
  760.         return count(Shop::getShops($active, $id_shop_group));
  761.     }
  762.  
  763.     /**
  764.      * Retrieve group ID of a shop
  765.      *
  766.      * @param int $shop_id Shop ID
  767.      * @return int Group ID
  768.      */
  769.     public static function getGroupFromShop($shop_id, $as_id = true)
  770.     {
  771.         Shop::cacheShops();
  772.         foreach (self::$shops as $group_id => $group_data)
  773.             if (array_key_exists($shop_id, $group_data['shops']))
  774.                 return ($as_id) ? $group_id : $group_data;
  775.         return false;
  776.     }
  777.  
  778.     /**
  779.      * If the shop group has the option $type activated, get all shops ID of this group, else get current shop ID
  780.      *
  781.      * @param int $shop_id
  782.      * @param int $type Shop::SHARE_CUSTOMER | Shop::SHARE_ORDER
  783.      * @return array
  784.      */
  785.     public static function getSharedShops($shop_id, $type)
  786.     {
  787.         if (!in_array($type, array(Shop::SHARE_CUSTOMER, Shop::SHARE_ORDER, SHOP::SHARE_STOCK)))
  788.             die('Wrong argument ($type) in Shop::getSharedShops() method');
  789.  
  790.         Shop::cacheShops();
  791.         foreach (self::$shops as $group_data)
  792.             if (array_key_exists($shop_id, $group_data['shops']) && $group_data[$type])
  793.                 return array_keys($group_data['shops']);
  794.         return array($shop_id);
  795.     }
  796.  
  797.     /**
  798.      * Get a list of ID concerned by the shop context (E.g. if context is shop group, get list of children shop ID)
  799.      *
  800.      * @param string $share If false, dont check share datas from group. Else can take a Shop::SHARE_* constant value
  801.      * @return array
  802.      */
  803.     public static function getContextListShopID($share = false)
  804.     {
  805.         if (Shop::getContext() == Shop::CONTEXT_SHOP)
  806.             $list = ($share) ? Shop::getSharedShops(Shop::getContextShopID(), $share) : array(Shop::getContextShopID());
  807.         elseif (Shop::getContext() == Shop::CONTEXT_GROUP)
  808.             $list = Shop::getShops(true, Shop::getContextShopGroupID(), true);
  809.         else
  810.             $list = Shop::getShops(true, null, true);
  811.  
  812.         return $list;
  813.     }
  814.  
  815.     /**
  816.      * Return the list of shop by id
  817.      *
  818.      * @param int $id
  819.      * @param string $identifier
  820.      * @param string $table
  821.      * @return array
  822.      */
  823.     public static function getShopById($id, $identifier, $table)
  824.     {
  825.         return Db::getInstance()->executeS('
  826.             SELECT `id_shop`, `'.bqSQL($identifier).'`
  827.             FROM `'._DB_PREFIX_.bqSQL($table).'_shop`
  828.             WHERE `'.bqSQL($identifier).'` = '.(int)$id
  829.         );
  830.     }
  831.  
  832.     /**
  833.      * Change the current shop context
  834.      *
  835.      * @param int $type Shop::CONTEXT_ALL | Shop::CONTEXT_GROUP | Shop::CONTEXT_SHOP
  836.      * @param int $id ID shop if CONTEXT_SHOP or id shop group if CONTEXT_GROUP
  837.      */
  838.     public static function setContext($type, $id = null)
  839.     {
  840.         switch ($type)
  841.         {
  842.             case self::CONTEXT_ALL :
  843.                 self::$context_id_shop = null;
  844.                 self::$context_id_shop_group = null;
  845.             break;
  846.  
  847.             case self::CONTEXT_GROUP :
  848.                 self::$context_id_shop = null;
  849.                 self::$context_id_shop_group = (int)$id;
  850.             break;
  851.  
  852.             case self::CONTEXT_SHOP :
  853.                 self::$context_id_shop = (int)$id;
  854.                 self::$context_id_shop_group = Shop::getGroupFromShop($id);
  855.             break;
  856.  
  857.             default :
  858.                 throw new PrestaShopException('Unknown context for shop');
  859.         }
  860.  
  861.         self::$context = $type;
  862.     }
  863.  
  864.     /**
  865.      * Get current context of shop
  866.      *
  867.      * @return int
  868.      */
  869.     public static function getContext()
  870.     {
  871.         return self::$context;
  872.     }
  873.  
  874.     /**
  875.      * Get current ID of shop if context is CONTEXT_SHOP
  876.      *
  877.      * @return int
  878.      */
  879.     public static function getContextShopID($null_value_without_multishop = false)
  880.     {
  881.         if ($null_value_without_multishop && !Shop::isFeatureActive())
  882.             return null;
  883.         return self::$context_id_shop;
  884.     }
  885.  
  886.     /**
  887.      * Get current ID of shop group if context is CONTEXT_SHOP or CONTEXT_GROUP
  888.      *
  889.      * @return int
  890.      */
  891.     public static function getContextShopGroupID($null_value_without_multishop = false)
  892.     {
  893.         if ($null_value_without_multishop && !Shop::isFeatureActive())
  894.             return null;
  895.  
  896.         return self::$context_id_shop_group;
  897.     }
  898.    
  899.     public static function getContextShopGroup()
  900.     {
  901.         static $context_shop_group = null;
  902.         if ($context_shop_group === null)
  903.             $context_shop_group = new ShopGroup((int)self::$context_id_shop_group);
  904.         return $context_shop_group;
  905.     }
  906.  
  907.     /**
  908.      * Add an sql restriction for shops fields
  909.      *
  910.      * @param int $share If false, dont check share datas from group. Else can take a Shop::SHARE_* constant value
  911.      * @param string $alias
  912.      */
  913.     public static function addSqlRestriction($share = false, $alias = null)
  914.     {
  915.         if ($alias)
  916.             $alias .= '.';
  917.  
  918.         $group = Shop::getGroupFromShop(Shop::getContextShopID(), false);
  919.         if ($share == Shop::SHARE_CUSTOMER && Shop::getContext() == Shop::CONTEXT_SHOP && $group['share_customer'])
  920.             $restriction = ' AND '.$alias.'id_shop_group = '.(int)Shop::getContextShopGroupID();
  921.         else
  922.             $restriction = ' AND '.$alias.'id_shop IN ('.implode(', ', Shop::getContextListShopID($share)).') ';
  923.         return $restriction;
  924.     }
  925.  
  926.     /**
  927.      * Add an SQL JOIN in query between a table and its associated table in multishop
  928.      *
  929.      * @param string $table Table name (E.g. product, module, etc.)
  930.      * @param string $alias Alias of table
  931.      * @param bool $inner_join Use or not INNER JOIN
  932.      * @param string $on
  933.      * @return string
  934.      */
  935.     public static function addSqlAssociation($table, $alias, $inner_join = true, $on = null, $force_not_default = false)
  936.     {
  937.         $table_alias = $table.'_shop';
  938.         if (strpos($table, '.') !== false)
  939.             list($table_alias, $table) = explode('.', $table);
  940.  
  941.         $asso_table = Shop::getAssoTable($table);
  942.         if ($asso_table === false || $asso_table['type'] != 'shop')
  943.             return;
  944.         $sql = (($inner_join) ? ' INNER' : ' LEFT').' JOIN '._DB_PREFIX_.$table.'_shop '.$table_alias.'
  945.         ON ('.$table_alias.'.id_'.$table.' = '.$alias.'.id_'.$table;
  946.         if ((int)self::$context_id_shop)
  947.             $sql .= ' AND '.$table_alias.'.id_shop = '.(int)self::$context_id_shop;
  948.         elseif (Shop::checkIdShopDefault($table) && !$force_not_default)
  949.             $sql .= ' AND '.$table_alias.'.id_shop = '.$alias.'.id_shop_default';
  950.         else
  951.             $sql .= ' AND '.$table_alias.'.id_shop IN ('.implode(', ', Shop::getContextListShopID()).')';
  952.         $sql .= (($on) ? ' AND '.$on : '').')';
  953.         return $sql;
  954.     }
  955.  
  956.     /**
  957.      * Add a restriction on id_shop for multishop lang table
  958.      *
  959.      * @param string $alias
  960.      * @param Context $context
  961.      * @return string
  962.      */
  963.     public static function addSqlRestrictionOnLang($alias = null, $id_shop = null)
  964.     {
  965.         if (is_null($id_shop))
  966.             $id_shop = (int)Context::getContext()->shop->id;
  967.         if (!$id_shop)
  968.             $id_shop = (int)Configuration::get('PS_SHOP_DEFAULT');
  969.  
  970.         return ' AND '.(($alias) ? $alias.'.' : '').'id_shop = '.$id_shop.' ';
  971.     }
  972.  
  973.     /**
  974.      * Get all groups and associated shops as subarrays
  975.      *
  976.      * @return array
  977.      */
  978.     public static function getTree()
  979.     {
  980.         Shop::cacheShops();
  981.         return self::$shops;
  982.     }
  983.  
  984.     /**
  985.      * @return bool Return true if multishop feature is active and at last 2 shops have been created
  986.      */
  987.     public static function isFeatureActive()
  988.     {
  989.         static $feature_active = null;
  990.  
  991.         if ($feature_active === null)
  992.             $feature_active = Configuration::getGlobalValue('PS_MULTISHOP_FEATURE_ACTIVE') && (Db::getInstance()->getValue('SELECT COUNT(*) FROM '._DB_PREFIX_.'shop') > 1);
  993.  
  994.         return $feature_active;
  995.     }
  996.  
  997.     public function copyShopData($old_id, $tables_import = false, $deleted = false)
  998.     {
  999.         // If we duplicate some specific data, automatically duplicate other data linked to the first
  1000.         // E.g. if carriers are duplicated for the shop, duplicate carriers langs too
  1001.  
  1002.         if (!$old_id)
  1003.             $old_id = Configuration::get('PS_SHOP_DEFAULT');
  1004.  
  1005.         if (isset($tables_import['carrier']))
  1006.         {
  1007.             $tables_import['carrier_tax_rules_group_shop'] = true;
  1008.             $tables_import['carrier_lang'] = true;
  1009.         }
  1010.  
  1011.         $tables_import['category_lang'] = true;
  1012.         if (isset($tables_import['product']))
  1013.             $tables_import['product_lang'] = true;
  1014.  
  1015.         if (isset($tables_import['module']))
  1016.         {
  1017.             $tables_import['module_currency'] = true;
  1018.             $tables_import['module_country'] = true;
  1019.             $tables_import['module_group'] = true;
  1020.         }
  1021.  
  1022.         if (isset($tables_import['hook_module']))
  1023.             $tables_import['hook_module_exceptions'] = true;
  1024.  
  1025.         if (isset($tables_import['attribute_group']))
  1026.             $tables_import['attribute'] = true;
  1027.  
  1028.         // Browse and duplicate data
  1029.         foreach (Shop::getAssoTables() as $table_name => $row)
  1030.         {
  1031.             if ($tables_import && !isset($tables_import[$table_name]))
  1032.                 continue;
  1033.  
  1034.             // Special case for stock_available if current shop is in a share stock group
  1035.             if ($table_name == 'stock_available')
  1036.             {
  1037.                 $group = new ShopGroup($this->id_shop_group);
  1038.                 if ($group->share_stock && $group->haveShops())
  1039.                     continue;
  1040.             }
  1041.  
  1042.             $id = 'id_'.$row['type'];
  1043.             if ($row['type'] == 'fk_shop')
  1044.                 $id = 'id_shop';
  1045.             else
  1046.                 $table_name .= '_'.$row['type'];
  1047.  
  1048.             if (!$deleted)
  1049.             {
  1050.                 $res = Db::getInstance()->getRow('SELECT * FROM `'._DB_PREFIX_.$table_name.'` WHERE `'.$id.'` = '.(int)$old_id);
  1051.                 if ($res)
  1052.                 {
  1053.                     unset($res[$id]);
  1054.                     if (isset($row['primary']))
  1055.                         unset($res[$row['primary']]);
  1056.  
  1057.                     $categories = Tools::getValue('categoryBox');
  1058.                     if ($table_name == 'product_shop' && count($categories) == 1)
  1059.                     {
  1060.                         unset($res['id_category_default']);
  1061.                         $keys = implode('`, `', array_keys($res));
  1062.                         $sql = 'INSERT IGNORE INTO `'._DB_PREFIX_.$table_name.'` (`'.$keys.'`, `id_category_default`, '.$id.')
  1063.                                 (SELECT `'.$keys.'`, '.(int)$categories[0].', '.(int)$this->id.' FROM '._DB_PREFIX_.$table_name.'
  1064.                                 WHERE `'.$id.'` = '.(int)$old_id.')';
  1065.                     }
  1066.                     else
  1067.                     {
  1068.                         $keys = implode('`, `', array_keys($res));
  1069.                         $sql = 'INSERT IGNORE INTO `'._DB_PREFIX_.$table_name.'` (`'.$keys.'`, '.$id.')
  1070.                                 (SELECT `'.$keys.'`, '.(int)$this->id.' FROM '._DB_PREFIX_.$table_name.'
  1071.                                 WHERE `'.$id.'` = '.(int)$old_id.')';
  1072.                     }
  1073.                     Db::getInstance()->execute($sql);
  1074.                 }
  1075.             }
  1076.         }
  1077.  
  1078.         // Hook for duplication of shop data
  1079.         $modules_list = Hook::getHookModuleExecList('actionShopDataDuplication');
  1080.         if (is_array($modules_list) && count($modules_list) > 0)
  1081.             foreach ($modules_list as $m)
  1082.                 if (!$tables_import || isset($tables_import['Module'.ucfirst($m['module'])]))
  1083.                     Hook::exec('actionShopDataDuplication', array(
  1084.                         'old_id_shop' => (int)$old_id,
  1085.                         'new_id_shop' => (int)$this->id,
  1086.                     ), $m['id_module']);
  1087.     }
  1088.  
  1089.     /**
  1090.      * @static
  1091.      * @param int $id
  1092.      * @return array
  1093.      */
  1094.     public static function getCategories($id = 0, $only_id = true)
  1095.     {
  1096.         // build query
  1097.         $query = new DbQuery();
  1098.         if ($only_id)
  1099.             $query->select('cs.`id_category`');
  1100.         else
  1101.             $query->select('DISTINCT cs.`id_category`, cl.`name`, cl.`link_rewrite`');
  1102.         $query->from('category_shop', 'cs');
  1103.         $query->leftJoin('category_lang', 'cl', 'cl.`id_category` = cs.`id_category` AND cl.`id_lang` = '.(int)Context::getContext()->language->id);
  1104.         $query->where('cs.`id_shop` = '.(int)$id);
  1105.         $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($query);
  1106.  
  1107.         if ($only_id)
  1108.         {
  1109.             $array = array();
  1110.             foreach ($result as $row)
  1111.                 $array[] = $row['id_category'];
  1112.             $array = array_unique($array);
  1113.         }
  1114.         else
  1115.             return $result;
  1116.  
  1117.         return $array;
  1118.     }
  1119.  
  1120.     /**
  1121.      * @deprecated 1.5.0 Use shop->id
  1122.      */
  1123.     public static function getCurrentShop()
  1124.     {
  1125.         Tools::displayAsDeprecated();
  1126.         return Context::getContext()->shop->id;
  1127.     }
  1128.  
  1129.     /**
  1130.      * @param string $entity
  1131.      * @param int $id_shop
  1132.      * @return array|bool
  1133.      */
  1134.     public static function getEntityIds($entity, $id_shop, $active = false, $delete = false)
  1135.     {
  1136.         if (!Shop::isTableAssociated($entity))
  1137.             return false;
  1138.  
  1139.         return Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS('
  1140.             SELECT entity.`id_'.pSQL($entity).'`
  1141.             FROM `'._DB_PREFIX_.pSQL($entity).'_shop`es
  1142.             LEFT JOIN '._DB_PREFIX_.pSQL($entity).' entity
  1143.                 ON (entity.`id_'.pSQL($entity).'` = es.`id_'.pSQL($entity).'`)
  1144.             WHERE es.`id_shop` = '.(int)$id_shop.
  1145.             ($active ? ' AND entity.`active` = 1' : '').
  1146.             ($delete ? ' AND entity.deleted = 0' : '')
  1147.         );
  1148.     }
  1149. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement