Example #1
0
 public function getContent()
 {
     $output = '<h2>' . $this->displayName . '</h2>';
     if (Tools::isSubmit('submitBlockRss')) {
         $urlfeed = strval(Tools::getValue('urlfeed'));
         $title = strval(Tools::getValue('title'));
         $nbr = intval(Tools::getValue('nbr'));
         if ($urlfeed and !Validate::isUrl($urlfeed)) {
             $errors[] = $this->l('Invalid feed URL');
         } elseif (!$title or empty($title) or !Validate::isGenericName($title)) {
             $errors[] = $this->l('Invalid title');
         } elseif (!$nbr or $nbr <= 0 or !Validate::isInt($nbr)) {
             $errors[] = $this->l('Invalid number of feeds');
         } else {
             Configuration::updateValue('RSS_FEED_URL', $urlfeed);
             Configuration::updateValue('RSS_FEED_TITLE', $title);
             Configuration::updateValue('RSS_FEED_NBR', $nbr);
         }
         if (isset($errors) and sizeof($errors)) {
             $output .= $this->displayError(implode('<br />', $errors));
         } else {
             $output .= $this->displayConfirmation($this->l('Settings updated'));
         }
     }
     return $output . $this->displayForm();
 }
Example #2
0
    /**
     * Add several tags in database and link it to a product
     *
     * @param integer $id_lang Language id
     * @param integer $id_product Product id to link tags with
     * @param string $string Tags separated by commas
     *
     * @return boolean Operation success
     */
    public static function addTags($id_lang, $id_product, $string)
    {
        if (!Validate::isUnsignedId($id_lang) or Validate::isTagsList($string)) {
            Tools::displayError();
        }
        $tmpTab = array_unique(array_map('trim', explode(',', $string)));
        $list = array();
        foreach ($tmpTab as $tag) {
            if (!Validate::isGenericName($tag)) {
                return false;
            }
            $tagObj = new Tag(NULL, trim($tag), intval($id_lang));
            /* Tag does not exist in database */
            if (!Validate::isLoadedObject($tagObj)) {
                $tagObj->name = trim($tag);
                $tagObj->id_lang = intval($id_lang);
                $tagObj->add();
            }
            if (!in_array($tagObj->id, $list)) {
                $list[] = $tagObj->id;
            }
        }
        $data = '';
        foreach ($list as $tag) {
            $data .= '(' . intval($tag) . ',' . intval($id_product) . '),';
        }
        $data = rtrim($data, ',');
        if (!Validate::isValuesList($list)) {
            Tools::displayError();
        }
        return Db::getInstance()->Execute('
		INSERT INTO `' . _DB_PREFIX_ . 'product_tag` (`id_tag`, `id_product`) 
		VALUES ' . $data);
    }
Example #3
0
 /**
  * Add several tags in database and link it to a product
  *
  * @param integer $id_lang Language id
  * @param integer $id_simpleblog_post Post id to link tags with
  * @param string|array $tag_list List of tags, as array or as a string with comas
  * @return boolean Operation success
  */
 public static function addTags($id_lang, $id_simpleblog_post, $tag_list, $separator = ',')
 {
     if (!Validate::isUnsignedId($id_lang)) {
         return false;
     }
     if (!is_array($tag_list)) {
         $tag_list = array_filter(array_unique(array_map('trim', preg_split('#\\' . $separator . '#', $tag_list, null, PREG_SPLIT_NO_EMPTY))));
     }
     $list = array();
     if (is_array($tag_list)) {
         foreach ($tag_list as $tag) {
             if (!Validate::isGenericName($tag)) {
                 return false;
             }
             $tag_obj = new SimpleBlogTag(null, $tag, (int) $id_lang);
             /* Tag does not exist in database */
             if (!Validate::isLoadedObject($tag_obj)) {
                 $tag_obj->name = $tag;
                 $tag_obj->id_lang = (int) $id_lang;
                 $tag_obj->add();
             }
             if (!in_array($tag_obj->id, $list)) {
                 $list[] = $tag_obj->id;
             }
         }
     }
     $data = '';
     foreach ($list as $tag) {
         $data .= '(' . (int) $tag . ',' . (int) $id_simpleblog_post . '),';
     }
     $data = rtrim($data, ',');
     $sql = 'INSERT INTO `' . _DB_PREFIX_ . 'simpleblog_post_tag` (`id_simpleblog_tag`, `id_simpleblog_post`) VALUES ' . $data;
     return Db::getInstance()->execute($sql);
 }
Example #4
0
    public static function loadData($p = 1, $limit = 50, $orderBy = NULL, $orderWay = NULL, $filter = array())
    {
        $where = '';
        if (!empty($filter['id_onepage']) && Validate::isInt($filter['id_onepage'])) {
            $where .= ' AND a.`id_onepage`=' . intval($filter['id_onepage']);
        }
        if (!empty($filter['view_name']) && Validate::isEntityName($filter['view_name'])) {
            $where .= ' AND a.`view_name` LIKE "%' . pSQL($filter['view_name']) . '%"';
        }
        if (!empty($filter['meta_title']) && Validate::isGenericName($filter['meta_title'])) {
            $where .= ' AND a.`meta_title` LIKE "%' . pSQL($filter['meta_title']) . '%"';
        }
        if (!empty($filter['rewrite']) && Validate::isLinkRewrite($filter['rewrite'])) {
            $where .= ' AND a.`rewrite` LIKE "%' . pSQL($filter['rewrite']) . '%"';
        }
        if (!is_null($orderBy) and !is_null($orderWay)) {
            $postion = 'ORDER BY ' . pSQL($orderBy) . ' ' . pSQL($orderWay);
        } else {
            $postion = 'ORDER BY `id_onepage` DESC';
        }
        $total = Db::getInstance()->getRow('SELECT count(*) AS total FROM `' . DB_PREFIX . 'onepage` a
				WHERE 1 ' . $where);
        if ($total == 0) {
            return false;
        }
        $result = Db::getInstance()->getAll('SELECT a.* FROM `' . DB_PREFIX . 'onepage` a
				WHERE 1 ' . $where . '
				' . $postion . '
				LIMIT ' . ($p - 1) * $limit . ',' . (int) $limit);
        $rows = array('total' => $total['total'], 'items' => $result);
        return $rows;
    }
 public function getContent()
 {
     $output = null;
     if (Tools::isSubmit('submit' . $this->name)) {
         $my_module_name = strval(Tools::getValue('INSTAMOJO'));
         if (!$my_module_name || empty($my_module_name) || !Validate::isGenericName($my_module_name)) {
             $output .= $this->displayError($this->l('Invalid Configuration value'));
         } else {
             Configuration::updateValue('INSTAMOJO', $my_module_name);
             $output .= $this->displayConfirmation($this->l('Settings updated'));
         }
     }
     return $this->display(__FILE__, '/views/templates/admin/configure_instamojo.tpl');
 }
 public function getContent()
 {
     $output = null;
     if (Tools::isSubmit('submit' . $this->name)) {
         $my_module_name = strval(Tools::getValue('SHOPCONNECTORMODULE_HASH'));
         if (!$my_module_name || empty($my_module_name) || !Validate::isGenericName($my_module_name)) {
             $output .= $this->displayError($this->l('Niepoprawna konfiguracja sklepu lub brak hasha.'));
         } else {
             Configuration::updateValue('SHOPCONNECTORMODULE_HASH', $my_module_name);
             $output .= $this->displayConfirmation($this->l('Settings updated'));
         }
     }
     return $output . $this->displayForm();
 }
Example #7
0
 public function getContent()
 {
     $output = null;
     if (Tools::isSubmit('submit' . $this->name)) {
         $ps_module_name = strval(Tools::getValue('PSMODULE_NAME'));
         if (!$ps_module_name || empty($ps_module_name) || !Validate::isGenericName($ps_module_name)) {
             $output .= $this->displayError($this->l('Invalid Configuration value'));
         } else {
             Configuration::updateValue('PSMODULE_NAME', $ps_module_name);
             $output .= $this->displayConfirmation($this->l('Settings updated'));
         }
     }
     return $output . $this->displayForm();
 }
Example #8
0
 /**
  * @see InstallAbstractModel::validate()
  */
 public function validate()
 {
     // List of required fields
     $required_fields = array('shop_name', 'shop_country', 'shop_timezone', 'admin_firstname', 'admin_lastname', 'admin_email', 'admin_password');
     foreach ($required_fields as $field) {
         if (!$this->session->{$field}) {
             $this->errors[$field] = $this->l('Field required');
         }
     }
     // Check shop name
     if ($this->session->shop_name && !Validate::isGenericName($this->session->shop_name)) {
         $this->errors['shop_name'] = $this->l('Invalid shop name');
     } else {
         if (strlen($this->session->shop_name) > 64) {
             $this->errors['shop_name'] = $this->l('The field %s is limited to %d characters', $this->l('shop name'), 64);
         }
     }
     // Check admin name
     if ($this->session->admin_firstname && !Validate::isName($this->session->admin_firstname)) {
         $this->errors['admin_firstname'] = $this->l('Your firstname contains some invalid characters');
     } else {
         if (strlen($this->session->admin_firstname) > 32) {
             $this->errors['admin_firstname'] = $this->l('The field %s is limited to %d characters', $this->l('firstname'), 32);
         }
     }
     if ($this->session->admin_lastname && !Validate::isName($this->session->admin_lastname)) {
         $this->errors['admin_lastname'] = $this->l('Your lastname contains some invalid characters');
     } else {
         if (strlen($this->session->admin_lastname) > 32) {
             $this->errors['admin_lastname'] = $this->l('The field %s is limited to %d characters', $this->l('lastname'), 32);
         }
     }
     // Check passwords
     if ($this->session->admin_password) {
         if (!Validate::isPasswdAdmin($this->session->admin_password)) {
             $this->errors['admin_password'] = $this->l('The password is incorrect (alphanumeric string with at least 8 characters)');
         } else {
             if ($this->session->admin_password != $this->session->admin_password_confirm) {
                 $this->errors['admin_password'] = $this->l('Password and its confirmation are different');
             }
         }
     }
     // Check email
     if ($this->session->admin_email && !Validate::isEmail($this->session->admin_email)) {
         $this->errors['admin_email'] = $this->l('This e-mail address is invalid');
     }
     return count($this->errors) ? false : true;
 }
Example #9
0
 public function getContent()
 {
     $this->registerHook('displayNav');
     //TODO: !!!
     $output = null;
     if (Tools::isSubmit('submit' . $this->name)) {
         $my_module_name = strval(Tools::getValue('MYMODULE_NAME'));
         if (!$my_module_name || empty($my_module_name) || !Validate::isGenericName($my_module_name)) {
             $output .= $this->displayError($this->l('Invalid Configuration value'));
         } else {
             Configuration::updateValue('MYMODULE_NAME', $my_module_name);
             $output .= $this->displayConfirmation($this->l('Settings updated'));
         }
     }
     $output .= $this->displayForm();
     $output .= $this->renderList();
     return $output;
 }
Example #10
0
 public function getContent()
 {
     $output = null;
     if (Tools::isSubmit('submit' . $this->name)) {
         $list_value = strval(Tools::getValue('PRODUCTUPDATE_LIST'));
         if (!$list_value || empty($list_value) || !Validate::isGenericName($list_value)) {
             $output .= $this->displayError($this->l('Invalid Configuration value'));
         } else {
             Configuration::updateValue('PRODUCTUPDATE_LIST', $list_value);
             Configuration::updateValue('PRODUCTUPDATE_STATUS', '0');
             return $this->display(__FILE__, 'productupdate.tpl');
             $output .= $this->displayConfirmation($this->l('Settings updated'));
         }
     }
     //$this->context->controller->addJS($this->_path.'productupdate.js');
     //return $this->display(__FILE__,'productupdate.tpl');
     return $output . $this->displayForm();
 }
Example #11
0
 public function getContent()
 {
     $output = '<h2>' . $this->displayName . '</h2>';
     if (Tools::isSubmit('submitBlockRss')) {
         $errors = array();
         $urlfeed = Tools::getValue('urlfeed');
         $title = Tools::getValue('title');
         $nbr = (int) Tools::getValue('nbr');
         if ($urlfeed and !Validate::isAbsoluteUrl($urlfeed)) {
             $errors[] = $this->l('Invalid feed URL');
         } elseif (!$title or empty($title) or !Validate::isGenericName($title)) {
             $errors[] = $this->l('Invalid title');
         } elseif (!$nbr or $nbr <= 0 or !Validate::isInt($nbr)) {
             $errors[] = $this->l('Invalid number of feeds');
         } elseif (stristr($urlfeed, $_SERVER['HTTP_HOST'] . __PS_BASE_URI__)) {
             $errors[] = $this->l('You have selected a feed URL on your own website. Please choose another URL');
         } elseif (!($contents = Tools::file_get_contents($urlfeed))) {
             $errors[] = $this->l('Feed is unreachable, check your URL');
         } else {
             try {
                 $xmlFeed = new XML_Feed_Parser($contents);
             } catch (XML_Feed_Parser_Exception $e) {
                 $errors[] = $this->l('Invalid feed:') . ' ' . $e->getMessage();
             }
         }
         if (!sizeof($errors)) {
             Configuration::updateValue('RSS_FEED_URL', $urlfeed);
             Configuration::updateValue('RSS_FEED_TITLE', $title);
             Configuration::updateValue('RSS_FEED_NBR', $nbr);
             $output .= $this->displayConfirmation($this->l('Settings updated'));
         } else {
             $output .= $this->displayError(implode('<br />', $errors));
         }
     } else {
         $errors = array();
         if (stristr(Configuration::get('RSS_FEED_URL'), $_SERVER['HTTP_HOST'] . __PS_BASE_URI__)) {
             $errors[] = $this->l('You have selected a feed URL on your own website. Please choose another URL');
         }
         if (sizeof($errors)) {
             $output .= $this->displayError(implode('<br />', $errors));
         }
     }
     return $output . $this->displayForm();
 }
 public function getContent()
 {
     $output = null;
     if (Tools::isSubmit('submit' . $this->name)) {
         $bla_email = strval(Tools::getValue('BLA_EMAIL'));
         if (empty($bla_email) || !Validate::isGenericName($bla_email)) {
             $output .= $this->displayError($this->l('Invalid Email value'));
         }
         if (empty($output)) {
             Configuration::updateValue('BLA_EMAIL', $bla_email);
             Configuration::updateValue('BLA_ACTIV_EMAIL', Tools::getValue('BLA_ACTIV_EMAIL'));
             Configuration::updateValue('BLA_ISLOG_CARUP', Tools::getValue('BLA_ISLOG_CARUP'));
             Configuration::updateValue('BLA_ISLOG_MODINST', Tools::getValue('BLA_ISLOG_MODINST'));
             Configuration::updateValue('BLA_ISLOG_MODREG', Tools::getValue('BLA_ISLOG_MODREG'));
             Configuration::updateValue('BLA_ISLOG_MODUREG', Tools::getValue('BLA_ISLOG_MODUREG'));
             $output .= $this->displayConfirmation($this->l('Settings updated'));
         }
     }
     return $output . $this->displayForm();
 }
Example #13
0
 public function getContent()
 {
     $output = null;
     if (Tools::isSubmit('submit' . $this->name)) {
         $la_tabcount = strval(Tools::getValue('LAMPACCESSORIES_TABCOUNT'));
         if (!$la_tabcount || empty($la_tabcount) || !Validate::isGenericName($la_tabcount)) {
             $output .= $this->displayError($this->l('Invalid Configuration value'));
         } else {
             Configuration::updateValue('LAMPACCESSORIES_TABCOUNT', intval($la_tabcount));
             $output .= $this->displayConfirmation($this->l('Settings updated'));
         }
         $la_itemcount = strval(Tools::getValue('LAMPACCESSORIES_ITEMCOUNT'));
         if (!$la_itemcount || empty($la_itemcount) || !Validate::isGenericName($la_itemcount)) {
             $output .= $this->displayError($this->l('Invalid Configuration value'));
         } else {
             Configuration::updateValue('LAMPACCESSORIES_ITEMCOUNT', intval($la_itemcount));
             $output .= $this->displayConfirmation($this->l('Settings updated'));
         }
     }
     return $output . $this->displayForm();
 }
 public function getContent()
 {
     $output = null;
     if (Tools::isSubmit('submit' . $this->name)) {
         $lp_site_id = Tools::getValue('LP_SITEID');
         if (!$lp_site_id || empty($lp_site_id) || !Validate::isGenericName($lp_site_id)) {
             $output .= $this->displayError($this->l('You have entered an invalid LivePerson ID.'));
         } else {
             Configuration::updateValue('LP_SITEID', $lp_site_id);
             $output .= $this->displayConfirmation($this->l('You have successfully connected your LivePerson account!  We deployed the LiveEngage tag to your store.'));
         }
     }
     $lp_site_id = Configuration::get('LP_SITEID');
     if ($lp_site_id == "0") {
         $lp_site_id = "";
     }
     $link = $this->context->link->getAdminLink('AdminModules');
     $link = $link . "&configure=liveperson";
     $this->context->smarty->assign(array('lp_site_id' => $lp_site_id, 'link' => $link));
     return $output . $this->display(__FILE__, 'views/templates/admin/configure.tpl');
 }
Example #15
0
    /**
     * Add several tags in database and link it to a product
     *
     * @param int $id_lang Language id
     * @param int $id_product Product id to link tags with
     * @param string|array $tag_list List of tags, as array or as a string with comas
     * @return bool Operation success
     */
    public static function addTags($id_lang, $id_product, $tag_list, $separator = ',')
    {
        if (!Validate::isUnsignedId($id_lang)) {
            return false;
        }
        if (!is_array($tag_list)) {
            $tag_list = array_filter(array_unique(array_map('trim', preg_split('#\\' . $separator . '#', $tag_list, null, PREG_SPLIT_NO_EMPTY))));
        }
        $list = array();
        if (is_array($tag_list)) {
            foreach ($tag_list as $tag) {
                if (!Validate::isGenericName($tag)) {
                    return false;
                }
                $tag = trim(Tools::substr($tag, 0, self::$definition['fields']['name']['size']));
                $tag_obj = new Tag(null, $tag, (int) $id_lang);
                /* Tag does not exist in database */
                if (!Validate::isLoadedObject($tag_obj)) {
                    $tag_obj->name = $tag;
                    $tag_obj->id_lang = (int) $id_lang;
                    $tag_obj->add();
                }
                if (!in_array($tag_obj->id, $list)) {
                    $list[] = $tag_obj->id;
                }
            }
        }
        $data = '';
        foreach ($list as $tag) {
            $data .= '(' . (int) $tag . ',' . (int) $id_product . ',' . (int) $id_lang . '),';
        }
        $data = rtrim($data, ',');
        $result = Db::getInstance()->execute('
		INSERT INTO `' . _DB_PREFIX_ . 'product_tag` (`id_tag`, `id_product`, `id_lang`)
		VALUES ' . $data);
        if ($list != array()) {
            self::updateTagCount($list);
        }
        return $result;
    }
Example #16
0
 public function getContent()
 {
     $output = null;
     if (Tools::isSubmit('submit' . $this->name)) {
         $my_module_name = strval(Tools::getValue('MYMODULE_NAME'));
         $codigo_fracc = strval(Tools::getValue('FRACC_CODE'));
         $min_cantidad = strval(Tools::getValue('MIN_AMOUNT'));
         $max_cantidad = strval(Tools::getValue('MAX_AMOUNT'));
         if (!$my_module_name || empty($my_module_name) || !Validate::isGenericName($my_module_name)) {
             $output .= $this->displayError($this->l('Este campo no puede estar vacio'));
         } else {
             Configuration::updateValue('MYMODULE_NAME', $my_module_name);
             $output .= $this->displayConfirmation($this->l('Valor actualizado'));
         }
         if (!$codigo_fracc || empty($codigo_fracc)) {
             $output .= $this->displayError($this->l('Valor no valido'));
         } else {
             Configuration::updateValue('FRACC_CODE', $codigo_fracc);
             $output .= $this->displayConfirmation($this->l('Codigo de fracciona actualizado'));
         }
         if ($min_cantidad > $max_cantidad) {
             $output .= $this->displayError($this->l('La cantidad minima no puede ser superior a la cantidad maxima'));
         } else {
             if (!$min_cantidad || empty($min_cantidad) || !Validate::isUnsignedFloat($min_cantidad)) {
                 $output .= $this->displayError($this->l('La cantidad mínima debe ser un valor numérico superior a cero'));
             } else {
                 Configuration::updateValue('MIN_AMOUNT', $min_cantidad);
                 $output .= $this->displayConfirmation($this->l('Cantidad mínima actualizada'));
             }
             if (!$max_cantidad || empty($max_cantidad) || !Validate::isUnsignedFloat($max_cantidad)) {
                 $output .= $this->displayError($this->l('La cantidad maxima debe ser un valor numérico superior a cero'));
             } else {
                 Configuration::updateValue('MAX_AMOUNT', $max_cantidad);
                 $output .= $this->displayConfirmation($this->l('Cantidad maxima actualizada'));
             }
         }
     }
     return $output . $this->displayForm();
 }
 /**
  * This controls the configuration page for this module.
  * @author Linus Lundevall <*****@*****.**>
  */
 public function getContent()
 {
     $output = null;
     if (Tools::isSubmit('submit' . $this->name)) {
         $image_cloud_gallery = strval(Tools::getValue('PDC_NAME'));
         if (!$image_cloud_gallery || empty($image_cloud_gallery) || !Validate::isGenericName($image_cloud_gallery)) {
             $output .= $this->displayError($this->l('Invalid Configuration value'));
         } else {
             Configuration::updateValue('PDC_NAME', $image_cloud_gallery);
             $output .= $this->displayConfirmation($this->l('Settings updated'));
         }
     }
     if (Tools::isSubmit('newItem')) {
         $this->addItem();
     } elseif (Tools::isSubmit('updateItem')) {
         $this->updateItem();
     } elseif (Tools::isSubmit('removeItem')) {
         $this->removeItem();
     }
     $output .= $this->renderThemeConfiguratorForm();
     return $output . $this->displayForm();
 }
Example #18
0
 public function getContent()
 {
     $output = '<h2>' . $this->displayName . '</h2>';
     if (Tools::isSubmit('submitBlockRss')) {
         $urlfeed = strval(Tools::getValue('urlfeed'));
         $title = strval(Tools::getValue('title'));
         $nbr = (int) Tools::getValue('nbr');
         if ($urlfeed and !Validate::isUrl($urlfeed)) {
             $errors[] = $this->l('Invalid feed URL');
         } elseif (!$title or empty($title) or !Validate::isGenericName($title)) {
             $errors[] = $this->l('Invalid title');
         } elseif (!$nbr or $nbr <= 0 or !Validate::isInt($nbr)) {
             $errors[] = $this->l('Invalid number of feeds');
         } else {
             if (stristr($urlfeed, $_SERVER['HTTP_HOST'] . __PS_BASE_URI__)) {
                 $errors[] = $this->l('Error: You have selected a feed URL on your own website. Please choose another URL (eg. http://news.google.com/?output=rss).');
             }
             Configuration::updateValue('RSS_FEED_URL', $urlfeed);
             Configuration::updateValue('RSS_FEED_TITLE', $title);
             Configuration::updateValue('RSS_FEED_NBR', $nbr);
         }
         if (isset($errors) and sizeof($errors)) {
             $output .= $this->displayError(implode('<br />', $errors));
         } else {
             $output .= $this->displayConfirmation($this->l('Settings updated'));
         }
     } else {
         $errors = array();
         if (stristr(Configuration::get('RSS_FEED_URL'), $_SERVER['HTTP_HOST'] . __PS_BASE_URI__)) {
             $errors[] = $this->l('Error: You have selected a feed URL on your own website. Please choose another URL (eg. http://news.google.com/?output=rss).');
         }
         if (sizeof($errors)) {
             $output .= $this->displayError(implode('<br />', $errors));
         }
     }
     return $output . $this->displayForm();
 }
 /**
  * @param SimpleXMLElement $xml
  * @return bool
  * @throws PrestaShopException
  */
 protected function _installTaxes($xml)
 {
     if (isset($xml->taxes->tax)) {
         $assoc_taxes = array();
         foreach ($xml->taxes->tax as $taxData) {
             /** @var SimpleXMLElement $taxData */
             $attributes = $taxData->attributes();
             if ($id_tax = Tax::getTaxIdByName($attributes['name'])) {
                 $assoc_taxes[(int) $attributes['id']] = $id_tax;
                 continue;
             }
             $tax = new Tax();
             $tax->name[(int) Configuration::get('PS_LANG_DEFAULT')] = (string) $attributes['name'];
             $tax->rate = (double) $attributes['rate'];
             $tax->active = 1;
             if (($error = $tax->validateFields(false, true)) !== true || ($error = $tax->validateFieldsLang(false, true)) !== true) {
                 $this->_errors[] = Tools::displayError('Invalid tax properties.') . ' ' . $error;
                 return false;
             }
             if (!$tax->add()) {
                 $this->_errors[] = Tools::displayError('An error occurred while importing the tax: ') . (string) $attributes['name'];
                 return false;
             }
             $assoc_taxes[(int) $attributes['id']] = $tax->id;
         }
         foreach ($xml->taxes->taxRulesGroup as $group) {
             /** @var SimpleXMLElement $group */
             $group_attributes = $group->attributes();
             if (!Validate::isGenericName($group_attributes['name'])) {
                 continue;
             }
             if (TaxRulesGroup::getIdByName($group['name'])) {
                 continue;
             }
             $trg = new TaxRulesGroup();
             $trg->name = $group['name'];
             $trg->active = 1;
             if (!$trg->save()) {
                 $this->_errors[] = Tools::displayError('This tax rule cannot be saved.');
                 return false;
             }
             foreach ($group->taxRule as $rule) {
                 /** @var SimpleXMLElement $rule */
                 $rule_attributes = $rule->attributes();
                 // Validation
                 if (!isset($rule_attributes['iso_code_country'])) {
                     continue;
                 }
                 $id_country = (int) Country::getByIso(strtoupper($rule_attributes['iso_code_country']));
                 if (!$id_country) {
                     continue;
                 }
                 if (!isset($rule_attributes['id_tax']) || !array_key_exists(strval($rule_attributes['id_tax']), $assoc_taxes)) {
                     continue;
                 }
                 // Default values
                 $id_state = (int) isset($rule_attributes['iso_code_state']) ? State::getIdByIso(strtoupper($rule_attributes['iso_code_state'])) : 0;
                 $id_county = 0;
                 $zipcode_from = 0;
                 $zipcode_to = 0;
                 $behavior = $rule_attributes['behavior'];
                 if (isset($rule_attributes['zipcode_from'])) {
                     $zipcode_from = $rule_attributes['zipcode_from'];
                     if (isset($rule_attributes['zipcode_to'])) {
                         $zipcode_to = $rule_attributes['zipcode_to'];
                     }
                 }
                 // Creation
                 $tr = new TaxRule();
                 $tr->id_tax_rules_group = $trg->id;
                 $tr->id_country = $id_country;
                 $tr->id_state = $id_state;
                 $tr->id_county = $id_county;
                 $tr->zipcode_from = $zipcode_from;
                 $tr->zipcode_to = $zipcode_to;
                 $tr->behavior = $behavior;
                 $tr->description = '';
                 $tr->id_tax = $assoc_taxes[strval($rule_attributes['id_tax'])];
                 $tr->save();
             }
         }
     }
     return true;
 }
Example #20
0
 public static function Send($id_lang, $template, $subject, $templateVars, $to, $toName = NULL, $from = NULL, $fromName = NULL, $fileAttachment = NULL, $modeSMTP = NULL, $templatePath = _PS_MAIL_DIR_)
 {
     $configuration = Configuration::getMultiple(array('PS_SHOP_EMAIL', 'PS_MAIL_METHOD', 'PS_MAIL_SERVER', 'PS_MAIL_USER', 'PS_MAIL_PASSWD', 'PS_SHOP_NAME', 'PS_MAIL_SMTP_ENCRYPTION', 'PS_MAIL_SMTP_PORT', 'PS_MAIL_METHOD', 'PS_MAIL_TYPE'));
     if (!isset($configuration['PS_MAIL_SMTP_ENCRYPTION'])) {
         $configuration['PS_MAIL_SMTP_ENCRYPTION'] = "off";
     }
     if (!isset($configuration['PS_MAIL_SMTP_PORT'])) {
         $configuration['PS_MAIL_SMTP_PORT'] = "default";
     }
     if (!isset($from)) {
         $from = $configuration['PS_SHOP_EMAIL'];
     }
     if (!isset($fromName)) {
         $fromName = $configuration['PS_SHOP_NAME'];
     }
     if (!empty($from) and !Validate::isEmail($from) or !empty($fromName) and !Validate::isMailName($fromName) or !is_array($to) and !Validate::isEmail($to) or !empty($toName) and !Validate::isMailName($toName) or !is_array($templateVars) or !Validate::isTplName($template) or !Validate::isMailSubject($subject)) {
         die(Tools::displayError('Error: mail parameters are corrupted'));
     }
     /* Construct multiple recipients list if needed */
     if (is_array($to)) {
         $to_list = new Swift_RecipientList();
         foreach ($to as $key => $addr) {
             $to_name = NULL;
             $addr = trim($addr);
             if (!Validate::isEmail($addr)) {
                 die(Tools::displayError('Error: mail parameters are corrupted'));
             }
             if ($toName and is_array($toName) and Validate::isGenericName($toName[$key])) {
                 $to_name = $toName[$key];
             }
             $to_list->addTo($addr, $to_name);
         }
         $to_plugin = $to[0];
         $to = $to_list;
     } else {
         /* Simple recipient, one address */
         $to_plugin = $to;
         $to = new Swift_Address($to, $toName);
     }
     try {
         /* Connect with the appropriate configuration */
         if (intval($configuration['PS_MAIL_METHOD']) == 2) {
             $connection = new Swift_Connection_SMTP($configuration['PS_MAIL_SERVER'], $configuration['PS_MAIL_SMTP_PORT'], $configuration['PS_MAIL_SMTP_ENCRYPTION'] == "ssl" ? Swift_Connection_SMTP::ENC_SSL : ($configuration['PS_MAIL_SMTP_ENCRYPTION'] == "tls" ? Swift_Connection_SMTP::ENC_TLS : Swift_Connection_SMTP::ENC_OFF));
             $connection->setTimeout(4);
             if (!$connection) {
                 return false;
             }
             if (!empty($configuration['PS_MAIL_USER']) and !empty($configuration['PS_MAIL_PASSWD'])) {
                 $connection->setUsername($configuration['PS_MAIL_USER']);
                 $connection->setPassword($configuration['PS_MAIL_PASSWD']);
             }
         } else {
             $connection = new Swift_Connection_NativeMail();
         }
         if (!$connection) {
             return false;
         }
         $swift = new Swift($connection);
         /* Get templates content */
         $iso = Language::getIsoById(intval($id_lang));
         if (!$iso) {
             die(Tools::displayError('Error - No iso code for email !'));
         }
         $template = $iso . '/' . $template;
         if (!file_exists($templatePath . $template . '.txt') or !file_exists($templatePath . $template . '.html')) {
             die(Tools::displayError('Error - The following email template is missing:') . ' ' . $templatePath . $template . '.txt');
         }
         $templateHtml = file_get_contents($templatePath . $template . '.html');
         $templateTxt = strip_tags(html_entity_decode(file_get_contents($templatePath . $template . '.txt'), NULL, 'utf-8'));
         include_once dirname(__FILE__) . '/../mails/' . $iso . '/lang.php';
         global $_LANGMAIL;
         /* Create mail and attach differents parts */
         $message = new Swift_Message('[' . Configuration::get('PS_SHOP_NAME') . '] ' . ((is_array($_LANGMAIL) and key_exists($subject, $_LANGMAIL)) ? $_LANGMAIL[$subject] : $subject));
         $templateVars['{shop_logo}'] = file_exists(_PS_IMG_DIR_ . 'logo.jpg') ? $message->attach(new Swift_Message_Image(new Swift_File(_PS_IMG_DIR_ . 'logo.jpg'))) : '';
         $templateVars['{shop_name}'] = htmlentities(Configuration::get('PS_SHOP_NAME'), NULL, 'utf-8');
         $templateVars['{shop_url}'] = 'http://' . htmlspecialchars($_SERVER['HTTP_HOST'], ENT_COMPAT, 'UTF-8') . __PS_BASE_URI__;
         $swift->attachPlugin(new Swift_Plugin_Decorator(array($to_plugin => $templateVars)), 'decorator');
         if ($configuration['PS_MAIL_TYPE'] == 3 or $configuration['PS_MAIL_TYPE'] == 2) {
             $message->attach(new Swift_Message_Part($templateTxt, 'text/plain', '8bit', 'utf-8'));
         }
         if ($configuration['PS_MAIL_TYPE'] == 3 or $configuration['PS_MAIL_TYPE'] == 1) {
             $message->attach(new Swift_Message_Part($templateHtml, 'text/html', '8bit', 'utf-8'));
         }
         if ($fileAttachment and isset($fileAttachment['content']) and isset($fileAttachment['name']) and isset($fileAttachment['mime'])) {
             $message->attach(new Swift_Message_Attachment($fileAttachment['content'], $fileAttachment['name'], $fileAttachment['mime']));
         }
         /* Send mail */
         $send = $swift->send($message, $to, new Swift_Address($from, $fromName));
         $swift->disconnect();
         return $send;
     } catch (Swift_ConnectionException $e) {
         return false;
     }
 }
Example #21
0
 public function postProcess()
 {
     // If id_order is sent, we instanciate a new Order object
     if (Tools::isSubmit('id_order') && Tools::getValue('id_order') > 0) {
         $order = new Order(Tools::getValue('id_order'));
         if (!Validate::isLoadedObject($order)) {
             $this->errors[] = Tools::displayError('The order cannot be found within your database.');
         }
         ShopUrl::cacheMainDomainForShop((int) $order->id_shop);
     }
     /* Update shipping number */
     if (Tools::isSubmit('submitShippingNumber') && isset($order)) {
         if ($this->tabAccess['edit'] === '1') {
             $order_carrier = new OrderCarrier(Tools::getValue('id_order_carrier'));
             if (!Validate::isLoadedObject($order_carrier)) {
                 $this->errors[] = Tools::displayError('The order carrier ID is invalid.');
             } elseif (!Validate::isTrackingNumber(Tools::getValue('tracking_number'))) {
                 $this->errors[] = Tools::displayError('The tracking number is incorrect.');
             } else {
                 // update shipping number
                 // Keep these two following lines for backward compatibility, remove on 1.6 version
                 $order->shipping_number = Tools::getValue('tracking_number');
                 $order->update();
                 // Update order_carrier
                 $order_carrier->tracking_number = pSQL(Tools::getValue('tracking_number'));
                 if ($order_carrier->update()) {
                     // Send mail to customer
                     $customer = new Customer((int) $order->id_customer);
                     $carrier = new Carrier((int) $order->id_carrier, $order->id_lang);
                     if (!Validate::isLoadedObject($customer)) {
                         throw new PrestaShopException('Can\'t load Customer object');
                     }
                     if (!Validate::isLoadedObject($carrier)) {
                         throw new PrestaShopException('Can\'t load Carrier object');
                     }
                     $templateVars = array('{followup}' => str_replace('@', $order->shipping_number, $carrier->url), '{firstname}' => $customer->firstname, '{lastname}' => $customer->lastname, '{id_order}' => $order->id, '{shipping_number}' => $order->shipping_number, '{order_name}' => $order->getUniqReference());
                     if (@Mail::Send((int) $order->id_lang, 'in_transit', Mail::l('Package in transit', (int) $order->id_lang), $templateVars, $customer->email, $customer->firstname . ' ' . $customer->lastname, null, null, null, null, _PS_MAIL_DIR_, true, (int) $order->id_shop)) {
                         Hook::exec('actionAdminOrdersTrackingNumberUpdate', array('order' => $order, 'customer' => $customer, 'carrier' => $carrier), null, false, true, false, $order->id_shop);
                         Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $order->id . '&vieworder&conf=4&token=' . $this->token);
                     } else {
                         $this->errors[] = Tools::displayError('An error occurred while sending an email to the customer.');
                     }
                 } else {
                     $this->errors[] = Tools::displayError('The order carrier cannot be updated.');
                 }
             }
         } else {
             $this->errors[] = Tools::displayError('You do not have permission to edit this.');
         }
     } elseif (Tools::isSubmit('submitState') && isset($order)) {
         if ($this->tabAccess['edit'] === '1') {
             $order_state = new OrderState(Tools::getValue('id_order_state'));
             if (!Validate::isLoadedObject($order_state)) {
                 $this->errors[] = Tools::displayError('The new order status is invalid.');
             } else {
                 $current_order_state = $order->getCurrentOrderState();
                 if ($current_order_state->id != $order_state->id) {
                     // Create new OrderHistory
                     $history = new OrderHistory();
                     $history->id_order = $order->id;
                     $history->id_employee = (int) $this->context->employee->id;
                     $use_existings_payment = false;
                     if (!$order->hasInvoice()) {
                         $use_existings_payment = true;
                     }
                     $history->changeIdOrderState((int) $order_state->id, $order, $use_existings_payment);
                     $carrier = new Carrier($order->id_carrier, $order->id_lang);
                     $templateVars = array();
                     if ($history->id_order_state == Configuration::get('PS_OS_SHIPPING') && $order->shipping_number) {
                         $templateVars = array('{followup}' => str_replace('@', $order->shipping_number, $carrier->url));
                     }
                     // Save all changes
                     if ($history->addWithemail(true, $templateVars)) {
                         // synchronizes quantities if needed..
                         if (Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT')) {
                             foreach ($order->getProducts() as $product) {
                                 if (StockAvailable::dependsOnStock($product['product_id'])) {
                                     StockAvailable::synchronize($product['product_id'], (int) $product['id_shop']);
                                 }
                             }
                         }
                         Tools::redirectAdmin(self::$currentIndex . '&id_order=' . (int) $order->id . '&vieworder&token=' . $this->token);
                     }
                     $this->errors[] = Tools::displayError('An error occurred while changing order status, or we were unable to send an email to the customer.');
                 } else {
                     $this->errors[] = Tools::displayError('The order has already been assigned this status.');
                 }
             }
         } else {
             $this->errors[] = Tools::displayError('You do not have permission to edit this.');
         }
     } elseif (Tools::isSubmit('submitMessage') && isset($order)) {
         if ($this->tabAccess['edit'] === '1') {
             $customer = new Customer(Tools::getValue('id_customer'));
             if (!Validate::isLoadedObject($customer)) {
                 $this->errors[] = Tools::displayError('The customer is invalid.');
             } elseif (!Tools::getValue('message')) {
                 $this->errors[] = Tools::displayError('The message cannot be blank.');
             } else {
                 /* Get message rules and and check fields validity */
                 $rules = call_user_func(array('Message', 'getValidationRules'), 'Message');
                 foreach ($rules['required'] as $field) {
                     if (($value = Tools::getValue($field)) == false && (string) $value != '0') {
                         if (!Tools::getValue('id_' . $this->table) || $field != 'passwd') {
                             $this->errors[] = sprintf(Tools::displayError('field %s is required.'), $field);
                         }
                     }
                 }
                 foreach ($rules['size'] as $field => $maxLength) {
                     if (Tools::getValue($field) && Tools::strlen(Tools::getValue($field)) > $maxLength) {
                         $this->errors[] = sprintf(Tools::displayError('field %1$s is too long (%2$d chars max).'), $field, $maxLength);
                     }
                 }
                 foreach ($rules['validate'] as $field => $function) {
                     if (Tools::getValue($field)) {
                         if (!Validate::$function(htmlentities(Tools::getValue($field), ENT_COMPAT, 'UTF-8'))) {
                             $this->errors[] = sprintf(Tools::displayError('field %s is invalid.'), $field);
                         }
                     }
                 }
                 if (!count($this->errors)) {
                     //check if a thread already exist
                     $id_customer_thread = CustomerThread::getIdCustomerThreadByEmailAndIdOrder($customer->email, $order->id);
                     if (!$id_customer_thread) {
                         $customer_thread = new CustomerThread();
                         $customer_thread->id_contact = 0;
                         $customer_thread->id_customer = (int) $order->id_customer;
                         $customer_thread->id_shop = (int) $this->context->shop->id;
                         $customer_thread->id_order = (int) $order->id;
                         $customer_thread->id_lang = (int) $this->context->language->id;
                         $customer_thread->email = $customer->email;
                         $customer_thread->status = 'open';
                         $customer_thread->token = Tools::passwdGen(12);
                         $customer_thread->add();
                     } else {
                         $customer_thread = new CustomerThread((int) $id_customer_thread);
                     }
                     $customer_message = new CustomerMessage();
                     $customer_message->id_customer_thread = $customer_thread->id;
                     $customer_message->id_employee = (int) $this->context->employee->id;
                     $customer_message->message = Tools::getValue('message');
                     $customer_message->private = Tools::getValue('visibility');
                     if (!$customer_message->add()) {
                         $this->errors[] = Tools::displayError('An error occurred while saving the message.');
                     } elseif ($customer_message->private) {
                         Tools::redirectAdmin(self::$currentIndex . '&id_order=' . (int) $order->id . '&vieworder&conf=11&token=' . $this->token);
                     } else {
                         $message = $customer_message->message;
                         if (Configuration::get('PS_MAIL_TYPE', null, null, $order->id_shop) != Mail::TYPE_TEXT) {
                             $message = Tools::nl2br($customer_message->message);
                         }
                         $varsTpl = array('{lastname}' => $customer->lastname, '{firstname}' => $customer->firstname, '{id_order}' => $order->id, '{order_name}' => $order->getUniqReference(), '{message}' => $message);
                         if (@Mail::Send((int) $order->id_lang, 'order_merchant_comment', Mail::l('New message regarding your order', (int) $order->id_lang), $varsTpl, $customer->email, $customer->firstname . ' ' . $customer->lastname, null, null, null, null, _PS_MAIL_DIR_, true, (int) $order->id_shop)) {
                             Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $order->id . '&vieworder&conf=11' . '&token=' . $this->token);
                         }
                     }
                     $this->errors[] = Tools::displayError('An error occurred while sending an email to the customer.');
                 }
             }
         } else {
             $this->errors[] = Tools::displayError('You do not have permission to delete this.');
         }
     } elseif (Tools::isSubmit('partialRefund') && isset($order)) {
         if ($this->tabAccess['edit'] == '1') {
             if (is_array($_POST['partialRefundProduct'])) {
                 $amount = 0;
                 $order_detail_list = array();
                 foreach ($_POST['partialRefundProduct'] as $id_order_detail => $amount_detail) {
                     $order_detail_list[$id_order_detail]['quantity'] = (int) $_POST['partialRefundProductQuantity'][$id_order_detail];
                     if (empty($amount_detail)) {
                         $order_detail = new OrderDetail((int) $id_order_detail);
                         $order_detail_list[$id_order_detail]['amount'] = $order_detail->unit_price_tax_incl * $order_detail_list[$id_order_detail]['quantity'];
                     } else {
                         $order_detail_list[$id_order_detail]['amount'] = (double) str_replace(',', '.', $amount_detail);
                     }
                     $amount += $order_detail_list[$id_order_detail]['amount'];
                     $order_detail = new OrderDetail((int) $id_order_detail);
                     if (!$order->hasBeenDelivered() || $order->hasBeenDelivered() && Tools::isSubmit('reinjectQuantities') && $order_detail_list[$id_order_detail]['quantity'] > 0) {
                         $this->reinjectQuantity($order_detail, $order_detail_list[$id_order_detail]['quantity']);
                     }
                 }
                 $shipping_cost_amount = (double) str_replace(',', '.', Tools::getValue('partialRefundShippingCost'));
                 if ($shipping_cost_amount > 0) {
                     $amount += $shipping_cost_amount;
                 }
                 $order_carrier = new OrderCarrier((int) $order->getIdOrderCarrier());
                 if (Validate::isLoadedObject($order_carrier)) {
                     $order_carrier->weight = (double) $order->getTotalWeight();
                     if ($order_carrier->update()) {
                         $order->weight = sprintf("%.3f " . Configuration::get('PS_WEIGHT_UNIT'), $order_carrier->weight);
                     }
                 }
                 if ($amount > 0) {
                     if (!OrderSlip::createPartialOrderSlip($order, $amount, $shipping_cost_amount, $order_detail_list)) {
                         $this->errors[] = Tools::displayError('You cannot generate a partial credit slip.');
                     }
                     // Generate voucher
                     if (Tools::isSubmit('generateDiscountRefund') && !count($this->errors)) {
                         $cart_rule = new CartRule();
                         $cart_rule->description = sprintf($this->l('Credit slip for order #%d'), $order->id);
                         $languages = Language::getLanguages(false);
                         foreach ($languages as $language) {
                             // Define a temporary name
                             $cart_rule->name[$language['id_lang']] = sprintf('V0C%1$dO%2$d', $order->id_customer, $order->id);
                         }
                         // Define a temporary code
                         $cart_rule->code = sprintf('V0C%1$dO%2$d', $order->id_customer, $order->id);
                         $cart_rule->quantity = 1;
                         $cart_rule->quantity_per_user = 1;
                         // Specific to the customer
                         $cart_rule->id_customer = $order->id_customer;
                         $now = time();
                         $cart_rule->date_from = date('Y-m-d H:i:s', $now);
                         $cart_rule->date_to = date('Y-m-d H:i:s', $now + 3600 * 24 * 365.25);
                         /* 1 year */
                         $cart_rule->partial_use = 1;
                         $cart_rule->active = 1;
                         $cart_rule->reduction_amount = $amount;
                         $cart_rule->reduction_tax = true;
                         $cart_rule->minimum_amount_currency = $order->id_currency;
                         $cart_rule->reduction_currency = $order->id_currency;
                         if (!$cart_rule->add()) {
                             $this->errors[] = Tools::displayError('You cannot generate a voucher.');
                         } else {
                             // Update the voucher code and name
                             foreach ($languages as $language) {
                                 $cart_rule->name[$language['id_lang']] = sprintf('V%1$dC%2$dO%3$d', $cart_rule->id, $order->id_customer, $order->id);
                             }
                             $cart_rule->code = sprintf('V%1$dC%2$dO%3$d', $cart_rule->id, $order->id_customer, $order->id);
                             if (!$cart_rule->update()) {
                                 $this->errors[] = Tools::displayError('You cannot generate a voucher.');
                             } else {
                                 $currency = $this->context->currency;
                                 $customer = new Customer((int) $order->id_customer);
                                 $params['{lastname}'] = $customer->lastname;
                                 $params['{firstname}'] = $customer->firstname;
                                 $params['{id_order}'] = $order->id;
                                 $params['{order_name}'] = $order->getUniqReference();
                                 $params['{voucher_amount}'] = Tools::displayPrice($cart_rule->reduction_amount, $currency, false);
                                 $params['{voucher_num}'] = $cart_rule->code;
                                 $customer = new Customer((int) $order->id_customer);
                                 @Mail::Send((int) $order->id_lang, 'voucher', sprintf(Mail::l('New voucher regarding your order %s', (int) $order->id_lang), $order->reference), $params, $customer->email, $customer->firstname . ' ' . $customer->lastname, null, null, null, null, _PS_MAIL_DIR_, true, (int) $order->id_shop);
                             }
                         }
                     }
                 } else {
                     $this->errors[] = Tools::displayError('You have to enter an amount if you want to create a partial credit slip.');
                 }
                 // Redirect if no errors
                 if (!count($this->errors)) {
                     Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $order->id . '&vieworder&conf=30&token=' . $this->token);
                 }
             } else {
                 $this->errors[] = Tools::displayError('The partial refund data is incorrect.');
             }
         } else {
             $this->errors[] = Tools::displayError('You do not have permission to delete this.');
         }
     } elseif (Tools::isSubmit('cancelProduct') && isset($order)) {
         if ($this->tabAccess['delete'] === '1') {
             if (!Tools::isSubmit('id_order_detail') && !Tools::isSubmit('id_customization')) {
                 $this->errors[] = Tools::displayError('You must select a product.');
             } elseif (!Tools::isSubmit('cancelQuantity') && !Tools::isSubmit('cancelCustomizationQuantity')) {
                 $this->errors[] = Tools::displayError('You must enter a quantity.');
             } else {
                 $productList = Tools::getValue('id_order_detail');
                 if ($productList) {
                     $productList = array_map('intval', $productList);
                 }
                 $customizationList = Tools::getValue('id_customization');
                 if ($customizationList) {
                     $customizationList = array_map('intval', $customizationList);
                 }
                 $qtyList = Tools::getValue('cancelQuantity');
                 if ($qtyList) {
                     $qtyList = array_map('intval', $qtyList);
                 }
                 $customizationQtyList = Tools::getValue('cancelCustomizationQuantity');
                 if ($customizationQtyList) {
                     $customizationQtyList = array_map('intval', $customizationQtyList);
                 }
                 $full_product_list = $productList;
                 $full_quantity_list = $qtyList;
                 if ($customizationList) {
                     foreach ($customizationList as $key => $id_order_detail) {
                         $full_product_list[(int) $id_order_detail] = $id_order_detail;
                         if (isset($customizationQtyList[$key])) {
                             $full_quantity_list[(int) $id_order_detail] += $customizationQtyList[$key];
                         }
                     }
                 }
                 if ($productList || $customizationList) {
                     if ($productList) {
                         $id_cart = Cart::getCartIdByOrderId($order->id);
                         $customization_quantities = Customization::countQuantityByCart($id_cart);
                         foreach ($productList as $key => $id_order_detail) {
                             $qtyCancelProduct = abs($qtyList[$key]);
                             if (!$qtyCancelProduct) {
                                 $this->errors[] = Tools::displayError('No quantity has been selected for this product.');
                             }
                             $order_detail = new OrderDetail($id_order_detail);
                             $customization_quantity = 0;
                             if (array_key_exists($order_detail->product_id, $customization_quantities) && array_key_exists($order_detail->product_attribute_id, $customization_quantities[$order_detail->product_id])) {
                                 $customization_quantity = (int) $customization_quantities[$order_detail->product_id][$order_detail->product_attribute_id];
                             }
                             if ($order_detail->product_quantity - $customization_quantity - $order_detail->product_quantity_refunded - $order_detail->product_quantity_return < $qtyCancelProduct) {
                                 $this->errors[] = Tools::displayError('An invalid quantity was selected for this product.');
                             }
                         }
                     }
                     if ($customizationList) {
                         $customization_quantities = Customization::retrieveQuantitiesFromIds(array_keys($customizationList));
                         foreach ($customizationList as $id_customization => $id_order_detail) {
                             $qtyCancelProduct = abs($customizationQtyList[$id_customization]);
                             $customization_quantity = $customization_quantities[$id_customization];
                             if (!$qtyCancelProduct) {
                                 $this->errors[] = Tools::displayError('No quantity has been selected for this product.');
                             }
                             if ($qtyCancelProduct > $customization_quantity['quantity'] - ($customization_quantity['quantity_refunded'] + $customization_quantity['quantity_returned'])) {
                                 $this->errors[] = Tools::displayError('An invalid quantity was selected for this product.');
                             }
                         }
                     }
                     if (!count($this->errors) && $productList) {
                         foreach ($productList as $key => $id_order_detail) {
                             $qty_cancel_product = abs($qtyList[$key]);
                             $order_detail = new OrderDetail((int) $id_order_detail);
                             if (!$order->hasBeenDelivered() || $order->hasBeenDelivered() && Tools::isSubmit('reinjectQuantities') && $qty_cancel_product > 0) {
                                 $this->reinjectQuantity($order_detail, $qty_cancel_product);
                             }
                             // Delete product
                             $order_detail = new OrderDetail((int) $id_order_detail);
                             if (!$order->deleteProduct($order, $order_detail, $qty_cancel_product)) {
                                 $this->errors[] = Tools::displayError('An error occurred while attempting to delete the product.') . ' <span class="bold">' . $order_detail->product_name . '</span>';
                             }
                             // Update weight SUM
                             $order_carrier = new OrderCarrier((int) $order->getIdOrderCarrier());
                             if (Validate::isLoadedObject($order_carrier)) {
                                 $order_carrier->weight = (double) $order->getTotalWeight();
                                 if ($order_carrier->update()) {
                                     $order->weight = sprintf("%.3f " . Configuration::get('PS_WEIGHT_UNIT'), $order_carrier->weight);
                                 }
                             }
                             Hook::exec('actionProductCancel', array('order' => $order, 'id_order_detail' => (int) $id_order_detail), null, false, true, false, $order->id_shop);
                         }
                     }
                     if (!count($this->errors) && $customizationList) {
                         foreach ($customizationList as $id_customization => $id_order_detail) {
                             $order_detail = new OrderDetail((int) $id_order_detail);
                             $qtyCancelProduct = abs($customizationQtyList[$id_customization]);
                             if (!$order->deleteCustomization($id_customization, $qtyCancelProduct, $order_detail)) {
                                 $this->errors[] = Tools::displayError('An error occurred while attempting to delete product customization.') . ' ' . $id_customization;
                             }
                         }
                     }
                     // E-mail params
                     if ((Tools::isSubmit('generateCreditSlip') || Tools::isSubmit('generateDiscount')) && !count($this->errors)) {
                         $customer = new Customer((int) $order->id_customer);
                         $params['{lastname}'] = $customer->lastname;
                         $params['{firstname}'] = $customer->firstname;
                         $params['{id_order}'] = $order->id;
                         $params['{order_name}'] = $order->getUniqReference();
                     }
                     // Generate credit slip
                     if (Tools::isSubmit('generateCreditSlip') && !count($this->errors)) {
                         if (!OrderSlip::createOrderSlip($order, $full_product_list, $full_quantity_list, Tools::isSubmit('shippingBack'))) {
                             $this->errors[] = Tools::displayError('A credit slip cannot be generated. ');
                         } else {
                             Hook::exec('actionOrderSlipAdd', array('order' => $order, 'productList' => $full_product_list, 'qtyList' => $full_quantity_list), null, false, true, false, $order->id_shop);
                             @Mail::Send((int) $order->id_lang, 'credit_slip', Mail::l('New credit slip regarding your order', (int) $order->id_lang), $params, $customer->email, $customer->firstname . ' ' . $customer->lastname, null, null, null, null, _PS_MAIL_DIR_, true, (int) $order->id_shop);
                         }
                     }
                     // Generate voucher
                     if (Tools::isSubmit('generateDiscount') && !count($this->errors)) {
                         $cartrule = new CartRule();
                         $languages = Language::getLanguages($order);
                         $cartrule->description = sprintf($this->l('Credit card slip for order #%d'), $order->id);
                         foreach ($languages as $language) {
                             // Define a temporary name
                             $cartrule->name[$language['id_lang']] = 'V0C' . (int) $order->id_customer . 'O' . (int) $order->id;
                         }
                         // Define a temporary code
                         $cartrule->code = 'V0C' . (int) $order->id_customer . 'O' . (int) $order->id;
                         $cartrule->quantity = 1;
                         $cartrule->quantity_per_user = 1;
                         // Specific to the customer
                         $cartrule->id_customer = $order->id_customer;
                         $now = time();
                         $cartrule->date_from = date('Y-m-d H:i:s', $now);
                         $cartrule->date_to = date('Y-m-d H:i:s', $now + 3600 * 24 * 365.25);
                         /* 1 year */
                         $cartrule->active = 1;
                         $products = $order->getProducts(false, $full_product_list, $full_quantity_list);
                         $total = 0;
                         foreach ($products as $product) {
                             $total += $product['unit_price_tax_incl'] * $product['product_quantity'];
                         }
                         if (Tools::isSubmit('shippingBack')) {
                             $total += $order->total_shipping;
                         }
                         $cartrule->reduction_amount = $total;
                         $cartrule->reduction_tax = true;
                         $cartrule->minimum_amount_currency = $order->id_currency;
                         $cartrule->reduction_currency = $order->id_currency;
                         if (!$cartrule->add()) {
                             $this->errors[] = Tools::displayError('You cannot generate a voucher.');
                         } else {
                             // Update the voucher code and name
                             foreach ($languages as $language) {
                                 $cartrule->name[$language['id_lang']] = 'V' . (int) $cartrule->id . 'C' . (int) $order->id_customer . 'O' . $order->id;
                             }
                             $cartrule->code = 'V' . (int) $cartrule->id . 'C' . (int) $order->id_customer . 'O' . $order->id;
                             if (!$cartrule->update()) {
                                 $this->errors[] = Tools::displayError('You cannot generate a voucher.');
                             } else {
                                 $currency = $this->context->currency;
                                 $params['{voucher_amount}'] = Tools::displayPrice($cartrule->reduction_amount, $currency, false);
                                 $params['{voucher_num}'] = $cartrule->code;
                                 @Mail::Send((int) $order->id_lang, 'voucher', sprintf(Mail::l('New voucher regarding your order %s', (int) $order->id_lang), $order->reference), $params, $customer->email, $customer->firstname . ' ' . $customer->lastname, null, null, null, null, _PS_MAIL_DIR_, true, (int) $order->id_shop);
                             }
                         }
                     }
                 } else {
                     $this->errors[] = Tools::displayError('No product or quantity has been selected.');
                 }
                 // Redirect if no errors
                 if (!count($this->errors)) {
                     Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $order->id . '&vieworder&conf=31&token=' . $this->token);
                 }
             }
         } else {
             $this->errors[] = Tools::displayError('You do not have permission to delete this.');
         }
     } elseif (Tools::isSubmit('messageReaded')) {
         Message::markAsReaded(Tools::getValue('messageReaded'), $this->context->employee->id);
     } elseif (Tools::isSubmit('submitAddPayment') && isset($order)) {
         if ($this->tabAccess['edit'] === '1') {
             $amount = str_replace(',', '.', Tools::getValue('payment_amount'));
             $currency = new Currency(Tools::getValue('payment_currency'));
             $order_has_invoice = $order->hasInvoice();
             if ($order_has_invoice) {
                 $order_invoice = new OrderInvoice(Tools::getValue('payment_invoice'));
             } else {
                 $order_invoice = null;
             }
             if (!Validate::isLoadedObject($order)) {
                 $this->errors[] = Tools::displayError('The order cannot be found');
             } elseif (!Validate::isNegativePrice($amount) || !(double) $amount) {
                 $this->errors[] = Tools::displayError('The amount is invalid.');
             } elseif (!Validate::isGenericName(Tools::getValue('payment_method'))) {
                 $this->errors[] = Tools::displayError('The selected payment method is invalid.');
             } elseif (!Validate::isString(Tools::getValue('payment_transaction_id'))) {
                 $this->errors[] = Tools::displayError('The transaction ID is invalid.');
             } elseif (!Validate::isLoadedObject($currency)) {
                 $this->errors[] = Tools::displayError('The selected currency is invalid.');
             } elseif ($order_has_invoice && !Validate::isLoadedObject($order_invoice)) {
                 $this->errors[] = Tools::displayError('The invoice is invalid.');
             } elseif (!Validate::isDate(Tools::getValue('payment_date'))) {
                 $this->errors[] = Tools::displayError('The date is invalid');
             } else {
                 if (!$order->addOrderPayment($amount, Tools::getValue('payment_method'), Tools::getValue('payment_transaction_id'), $currency, Tools::getValue('payment_date'), $order_invoice)) {
                     $this->errors[] = Tools::displayError('An error occurred during payment.');
                 } else {
                     Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $order->id . '&vieworder&conf=4&token=' . $this->token);
                 }
             }
         } else {
             $this->errors[] = Tools::displayError('You do not have permission to edit this.');
         }
     } elseif (Tools::isSubmit('submitEditNote')) {
         $note = Tools::getValue('note');
         $order_invoice = new OrderInvoice((int) Tools::getValue('id_order_invoice'));
         if (Validate::isLoadedObject($order_invoice) && Validate::isCleanHtml($note)) {
             if ($this->tabAccess['edit'] === '1') {
                 $order_invoice->note = $note;
                 if ($order_invoice->save()) {
                     Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $order_invoice->id_order . '&vieworder&conf=4&token=' . $this->token);
                 } else {
                     $this->errors[] = Tools::displayError('The invoice note was not saved.');
                 }
             } else {
                 $this->errors[] = Tools::displayError('You do not have permission to edit this.');
             }
         } else {
             $this->errors[] = Tools::displayError('The invoice for edit note was unable to load. ');
         }
     } elseif (Tools::isSubmit('submitAddOrder') && ($id_cart = Tools::getValue('id_cart')) && ($module_name = Tools::getValue('payment_module_name')) && ($id_order_state = Tools::getValue('id_order_state')) && Validate::isModuleName($module_name)) {
         if ($this->tabAccess['edit'] === '1') {
             $payment_module = Module::getInstanceByName($module_name);
             $cart = new Cart((int) $id_cart);
             Context::getContext()->currency = new Currency((int) $cart->id_currency);
             Context::getContext()->customer = new Customer((int) $cart->id_customer);
             $employee = new Employee((int) Context::getContext()->cookie->id_employee);
             $payment_module->validateOrder((int) $cart->id, (int) $id_order_state, $cart->getOrderTotal(true, Cart::BOTH), $payment_module->displayName, $this->l('Manual order -- Employee:') . ' ' . substr($employee->firstname, 0, 1) . '. ' . $employee->lastname, array(), null, false, $cart->secure_key);
             if ($payment_module->currentOrder) {
                 Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $payment_module->currentOrder . '&vieworder' . '&token=' . $this->token);
             }
         } else {
             $this->errors[] = Tools::displayError('You do not have permission to add this.');
         }
     } elseif ((Tools::isSubmit('submitAddressShipping') || Tools::isSubmit('submitAddressInvoice')) && isset($order)) {
         if ($this->tabAccess['edit'] === '1') {
             $address = new Address(Tools::getValue('id_address'));
             if (Validate::isLoadedObject($address)) {
                 // Update the address on order
                 if (Tools::isSubmit('submitAddressShipping')) {
                     $order->id_address_delivery = $address->id;
                 } elseif (Tools::isSubmit('submitAddressInvoice')) {
                     $order->id_address_invoice = $address->id;
                 }
                 $order->update();
                 Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $order->id . '&vieworder&conf=4&token=' . $this->token);
             } else {
                 $this->errors[] = Tools::displayError('This address can\'t be loaded');
             }
         } else {
             $this->errors[] = Tools::displayError('You do not have permission to edit this.');
         }
     } elseif (Tools::isSubmit('submitChangeCurrency') && isset($order)) {
         if ($this->tabAccess['edit'] === '1') {
             if (Tools::getValue('new_currency') != $order->id_currency && !$order->valid) {
                 $old_currency = new Currency($order->id_currency);
                 $currency = new Currency(Tools::getValue('new_currency'));
                 if (!Validate::isLoadedObject($currency)) {
                     throw new PrestaShopException('Can\'t load Currency object');
                 }
                 // Update order detail amount
                 foreach ($order->getOrderDetailList() as $row) {
                     $order_detail = new OrderDetail($row['id_order_detail']);
                     $fields = array('ecotax', 'product_price', 'reduction_amount', 'total_shipping_price_tax_excl', 'total_shipping_price_tax_incl', 'total_price_tax_incl', 'total_price_tax_excl', 'product_quantity_discount', 'purchase_supplier_price', 'reduction_amount', 'reduction_amount_tax_incl', 'reduction_amount_tax_excl', 'unit_price_tax_incl', 'unit_price_tax_excl', 'original_product_price');
                     foreach ($fields as $field) {
                         $order_detail->{$field} = Tools::convertPriceFull($order_detail->{$field}, $old_currency, $currency);
                     }
                     $order_detail->update();
                     $order_detail->updateTaxAmount($order);
                 }
                 $id_order_carrier = (int) $order->getIdOrderCarrier();
                 if ($id_order_carrier) {
                     $order_carrier = $order_carrier = new OrderCarrier((int) $order->getIdOrderCarrier());
                     $order_carrier->shipping_cost_tax_excl = (double) Tools::convertPriceFull($order_carrier->shipping_cost_tax_excl, $old_currency, $currency);
                     $order_carrier->shipping_cost_tax_incl = (double) Tools::convertPriceFull($order_carrier->shipping_cost_tax_incl, $old_currency, $currency);
                     $order_carrier->update();
                 }
                 // Update order && order_invoice amount
                 $fields = array('total_discounts', 'total_discounts_tax_incl', 'total_discounts_tax_excl', 'total_discount_tax_excl', 'total_discount_tax_incl', 'total_paid', 'total_paid_tax_incl', 'total_paid_tax_excl', 'total_paid_real', 'total_products', 'total_products_wt', 'total_shipping', 'total_shipping_tax_incl', 'total_shipping_tax_excl', 'total_wrapping', 'total_wrapping_tax_incl', 'total_wrapping_tax_excl');
                 $invoices = $order->getInvoicesCollection();
                 if ($invoices) {
                     foreach ($invoices as $invoice) {
                         foreach ($fields as $field) {
                             if (isset($invoice->{$field})) {
                                 $invoice->{$field} = Tools::convertPriceFull($invoice->{$field}, $old_currency, $currency);
                             }
                         }
                         $invoice->save();
                     }
                 }
                 foreach ($fields as $field) {
                     if (isset($order->{$field})) {
                         $order->{$field} = Tools::convertPriceFull($order->{$field}, $old_currency, $currency);
                     }
                 }
                 // Update currency in order
                 $order->id_currency = $currency->id;
                 // Update exchange rate
                 $order->conversion_rate = (double) $currency->conversion_rate;
                 $order->update();
             } else {
                 $this->errors[] = Tools::displayError('You cannot change the currency.');
             }
         } else {
             $this->errors[] = Tools::displayError('You do not have permission to edit this.');
         }
     } elseif (Tools::isSubmit('submitGenerateInvoice') && isset($order)) {
         if (!Configuration::get('PS_INVOICE', null, null, $order->id_shop)) {
             $this->errors[] = Tools::displayError('Invoice management has been disabled.');
         } elseif ($order->hasInvoice()) {
             $this->errors[] = Tools::displayError('This order already has an invoice.');
         } else {
             $order->setInvoice(true);
             Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $order->id . '&vieworder&conf=4&token=' . $this->token);
         }
     } elseif (Tools::isSubmit('submitDeleteVoucher') && isset($order)) {
         if ($this->tabAccess['edit'] === '1') {
             $order_cart_rule = new OrderCartRule(Tools::getValue('id_order_cart_rule'));
             if (Validate::isLoadedObject($order_cart_rule) && $order_cart_rule->id_order == $order->id) {
                 if ($order_cart_rule->id_order_invoice) {
                     $order_invoice = new OrderInvoice($order_cart_rule->id_order_invoice);
                     if (!Validate::isLoadedObject($order_invoice)) {
                         throw new PrestaShopException('Can\'t load Order Invoice object');
                     }
                     // Update amounts of Order Invoice
                     $order_invoice->total_discount_tax_excl -= $order_cart_rule->value_tax_excl;
                     $order_invoice->total_discount_tax_incl -= $order_cart_rule->value;
                     $order_invoice->total_paid_tax_excl += $order_cart_rule->value_tax_excl;
                     $order_invoice->total_paid_tax_incl += $order_cart_rule->value;
                     // Update Order Invoice
                     $order_invoice->update();
                 }
                 // Update amounts of order
                 $order->total_discounts -= $order_cart_rule->value;
                 $order->total_discounts_tax_incl -= $order_cart_rule->value;
                 $order->total_discounts_tax_excl -= $order_cart_rule->value_tax_excl;
                 $order->total_paid += $order_cart_rule->value;
                 $order->total_paid_tax_incl += $order_cart_rule->value;
                 $order->total_paid_tax_excl += $order_cart_rule->value_tax_excl;
                 // Delete Order Cart Rule and update Order
                 $order_cart_rule->delete();
                 $order->update();
                 Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $order->id . '&vieworder&conf=4&token=' . $this->token);
             } else {
                 $this->errors[] = Tools::displayError('You cannot edit this cart rule.');
             }
         } else {
             $this->errors[] = Tools::displayError('You do not have permission to edit this.');
         }
     } elseif (Tools::isSubmit('submitNewVoucher') && isset($order)) {
         if ($this->tabAccess['edit'] === '1') {
             if (!Tools::getValue('discount_name')) {
                 $this->errors[] = Tools::displayError('You must specify a name in order to create a new discount.');
             } else {
                 if ($order->hasInvoice()) {
                     // If the discount is for only one invoice
                     if (!Tools::isSubmit('discount_all_invoices')) {
                         $order_invoice = new OrderInvoice(Tools::getValue('discount_invoice'));
                         if (!Validate::isLoadedObject($order_invoice)) {
                             throw new PrestaShopException('Can\'t load Order Invoice object');
                         }
                     }
                 }
                 $cart_rules = array();
                 $discount_value = (double) str_replace(',', '.', Tools::getValue('discount_value'));
                 switch (Tools::getValue('discount_type')) {
                     // Percent type
                     case 1:
                         if ($discount_value < 100) {
                             if (isset($order_invoice)) {
                                 $cart_rules[$order_invoice->id]['value_tax_incl'] = Tools::ps_round($order_invoice->total_paid_tax_incl * $discount_value / 100, 2);
                                 $cart_rules[$order_invoice->id]['value_tax_excl'] = Tools::ps_round($order_invoice->total_paid_tax_excl * $discount_value / 100, 2);
                                 // Update OrderInvoice
                                 $this->applyDiscountOnInvoice($order_invoice, $cart_rules[$order_invoice->id]['value_tax_incl'], $cart_rules[$order_invoice->id]['value_tax_excl']);
                             } elseif ($order->hasInvoice()) {
                                 $order_invoices_collection = $order->getInvoicesCollection();
                                 foreach ($order_invoices_collection as $order_invoice) {
                                     $cart_rules[$order_invoice->id]['value_tax_incl'] = Tools::ps_round($order_invoice->total_paid_tax_incl * $discount_value / 100, 2);
                                     $cart_rules[$order_invoice->id]['value_tax_excl'] = Tools::ps_round($order_invoice->total_paid_tax_excl * $discount_value / 100, 2);
                                     // Update OrderInvoice
                                     $this->applyDiscountOnInvoice($order_invoice, $cart_rules[$order_invoice->id]['value_tax_incl'], $cart_rules[$order_invoice->id]['value_tax_excl']);
                                 }
                             } else {
                                 $cart_rules[0]['value_tax_incl'] = Tools::ps_round($order->total_paid_tax_incl * $discount_value / 100, 2);
                                 $cart_rules[0]['value_tax_excl'] = Tools::ps_round($order->total_paid_tax_excl * $discount_value / 100, 2);
                             }
                         } else {
                             $this->errors[] = Tools::displayError('The discount value is invalid.');
                         }
                         break;
                         // Amount type
                     // Amount type
                     case 2:
                         if (isset($order_invoice)) {
                             if ($discount_value > $order_invoice->total_paid_tax_incl) {
                                 $this->errors[] = Tools::displayError('The discount value is greater than the order invoice total.');
                             } else {
                                 $cart_rules[$order_invoice->id]['value_tax_incl'] = Tools::ps_round($discount_value, 2);
                                 $cart_rules[$order_invoice->id]['value_tax_excl'] = Tools::ps_round($discount_value / (1 + $order->getTaxesAverageUsed() / 100), 2);
                                 // Update OrderInvoice
                                 $this->applyDiscountOnInvoice($order_invoice, $cart_rules[$order_invoice->id]['value_tax_incl'], $cart_rules[$order_invoice->id]['value_tax_excl']);
                             }
                         } elseif ($order->hasInvoice()) {
                             $order_invoices_collection = $order->getInvoicesCollection();
                             foreach ($order_invoices_collection as $order_invoice) {
                                 if ($discount_value > $order_invoice->total_paid_tax_incl) {
                                     $this->errors[] = Tools::displayError('The discount value is greater than the order invoice total.') . $order_invoice->getInvoiceNumberFormatted(Context::getContext()->language->id, (int) $order->id_shop) . ')';
                                 } else {
                                     $cart_rules[$order_invoice->id]['value_tax_incl'] = Tools::ps_round($discount_value, 2);
                                     $cart_rules[$order_invoice->id]['value_tax_excl'] = Tools::ps_round($discount_value / (1 + $order->getTaxesAverageUsed() / 100), 2);
                                     // Update OrderInvoice
                                     $this->applyDiscountOnInvoice($order_invoice, $cart_rules[$order_invoice->id]['value_tax_incl'], $cart_rules[$order_invoice->id]['value_tax_excl']);
                                 }
                             }
                         } else {
                             if ($discount_value > $order->total_paid_tax_incl) {
                                 $this->errors[] = Tools::displayError('The discount value is greater than the order total.');
                             } else {
                                 $cart_rules[0]['value_tax_incl'] = Tools::ps_round($discount_value, 2);
                                 $cart_rules[0]['value_tax_excl'] = Tools::ps_round($discount_value / (1 + $order->getTaxesAverageUsed() / 100), 2);
                             }
                         }
                         break;
                         // Free shipping type
                     // Free shipping type
                     case 3:
                         if (isset($order_invoice)) {
                             if ($order_invoice->total_shipping_tax_incl > 0) {
                                 $cart_rules[$order_invoice->id]['value_tax_incl'] = $order_invoice->total_shipping_tax_incl;
                                 $cart_rules[$order_invoice->id]['value_tax_excl'] = $order_invoice->total_shipping_tax_excl;
                                 // Update OrderInvoice
                                 $this->applyDiscountOnInvoice($order_invoice, $cart_rules[$order_invoice->id]['value_tax_incl'], $cart_rules[$order_invoice->id]['value_tax_excl']);
                             }
                         } elseif ($order->hasInvoice()) {
                             $order_invoices_collection = $order->getInvoicesCollection();
                             foreach ($order_invoices_collection as $order_invoice) {
                                 if ($order_invoice->total_shipping_tax_incl <= 0) {
                                     continue;
                                 }
                                 $cart_rules[$order_invoice->id]['value_tax_incl'] = $order_invoice->total_shipping_tax_incl;
                                 $cart_rules[$order_invoice->id]['value_tax_excl'] = $order_invoice->total_shipping_tax_excl;
                                 // Update OrderInvoice
                                 $this->applyDiscountOnInvoice($order_invoice, $cart_rules[$order_invoice->id]['value_tax_incl'], $cart_rules[$order_invoice->id]['value_tax_excl']);
                             }
                         } else {
                             $cart_rules[0]['value_tax_incl'] = $order->total_shipping_tax_incl;
                             $cart_rules[0]['value_tax_excl'] = $order->total_shipping_tax_excl;
                         }
                         break;
                     default:
                         $this->errors[] = Tools::displayError('The discount type is invalid.');
                 }
                 $res = true;
                 foreach ($cart_rules as &$cart_rule) {
                     $cartRuleObj = new CartRule();
                     $cartRuleObj->date_from = date('Y-m-d H:i:s', strtotime('-1 hour', strtotime($order->date_add)));
                     $cartRuleObj->date_to = date('Y-m-d H:i:s', strtotime('+1 hour'));
                     $cartRuleObj->name[Configuration::get('PS_LANG_DEFAULT')] = Tools::getValue('discount_name');
                     $cartRuleObj->quantity = 0;
                     $cartRuleObj->quantity_per_user = 1;
                     if (Tools::getValue('discount_type') == 1) {
                         $cartRuleObj->reduction_percent = $discount_value;
                     } elseif (Tools::getValue('discount_type') == 2) {
                         $cartRuleObj->reduction_amount = $cart_rule['value_tax_excl'];
                     } elseif (Tools::getValue('discount_type') == 3) {
                         $cartRuleObj->free_shipping = 1;
                     }
                     $cartRuleObj->active = 0;
                     if ($res = $cartRuleObj->add()) {
                         $cart_rule['id'] = $cartRuleObj->id;
                     } else {
                         break;
                     }
                 }
                 if ($res) {
                     foreach ($cart_rules as $id_order_invoice => $cart_rule) {
                         // Create OrderCartRule
                         $order_cart_rule = new OrderCartRule();
                         $order_cart_rule->id_order = $order->id;
                         $order_cart_rule->id_cart_rule = $cart_rule['id'];
                         $order_cart_rule->id_order_invoice = $id_order_invoice;
                         $order_cart_rule->name = Tools::getValue('discount_name');
                         $order_cart_rule->value = $cart_rule['value_tax_incl'];
                         $order_cart_rule->value_tax_excl = $cart_rule['value_tax_excl'];
                         $res &= $order_cart_rule->add();
                         $order->total_discounts += $order_cart_rule->value;
                         $order->total_discounts_tax_incl += $order_cart_rule->value;
                         $order->total_discounts_tax_excl += $order_cart_rule->value_tax_excl;
                         $order->total_paid -= $order_cart_rule->value;
                         $order->total_paid_tax_incl -= $order_cart_rule->value;
                         $order->total_paid_tax_excl -= $order_cart_rule->value_tax_excl;
                     }
                     // Update Order
                     $res &= $order->update();
                 }
                 if ($res) {
                     Tools::redirectAdmin(self::$currentIndex . '&id_order=' . $order->id . '&vieworder&conf=4&token=' . $this->token);
                 } else {
                     $this->errors[] = Tools::displayError('An error occurred during the OrderCartRule creation');
                 }
             }
         } else {
             $this->errors[] = Tools::displayError('You do not have permission to edit this.');
         }
     }
     parent::postProcess();
 }
 public function getContent()
 {
     $this->_html = '';
     // Add a link
     if (Tools::isSubmit('submitLinkAdd')) {
         if (empty($_POST['text_' . Configuration::get('PS_LANG_DEFAULT')]) || empty($_POST['url'])) {
             $this->_html .= $this->displayError($this->l('You must fill in all fields.'));
         } elseif (!Validate::isUrl(str_replace('http://', '', $_POST['url']))) {
             $this->_html .= $this->displayError($this->l('Bad URL'));
         } else {
             if ($this->addLink()) {
                 $this->_html .= $this->displayConfirmation($this->l('The link has been added.'));
             } else {
                 $this->_html .= $this->displayError($this->l('An error occurred during link creation.'));
             }
         }
     } elseif (Tools::isSubmit('submitTitle')) {
         if (empty($_POST['title_' . Configuration::get('PS_LANG_DEFAULT')])) {
             $this->_html .= $this->displayError($this->l('"title" field cannot be empty.'));
         } elseif (!empty($_POST['title_url']) && !Validate::isUrl(str_replace('http://', '', $_POST['title_url']))) {
             $this->_html .= $this->displayError($this->l('The \'title\' field is invalid'));
         } elseif (!Validate::isGenericName($_POST['title_' . Configuration::get('PS_LANG_DEFAULT')])) {
             $this->_html .= $this->displayError($this->l('The \'title\' field is invalid'));
         } elseif (!$this->updateTitle()) {
             $this->_html .= $this->displayError($this->l('An error occurred during title updating.'));
         } else {
             $this->_html .= $this->displayConfirmation($this->l('The block title has been updated.'));
         }
     } elseif (Tools::isSubmit('deleteblocklink') && Tools::getValue('id')) {
         if (!is_numeric(Tools::getValue('id')) || !$this->deleteLink()) {
             $this->_html .= $this->displayError($this->l('An error occurred during link deletion.'));
         } else {
             $this->_html .= $this->displayConfirmation($this->l('The link has been deleted.'));
         }
     }
     if (isset($_POST['submitOrderWay'])) {
         if (Configuration::updateValue('PS_BLOCKLINK_ORDERWAY', (int) Tools::getValue('orderWay'))) {
             $this->_html .= $this->displayConfirmation($this->l('Sort order updated'));
         } else {
             $this->_html .= $this->displayError($this->l('An error occurred during sort order set-up.'));
         }
     }
     $this->_html .= $this->renderForm();
     $this->_html .= $this->renderList();
     return $this->_html;
 }
    public function postProcess()
    {
        global $cookie, $smarty;
        if (Tools::isSubmit('ajaxProductFilter')) {
            $fakeEmployee = new Employee();
            $fakeEmployee->stats_date_from = $cookie->stats_date_from;
            $fakeEmployee->stats_date_to = $cookie->stats_date_to;
            $result = Db::getInstance()->getRow('
			SELECT `id_referrer`
			FROM `' . _DB_PREFIX_ . 'referrer`
			WHERE `id_referrer` = ' . intval(Tools::getValue('id_referrer')) . ' AND `passwd` = \'' . pSQL(Tools::getValue('token')) . '\'');
            if (isset($result['id_referrer']) ? $result['id_referrer'] : false) {
                Referrer::getAjaxProduct(intval(Tools::getValue('id_referrer')), intval(Tools::getValue('id_product')), $fakeEmployee);
            }
        } elseif (Tools::isSubmit('logout_tracking')) {
            unset($cookie->tracking_id);
            unset($cookie->tracking_passwd);
            Tools::redirect('modules/trackingfront/stats.php');
        } elseif (Tools::isSubmit('submitLoginTracking')) {
            $errors = array();
            $login = trim(Tools::getValue('login'));
            $passwd = trim(Tools::getValue('passwd'));
            if (empty($login)) {
                $errors[] = $this->l('login is required');
            } elseif (!Validate::isGenericName($login)) {
                $errors[] = $this->l('invalid login');
            } elseif (empty($passwd)) {
                $errors[] = $this->l('password is required');
            } elseif (!Validate::isPasswd($passwd)) {
                $errors[] = $this->l('invalid password');
            } else {
                $passwd = Tools::encrypt($passwd);
                $result = Db::getInstance()->getRow('
				SELECT `id_referrer`
				FROM `' . _DB_PREFIX_ . 'referrer`
				WHERE `name` = \'' . pSQL($login) . '\' AND `passwd` = \'' . pSQL($passwd) . '\'');
                if (!isset($result['id_referrer']) or !($tracking_id = intval($result['id_referrer']))) {
                    $errors[] = $this->l('authentication failed');
                } else {
                    $cookie->tracking_id = $tracking_id;
                    $cookie->tracking_passwd = $passwd;
                    Tools::redirect('modules/trackingfront/stats.php');
                }
            }
            $smarty->assign('errors', $errors);
        }
        if (Tools::isSubmit('submitDatePicker')) {
            $cookie->stats_date_from = Tools::getValue('datepickerFrom');
            $cookie->stats_date_to = Tools::getValue('datepickerTo');
        }
        if (Tools::isSubmit('submitDateDay')) {
            $from = date('Y-m-d');
            $to = date('Y-m-d');
        }
        if (Tools::isSubmit('submitDateDayPrev')) {
            $yesterday = time() - 60 * 60 * 24;
            $from = date('Y-m-d', $yesterday);
            $to = date('Y-m-d', $yesterday);
        }
        if (Tools::isSubmit('submitDateMonth')) {
            $from = date('Y-m-01');
            $to = date('Y-m-t');
        }
        if (Tools::isSubmit('submitDateMonthPrev')) {
            $m = date('m') == 1 ? 12 : date('m') - 1;
            $y = $m == 12 ? date('Y') - 1 : date('Y');
            $from = $y . '-' . $m . '-01';
            $to = $y . '-' . $m . date('-t', mktime(12, 0, 0, $m, 15, $y));
        }
        if (Tools::isSubmit('submitDateYear')) {
            $from = date('Y-01-01');
            $to = date('Y-12-31');
        }
        if (Tools::isSubmit('submitDateYearPrev')) {
            $from = date('Y') - 1 . date('-01-01');
            $to = date('Y') - 1 . date('-12-31');
        }
    }
