PageRenderTime 39ms CodeModel.GetById 8ms app.highlight 24ms RepoModel.GetById 1ms app.codeStats 0ms

/controllers/admin/AdminShopController.php

https://github.com/netplayer/PrestaShop
PHP | 790 lines | 618 code | 92 blank | 80 comment | 100 complexity | 5564fcb64d76f7f2244de3635bcdcec9 MD5 | raw file
  1<?php
  2/*
  3* 2007-2014 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-2014 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
 28class AdminShopControllerCore extends AdminController
 29{
 30	public function __construct()
 31	{
 32		$this->bootstrap = true;
 33		$this->context = Context::getContext();
 34		$this->table = 'shop';
 35		$this->className = 'Shop';
 36		$this->multishop_context = Shop::CONTEXT_ALL;
 37		$this->id_shop_group = Tools::getValue('id_shop_group');
 38		$this->list_skip_actions['delete'] = array((int)Configuration::get('PS_SHOP_DEFAULT'));
 39		$this->fields_list = array(
 40			'id_shop' => array(
 41				'title' => $this->l('Shop ID'),
 42				'align' => 'center',
 43				'class' => 'fixed-width-xs'
 44			),
 45			'name' => array(
 46				'title' => $this->l('Shop name'),
 47				'filter_key' => 'a!name',
 48				'width' => 200,
 49			),
 50			'shop_group_name' => array(
 51				'title' => $this->l('Shop group'),
 52				'width' => 150,
 53				'filter_key' => 'gs!name'
 54			),
 55			'category_name' => array(
 56				'title' => $this->l('Root category'),
 57				'width' => 150,
 58				'filter_key' => 'cl!name'
 59			),
 60			'url' => array(
 61				'title' => $this->l('Main URL for this shop'),
 62				'havingFilter' => 'url',
 63			),
 64			/*'active' => array(
 65				'title' => $this->l('Enabled'),
 66				'align' => 'center',
 67				'active' => 'status',
 68				'type' => 'bool',
 69				'orderby' => false,
 70				'filter_key' => 'active',
 71				'width' => 50,
 72			)*/
 73		);
 74
 75		parent::__construct();
 76	}
 77
 78	public function viewAccess($disable = false)
 79	{
 80		return Configuration::get('PS_MULTISHOP_FEATURE_ACTIVE');
 81	}
 82
 83	public function initPageHeaderToolbar()
 84	{
 85		parent::initPageHeaderToolbar();
 86
 87		if (!$this->display && $this->id_shop_group)
 88		{
 89			if ($this->id_object)
 90				$this->loadObject();
 91
 92			if (!$this->id_shop_group && $this->object && $this->object->id_shop_group)
 93				$this->id_shop_group = $this->object->id_shop_group;
 94
 95			$this->page_header_toolbar_btn['edit'] = array(
 96				'desc' => $this->l('Edit this shop group'),
 97				'href' => $this->context->link->getAdminLink('AdminShopGroup').'&updateshop_group&id_shop_group='
 98					.$this->id_shop_group,
 99			);
100
101			$this->page_header_toolbar_btn['new'] = array(
102				'desc' => $this->l('Add new shop'),
103				'href' => $this->context->link->getAdminLink('AdminShop').'&add'.$this->table.'&id_shop_group='
104					.$this->id_shop_group,
105			);
106		}
107	}
108
109	public function initToolbar()
110	{
111		parent::initToolbar();
112
113		if ($this->display != 'edit' && $this->display != 'add')
114		{
115			if ($this->id_object)
116				$this->loadObject();
117
118			if (!$this->id_shop_group && $this->object && $this->object->id_shop_group)
119				$this->id_shop_group = $this->object->id_shop_group;
120
121			$this->toolbar_btn['new'] = array(
122				'desc' => $this->l('Add new shop'),
123				'href' => $this->context->link->getAdminLink('AdminShop').'&add'.$this->table.'&id_shop_group='
124					.$this->id_shop_group,
125			);
126		}
127	}
128
129	public function initContent()
130	{
131		parent::initContent();
132
133		$this->addJqueryPlugin('cooki-plugin');
134		$data = Shop::getTree();
135
136		foreach ($data as $key_group => &$group)
137			foreach ($group['shops'] as $key_shop => &$shop)
138			{
139				$current_shop = new Shop($shop['id_shop']);
140				$urls = $current_shop->getUrls();
141
142				foreach ($urls as $key_url => &$url)
143				{
144					$title = $url['domain'].$url['physical_uri'].$url['virtual_uri'];
145					if (strlen($title) > 23)
146						$title = substr($title, 0, 23).'...';
147
148					$url['name'] = $title;
149					$shop['urls'][$url['id_shop_url']] = $url;
150				}
151			}
152
153		$shops_tree = new HelperTreeShops('shops-tree', 'Multistore tree');
154		$shops_tree->setNodeFolderTemplate('shop_tree_node_folder.tpl')->setNodeItemTemplate('shop_tree_node_item.tpl')
155			->setHeaderTemplate('shop_tree_header.tpl')->setActions(array(
156				new TreeToolbarLink(
157					'Collapse All',
158					'#',
159					'$(\'#'.$shops_tree->getId().'\').tree(\'collapseAll\'); return false;',
160					'icon-collapse-alt'),
161				new TreeToolbarLink(
162					'Expand All',
163					'#',
164					'$(\'#'.$shops_tree->getId().'\').tree(\'expandAll\'); return false;',
165					'icon-expand-alt')
166			))
167			->setAttribute('url_shop_group', $this->context->link->getAdminLink('AdminShopGroup'))
168			->setAttribute('url_shop', $this->context->link->getAdminLink('AdminShop'))
169			->setAttribute('url_shop_url', $this->context->link->getAdminLink('AdminShopUrl'))
170			->setData($data);
171		$shops_tree = $shops_tree->render(null, false, false);
172
173		if ($this->display == 'edit')
174			$this->toolbar_title[] = $this->object->name;
175		else if (!$this->display && $this->id_shop_group)
176		{
177			$group = new ShopGroup($this->id_shop_group);
178			$this->toolbar_title[] = $group->name;
179		}
180
181		$this->context->smarty->assign(array(
182			'toolbar_scroll' => 1,
183			'toolbar_btn' => $this->toolbar_btn,
184			'title' => $this->toolbar_title,
185			'shops_tree' => $shops_tree
186		));
187	}
188
189	public function renderList()
190	{
191		$this->addRowAction('edit');
192		$this->addRowAction('delete');
193
194		$this->_select = 'gs.name shop_group_name, cl.name category_name, CONCAT(\'http://\', su.domain, su.physical_uri, su.virtual_uri) AS url';
195		$this->_join = '
196			LEFT JOIN `'._DB_PREFIX_.'shop_group` gs
197				ON (a.id_shop_group = gs.id_shop_group)
198			LEFT JOIN `'._DB_PREFIX_.'category_lang` cl
199				ON (a.id_category = cl.id_category AND cl.id_lang='.(int)$this->context->language->id.')
200			LEFT JOIN '._DB_PREFIX_.'shop_url su
201				ON a.id_shop = su.id_shop AND su.main = 1
202		';
203		$this->_group = 'GROUP BY a.id_shop';
204
205		if ($id_shop_group = (int)Tools::getValue('id_shop_group'))
206			$this->_where = 'AND a.id_shop_group = '.$id_shop_group;
207
208		return parent::renderList();
209	}
210
211	public function displayAjaxGetCategoriesFromRootCategory()
212	{
213		if (Tools::isSubmit('id_category'))
214		{
215			$selected_cat = array((int)Tools::getValue('id_category'));
216			$children = Category::getChildren((int)Tools::getValue('id_category'), $this->context->language->id);
217			foreach ($children as $child)
218				$selected_cat[] = $child['id_category'];
219
220			$helper = new HelperTreeCategories('categories-tree', null, (int)Tools::getValue('id_category'), null, false);
221			$this->content = $helper->setSelectedCategories($selected_cat)->setUseSearch(true)->setUseCheckBox(true)
222				->render();
223		}
224		parent::displayAjax();
225	}
226
227	public function postProcess()
228	{
229		if (Tools::isSubmit('id_category_default'))
230			$_POST['id_category'] = Tools::getValue('id_category_default');
231		/*if ((Tools::isSubmit('status') ||
232			Tools::isSubmit('status'.$this->table) ||
233			(Tools::isSubmit('submitAdd'.$this->table) && Tools::getValue($this->identifier) && !Tools::getValue('active'))) &&
234			$this->loadObject() && $this->loadObject()->active)
235		{
236			if (Tools::getValue('id_shop') == Configuration::get('PS_SHOP_DEFAULT'))
237				$this->errors[] = Tools::displayError('You cannot disable the default shop.');
238			else if (Shop::getTotalShops() == 1)
239				$this->errors[] = Tools::displayError('You cannot disable the last shop.');
240		}*/
241		
242		if (Tools::isSubmit('submitAddshopAndStay') || Tools::isSubmit('submitAddshop'))
243		{
244			$shop_group = new ShopGroup((int)Tools::getValue('id_shop_group'));
245			if ($shop_group->shopNameExists(Tools::getValue('name'), (int)Tools::getValue('id_shop')))
246				$this->errors[] = Tools::displayError('You cannot have two shops with the same name in the same group.');
247		}
248
249		if (count($this->errors))
250			return false;
251
252		$result = parent::postProcess();
253
254		if ($result !== false && (Tools::isSubmit('submitAddshopAndStay') || Tools::isSubmit('submitAddshop')) && (int)$result->id_category != (int)Configuration::get('PS_HOME_CATEGORY', null, null, (int)$result->id))
255			Configuration::updateValue('PS_HOME_CATEGORY', (int)$result->id_category, false, null, (int)$result->id);
256
257		if ($this->redirect_after)
258			$this->redirect_after .= '&id_shop_group='.$this->id_shop_group;
259
260		return $result;
261	}
262
263	public function processDelete()
264	{
265		if (!Validate::isLoadedObject($object = $this->loadObject()))
266			$this->errors[] = Tools::displayError('Unable to load this shop.');
267		else if (!Shop::hasDependency($object->id))
268		{
269			$result = Category::deleteCategoriesFromShop($object->id) && parent::processDelete();
270			Tools::generateHtaccess();
271			return $result;
272		}
273		else
274			$this->errors[] = Tools::displayError('You can\'t delete this shop (customer and/or order dependency).');
275
276		return false;
277	}
278
279	protected function afterAdd($new_shop)
280	{
281		$import_data = Tools::getValue('importData', array());
282
283		// The root category should be at least imported
284		$new_shop->copyShopData((int)Tools::getValue('importFromShop'), $import_data);
285
286		// copy default data
287		if (!Tools::getValue('useImportData') || (is_array($import_data) && !isset($import_data['group'])))
288		{
289			$sql = 'INSERT INTO `'._DB_PREFIX_.'group_shop` (`id_shop`, `id_group`)
290					VALUES
291					('.(int)$new_shop->id.', '.(int)Configuration::get('PS_UNIDENTIFIED_GROUP').'),
292					('.(int)$new_shop->id.', '.(int)Configuration::get('PS_GUEST_GROUP').'),
293					('.(int)$new_shop->id.', '.(int)Configuration::get('PS_CUSTOMER_GROUP').')
294				';
295			Db::getInstance()->execute($sql);
296		}
297
298		return parent::afterAdd($new_shop);
299	}
300
301	protected function afterUpdate($new_shop)
302	{
303		$categories = Tools::getValue('categoryBox');
304		array_unshift($categories, Configuration::get('PS_ROOT_CATEGORY'));
305
306		if (!Category::updateFromShop($categories, $new_shop->id))
307			$this->errors[] = $this->l('You need to select at least the root category.');
308		if (Tools::getValue('useImportData') && ($import_data = Tools::getValue('importData')) && is_array($import_data))
309			$new_shop->copyShopData((int)Tools::getValue('importFromShop'), $import_data);
310		return parent::afterUpdate($new_shop);
311	}
312
313	public function getList($id_lang, $order_by = null, $order_way = null, $start = 0, $limit = null, $id_lang_shop = false)
314	{
315		if (Shop::getContext() == Shop::CONTEXT_GROUP)
316			$this->_where .= ' AND a.id_shop_group = '.(int)Shop::getContextShopGroupID();
317
318		parent::getList($id_lang, $order_by, $order_way, $start, $limit, $id_lang_shop);
319		$shop_delete_list = array();
320
321		// don't allow to remove shop which have dependencies (customers / orders / ... )
322		foreach ($this->_list as &$shop)
323		{
324			if (Shop::hasDependency($shop['id_shop']))
325				$shop_delete_list[] = $shop['id_shop'];
326		}
327		$this->context->smarty->assign('shops_having_dependencies', $shop_delete_list);
328	}
329
330	public function renderForm()
331	{
332		if (!($obj = $this->loadObject(true)))
333			return;
334
335		$this->fields_form = array(
336			'legend' => array(
337				'title' => $this->l('Shop'),
338				'icon' => 'icon-shopping-cart'
339			),
340			'input' => array(
341				array(
342					'type' => 'text',
343					'label' => $this->l('Shop name'),
344					'desc' => array($this->l('This field does not refer to the shop name visible in the Front Office.'),
345							sprintf($this->l('Follow %sthis link%s to edit the shop name used on the Front Office.'), '<a href="'.$this->context->link->getAdminLink('AdminStores').'#store_fieldset_general">', '</a>')),
346					'name' => 'name',
347					'required' => true,
348				)
349			)
350		);
351
352		$display_group_list = true;
353		if ($this->display == 'edit')
354		{
355			$group = new ShopGroup($obj->id_shop_group);
356			if ($group->share_customer || $group->share_order || $group->share_stock)
357				$display_group_list = false;
358		}
359
360		if ($display_group_list)
361		{
362			$options = array();
363			foreach (ShopGroup::getShopGroups() as $group)
364			{
365				if ($this->display == 'edit' && ($group->share_customer || $group->share_order || $group->share_stock) && ShopGroup::hasDependency($group->id))
366					continue;
367
368				$options[] = array(
369					'id_shop_group' =>	$group->id,
370					'name' =>			$group->name,
371				);
372			}
373
374			if ($this->display == 'add')
375				$group_desc = $this->l('Warning: You won\'t be able to change the group of this shop if this shop belongs to a group with one of these options activated: Share Customers, Share Quantities or Share Orders.');
376			else
377				$group_desc = $this->l('You can only move your shop to a shop group with all "share" options disabled -- or to a shop group with no customers/orders.');
378
379			$this->fields_form['input'][] = array(
380				'type' => 'select',
381				'label' => $this->l('Shop group'),
382				'desc' => $group_desc,
383				'name' => 'id_shop_group',
384				'options' => array(
385					'query' => $options,
386					'id' => 'id_shop_group',
387					'name' => 'name',
388				),
389			);
390		}
391		else
392		{
393			$this->fields_form['input'][] = array(
394				'type' => 'hidden',
395				'name' => 'id_shop_group',
396				'default' => $group->name
397			);
398			$this->fields_form['input'][] = array(
399				'type' => 'textShopGroup',
400				'label' => $this->l('Shop group'),
401				'desc' => $this->l('You can\'t edit the shop group because the current shop belongs to a group with the "share" option enabled.'),
402				'name' => 'id_shop_group',
403				'value' => $group->name
404			);
405		}
406
407		$categories = Category::getRootCategories($this->context->language->id);
408		$this->fields_form['input'][] = array(
409			'type' => 'select',
410			'label' => $this->l('Category root'),
411			'desc' => sprintf($this->l('This is the root category of the store that you\'ve created. To define a new root category for your store, %splease click here%s.'), '<a href="'.$this->context->link->getAdminLink('AdminCategories').'&addcategoryroot" target="_blank">', '</a>'),
412			'name' => 'id_category',
413			'options' => array(
414				'query' => $categories,
415				'id' => 'id_category',
416				'name' => 'name'
417			)
418		);
419
420		if (Tools::isSubmit('id_shop'))
421		{
422			$shop = new Shop((int)Tools::getValue('id_shop'));
423			$id_root = $shop->id_category;
424		}
425		else
426			$id_root = $categories[0]['id_category'];
427
428
429		$id_shop = (int)Tools::getValue('id_shop');
430		self::$currentIndex = self::$currentIndex.'&id_shop_group='.(int)(Tools::getValue('id_shop_group') ?
431			Tools::getValue('id_shop_group') : (isset($obj->id_shop_group) ? $obj->id_shop_group : Shop::getContextShopGroupID()));
432		$shop = new Shop($id_shop);
433		$selected_cat = Shop::getCategories($id_shop);
434
435		if (empty($selected_cat))
436		{
437			// get first category root and preselect all these children
438			$root_categories = Category::getRootCategories();
439			$root_category = new Category($root_categories[0]['id_category']);
440			$children = $root_category->getAllChildren($this->context->language->id);
441			$selected_cat[] = $root_categories[0]['id_category'];
442			
443			foreach ($children as $child)
444				$selected_cat[] = $child->id;
445		}
446
447		if (Shop::getContext() == Shop::CONTEXT_SHOP && Tools::isSubmit('id_shop'))
448			$root_category = new Category($shop->id_category);
449		else
450			$root_category = new Category($id_root);
451
452		$this->fields_form['input'][] = array(
453			'type' => 'categories',
454			'name' => 'categoryBox',
455			'label' => $this->l('Associated categories'),
456			'tree' => array(
457				'id' => 'categories-tree',
458				'selected_categories' => $selected_cat,
459				'root_category' => $root_category->id,
460				'use_search' => true,
461				'use_checkbox' => true
462			),
463			'desc' => $this->l('By selecting associated categories, you are choosing to share the categories between shops. Once associated between shops, any alteration of this category will impact every shop.')
464		);
465		/*$this->fields_form['input'][] = array(
466			'type' => 'switch',
467			'label' => $this->l('Enabled'),
468			'name' => 'active',
469			'required' => true,
470			'is_bool' => true,
471			'values' => array(
472				array(
473					'id' => 'active_on',
474					'value' => 1
475				),
476				array(
477					'id' => 'active_off',
478					'value' => 0
479				)
480			),
481			'desc' => $this->l('Enable or disable your store?')
482		);*/
483
484		$themes = Theme::getThemes();
485		if (!isset($obj->id_theme))
486			foreach ($themes as $theme)
487				if (isset($theme->id))
488				{
489					$id_theme = $theme->id;
490					break;
491				}
492
493		$this->fields_form['input'][] = array(
494			'type' => 'theme',
495			'label' => $this->l('Theme'),
496			'name' => 'theme',
497			'values' => $themes
498		);
499
500		$this->fields_form['submit'] = array(
501			'title' => $this->l('Save'),
502		);
503
504		if (Shop::getTotalShops() > 1 && $obj->id)
505			$disabled = array('active' => false);
506		else
507			$disabled = false;
508
509		$import_data = array(
510			'carrier' => $this->l('Carriers'),
511			'cms' => $this->l('CMS pages'),
512			'contact' => $this->l('Contact information'),
513			'country' => $this->l('Countries'),
514			'currency' => $this->l('Currencies'),
515			'discount' => $this->l('Discount prices'),
516			'employee' => $this->l('Employees'),
517			'image' => $this->l('Images'),
518			'lang' => $this->l('Languages'),
519			'manufacturer' => $this->l('Manufacturers'),
520			'module' => $this->l('Modules'),
521			'hook_module' => $this->l('Module hooks'),
522			'meta_lang' => $this->l('Meta information'),
523			'product' => $this->l('Products'),
524			'product_attribute' => $this->l('Product combinations'),
525			'scene' => $this->l('Scenes'),
526			'stock_available' => $this->l('Available quantities for sale'),
527			'store' => $this->l('Stores'),
528			'warehouse' => $this->l('Warehouses'),
529			'webservice_account' => $this->l('Webservice accounts'),
530			'attribute_group' => $this->l('Attribute groups'),
531			'feature' => $this->l('Features'),
532			'group' => $this->l('Customer groups'),
533			'tax_rules_group' => $this->l('Tax rules groups'),
534			'supplier' => $this->l('Suppliers'),
535			'referrer' => $this->l('Referrers/affiliates'),
536			'zone' => $this->l('Zones'),
537			'cart_rule' => $this->l('Cart rules'),
538		);
539		
540		// Hook for duplication of shop data
541		$modules_list = Hook::getHookModuleExecList('actionShopDataDuplication');
542		if (is_array($modules_list) && count($modules_list) > 0)
543			foreach ($modules_list as $m)
544				$import_data['Module'.ucfirst($m['module'])] = Module::getModuleName($m['module']);
545
546		asort($import_data);
547				
548		if (!$this->object->id)
549			$this->fields_import_form = array(
550				'radio' => array(
551					'type' => 'radio',
552					'label' => $this->l('Import data'),
553					'name' => 'useImportData',
554					'value' => 1
555				),
556				'select' => array(
557					'type' => 'select',
558					'name' => 'importFromShop',
559					'label' => $this->l('Choose the source shop'),
560					'options' => array(
561						'query' => Shop::getShops(false),
562						'name' => 'name'
563					)
564				),
565				'allcheckbox' => array(
566					'type' => 'checkbox',
567					'label' => $this->l('Choose data to import'),
568					'values' => $import_data
569				),
570				'desc' => $this->l('Use this option to associate data (products, modules, etc.) the same way for each selected shop.')
571			);
572
573		$this->fields_value = array(
574            'id_shop_group' => (Tools::getValue('id_shop_group') ? Tools::getValue('id_shop_group') :
575                (isset($obj->id_shop_group)) ? $obj->id_shop_group : Shop::getContextShopGroupID()),
576            'id_category' => (Tools::getValue('id_category') ? Tools::getValue('id_category') :
577                (isset($obj->id_category)) ? $obj->id_category : (int)Configuration::get('PS_HOME_CATEGORY')),
578			'id_theme_checked' => (isset($obj->id_theme) ? $obj->id_theme : $id_theme)
579		);
580
581		$ids_category = array();
582		$shops = Shop::getShops(false);
583		foreach ($shops as $shop)
584			$ids_category[$shop['id_shop']] = $shop['id_category'];
585
586		$this->tpl_form_vars = array(
587			'disabled' => $disabled,
588			'checked' => (Tools::getValue('addshop') !== false) ? true : false,
589			'defaultShop' => (int)Configuration::get('PS_SHOP_DEFAULT'),
590			'ids_category' => $ids_category,
591		);
592		if (isset($this->fields_import_form))
593			$this->tpl_form_vars = array_merge($this->tpl_form_vars, array('form_import' => $this->fields_import_form));
594
595		return parent::renderForm();
596	}
597
598
599	/**
600	 * Object creation
601	 */
602	public function processAdd()
603	{
604		if (!Tools::getValue('categoryBox') || !in_array(Tools::getValue('id_category'), Tools::getValue('categoryBox')))
605			$this->errors[] = $this->l('You need to select at least the root category.');
606
607		if (Tools::isSubmit('id_category_default'))
608			$_POST['id_category'] = (int)Tools::getValue('id_category_default');
609	
610		/* Checking fields validity */
611		$this->validateRules();
612
613		if (!count($this->errors))
614		{
615			$object = new $this->className();
616			$this->copyFromPost($object, $this->table);
617			$this->beforeAdd($object);
618			if (!$object->add())
619			{
620				$this->errors[] = Tools::displayError('An error occurred while creating an object.').
621					' <b>'.$this->table.' ('.Db::getInstance()->getMsgError().')</b>';
622			}
623			/* voluntary do affectation here */
624			else if (($_POST[$this->identifier] = $object->id) && $this->postImage($object->id) && !count($this->errors) && $this->_redirect)
625			{
626				$parent_id = (int)Tools::getValue('id_parent', 1);
627				$this->afterAdd($object);
628				$this->updateAssoShop($object->id);
629				// Save and stay on same form
630				if (Tools::isSubmit('submitAdd'.$this->table.'AndStay'))
631					$this->redirect_after = self::$currentIndex.'&'.$this->identifier.'='.$object->id.'&conf=3&update'.$this->table.'&token='.$this->token;
632				// Save and back to parent
633				if (Tools::isSubmit('submitAdd'.$this->table.'AndBackToParent'))
634					$this->redirect_after = self::$currentIndex.'&'.$this->identifier.'='.$parent_id.'&conf=3&token='.$this->token;
635				// Default behavior (save and back)
636				if (empty($this->redirect_after))
637					$this->redirect_after = self::$currentIndex.($parent_id ? '&'.$this->identifier.'='.$object->id : '').'&conf=3&token='.$this->token;
638			}
639		}
640
641		$this->errors = array_unique($this->errors);
642		if (count($this->errors) > 0)
643		{
644			$this->display = 'add';
645			return;
646		}
647
648		$object->associateSuperAdmins();
649
650		$categories = Tools::getValue('categoryBox');
651		array_unshift($categories, Configuration::get('PS_ROOT_CATEGORY'));
652		Category::updateFromShop($categories, $object->id);
653		Search::indexation(true);
654		return $object;
655	}
656
657	public function initCategoriesAssociation($id_root = null)
658	{
659		if (is_null($id_root))
660			$id_root = Configuration::get('PS_ROOT_CATEGORY');
661		$id_shop = (int)Tools::getValue('id_shop');
662		$shop = new Shop($id_shop);
663		$selected_cat = Shop::getCategories($id_shop);
664		if (empty($selected_cat))
665		{
666			// get first category root and preselect all these children
667			$root_categories = Category::getRootCategories();
668			$root_category = new Category($root_categories[0]['id_category']);
669			$children = $root_category->getAllChildren($this->context->language->id);
670			$selected_cat[] = $root_categories[0]['id_category'];
671			
672			foreach ($children as $child)
673				$selected_cat[] = $child->id;
674		}
675		if (Shop::getContext() == Shop::CONTEXT_SHOP && Tools::isSubmit('id_shop'))
676			$root_category = new Category($shop->id_category);
677		else
678			$root_category = new Category($id_root);
679		$root_category = array('id_category' => $root_category->id, 'name' => $root_category->name[$this->context->language->id]);
680
681		$helper = new Helper();
682		return $helper->renderCategoryTree($root_category, $selected_cat, 'categoryBox', false, true);
683	}
684
685	public function ajaxProcessTree()
686	{
687		$tree = array();
688		$sql = 'SELECT g.id_shop_group, g.name as group_name, s.id_shop, s.name as shop_name, u.id_shop_url, u.domain, u.physical_uri, u.virtual_uri
689				FROM '._DB_PREFIX_.'shop_group g
690				LEFT JOIN  '._DB_PREFIX_.'shop s ON g.id_shop_group = s.id_shop_group
691				LEFT JOIN  '._DB_PREFIX_.'shop_url u ON u.id_shop = s.id_shop
692				ORDER BY g.name, s.name, u.domain';
693		$results = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sql);
694		foreach ($results as $row)
695		{
696			$id_shop_group = $row['id_shop_group'];
697			$id_shop = $row['id_shop'];
698			$id_shop_url = $row['id_shop_url'];
699
700			// Group list
701			if (!isset($tree[$id_shop_group]))
702				$tree[$id_shop_group] = array(
703					'data' => array(
704						'title' => '<b>'.$this->l('Group').'</b> '.$row['group_name'],
705						'icon' => 'themes/'.$this->context->employee->bo_theme.'/img/tree-multishop-groups.png',
706						'attr' => array(
707							'href' => $this->context->link->getAdminLink('AdminShop').'&id_shop_group='.$id_shop_group,
708							'title' => sprintf($this->l('Click here to display the shops in the %s shop group', 'AdminShop', false, false), $row['group_name']),
709						),
710					),
711					'attr' => array(
712						'id' => 'tree-group-'.$id_shop_group,
713					),
714					'children' => array(),
715				);
716
717			// Shop list
718			if (!$id_shop)
719				continue;
720
721			if (!isset($tree[$id_shop_group]['children'][$id_shop]))
722				$tree[$id_shop_group]['children'][$id_shop] = array(
723					'data' => array(
724						'title' => $row['shop_name'],
725						'icon' => 'themes/'.$this->context->employee->bo_theme.'/img/tree-multishop-shop.png',
726						'attr' => array(
727							'href' => $this->context->link->getAdminLink('AdminShopUrl').'&id_shop='.$id_shop,
728							'title' => sprintf($this->l('Click here to display the URLs of the %s shop', 'AdminShop', false, false), $row['shop_name']),
729						)
730					),
731					'attr' => array(
732						'id' => 'tree-shop-'.$id_shop,
733					),
734					'children' => array(),
735				);
736			// Url list
737			if (!$id_shop_url)
738				continue;
739
740			if (!isset($tree[$id_shop_group]['children'][$id_shop]['children'][$id_shop_url]))
741			{
742				$url = $row['domain'].$row['physical_uri'].$row['virtual_uri'];
743				if (strlen($url) > 23)
744					$url = substr($url, 0, 23).'...';
745
746				$tree[$id_shop_group]['children'][$id_shop]['children'][$id_shop_url] = array(
747					'data' => array(
748						'title' => $url,
749						'icon' => 'themes/'.$this->context->employee->bo_theme.'/img/tree-multishop-url.png',
750						'attr' => array(
751							'href' => $this->context->link->getAdminLink('AdminShopUrl').'&updateshop_url&id_shop_url='.$id_shop_url,
752							'title' => $row['domain'].$row['physical_uri'].$row['virtual_uri'],
753						)
754					),
755					'attr' => array(
756						'id' => 'tree-url-'.$id_shop_url,
757					),
758				);
759			}
760		}
761
762		// jstree need to have children as array and not object, so we use sort to get clean keys
763		// DO NOT REMOVE this code, even if it seems really strange ;)
764		sort($tree);
765		foreach ($tree as &$groups)
766		{
767			sort($groups['children']);
768			foreach ($groups['children'] as &$shops)
769				sort($shops['children']);
770		}
771
772		$tree = array(array(
773			'data' => array(
774				'title' => '<b>'.$this->l('Shop groups list').'</b>',
775				'icon' => 'themes/'.$this->context->employee->bo_theme.'/img/tree-multishop-root.png',
776				'attr' => array(
777					'href' => $this->context->link->getAdminLink('AdminShopGroup'),
778					'title' => $this->l('Click here to display the list of shop groups', 'AdminShop', false, false),
779				)
780			),
781			'attr' => array(
782				'id' => 'tree-root',
783			),
784			'state' => 'open',
785			'children' => $tree,
786		));
787
788		die(Tools::jsonEncode($tree));
789	}
790}