Ejemplo n.º 1
0
    public function __construct($id = NULL, $id_lang = NULL)
    {
        $this->def = ObjectModel::getDefinition($this);
        // Check if the id configuration is set in the configuration_lang table.
        // Otherwise configuration is not set as translated configuration.
        if ($id !== null) {
            $id_translated = Db::getInstance()->executeS('				SELECT `' . bqSQL($this->def['primary']) . '`
				FROM `' . bqSQL(_DB_PREFIX_ . $this->def['table']) . '_lang`
				WHERE `' . bqSQL($this->def['primary']) . '`=' . (int) $id . ' LIMIT 0,1
			');
            if (empty($id_translated)) {
                $id = null;
            }
        }
        parent::__construct($id, $id_lang);
    }
Ejemplo n.º 2
0
    public function getFilteredObjectDetails()
    {
        $objects = array();
        if (!isset($this->urlFragments['display'])) {
            $this->fieldsToDisplay = 'full';
        }
        //get entity details
        $object = new $this->resourceConfiguration['retrieveData']['className']((int) $this->urlSegment[1]);
        if ($object->id) {
            $objects[] = $object;
            // Check if Object is accessible for this/those id_shop
            $assoc = Shop::getAssoTable($this->resourceConfiguration['retrieveData']['table']);
            if ($assoc !== false) {
                $check_shop_group = false;
                $sql = 'SELECT 1
	 						FROM `' . bqSQL(_DB_PREFIX_ . $this->resourceConfiguration['retrieveData']['table']);
                if ($assoc['type'] != 'fk_shop') {
                    $sql .= '_' . $assoc['type'];
                } else {
                    $def = ObjectModel::getDefinition($this->resourceConfiguration['retrieveData']['className']);
                    if (isset($def['fields']) && isset($def['fields']['id_shop_group'])) {
                        $check_shop_group = true;
                    }
                }
                $sql .= '`';
                foreach (self::$shopIDs as $id_shop) {
                    $OR[] = ' (id_shop = ' . (int) $id_shop . ($check_shop_group ? ' OR (id_shop = 0 AND id_shop_group=' . (int) Shop::getGroupFromShop((int) $id_shop) . ')' : '') . ') ';
                }
                $check = ' WHERE (' . implode('OR', $OR) . ') AND `' . bqSQL($this->resourceConfiguration['fields']['id']['sqlId']) . '` = ' . (int) $this->urlSegment[1];
                if (!Db::getInstance()->getValue($sql . $check)) {
                    $this->setError(404, 'This ' . $this->resourceConfiguration['retrieveData']['className'] . ' (' . (int) $this->urlSegment[1] . ') does not exists on this shop', 131);
                }
            }
            return $objects;
        }
        if (!count($this->errors)) {
            $this->objOutput->setStatus(404);
            $this->_outputEnabled = false;
            return false;
        }
    }
Ejemplo n.º 3
0
 /**
  * Manage page display (form, list...)
  *
  * @param string $className Allow to validate a different class than the current one
  */
 public function validateRules($class_name = false)
 {
     if (!$class_name) {
         $class_name = $this->className;
     }
     $object = new $class_name();
     if (method_exists($this, 'getValidationRules')) {
         $definition = $this->getValidationRules();
     } else {
         $definition = ObjectModel::getDefinition($class_name);
     }
     $default_language = new Language((int) Configuration::get('PS_LANG_DEFAULT'));
     foreach ($definition['fields'] as $field => $def) {
         $skip = array();
         if (in_array($field, array('passwd', 'no-picture'))) {
             $skip = array('required');
         }
         if (isset($def['lang']) && $def['lang']) {
             if (isset($def['required']) && $def['required']) {
                 $value = Tools::getValue($field . '_' . $default_language->id);
                 if (empty($value)) {
                     $this->errors[$field . '_' . $default_language->id] = sprintf(Tools::displayError('The field %1$s is required at least in %2$s.'), $object->displayFieldName($field, $class_name), $default_language->name);
                 }
             }
             foreach (Language::getLanguages(false) as $language) {
                 $value = Tools::getValue($field . '_' . $language['id_lang']);
                 if (!empty($value)) {
                     if (($error = $object->validateField($field, $value, $language['id_lang'], $skip, true)) !== true) {
                         $this->errors[$field . '_' . $language['id_lang']] = $error;
                     }
                 }
             }
         } else {
             if (($error = $object->validateField($field, Tools::getValue($field), null, $skip, true)) !== true) {
                 $this->errors[$field] = $error;
             }
         }
     }
     /* Overload this method for custom checking */
     $this->_childValidation();
     /* Checking for multilingual fields validity */
     if (isset($rules['validateLang']) && is_array($rules['validateLang'])) {
         foreach ($rules['validateLang'] as $field_lang => $function) {
             foreach ($languages as $language) {
                 if (($value = Tools::getValue($field_lang . '_' . $language['id_lang'])) !== false && !empty($value)) {
                     if (Tools::strtolower($function) == 'iscleanhtml' && Configuration::get('PS_ALLOW_HTML_IFRAME')) {
                         $res = Validate::$function($value, true);
                     } else {
                         $res = Validate::$function($value);
                     }
                     if (!$res) {
                         $this->errors[$field_lang . '_' . $language['id_lang']] = sprintf(Tools::displayError('The %1$s field (%2$s) is invalid.'), call_user_func(array($class_name, 'displayFieldName'), $field_lang, $class_name), $language['name']);
                     }
                 }
             }
         }
     }
 }
Ejemplo n.º 4
0
 /**
  * renderForm contains all necessary initialization needed for all tabs
  *
  * @return string|void
  */
 public function renderForm()
 {
     // This nice code (irony) is here to store the product name, because the row after will erase product name in multishop context
     $this->product_name = $this->object->name[$this->context->language->id];
     if (!method_exists($this, 'initForm' . $this->tab_display)) {
         return;
     }
     $product = $this->object;
     // Product for multishop
     $this->context->smarty->assign('bullet_common_field', '');
     if (Shop::isFeatureActive() && $this->display == 'edit') {
         if (Shop::getContext() != Shop::CONTEXT_SHOP) {
             $this->context->smarty->assign(array('display_multishop_checkboxes' => true, 'multishop_check' => Tools::getValue('multishop_check')));
         }
         if (Shop::getContext() != Shop::CONTEXT_ALL) {
             $this->context->smarty->assign('bullet_common_field', '<i class="icon-circle text-orange"></i>');
             $this->context->smarty->assign('display_common_field', true);
         }
     }
     $this->tpl_form_vars['tabs_preloaded'] = $this->available_tabs;
     $this->tpl_form_vars['product_type'] = (int) Tools::getValue('type_product', $product->getType());
     $this->getLanguages();
     $this->tpl_form_vars['id_lang_default'] = Configuration::get('PS_LANG_DEFAULT');
     $this->tpl_form_vars['currentIndex'] = self::$currentIndex;
     $this->tpl_form_vars['display_multishop_checkboxes'] = Shop::isFeatureActive() && Shop::getContext() != Shop::CONTEXT_SHOP && $this->display == 'edit';
     $this->fields_form = array('');
     $this->tpl_form_vars['token'] = $this->token;
     $this->tpl_form_vars['combinationImagesJs'] = $this->getCombinationImagesJs();
     $this->tpl_form_vars['PS_ALLOW_ACCENTED_CHARS_URL'] = (int) Configuration::get('PS_ALLOW_ACCENTED_CHARS_URL');
     $this->tpl_form_vars['post_data'] = Tools::jsonEncode($_POST);
     $this->tpl_form_vars['save_error'] = !empty($this->errors);
     $this->tpl_form_vars['ps_force_friendly_product'] = Configuration::get('PS_FORCE_FRIENDLY_PRODUCT');
     // autoload rich text editor (tiny mce)
     $this->tpl_form_vars['tinymce'] = true;
     $iso = $this->context->language->iso_code;
     $this->tpl_form_vars['iso'] = file_exists(_PS_CORE_DIR_ . '/js/tiny_mce/langs/' . $iso . '.js') ? $iso : 'en';
     $this->tpl_form_vars['path_css'] = _THEME_CSS_DIR_;
     $this->tpl_form_vars['ad'] = __PS_BASE_URI__ . basename(_PS_ADMIN_DIR_);
     if (Validate::isLoadedObject($this->object)) {
         $id_product = (int) $this->object->id;
     } else {
         $id_product = (int) Tools::getvalue('id_product');
     }
     $this->tpl_form_vars['form_action'] = $this->context->link->getAdminLink('AdminProducts') . '&' . ($id_product ? 'id_product=' . (int) $id_product : 'addproduct');
     $this->tpl_form_vars['id_product'] = $id_product;
     //Добавляем в форму переменную с рекомендуемым reference = максимальный в базе + 1
     if (!$id_product) {
         $result = "";
         $sql = "SELECT LPAD(max(LPAD(RIGHT(`reference`, 5),5,0))+1,5,0) as ref FROM `" . _DB_PREFIX_ . "product`\nWHERE `reference` REGEXP '^-?[0-9]+\$'";
         $result = Db::getInstance()->getValue($sql);
         if ($result) {
             $this->tpl_form_vars['next_free_reference'] = $result;
         }
     }
     // Transform configuration option 'upload_max_filesize' in octets
     $upload_max_filesize = Tools::getOctets(ini_get('upload_max_filesize'));
     // Transform configuration option 'upload_max_filesize' in MegaOctets
     $upload_max_filesize = $upload_max_filesize / 1024 / 1024;
     $this->tpl_form_vars['upload_max_filesize'] = $upload_max_filesize;
     $this->tpl_form_vars['country_display_tax_label'] = $this->context->country->display_tax_label;
     $this->tpl_form_vars['has_combinations'] = $this->object->hasAttributes();
     $this->product_exists_in_shop = true;
     if ($this->display == 'edit' && Validate::isLoadedObject($product) && Shop::isFeatureActive() && Shop::getContext() == Shop::CONTEXT_SHOP && !$product->isAssociatedToShop($this->context->shop->id)) {
         $this->product_exists_in_shop = false;
         if ($this->tab_display == 'Informations') {
             $this->displayWarning($this->l('Warning: The product does not exist in this shop'));
         }
         $default_product = new Product();
         $definition = ObjectModel::getDefinition($product);
         foreach ($definition['fields'] as $field_name => $field) {
             if (isset($field['shop']) && $field['shop']) {
                 $product->{$field_name} = ObjectModel::formatValue($default_product->{$field_name}, $field['type']);
             }
         }
     }
     // let's calculate this once for all
     if (!Validate::isLoadedObject($this->object) && Tools::getValue('id_product')) {
         $this->errors[] = 'Unable to load object';
     } else {
         $this->_displayDraftWarning($this->object->active);
         // if there was an error while saving, we don't want to lose posted data
         if (!empty($this->errors)) {
             $this->copyFromPost($this->object, $this->table);
         }
         $this->initPack($this->object);
         $this->{'initForm' . $this->tab_display}($this->object);
         $this->tpl_form_vars['product'] = $this->object;
         if ($this->ajax) {
             if (!isset($this->tpl_form_vars['custom_form'])) {
                 throw new PrestaShopException('custom_form empty for action ' . $this->tab_display);
             } else {
                 return $this->tpl_form_vars['custom_form'];
             }
         }
     }
     $parent = parent::renderForm();
     $this->addJqueryPlugin(array('autocomplete', 'fancybox', 'typewatch'));
     return $parent;
 }
 /**
  * renderForm contains all necessary initialization needed for all tabs
  *
  * @return void
  */
 public function renderForm()
 {
     // This nice code (irony) is here to store the product name, because the row after will erase product name in multishop context
     $this->product_name = $this->object->name[$this->context->language->id];
     if (!method_exists($this, 'initForm' . $this->tab_display)) {
         return;
     }
     $product = $this->object;
     // Product for multishop
     $this->context->smarty->assign('bullet_common_field', '');
     if (Shop::isFeatureActive() && $this->display == 'edit') {
         if (Shop::getContext() != Shop::CONTEXT_SHOP) {
             $this->context->smarty->assign(array('display_multishop_checkboxes' => true, 'multishop_check' => Tools::getValue('multishop_check')));
         }
         if (Shop::getContext() != Shop::CONTEXT_ALL) {
             $this->context->smarty->assign('bullet_common_field', '<img src="themes/' . $this->context->employee->bo_theme . '/img/bullet_orange.png" style="vertical-align: bottom" />');
             $this->context->smarty->assign('display_common_field', true);
         }
     }
     $this->tpl_form_vars['tabs_preloaded'] = $this->available_tabs;
     $this->tpl_form_vars['product_type'] = (int) Tools::getValue('type_product', $product->getType());
     $this->getLanguages();
     $this->tpl_form_vars['id_lang_default'] = Configuration::get('PS_LANG_DEFAULT');
     $this->tpl_form_vars['currentIndex'] = self::$currentIndex;
     $this->tpl_form_vars['display_multishop_checkboxes'] = Shop::isFeatureActive() && Shop::getContext() != Shop::CONTEXT_SHOP && $this->display == 'edit';
     $this->fields_form = array('');
     $this->tpl_form_vars['token'] = $this->token;
     $this->tpl_form_vars['combinationImagesJs'] = $this->getCombinationImagesJs();
     $this->tpl_form_vars['PS_ALLOW_ACCENTED_CHARS_URL'] = (int) Configuration::get('PS_ALLOW_ACCENTED_CHARS_URL');
     $this->tpl_form_vars['post_data'] = Tools::jsonEncode($_POST);
     $this->tpl_form_vars['save_error'] = !empty($this->errors);
     // autoload rich text editor (tiny mce)
     $this->tpl_form_vars['tinymce'] = true;
     $iso = $this->context->language->iso_code;
     $this->tpl_form_vars['iso'] = file_exists(_PS_ROOT_DIR_ . '/js/tiny_mce/langs/' . $iso . '.js') ? $iso : 'en';
     $this->tpl_form_vars['ad'] = dirname($_SERVER['PHP_SELF']);
     if (Validate::isLoadedObject($this->object)) {
         $id_product = (int) $this->object->id;
     } else {
         $id_product = (int) Tools::getvalue('id_product');
     }
     $this->tpl_form_vars['form_action'] = $this->context->link->getAdminLink('AdminProducts') . '&amp;' . ($id_product ? 'id_product=' . (int) $id_product : 'addproduct');
     $this->tpl_form_vars['id_product'] = $id_product;
     // Transform configuration option 'upload_max_filesize' in octets
     $upload_max_filesize = Tools::getOctets(ini_get('upload_max_filesize'));
     // Transform configuration option 'upload_max_filesize' in MegaOctets
     $upload_max_filesize = $upload_max_filesize / 1024 / 1024;
     $this->tpl_form_vars['upload_max_filesize'] = $upload_max_filesize;
     $this->tpl_form_vars['country_display_tax_label'] = $this->context->country->display_tax_label;
     $this->tpl_form_vars['has_combinations'] = $this->object->hasAttributes();
     $this->product_exists_in_shop = true;
     if ($this->display == 'edit' && Validate::isLoadedObject($product) && Shop::isFeatureActive() && Shop::getContext() == Shop::CONTEXT_SHOP && !$product->isAssociatedToShop($this->context->shop->id)) {
         $this->product_exists_in_shop = false;
         if ($this->tab_display == 'Informations') {
             $this->displayWarning($this->l('Warning: The product does not exist in this shop.'));
         }
         $default_product = new Product();
         $definition = ObjectModel::getDefinition($product);
         foreach ($definition['fields'] as $field_name => $field) {
             if (isset($field['shop']) && $field['shop']) {
                 $product->{$field_name} = ObjectModel::formatValue($default_product->{$field_name}, $field['type']);
             }
         }
     }
     // let's calculate this once for all
     if (!Validate::isLoadedObject($this->object) && Tools::getValue('id_product')) {
         $this->errors[] = 'Unable to load object';
     } else {
         $this->_displayDraftWarning($this->object->active);
         // if there was an error while saving, we don't want to lose posted data
         if (!empty($this->errors)) {
             $this->copyFromPost($this->object, $this->table);
         }
         $this->initPack($this->object);
         $this->{'initForm' . $this->tab_display}($this->object);
         $this->tpl_form_vars['product'] = $this->object;
         if ($this->ajax) {
             if (!isset($this->tpl_form_vars['custom_form'])) {
                 throw new PrestaShopException('custom_form empty for action ' . $this->tab_display);
             } else {
                 return $this->tpl_form_vars['custom_form'];
             }
         }
     }
     $parent = parent::renderForm();
     $this->addJqueryPlugin(array('autocomplete', 'fancybox', 'typewatch'));
     return $parent;
 }
 public function renderForm()
 {
     $this->product_name = $this->object->name[$this->context->language->id];
     if (!method_exists($this, 'initForm' . $this->tab_display)) {
         return;
     }
     $product = $this->object;
     $this->context->smarty->assign('bullet_common_field', '');
     if (Shop::isFeatureActive() && $this->display == 'edit') {
         if (Shop::getContext() != Shop::CONTEXT_SHOP) {
             $this->context->smarty->assign(array('display_multishop_checkboxes' => true, 'multishop_check' => Tools::getValue('multishop_check')));
         }
         if (Shop::getContext() != Shop::CONTEXT_ALL) {
             $this->context->smarty->assign('bullet_common_field', '<i class="icon-circle text-orange"></i>');
             $this->context->smarty->assign('display_common_field', true);
         }
     }
     $this->tpl_form_vars['tabs_preloaded'] = $this->available_tabs;
     $this->tpl_form_vars['product_type'] = (int) Tools::getValue('type_product', $product->getType());
     $this->getLanguages();
     $this->tpl_form_vars['id_lang_default'] = Configuration::get('PS_LANG_DEFAULT');
     $this->tpl_form_vars['currentIndex'] = self::$currentIndex;
     $this->tpl_form_vars['display_multishop_checkboxes'] = Shop::isFeatureActive() && Shop::getContext() != Shop::CONTEXT_SHOP && $this->display == 'edit';
     $this->fields_form = array('');
     $this->tpl_form_vars['token'] = $this->token;
     $this->tpl_form_vars['combinationImagesJs'] = $this->getCombinationImagesJs();
     $this->tpl_form_vars['PS_ALLOW_ACCENTED_CHARS_URL'] = (int) Configuration::get('PS_ALLOW_ACCENTED_CHARS_URL');
     $this->tpl_form_vars['post_data'] = json_encode($_POST);
     $this->tpl_form_vars['save_error'] = !empty($this->errors);
     $this->tpl_form_vars['mod_evasive'] = Tools::apacheModExists('evasive');
     $this->tpl_form_vars['mod_security'] = Tools::apacheModExists('security');
     $this->tpl_form_vars['ps_force_friendly_product'] = Configuration::get('PS_FORCE_FRIENDLY_PRODUCT');
     $this->tpl_form_vars['tinymce'] = true;
     $iso = $this->context->language->iso_code;
     $this->tpl_form_vars['iso'] = file_exists(_PS_CORE_DIR_ . '/js/tiny_mce/langs/' . $iso . '.js') ? $iso : 'en';
     $this->tpl_form_vars['path_css'] = _THEME_CSS_DIR_;
     $this->tpl_form_vars['ad'] = __PS_BASE_URI__ . basename(_PS_ADMIN_DIR_);
     if (Validate::isLoadedObject($this->object)) {
         $id_product = (int) $this->object->id;
     } else {
         $id_product = (int) Tools::getvalue('id_product');
     }
     $this->tpl_form_vars['form_action'] = $this->context->link->getAdminLink('AdminProducts') . '&' . ($id_product ? 'id_product=' . (int) $id_product : 'addproduct');
     $this->tpl_form_vars['id_product'] = $id_product;
     $upload_max_filesize = Tools::getOctets(ini_get('upload_max_filesize'));
     $upload_max_filesize = $upload_max_filesize / 1024 / 1024;
     $this->tpl_form_vars['upload_max_filesize'] = $upload_max_filesize;
     $this->tpl_form_vars['country_display_tax_label'] = $this->context->country->display_tax_label;
     $this->tpl_form_vars['has_combinations'] = $this->object->hasAttributes();
     $this->product_exists_in_shop = true;
     if ($this->display == 'edit' && Validate::isLoadedObject($product) && Shop::isFeatureActive() && Shop::getContext() == Shop::CONTEXT_SHOP && !$product->isAssociatedToShop($this->context->shop->id)) {
         $this->product_exists_in_shop = false;
         if ($this->tab_display == 'Informations') {
             $this->displayWarning($this->l('Warning: The product does not exist in this shop'));
         }
         $default_product = new Product();
         $definition = ObjectModel::getDefinition($product);
         foreach ($definition['fields'] as $field_name => $field) {
             if (isset($field['shop']) && $field['shop']) {
                 $product->{$field_name} = ObjectModel::formatValue($default_product->{$field_name}, $field['type']);
             }
         }
     }
     if (!Validate::isLoadedObject($this->object) && Tools::getValue('id_product')) {
         $this->errors[] = 'Unable to load object';
     } else {
         $this->_displayDraftWarning($this->object->active);
         if (!empty($this->errors)) {
             $this->copyFromPost($this->object, $this->table);
         }
         $this->initPack($this->object);
         $this->{'initForm' . $this->tab_display}($this->object);
         $this->tpl_form_vars['product'] = $this->object;
         if ($this->ajax) {
             if (!isset($this->tpl_form_vars['custom_form'])) {
                 throw new PrestaShopException('custom_form empty for action ' . $this->tab_display);
             } else {
                 return $this->tpl_form_vars['custom_form'];
             }
         }
     }
     $parent = parent::renderForm();
     $this->addJqueryPlugin(array('autocomplete', 'fancybox', 'typewatch'));
     return $parent;
 }
Ejemplo n.º 7
0
 /**
  * Return the field value for the specified language if the field is multilang,
  * else the field value.
  *
  * @since 1.5.0.1
  * @param string   $field_name
  * @param int|null $id_lang
  *
  * @return mixed
  * @throws PrestaShopException
  */
 public function getFieldByLang($field_name, $id_lang = null)
 {
     $definition = ObjectModel::getDefinition($this);
     // Is field in definition?
     if ($definition && isset($definition['fields'][$field_name])) {
         $field = $definition['fields'][$field_name];
         // Is field multilang?
         if (isset($field['lang']) && $field['lang']) {
             if (is_array($this->{$field_name})) {
                 return $this->{$field_name}[$id_lang ? $id_lang : Context::getContext()->language->id];
             }
         }
         return $this->{$field_name};
     } else {
         throw new PrestaShopException('Could not load field from definition.');
     }
 }
 public function getValidationRules()
 {
     $step_number = (int) Tools::getValue('step_number');
     if (!$step_number) {
         return;
     }
     if ($step_number == 4 && !Shop::isFeatureActive() || $step_number == 5 && Shop::isFeatureActive()) {
         return array('fields' => array());
     }
     $step_fields = array(1 => array('name', 'delay', 'grade', 'url'), 2 => array('is_free', 'id_tax_rules_group', 'shipping_handling', 'shipping_method', 'range_behavior'), 3 => array('range_behavior', 'max_height', 'max_width', 'max_depth', 'max_weight'), 4 => array());
     if (Shop::isFeatureActive()) {
         $tmp = $step_fields;
         $step_fields = array_slice($tmp, 0, 1, true) + array(2 => array('shop'));
         $step_fields[3] = $tmp[2];
         $step_fields[4] = $tmp[3];
     }
     $definition = ObjectModel::getDefinition('Carrier');
     foreach ($definition['fields'] as $field => $def) {
         if (is_array($step_fields[$step_number]) && !in_array($field, $step_fields[$step_number])) {
             unset($definition['fields'][$field]);
         }
     }
     return $definition;
 }
Ejemplo n.º 9
0
    /**
     * Chooses the "optimal" image type to use for product image urls.
     *
     * The type is chosen based on which image type has a width closest to `self::OPTIMAL_PRODUCT_IMAGE_WIDTH`.
     *
     * @return string|false the image type name or false if not found.
     */
    protected function chooseOptimalImageType()
    {
        $definition = _PS_VERSION_ >= '1.5' ? ObjectModel::getDefinition('ImageType') : array();
        $table_name = isset($definition['table']) ? $definition['table'] : 'image_type';
        $available_image_types = Db::getInstance()->executeS('
			SELECT * FROM `' . _DB_PREFIX_ . pSQL($table_name) . '`
			WHERE `products` = 1
			ORDER BY `width` ASC
		');
        $optimal = self::OPTIMAL_PRODUCT_IMAGE_WIDTH;
        $found = array();
        foreach ($available_image_types as $available) {
            if (empty($found) || abs($optimal - (int) $found['width']) > abs((int) $available['width'] - $optimal)) {
                $found = $available;
            }
        }
        return isset($found['name']) ? $found['name'] : false;
    }
Ejemplo n.º 10
0
 /**
  * Fill (hydrate) a list of objects in order to get a collection of these objects
  *
  * @param string $class Class of objects to hydrate
  * @param array $datas List of data (multi-dimensional array)
  * @param int $id_lang
  * @return array
  * @throws Exception
  */
 public static function hydrateCollection($class, array $datas, $id_lang = null)
 {
     if (!class_exists($class)) {
         throw new Exception("Class '{$class}' not found");
     }
     $collection = array();
     $rows = array();
     if ($datas) {
         $definition = ObjectModel::getDefinition($class);
         if (!array_key_exists($definition['primary'], $datas[0])) {
             throw new Exception("Identifier '{$definition['primary']}' not found for class '{$class}'");
         }
         foreach ($datas as $row) {
             // Get object common properties
             $id = $row[$definition['primary']];
             if (!isset($rows[$id])) {
                 $rows[$id] = $row;
             }
         }
     }
     // Hydrate objects
     foreach ($rows as $row) {
         $obj = new $class();
         $obj->hydrate($row);
         $collection[] = $obj;
     }
     return $collection;
 }
 protected function loadObject($opt = false)
 {
     $result = parent::loadObject($opt);
     if ($result && Validate::isLoadedObject($this->object)) {
         if (Shop::getContext() == Shop::CONTEXT_SHOP && Shop::isFeatureActive() && !$this->object->isAssociatedToShop()) {
             $default_offer = new AphOffer((int) $this->object->id, false, null, (int) $this->object->id_shop_default);
             $def = ObjectModel::getDefinition($this->object);
             foreach ($def['fields'] as $field_name => $row) {
                 if (is_array($default_offer->{$field_name})) {
                     foreach ($default_offer->{$field_name} as $key => $value) {
                         $this->object->{$field_name}[$key] = $value;
                     }
                 } else {
                     $this->object->{$field_name} = $default_offer->{$field_name};
                 }
             }
         }
     }
     return $result;
 }
Ejemplo n.º 12
0
 /**
  * Get definition of an association
  *
  * @param string $association
  * @return array
  */
 protected function getDefinition($association)
 {
     if (!$association) {
         return $this->definition;
     }
     if (!isset($this->association_definition[$association])) {
         $definition = $this->definition;
         $split = explode('.', $association);
         $is_lang = false;
         for ($i = 0, $total_association = count($split); $i < $total_association; $i++) {
             $asso = $split[$i];
             // Check is current association exists in current definition
             if (!isset($definition['associations'][$asso])) {
                 throw new PrestaShopException('Association ' . $asso . ' not found for class ' . $this->definition['classname']);
             }
             $current_def = $definition['associations'][$asso];
             // Special case for lang alias
             if ($asso == self::LANG_ALIAS) {
                 $is_lang = true;
                 break;
             }
             $classname = isset($current_def['object']) ? $current_def['object'] : Tools::toCamelCase($asso, true);
             $definition = ObjectModel::getDefinition($classname);
         }
         // Get definition of associated entity and add information on current association
         $current_def['name'] = $asso;
         if (!isset($current_def['object'])) {
             $current_def['object'] = Tools::toCamelCase($asso, true);
         }
         if (!isset($current_def['field'])) {
             $current_def['field'] = 'id_' . $asso;
         }
         if (!isset($current_def['foreign_field'])) {
             $current_def['foreign_field'] = 'id_' . $asso;
         }
         if ($total_association > 1) {
             unset($split[$total_association - 1]);
             $current_def['complete_field'] = implode('.', $split) . '.' . $current_def['field'];
         } else {
             $current_def['complete_field'] = $current_def['field'];
         }
         $current_def['complete_foreign_field'] = $association . '.' . $current_def['field'];
         $definition['is_lang'] = $is_lang;
         $definition['asso'] = $current_def;
         $this->association_definition[$association] = $definition;
     } else {
         $definition = $this->association_definition[$association];
     }
     return $definition;
 }
Ejemplo n.º 13
0
    /**
     * Check if user is already registered in database
     *
     * @param string $id_user user id
     * @param $return_id boolean
     * @return Customer ID if found, false otherwise
     */
    public static function customerExists($id_user, $return_id = false)
    {
        $definition = ObjectModel::getDefinition($this);
        $result = Db::getInstance()->getValue('
			SELECT id_customer
			FROM `' . _DB_PREFIX_ . bqSQL($definition['table']) . '`
			WHERE `id_user` = \'' . pSQL($id_user) . '\'');
        return $return_id ? (int) $result : (bool) $result;
    }