Example #24
0
 private function checkDocumentation()
 {
     $extensions = array('.pdf', '.txt');
     if (isset($_FILES['documentation']) && $_FILES['documentation']['name'] != '') {
         $extension = strrchr($_FILES['documentation']['name'], '.');
         $name = Tools::getValue('documentationName');
         if (!in_array($extension, $extensions)) {
             $this->errors[] = $this->l('File extension must be .txt or .pdf');
         } elseif ($_FILES['documentation']['error'] > 0 || $_FILES['documentation']['size'] > 1048576) {
             $this->errors[] = $this->l('An error occurred during documentation upload');
         } elseif (!$name || !Validate::isGenericName($name) || strlen($name) > self::MAX_NAME_LENGTH) {
             $this->errors[] = $this->l('Please enter a valid documentation name');
         }
     }
     if (count($this->errors) > 0) {
         return false;
     }
     return true;
 }
 /**
  * When submitted the config form!
  *
  * @return string
  */
 public function getContent()
 {
     $output = null;
     $languages = Language::getLanguages(false);
     if (Tools::isSubmit('submit' . $this->name)) {
         $labsmobile_username = (string) Tools::getValue('LABSMOBILE_USERNAME');
         if (!$labsmobile_username || empty($labsmobile_username) || !Validate::isEmail($labsmobile_username)) {
             $output .= $this->displayError($this->l('Invalid username'));
         } else {
             Configuration::updateValue('LABSMOBILE_USERNAME', $labsmobile_username);
             $output .= $this->displayConfirmation($this->l('Username updated'));
         }
         // Password field
         $labsmobile_password = (string) Tools::getValue('LABSMOBILE_PASSWORD');
         if (!$labsmobile_password || empty($labsmobile_password) || !Validate::isGenericName($labsmobile_password)) {
             $output .= $this->displayError($this->l('Invalid password'));
         } else {
             Configuration::updateValue('LABSMOBILE_PASSWORD', $labsmobile_password);
             $output .= $this->displayConfirmation($this->l('Password updated'));
         }
         // Alphanumeric sender. we validate just if the user opted in.
         $labsmobile_alpha_sender = (string) Tools::getValue('LABSMOBILE_DEFAULT_ALPHASENDER');
         $labsmobile_alpha_sender = trim($labsmobile_alpha_sender);
         if (!$labsmobile_alpha_sender || empty($labsmobile_alpha_sender) || !$this->isValidAlphasender($labsmobile_alpha_sender)) {
             $output .= $this->displayError($this->l('Invalid Alpha Sender'));
         } else {
             Configuration::updateValue('LABSMOBILE_DEFAULT_ALPHASENDER', $labsmobile_alpha_sender);
             $output .= $this->displayConfirmation($this->l('Alpha Sender updated'));
         }
         // New Order Notification active
         $labsmobile_neworder_active = Tools::getValue('LABSMOBILE_ORDER_NOTIFICATION_ACTIVE');
         Configuration::updateValue('LABSMOBILE_ORDER_NOTIFICATION_ACTIVE', $labsmobile_neworder_active);
         $this->logMessage('New order notification active');
         $this->logMessage($labsmobile_neworder_active);
         if ($labsmobile_neworder_active) {
             // New Order notification Template
             $labsmobile_order_template = (string) Tools::getValue('LABSMOBILE_ORDER_TEMPLATE');
             if (!$labsmobile_order_template || empty($labsmobile_order_template)) {
                 Configuration::updateValue('LABSMOBILE_ORDER_TEMPLATE', Configuration::get('LABSMOBILE_ORDER_TEMPLATE'));
             } else {
                 Configuration::updateValue('LABSMOBILE_ORDER_TEMPLATE', $labsmobile_order_template);
             }
             $output .= $this->displayConfirmation($this->l('Order Template updated'));
             // New Order Recipient
             $labsmobile_order_recipient = (string) Tools::getValue('LABSMOBILE_ORDER_RECIPIENT');
             $labsmobile_order_recipient = $this->normalizeNumber($labsmobile_order_recipient);
             if (!$labsmobile_order_recipient || empty($labsmobile_order_recipient) || !Validate::isGenericName($labsmobile_order_recipient) || !$this->isValidMobileNumber($labsmobile_order_recipient)) {
                 $output .= $this->displayError($this->l('Invalid Order Recipient'));
             } else {
                 Configuration::updateValue('LABSMOBILE_ORDER_RECIPIENT', $labsmobile_order_recipient);
                 $output .= $this->displayConfirmation($this->l('Order Recipient Updated'));
             }
         }
         // Shipment active
         // Update the checkbox
         $labsmobile_shipment_active = Tools::getValue('LABSMOBILE_SHIPMENTSTATUS_NOTIFICATION_ACTIVE');
         Configuration::updateValue('LABSMOBILE_SHIPMENTSTATUS_NOTIFICATION_ACTIVE', $labsmobile_shipment_active);
         $this->logMessage('shipment active');
         $this->logMessage($labsmobile_shipment_active);
         // Shipment Template
         if ($labsmobile_shipment_active) {
             $values = array();
             foreach ($languages as $lang) {
                 $labsmobile_shipment_template = (string) Tools::getValue('LABSMOBILE_SHIPMENTSTATUS_NOTIFICATION_TEMPLATE_' . $lang['id_lang']);
                 if (!$labsmobile_shipment_template || empty($labsmobile_shipment_template)) {
                     $values['LABSMOBILE_SHIPMENTSTATUS_NOTIFICATION_TEMPLATE'][$lang['id_lang']] = Configuration::get('LABSMOBILE_SHIPMENTSTATUS_NOTIFICATION_TEMPLATE');
                 } else {
                     $values['LABSMOBILE_SHIPMENTSTATUS_NOTIFICATION_TEMPLATE'][$lang['id_lang']] = $labsmobile_shipment_template;
                 }
             }
             Configuration::updateValue('LABSMOBILE_SHIPMENTSTATUS_NOTIFICATION_TEMPLATE', $values['LABSMOBILE_SHIPMENTSTATUS_NOTIFICATION_TEMPLATE']);
             $output .= $this->displayConfirmation($this->l('Shipment Template updated'));
         }
         $this->logMessage('Updated config Values');
         $this->dumpConfig();
     }
     return $output . $this->displayForm();
 }
Example #26
0
 public function getContent()
 {
     $output = null;
     if (Tools::isSubmit('submitApiKey')) {
         $key = (string) Tools::getValue('CASHWAY_API_KEY');
         $secret = (string) Tools::getValue('CASHWAY_API_SECRET');
         if (!$key || empty($key) || !Validate::isGenericName($key)) {
             $output .= $this->displayError($this->l('Missing API key.'));
         } else {
             Configuration::updateValue('CASHWAY_API_KEY', $key);
             $output .= $this->displayConfirmation($this->l('API key updated.'));
         }
         if (!$secret || empty($secret) || !Validate::isGenericName($secret)) {
             $output .= $this->displayError($this->l('Missing API secret.'));
         } else {
             Configuration::updateValue('CASHWAY_API_SECRET', $secret);
             $output .= $this->displayConfirmation($this->l('API secret updated.'));
         }
         $this->updateNotificationParameters();
     }
     if (Tools::isSubmit('submitSettings')) {
         Configuration::updateValue('CASHWAY_OS_PAYMENT', (int) Tools::getValue('CASHWAY_OS_PAYMENT'));
         Configuration::updateValue('CASHWAY_PAYMENT_TEMPLATE', Tools::getValue('CASHWAY_PAYMENT_TEMPLATE'));
         Configuration::updateValue('CASHWAY_SEND_EMAIL', Tools::getValue('CASHWAY_SEND_EMAIL'));
         Configuration::updateValue('CASHWAY_USE_STAGING', Tools::getValue('CASHWAY_USE_STAGING'));
     }
     if (Tools::isSubmit('submitRegister')) {
         $params = array();
         $params['name'] = Tools::getValue('name');
         $params['email'] = Tools::getValue('email');
         $params['password'] = Tools::getValue('password');
         $params['phone'] = Tools::getValue('phone');
         $params['country'] = Tools::getValue('country');
         $params['company'] = Tools::getValue('company');
         $params['url'] = $this->context->shop->getBaseURL();
         if (!$params['name'] || empty($params['name']) || !Validate::isGenericName($params['name'])) {
             $output .= $this->displayError($this->l('Missing name.'));
         }
         if (!$params['password'] || empty($params['password']) || !Validate::isGenericName($params['password'])) {
             $output .= $this->displayError($this->l('Missing password.'));
         } elseif (!$params['email'] || empty($params['email']) || !Validate::isEmail($params['email'])) {
             $output .= $this->displayError($this->l('Missing email.'));
         } elseif (!$params['phone'] || empty($params['phone']) || !Validate::isPhoneNumber($params['phone'])) {
             $output .= $this->displayError($this->l('Missing phone.'));
         } elseif (!$params['country'] || empty($params['country']) || !Validate::isLangIsoCode($params['country'])) {
             $output .= $this->displayError($this->l('Missing country.'));
         } elseif (!$params['company'] || empty($params['company']) || !Validate::isGenericName($params['company'])) {
             $output .= $this->displayError($this->l('Missing company.'));
         } else {
             $cashway = self::getCashWayAPI();
             $res = $cashway->registerAccount($params);
             if (isset($res['errors'])) {
                 foreach ($res['errors'] as $key => $value) {
                     $output .= $this->displayError($value['code'] . ' => ' . $value['message']);
                 }
             } elseif ($res['status'] == 'newbie') {
                 Configuration::updateValue('CASHWAY_API_KEY', $res['api_key']);
                 Configuration::updateValue('CASHWAY_API_SECRET', $res['api_secret']);
                 $this->updateNotificationParameters();
                 $output .= $this->displayConfirmation($this->l('Register completed'));
             }
         }
     }
     return $output . $this->renderForm();
 }
 public function getContent()
 {
     $output = null;
     if (Tools::isSubmit('submit' . $this->name)) {
         $send24_title = (string) Tools::getValue('send24_title');
         $send24_consumer_key = (string) Tools::getValue('send24_consumer_key');
         $send24_consumer_secret = (string) Tools::getValue('send24_consumer_secret');
         $start_work_express = (string) Tools::getValue('start_work_express');
         $end_work_express = (string) Tools::getValue('end_work_express');
         $error = false;
         // Check title.
         if (!$send24_title || empty($send24_title) || !Validate::isGenericName($send24_title)) {
             $output .= $this->displayError($this->l('Invalid title value'));
             $error = true;
         }
         // Check key.
         if (!$send24_consumer_key || empty($send24_consumer_key) || !Validate::isGenericName($send24_consumer_key)) {
             $output .= $this->displayError($this->l('Invalid consumer key'));
             $error = true;
         }
         // Check secret.
         if (!$send24_consumer_secret || empty($send24_consumer_secret) || !Validate::isGenericName($send24_consumer_secret)) {
             $output .= $this->displayError($this->l('Invalid consumer secret'));
             $error = true;
         }
         // Check start work.
         if (!$start_work_express || empty($start_work_express) || !Validate::isGenericName($start_work_express)) {
             $output .= $this->displayError($this->l('Invalid start work time'));
             $error = true;
         }
         // Check end work.
         if (!$end_work_express || empty($end_work_express) || !Validate::isGenericName($end_work_express)) {
             $output .= $this->displayError($this->l('Invalid end work time'));
             $error = true;
         }
         // Check keys authorization send24.com
         $ch = curl_init();
         curl_setopt($ch, CURLOPT_URL, "https://send24.com/wc-api/v3/get_service_area/" . $this->postcode);
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
         curl_setopt($ch, CURLOPT_HEADER, false);
         curl_setopt($ch, CURLOPT_USERPWD, $send24_consumer_key . ":" . $send24_consumer_secret);
         curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
         $zip_area = curl_exec($ch);
         $zip = Tools::jsonDecode($zip_area, true);
         if (!empty($zip['errors'])) {
             $output .= $this->displayError($this->l('Invalid key authorization'));
         }
         if ($error == false) {
             Configuration::updateValue('send24_title', $send24_title);
             Configuration::updateValue('send24_consumer_key', $send24_consumer_key);
             Configuration::updateValue('send24_consumer_secret', $send24_consumer_secret);
             Configuration::updateValue('start_work_express', $start_work_express);
             Configuration::updateValue('end_work_express', $end_work_express);
             $output .= $this->displayConfirmation($this->l('Settings updated'));
         }
     }
     return $output . $this->displayForm();
 }
Example #28
0
 public static function create_category($parent, $name, $linkRewrite, $description = '', $meta_title = '', $meta_description = '', $meta_keywords = '')
 {
     $configuration = PS_CLI_CONFIGURE::getConfigurationInstance();
     $category = new CMSCategory();
     if (!Validate::isUnsignedId($parent)) {
         echo "Error, {$parent} is not a valid category ID\n";
         return false;
     }
     $parentCat = new CMSCategory($parent);
     if (!Validate::isloadedObject($parentCat)) {
         echo "Error: category {$parentCat} does not exists\n";
         return false;
     }
     $category->id_parent = $parent;
     if (!Validate::isName($name)) {
         echo "Error, {$name} is not a valid category name\n";
         return false;
     }
     $category->name = array($configuration->lang => $name);
     if (!Validate::isLinkRewrite($linkRewrite)) {
         echo "Error, {$linkRewrite} is not a valid link rewrite\n";
         return false;
     }
     $category->link_rewrite = array($configuration->lang => $linkRewrite);
     if (!Validate::isCleanHtml($description)) {
         echo "Warning, {$description} is not a valid category description\n";
         $description = '';
     }
     $category->description = array($configuration->lang => $description);
     if (!Validate::isGenericName($meta_title)) {
         echo "Warning, {$meta_title} is not a valid value for meta_title\n";
         $meta_title = '';
     }
     $category->meta_title = array($configuration->lang => $meta_title);
     if (!Validate::isGenericName($meta_description)) {
         echo "Warning, {$meta_description} is not a valid value for meta_description\n";
         $meta_description = '';
     }
     $category->meta_description = array($configuration->lang => $meta_description);
     if (!Validate::isGenericName($meta_keywords)) {
         echo "Warning, {$meta_keywords} is not a valid value for meta_keywords\n";
         $meta_keywords = '';
     }
     $category->meta_keywords = array($configuration->lang => $meta_keywords);
     if ($category->add()) {
         if ($configuration->porcelain) {
             echo $category->id_cms_category;
         } else {
             echo "Successfully created category {$category->id_cms_category}\n";
         }
         return true;
     } else {
         echo "Error, could not create category {$name}\n";
         return false;
     }
 }
Example #29
0
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
*  @author PrestaShop SA <*****@*****.**>
*  @copyright  2007-2015 PrestaShop SA
*  @license    http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
*  International Registered Trademark & Property of PrestaShop SA
*/
if (!defined('_PS_ADMIN_DIR_')) {
    define('_PS_ADMIN_DIR_', getcwd());
}
require_once _PS_ADMIN_DIR_ . '/../config/config.inc.php';
require_once _PS_ADMIN_DIR_ . '/init.php';
if (isset($_GET['img']) and Validate::isMd5($_GET['img']) and isset($_GET['name']) and Validate::isGenericName($_GET['name']) and file_exists(_PS_UPLOAD_DIR_ . $_GET['img'])) {
    header('Content-type: image/jpeg');
    header('Content-Disposition: attachment; filename="' . $_GET['name'] . '.jpg"');
    echo file_get_contents(_PS_UPLOAD_DIR_ . $_GET['img']);
}
Example #30
0
 protected function ajaxProcessAddComment()
 {
     $module_instance = new ProductComments();
     $result = true;
     $id_guest = 0;
     $id_customer = $this->context->customer->id;
     if (!$id_customer) {
         $id_guest = $this->context->cookie->id_guest;
     }
     $errors = array();
     // Validation
     if (!Validate::isInt(Tools::getValue('id_product'))) {
         $errors[] = $module_instance->l('ID product is incorrect', 'default');
     }
     if (!Tools::getValue('title') || !Validate::isGenericName(Tools::getValue('title'))) {
         $errors[] = $module_instance->l('Title is incorrect', 'default');
     }
     if (!Tools::getValue('content') || !Validate::isMessage(Tools::getValue('content'))) {
         $errors[] = $module_instance->l('Comment is incorrect', 'default');
     }
     if (!$id_customer && (!Tools::isSubmit('customer_name') || !Tools::getValue('customer_name') || !Validate::isGenericName(Tools::getValue('customer_name')))) {
         $errors[] = $module_instance->l('Customer name is incorrect', 'default');
     }
     if (!$this->context->customer->id && !Configuration::get('PRODUCT_COMMENTS_ALLOW_GUESTS')) {
         $errors[] = $module_instance->l('You must be logged in order to send a comment', 'default');
     }
     if (!count(Tools::getValue('criterion'))) {
         $errors[] = $module_instance->l('You must give a rating', 'default');
     }
     $product = new Product(Tools::getValue('id_product'));
     if (!$product->id) {
         $errors[] = $module_instance->l('Product not found', 'default');
     }
     if (!count($errors)) {
         $customer_comment = ProductComment::getByCustomer(Tools::getValue('id_product'), $id_customer, true, $id_guest);
         if (!$customer_comment || $customer_comment && strtotime($customer_comment['date_add']) + (int) Configuration::get('PRODUCT_COMMENTS_MINIMAL_TIME') < time()) {
             $comment = new ProductComment();
             $comment->content = strip_tags(Tools::getValue('content'));
             $comment->id_product = (int) Tools::getValue('id_product');
             $comment->id_customer = (int) $id_customer;
             $comment->id_guest = $id_guest;
             $comment->customer_name = Tools::getValue('customer_name');
             if (!$comment->customer_name) {
                 $comment->customer_name = pSQL($this->context->customer->firstname . ' ' . $this->context->customer->lastname);
             }
             $comment->title = Tools::getValue('title');
             $comment->grade = 0;
             $comment->validate = 0;
             $comment->save();
             $grade_sum = 0;
             foreach (Tools::getValue('criterion') as $id_product_comment_criterion => $grade) {
                 $grade_sum += $grade;
                 $product_comment_criterion = new ProductCommentCriterion($id_product_comment_criterion);
                 if ($product_comment_criterion->id) {
                     $product_comment_criterion->addGrade($comment->id, $grade);
                 }
             }
             if (count(Tools::getValue('criterion')) >= 1) {
                 $comment->grade = $grade_sum / count(Tools::getValue('criterion'));
                 // Update Grade average of comment
                 $comment->save();
             }
             $result = true;
         } else {
             $result = false;
             $errors[] = $module_instance->l('You should wait') . ' ' . Configuration::get('PRODUCT_COMMENTS_MINIMAL_TIME') . ' ' . $module_instance->l('seconds before posting a new comment');
         }
     } else {
         $result = false;
     }
     die(Tools::jsonEncode(array('result' => $result, 'errors' => $errors)));
 }