public function setFlushImage($flushImage = true) { if ($flushImage !== false and is_object($this->image)) { $this->image->delete(); $this->image = null; } }
function delPage() { //Delete if ($GLOBALS["action"] == "delete" && $GLOBALS["id"] != null) { global $database; $delpage = new Page("pages"); $id = $delpage::$id = "Id=" . $GLOBALS["id"]; $delpage->delete(); if ($database->affectedRows()) { //delete corresponding image $imgdirpath = "../"; $image_path = $imgdirpath . PAGEIMG_DIR; $delimage = new Image("pageimgs"); $getimage = $delimage::findRow("Pageid='{$GLOBALS["id"]}'"); if ($database->getNumofRows() > 0) { unlink($image_path . $getimage->Imgname . "." . $getimage->Extention); //delete image unlink($imgdirpath . TEMP_DIR . $getimage->Imgname . "." . $getimage->Extention); //delete thumb image $delimage::$id = "Id=" . $GLOBALS["id"]; $delimage->delete(); } } } header("Location: " . filter_var($_SERVER['PHP_SELF'] . "?action=view&target=managepage")); }
/** * Apaga */ public function deleteAction() { $status = false; if (isset($_POST)) { if (isset($_REQUEST['id'])) { $id = (int) $_REQUEST['id']; $image = Image::find($id); if ($image) { $status = Image::delete($image->getId()); // Se a imagem foi apagada com sucesso realiza as demais ações if ($status) { // Apaga os tamanhos de imagem $condition = sprintf("image_id = %s", $image->getId()); ImageSize::deleteAll($condition); // Gerenciador de imagens $imageManager = new ImageManager($image); // Apaga o diretório das imagens $imageManager->removeDir(); } } } } // Cria a variável flash if ($status) { $this->setFlash('notice_success', 'Image deleted successfully.'); } else { $this->setFlash('notice_error', 'Delete image failed.'); } // Redireciona para a listagem $this->redirectTo('image', 'list'); }
public function destroyAction() { $this->logger->entering(); $this->logger->info('Quoting to protect against injection'); $where = $this->db->quoteInto('id = ?', $this->_getParam('id')); $this->logger->info('Deleting the image'); $images = new Image(); $images->delete($where); $this->logger->info('Redirecting to new image action'); $this->_redirect('image/new'); $this->logger->exiting(); }
private static function deleteExpired() { if (is_writable(Image::PATH)) { $query = 'select id from books where expired < now()'; $result = mysql_query($query); while ($row = mysql_fetch_row($result)) { $img = new Image($row[0]); $img->delete(); } } $query = 'delete from books where expired < now()'; mysql_query($query); }
function testDelete() { $imageFull = Image::PATH . '0.png'; $imageThumb = Image::PATH . '0_thumb.png'; touch($imageFull); touch($imageThumb); $image = new Image(0); $image->delete(); if (is_file($imageFull)) { if (is_file($imageThumb)) { unlink($imageThumb); } unlink($imageFull); $this->fail("Image was not deleted."); } }
/** * 删除所有产品图片 * * @return bool success */ public function deleteImages() { $result = Db::getInstance()->getAll(' SELECT `id_image` FROM `' . DB_PREFIX . 'product_to_image` WHERE `id_product` = ' . (int) $this->id); $deleted = array(); if ($result) { foreach ($result as $row) { $image = new Image($row['id_image']); if ($image->delete()) { $deleted[] = (int) $row['id_image']; } } } if (count($deleted) > 0) { return Db::getInstance()->exec('DELETE FROM ' . DB_PREFIX . 'product_to_image WHERE id_image IN(' . implode(',', $deleted) . ')'); } return false; }
/** * 删除图片并更新排序 * */ function ajaxProcessDeleteProductImage() { $res = true; /* Delete product image */ $id_image = (int) Tools::Q('id_image'); $id_product = (int) Tools::Q('id_product'); $image = new Image($id_image); if ($image->delete()) { if (Db::getInstance()->exec('DELETE FROM ' . DB_PREFIX . 'product_to_image WHERE id_image=' . $id_image)) { // update positions $result = Db::getInstance()->getAll(' SELECT * FROM `' . DB_PREFIX . 'product_to_image` WHERE `id_product` = ' . $id_product . ' ORDER BY `position` '); $i = 1; if ($result) { foreach ($result as $row) { if ($row['id_image'] == $id_image && $row['cover'] == 1 && $i == 1) { $row['cover'] = 1; } $row['position'] = $i++; Db::getInstance()->update(DB_PREFIX . 'product_to_image', $row, '`id_image` = ' . (int) $row['id_image'], 1); } } } else { $res &= false; } } else { $res &= false; } if ($res) { die(json_encode(array('status' => 'ok', 'confirmations' => '操作成功!', 'content' => array('id' => $image->id)))); } else { die(json_encode(array('status' => 'error', 'confirmations' => '删除文件失败!'))); } }
} else { $type = $_GET['type']; } $module_name = $type.'MediaGalleryModule'; $setting_data = array('middle' => array($module_name)); // deleting images try { if(isset($_GET['action']) && ($_GET['action']=='delete') && ($login_uid)) { $id = $_GET['id']; $type = $_POST['media_type']; $album_id = $_POST['album_id']; if ($_GET['type'] == 'image') { $new_image = new Image(); $new_image->content_id = $id; $new_image->delete($id); $msg = 2004; header("Location: $base_url/media_gallery.php?type=$type&msg_id=$msg&album_id=$album_id"); exit; } if ($_GET['type'] == 'audio') { $new_image = new Audio(); $new_image->content_id = $id; $new_image->delete($id); $msg = 2005; header("Location: $base_url/media_gallery.php?type=$type&msg_id=$msg&album_id=$album_id"); exit; } if ($_GET['type'] == 'video') {
/** * Management of normal images CRUD * * @param boolean $filename_exists if the filename exists * @param string $filename the image path * @param array $imageSizes The * @param string $directory * @return boolean */ protected function manageDeclinatedImagesCRUD($filename_exists, $filename, $imageSizes, $directory) { switch ($this->wsObject->method) { // Display the image case 'GET': case 'HEAD': if ($filename_exists) { $this->imgToDisplay = $filename; } else { throw new WebserviceException('This image does not exist on disk', array(61, 500)); } break; // Modify the image // Modify the image case 'PUT': if ($filename_exists) { if ($this->writePostedImageOnDisk($filename, null, null, $imageSizes, $directory)) { $this->imgToDisplay = $filename; return true; } else { throw new WebserviceException('Unable to save this image.', array(62, 500)); } } else { throw new WebserviceException('This image does not exist on disk', array(63, 500)); } break; // Delete the image // Delete the image case 'DELETE': if ($filename_exists) { // Delete products image in DB if ($this->imageType == 'products') { $image = new Image((int) $this->wsObject->urlSegment[3]); return $image->delete(); } elseif (in_array($this->imageType, array('categories', 'manufacturers', 'suppliers', 'stores'))) { $object = new $this->wsObject->resourceList[$this->imageType]['class']((int) $this->wsObject->urlSegment[2]); return $object->deleteImage(true); } else { return $this->deleteImageOnDisk($filename, $imageSizes, $directory); } } else { throw new WebserviceException('This image does not exist on disk', array(64, 500)); } break; // Add the image // Add the image case 'POST': if ($filename_exists) { throw new WebserviceException('This image already exists. To modify it, please use the PUT method', array(65, 400)); } else { if ($this->writePostedImageOnDisk($filename, null, null, $imageSizes, $directory)) { return true; } else { throw new WebserviceException('Unable to save this image', array(66, 500)); } } break; default: throw new WebserviceException('This method is not allowed', array(67, 405)); } }
public function ajaxProcessDeleteProductImage() { $this->display = 'content'; $res = true; /* Delete product image */ $image = new Image((int) Tools::getValue('id_image')); $this->content['id'] = $image->id; $res &= $image->delete(); // if deleted image was the cover, change it to the first one if (!Image::getCover($image->id_product)) { $res &= Db::getInstance()->execute(' UPDATE `' . _DB_PREFIX_ . 'image_shop` image_shop, ' . _DB_PREFIX_ . 'image i SET image_shop.`cover` = 1, i.cover = 1 WHERE image_shop.`id_image` = (SELECT id_image FROM (SELECT image_shop.id_image FROM ' . _DB_PREFIX_ . 'image i' . Shop::addSqlAssociation('image', 'i') . ' WHERE i.id_product =' . (int) $image->id_product . ' LIMIT 1 ) tmpImage) AND id_shop=' . (int) $this->context->shop->id . ' AND i.id_image = image_shop.id_image '); } if (file_exists(_PS_TMP_IMG_DIR_ . 'product_' . $image->id_product . '.jpg')) { $res &= @unlink(_PS_TMP_IMG_DIR_ . 'product_' . $image->id_product . '.jpg'); } if (file_exists(_PS_TMP_IMG_DIR_ . 'product_mini_' . $image->id_product . '_' . $this->context->shop->id . '.jpg')) { $res &= @unlink(_PS_TMP_IMG_DIR_ . 'product_mini_' . $image->id_product . '_' . $this->context->shop->id . '.jpg'); } if ($res) { $this->jsonConfirmation($this->_conf[7]); } else { $this->jsonError(Tools::displayError('An error occurred while attempting to delete the product image.')); } }
private function AddImage($object, $url) { $shops = Shop::getShops(true, null, true); $url = str_replace(' ', '%20', $url); $image = new Image(); $image->id_product = (int) $object->id; $image->position = Image::getHighestPosition($object->id) + 1; $image->cover = 1; // file_exists doesn't work with HTTP protocol if (@fopen($url, 'r') == false) { $error = true; } else { if (($field_error = $image->validateFields(false, true)) === true && ($lang_field_error = $image->validateFieldsLang(false, true)) === true && $image->add()) { // associate image to selected shops $image->associateTo($shops); if (!self::copyImg($object->id, $image->id, $url)) { $image->delete(); $this->errors[] = sprintf(Tools::displayError('Error copying image: %s'), $url); } } else { $error = true; } } }
protected function attributeImportOne($info, $default_language, &$groups, &$attributes, $regenerate, $shop_is_feature_active, $validateOnly = false) { AdminImportController::setDefaultValues($info); if (!$shop_is_feature_active) { $info['shop'] = 1; } elseif (!isset($info['shop']) || empty($info['shop'])) { $info['shop'] = implode($this->multiple_value_separator, Shop::getContextListShopID()); } // Get shops for each attributes $info['shop'] = explode($this->multiple_value_separator, $info['shop']); $id_shop_list = array(); if (is_array($info['shop']) && count($info['shop'])) { foreach ($info['shop'] as $shop) { if (!empty($shop) && !is_numeric($shop)) { $id_shop_list[] = Shop::getIdByName($shop); } elseif (!empty($shop)) { $id_shop_list[] = $shop; } } } if (isset($info['id_product']) && $info['id_product']) { $product = new Product((int) $info['id_product'], false, $default_language); } elseif (Tools::getValue('match_ref') && isset($info['product_reference']) && $info['product_reference']) { $datas = Db::getInstance()->getRow(' SELECT p.`id_product` FROM `' . _DB_PREFIX_ . 'product` p ' . Shop::addSqlAssociation('product', 'p') . ' WHERE p.`reference` = "' . pSQL($info['product_reference']) . '" ', false); if (isset($datas['id_product']) && $datas['id_product']) { $product = new Product((int) $datas['id_product'], false, $default_language); } } else { return; } $id_image = array(); if (isset($info['image_url']) && $info['image_url']) { $info['image_url'] = explode($this->multiple_value_separator, $info['image_url']); if (is_array($info['image_url']) && count($info['image_url'])) { foreach ($info['image_url'] as $key => $url) { $url = trim($url); $product_has_images = (bool) Image::getImages($this->context->language->id, $product->id); $image = new Image(); $image->id_product = (int) $product->id; $image->position = Image::getHighestPosition($product->id) + 1; $image->cover = !$product_has_images ? true : false; if (isset($info['image_alt'])) { $alt = self::split($info['image_alt']); if (isset($alt[$key]) && strlen($alt[$key]) > 0) { $alt = self::createMultiLangField($alt[$key]); $image->legend = $alt; } } $field_error = $image->validateFields(UNFRIENDLY_ERROR, true); $lang_field_error = $image->validateFieldsLang(UNFRIENDLY_ERROR, true); if ($field_error === true && $lang_field_error === true && !$validateOnly && $image->add()) { $image->associateTo($id_shop_list); // FIXME: 2s/image ! if (!AdminImportController::copyImg($product->id, $image->id, $url, 'products', !$regenerate)) { $this->warnings[] = sprintf($this->trans('Error copying image: %s', array(), 'Admin.Parameters.Notification'), $url); $image->delete(); } else { $id_image[] = (int) $image->id; } // until here } else { if (!$validateOnly) { $this->warnings[] = sprintf($this->trans('%s cannot be saved', array(), 'Admin.Parameters.Notification'), isset($image->id_product) ? ' (' . $image->id_product . ')' : ''); } if ($field_error !== true || $lang_field_error !== true) { $this->errors[] = ($field_error !== true ? $field_error : '') . (isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : '') . mysql_error(); } } } } } elseif (isset($info['image_position']) && $info['image_position']) { $info['image_position'] = explode($this->multiple_value_separator, $info['image_position']); if (is_array($info['image_position']) && count($info['image_position'])) { foreach ($info['image_position'] as $position) { // choose images from product by position $images = $product->getImages($default_language); if ($images) { foreach ($images as $row) { if ($row['position'] == (int) $position) { $id_image[] = (int) $row['id_image']; break; } } } if (empty($id_image)) { $this->warnings[] = sprintf($this->trans('No image was found for combination with id_product = %s and image position = %s.', array(), 'Admin.Parameters.Notification'), $product->id, (int) $position); } } } } $id_attribute_group = 0; // groups $groups_attributes = array(); if (isset($info['group'])) { foreach (explode($this->multiple_value_separator, $info['group']) as $key => $group) { if (empty($group)) { continue; } $tab_group = explode(':', $group); $group = trim($tab_group[0]); if (!isset($tab_group[1])) { $type = 'select'; } else { $type = trim($tab_group[1]); } // sets group $groups_attributes[$key]['group'] = $group; // if position is filled if (isset($tab_group[2])) { $position = trim($tab_group[2]); } else { $position = false; } if (!isset($groups[$group])) { $obj = new AttributeGroup(); $obj->is_color_group = false; $obj->group_type = pSQL($type); $obj->name[$default_language] = $group; $obj->public_name[$default_language] = $group; $obj->position = !$position ? AttributeGroup::getHigherPosition() + 1 : $position; if (($field_error = $obj->validateFields(UNFRIENDLY_ERROR, true)) === true && ($lang_field_error = $obj->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true) { // here, cannot avoid attributeGroup insertion to avoid an error during validation step. //if (!$validateOnly) { $obj->add(); $obj->associateTo($id_shop_list); $groups[$group] = $obj->id; //} } else { $this->errors[] = ($field_error !== true ? $field_error : '') . (isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : ''); } // fills groups attributes $id_attribute_group = $obj->id; $groups_attributes[$key]['id'] = $id_attribute_group; } else { // already exists $id_attribute_group = $groups[$group]; $groups_attributes[$key]['id'] = $id_attribute_group; } } } // inits attribute $id_product_attribute = 0; $id_product_attribute_update = false; $attributes_to_add = array(); // for each attribute if (isset($info['attribute'])) { foreach (explode($this->multiple_value_separator, $info['attribute']) as $key => $attribute) { if (empty($attribute)) { continue; } $tab_attribute = explode(':', $attribute); $attribute = trim($tab_attribute[0]); // if position is filled if (isset($tab_attribute[1])) { $position = trim($tab_attribute[1]); } else { $position = false; } if (isset($groups_attributes[$key])) { $group = $groups_attributes[$key]['group']; if (!isset($attributes[$group . '_' . $attribute]) && count($groups_attributes[$key]) == 2) { $id_attribute_group = $groups_attributes[$key]['id']; $obj = new Attribute(); // sets the proper id (corresponding to the right key) $obj->id_attribute_group = $groups_attributes[$key]['id']; $obj->name[$default_language] = str_replace('\\n', '', str_replace('\\r', '', $attribute)); $obj->position = !$position && isset($groups[$group]) ? Attribute::getHigherPosition($groups[$group]) + 1 : $position; if (($field_error = $obj->validateFields(UNFRIENDLY_ERROR, true)) === true && ($lang_field_error = $obj->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true) { if (!$validateOnly) { $obj->add(); $obj->associateTo($id_shop_list); $attributes[$group . '_' . $attribute] = $obj->id; } } else { $this->errors[] = ($field_error !== true ? $field_error : '') . (isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : ''); } } $info['minimal_quantity'] = isset($info['minimal_quantity']) && $info['minimal_quantity'] ? (int) $info['minimal_quantity'] : 1; $info['wholesale_price'] = str_replace(',', '.', $info['wholesale_price']); $info['price'] = str_replace(',', '.', $info['price']); $info['ecotax'] = str_replace(',', '.', $info['ecotax']); $info['weight'] = str_replace(',', '.', $info['weight']); $info['available_date'] = Validate::isDate($info['available_date']) ? $info['available_date'] : null; if (!Validate::isEan13($info['ean13'])) { $this->warnings[] = sprintf($this->trans('EAN13 "%1s" has incorrect value for product with id %2d.', array(), 'Admin.Parameters.Notification'), $info['ean13'], $product->id); $info['ean13'] = ''; } if ($info['default_on'] && !$validateOnly) { $product->deleteDefaultAttributes(); } // if a reference is specified for this product, get the associate id_product_attribute to UPDATE if (isset($info['reference']) && !empty($info['reference'])) { $id_product_attribute = Combination::getIdByReference($product->id, strval($info['reference'])); // updates the attribute if ($id_product_attribute && !$validateOnly) { // gets all the combinations of this product $attribute_combinations = $product->getAttributeCombinations($default_language); foreach ($attribute_combinations as $attribute_combination) { if ($id_product_attribute && in_array($id_product_attribute, $attribute_combination)) { // FIXME: ~3s/declinaison $product->updateAttribute($id_product_attribute, (double) $info['wholesale_price'], (double) $info['price'], (double) $info['weight'], 0, Configuration::get('PS_USE_ECOTAX') ? (double) $info['ecotax'] : 0, $id_image, strval($info['reference']), strval($info['ean13']), (int) $info['default_on'], 0, strval($info['upc']), (int) $info['minimal_quantity'], $info['available_date'], null, $id_shop_list); $id_product_attribute_update = true; if (isset($info['supplier_reference']) && !empty($info['supplier_reference'])) { $product->addSupplierReference($product->id_supplier, $id_product_attribute, $info['supplier_reference']); } // until here } } } } // if no attribute reference is specified, creates a new one if (!$id_product_attribute && !$validateOnly) { $id_product_attribute = $product->addCombinationEntity((double) $info['wholesale_price'], (double) $info['price'], (double) $info['weight'], 0, Configuration::get('PS_USE_ECOTAX') ? (double) $info['ecotax'] : 0, (int) $info['quantity'], $id_image, strval($info['reference']), 0, strval($info['ean13']), (int) $info['default_on'], 0, strval($info['upc']), (int) $info['minimal_quantity'], $id_shop_list, $info['available_date']); if (isset($info['supplier_reference']) && !empty($info['supplier_reference'])) { $product->addSupplierReference($product->id_supplier, $id_product_attribute, $info['supplier_reference']); } } // fills our attributes array, in order to add the attributes to the product_attribute afterwards if (isset($attributes[$group . '_' . $attribute])) { $attributes_to_add[] = (int) $attributes[$group . '_' . $attribute]; } // after insertion, we clean attribute position and group attribute position if (!$validateOnly) { $obj = new Attribute(); $obj->cleanPositions((int) $id_attribute_group, false); AttributeGroup::cleanPositions(); } } } } $product->checkDefaultAttributes(); if (!$product->cache_default_attribute && !$validateOnly) { Product::updateDefaultAttribute($product->id); } if ($id_product_attribute) { if (!$validateOnly) { // now adds the attributes in the attribute_combination table if ($id_product_attribute_update) { Db::getInstance()->execute(' DELETE FROM ' . _DB_PREFIX_ . 'product_attribute_combination WHERE id_product_attribute = ' . (int) $id_product_attribute); } foreach ($attributes_to_add as $attribute_to_add) { Db::getInstance()->execute(' INSERT IGNORE INTO ' . _DB_PREFIX_ . 'product_attribute_combination (id_attribute, id_product_attribute) VALUES (' . (int) $attribute_to_add . ',' . (int) $id_product_attribute . ')', false); } } // set advanced stock managment if (isset($info['advanced_stock_management'])) { if ($info['advanced_stock_management'] != 1 && $info['advanced_stock_management'] != 0) { $this->warnings[] = sprintf($this->trans('Advanced stock management has incorrect value. Not set for product with id %d.', array(), 'Admin.Parameters.Notification'), $product->id); } elseif (!Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT') && $info['advanced_stock_management'] == 1) { $this->warnings[] = sprintf($this->trans('Advanced stock management is not enabled, cannot enable on product with id %d.', array(), 'Admin.Parameters.Notification'), $product->id); } elseif (!$validateOnly) { $product->setAdvancedStockManagement($info['advanced_stock_management']); } // automaticly disable depends on stock, if a_s_m set to disabled if (!$validateOnly && StockAvailable::dependsOnStock($product->id) == 1 && $info['advanced_stock_management'] == 0) { StockAvailable::setProductDependsOnStock($product->id, 0, null, $id_product_attribute); } } // Check if warehouse exists if (isset($info['warehouse']) && $info['warehouse']) { if (!Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT')) { $this->warnings[] = sprintf($this->trans('Advanced stock management is not enabled, warehouse is not set on product with id %d.', array(), 'Admin.Parameters.Notification'), $product->id); } else { if (Warehouse::exists($info['warehouse'])) { $warehouse_location_entity = new WarehouseProductLocation(); $warehouse_location_entity->id_product = $product->id; $warehouse_location_entity->id_product_attribute = $id_product_attribute; $warehouse_location_entity->id_warehouse = $info['warehouse']; if (!$validateOnly) { if (WarehouseProductLocation::getProductLocation($product->id, $id_product_attribute, $info['warehouse']) !== false) { $warehouse_location_entity->update(); } else { $warehouse_location_entity->save(); } StockAvailable::synchronize($product->id); } } else { $this->warnings[] = sprintf($this->trans('Warehouse did not exist, cannot set on product %1$s.', array(), 'Admin.Parameters.Notification'), $product->name[$default_language]); } } } // stock available if (isset($info['depends_on_stock'])) { if ($info['depends_on_stock'] != 0 && $info['depends_on_stock'] != 1) { $this->warnings[] = sprintf($this->trans('Incorrect value for "Depends on stock" for product %1$s ', array(), 'Admin.Notifications.Error'), $product->name[$default_language]); } elseif ((!$info['advanced_stock_management'] || $info['advanced_stock_management'] == 0) && $info['depends_on_stock'] == 1) { $this->warnings[] = sprintf($this->trans('Advanced stock management is not enabled, cannot set "Depends on stock" for product %1$s ', array(), 'Admin.Parameters.Notification'), $product->name[$default_language]); } elseif (!$validateOnly) { StockAvailable::setProductDependsOnStock($product->id, $info['depends_on_stock'], null, $id_product_attribute); } // This code allows us to set qty and disable depends on stock if (isset($info['quantity']) && (int) $info['quantity']) { // if depends on stock and quantity, add quantity to stock if ($info['depends_on_stock'] == 1) { $stock_manager = StockManagerFactory::getManager(); $price = str_replace(',', '.', $info['wholesale_price']); if ($price == 0) { $price = 1.0E-6; } $price = round(floatval($price), 6); $warehouse = new Warehouse($info['warehouse']); if (!$validateOnly && $stock_manager->addProduct((int) $product->id, $id_product_attribute, $warehouse, (int) $info['quantity'], 1, $price, true)) { StockAvailable::synchronize((int) $product->id); } } elseif (!$validateOnly) { if ($shop_is_feature_active) { foreach ($id_shop_list as $shop) { StockAvailable::setQuantity((int) $product->id, $id_product_attribute, (int) $info['quantity'], (int) $shop); } } else { StockAvailable::setQuantity((int) $product->id, $id_product_attribute, (int) $info['quantity'], $this->context->shop->id); } } } } elseif (!$validateOnly) { // if not depends_on_stock set, use normal qty if ($shop_is_feature_active) { foreach ($id_shop_list as $shop) { StockAvailable::setQuantity((int) $product->id, $id_product_attribute, (int) $info['quantity'], (int) $shop); } } else { StockAvailable::setQuantity((int) $product->id, $id_product_attribute, (int) $info['quantity'], $this->context->shop->id); } } } }
$userImage->setImageType('jpeg'); $userImage->scale(130, 170); // Ordnerspeicherung if ($gPreferences['profile_photo_storage'] == 1) { $userImage->copyToFile(null, SERVER_PATH . '/adm_my_files/user_profile_photos/' . $getUserId . '_new.jpg'); } else { // Foto in PHP-Temp-Ordner übertragen $userImage->copyToFile(null, $_FILES['userfile']['tmp_name'][0]); // Foto aus PHP-Temp-Ordner einlesen $userImageData = fread(fopen($_FILES['userfile']['tmp_name'][0], 'r'), $_FILES['userfile']['size'][0]); // Zwischenspeichern des neuen Fotos in der Session $gCurrentSession->setValue('ses_binary', $userImageData); $gCurrentSession->save(); } // Image-Objekt löschen $userImage->delete(); if ($getUserId == $gCurrentUser->getValue('usr_id')) { $headline = $gL10n->get('PRO_EDIT_MY_PROFILE_PICTURE'); } else { $headline = $gL10n->get('PRO_EDIT_PROFILE_PIC_FROM', $user->getValue('FIRST_NAME'), $user->getValue('LAST_NAME')); } // create html page object $page = new HtmlPage($headline); $page->addJavascript('$("#btn_cancel").click(function() { self.location.href=\'' . $g_root_path . '/adm_program/modules/profile/profile_photo_edit.php?mode=dont_save&usr_id=' . $getUserId . '\'; });', true); // show form $form = new HtmlForm('show_new_profile_picture_form', $g_root_path . '/adm_program/modules/profile/profile_photo_edit.php?mode=save&usr_id=' . $getUserId, $page); $form->addCustomContent($gL10n->get('PRO_CURRENT_PICTURE'), '<img class="imageFrame" src="profile_photo_show.php?usr_id=' . $getUserId . '" alt="' . $gL10n->get('PRO_CURRENT_PICTURE') . '" />'); $form->addCustomContent($gL10n->get('PRO_NEW_PICTURE'), '<img class="imageFrame" src="profile_photo_show.php?usr_id=' . $getUserId . '&new_photo=1" alt="' . $gL10n->get('PRO_NEW_PICTURE') . '" />'); $form->addLine();
public function attributeImport() { $default_language = Configuration::get('PS_LANG_DEFAULT'); $groups = array(); foreach (AttributeGroup::getAttributesGroups($default_language) as $group) { $groups[$group['name']] = (int) $group['id_attribute_group']; } $attributes = array(); foreach (Attribute::getAttributes($default_language) as $attribute) { $attributes[$attribute['attribute_group'] . '_' . $attribute['name']] = (int) $attribute['id_attribute']; } $this->receiveTab(); $handle = $this->openCsvFile(); AdminImportController::setLocale(); for ($current_line = 0; $line = fgetcsv($handle, MAX_LINE_SIZE, $this->separator); $current_line++) { if (count($line) == 1 && empty($line[0])) { continue; } if (Tools::getValue('convert')) { $line = $this->utf8EncodeArray($line); } $info = AdminImportController::getMaskedRow($line); $info = array_map('trim', $info); AdminImportController::setDefaultValues($info); if (!Shop::isFeatureActive()) { $info['shop'] = 1; } elseif (!isset($info['shop']) || empty($info['shop'])) { $info['shop'] = implode($this->multiple_value_separator, Shop::getContextListShopID()); } // Get shops for each attributes $info['shop'] = explode($this->multiple_value_separator, $info['shop']); $id_shop_list = array(); foreach ($info['shop'] as $shop) { if (!is_numeric($shop)) { $id_shop_list[] = Shop::getIdByName($shop); } else { $id_shop_list[] = $shop; } } if (isset($info['id_product'])) { $product = new Product((int) $info['id_product'], false, $default_language); } else { continue; } $id_image = null; //delete existing images if "delete_existing_images" is set to 1 if (array_key_exists('delete_existing_images', $info) && $info['delete_existing_images'] && !isset($this->cache_image_deleted[(int) $product->id])) { $product->deleteImages(); $this->cache_image_deleted[(int) $product->id] = true; } if (isset($info['image_url']) && $info['image_url']) { $product_has_images = (bool) Image::getImages($this->context->language->id, $product->id); $url = $info['image_url']; $image = new Image(); $image->id_product = (int) $product->id; $image->position = Image::getHighestPosition($product->id) + 1; $image->cover = !$product_has_images ? true : false; $field_error = $image->validateFields(UNFRIENDLY_ERROR, true); $lang_field_error = $image->validateFieldsLang(UNFRIENDLY_ERROR, true); if ($field_error === true && $lang_field_error === true && $image->add()) { $image->associateTo($id_shop_list); if (!AdminImportController::copyImg($product->id, $image->id, $url)) { $this->warnings[] = sprintf(Tools::displayError('Error copying image: %s'), $url); $image->delete(); } else { $id_image = array($image->id); } } else { $this->warnings[] = sprintf(Tools::displayError('%s cannot be saved'), isset($image->id_product) ? ' (' . $image->id_product . ')' : ''); $this->errors[] = ($field_error !== true ? $field_error : '') . (isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : '') . mysql_error(); } } elseif (isset($info['image_position']) && $info['image_position']) { $images = $product->getImages($default_language); if ($images) { foreach ($images as $row) { if ($row['position'] == (int) $info['image_position']) { $id_image = array($row['id_image']); break; } } } if (!$id_image) { $this->warnings[] = sprintf(Tools::displayError('No image was found for combination with id_product = %s and image position = %s.'), $product->id, (int) $info['image_position']); } } $id_attribute_group = 0; // groups $groups_attributes = array(); if (isset($info['group'])) { foreach (explode($this->multiple_value_separator, $info['group']) as $key => $group) { $tab_group = explode(':', $group); $group = trim($tab_group[0]); if (!isset($tab_group[1])) { $type = 'select'; } else { $type = trim($tab_group[1]); } // sets group $groups_attributes[$key]['group'] = $group; // if position is filled if (isset($tab_group[2])) { $position = trim($tab_group[2]); } else { $position = false; } if (!isset($groups[$group])) { $obj = new AttributeGroup(); $obj->is_color_group = false; $obj->group_type = pSQL($type); $obj->name[$default_language] = $group; $obj->public_name[$default_language] = $group; $obj->position = !$position ? AttributeGroup::getHigherPosition() + 1 : $position; if (($field_error = $obj->validateFields(UNFRIENDLY_ERROR, true)) === true && ($lang_field_error = $obj->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true) { $obj->add(); $obj->associateTo($id_shop_list); $groups[$group] = $obj->id; } else { $this->errors[] = ($field_error !== true ? $field_error : '') . (isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : ''); } // fils groups attributes $id_attribute_group = $obj->id; $groups_attributes[$key]['id'] = $id_attribute_group; } else { $id_attribute_group = $groups[$group]; $groups_attributes[$key]['id'] = $id_attribute_group; } } } // inits attribute $id_product_attribute = 0; $id_product_attribute_update = false; $attributes_to_add = array(); // for each attribute if (isset($info['attribute'])) { foreach (explode($this->multiple_value_separator, $info['attribute']) as $key => $attribute) { $tab_attribute = explode(':', $attribute); $attribute = trim($tab_attribute[0]); // if position is filled if (isset($tab_attribute[1])) { $position = trim($tab_attribute[1]); } else { $position = false; } if (isset($groups_attributes[$key])) { $group = $groups_attributes[$key]['group']; if (!isset($attributes[$group . '_' . $attribute]) && count($groups_attributes[$key]) == 2) { $id_attribute_group = $groups_attributes[$key]['id']; $obj = new Attribute(); // sets the proper id (corresponding to the right key) $obj->id_attribute_group = $groups_attributes[$key]['id']; $obj->name[$default_language] = str_replace('\\n', '', str_replace('\\r', '', $attribute)); $obj->position = !$position && isset($groups[$group]) ? Attribute::getHigherPosition($groups[$group]) + 1 : $position; if (($field_error = $obj->validateFields(UNFRIENDLY_ERROR, true)) === true && ($lang_field_error = $obj->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true) { $obj->add(); $obj->associateTo($id_shop_list); $attributes[$group . '_' . $attribute] = $obj->id; } else { $this->errors[] = ($field_error !== true ? $field_error : '') . (isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : ''); } } $info['minimal_quantity'] = isset($info['minimal_quantity']) && $info['minimal_quantity'] ? (int) $info['minimal_quantity'] : 1; $info['wholesale_price'] = str_replace(',', '.', $info['wholesale_price']); $info['price'] = str_replace(',', '.', $info['price']); $info['ecotax'] = str_replace(',', '.', $info['ecotax']); $info['weight'] = str_replace(',', '.', $info['weight']); // if a reference is specified for this product, get the associate id_product_attribute to UPDATE if (isset($info['reference']) && !empty($info['reference'])) { $id_product_attribute = Combination::getIdByReference($product->id, strval($info['reference'])); // updates the attribute if ($id_product_attribute) { // gets all the combinations of this product $attribute_combinations = $product->getAttributeCombinations($default_language); foreach ($attribute_combinations as $attribute_combination) { if ($id_product_attribute && in_array($id_product_attribute, $attribute_combination)) { $product->updateAttribute($id_product_attribute, (double) $info['wholesale_price'], (double) $info['price'], (double) $info['weight'], 0, (double) $info['ecotax'], $id_image, strval($info['reference']), strval($info['ean13']), (int) $info['default_on'], 0, strval($info['upc']), (int) $info['minimal_quantity'], 0, null, $id_shop_list); $id_product_attribute_update = true; } } } } // if no attribute reference is specified, creates a new one if (!$id_product_attribute) { $id_product_attribute = $product->addCombinationEntity((double) $info['wholesale_price'], (double) $info['price'], (double) $info['weight'], 0, (double) $info['ecotax'], (int) $info['quantity'], $id_image, strval($info['reference']), 0, strval($info['ean13']), (int) $info['default_on'], 0, strval($info['upc']), (int) $info['minimal_quantity'], $id_shop_list); } // fills our attributes array, in order to add the attributes to the product_attribute afterwards if (isset($attributes[$group . '_' . $attribute])) { $attributes_to_add[] = (int) $attributes[$group . '_' . $attribute]; } // after insertion, we clean attribute position and group attribute position $obj = new Attribute(); $obj->cleanPositions((int) $id_attribute_group, false); AttributeGroup::cleanPositions(); } } } $product->checkDefaultAttributes(); if (!$product->cache_default_attribute) { Product::updateDefaultAttribute($product->id); } if ($id_product_attribute) { // now adds the attributes in the attribute_combination table if ($id_product_attribute_update) { Db::getInstance()->execute(' DELETE FROM ' . _DB_PREFIX_ . 'product_attribute_combination WHERE id_product_attribute = ' . (int) $id_product_attribute); } foreach ($attributes_to_add as $attribute_to_add) { Db::getInstance()->execute(' INSERT IGNORE INTO ' . _DB_PREFIX_ . 'product_attribute_combination (id_attribute, id_product_attribute) VALUES (' . (int) $attribute_to_add . ',' . (int) $id_product_attribute . ')'); } StockAvailable::setQuantity($product->id, $id_product_attribute, (int) $info['quantity']); } } $this->closeCsvFile($handle); }
public function cropCover($id) { $top = \Input::get('top'); $failed = json_encode(['status' => 'error', 'message' => trans('photo.error', ['size' => formatBytes()])]); $page = $this->pageRepository->get($id); if (!$page or !$page->isOwner()) { return $failed; } $image = $this->photo->cropImage(base_path($page->original_cover), 'cover/', 0, abs($top), 1000, 300, false); $image = str_replace('%d', 'original', $image->result()); if (!empty($image)) { /** * Update user profile cover */ if ($page->cover and $page->cover != $page->original_cover) { \Image::delete($page->cover); } $page->cover = $image; $page->save(); return json_encode(['status' => 'success', 'url' => \Image::url($image)]); } else { return json_encode(['status' => 'error', 'message' => 'Error things']); } }
public function delete($path) { return \Image::delete($path); }
/** * Performs the action; returns true on success, false on error. * * @param $p_context - the current context object * @return bool */ public function takeAction(CampContext &$p_context) { if (!is_object($this->m_interview)) { return false; } $User = $p_context->user; if (!$User->has_permission('plugin_interview_admin')) { $this->m_error = new PEAR_Error('User have no permission to maintain interviews.', ACTION_INTERVIEW_ERR_NO_PERMISSION); return false; } $image_id = $this->m_interview->getProperty('fk_image_id'); if ($this->m_properties['image_delete'] && $image_id) { $Image = new Image($this->m_interview->getProperty('fk_image_id')); $Image->delete(); $image_id = null; } else { $file = $this->m_properties['image']; if (strlen($file['name'])) { $attributes = array( 'Description' => strlen($this->m_properties['f_interview_image_description']) ? $this->m_properties['f_interview_image_description'] : $file['name'], ); $Image = Image::OnImageUpload($file, $attributes, $p_user_id, !empty($image_id) ? $image_id : null); if (is_a($Image, 'Image')) { $image_id = $Image->getProperty('Id'); } else { return false; } } } if ($this->m_interview->exists()) { // edit existing interview $this->m_interview->setProperty('fk_language_id', $this->m_properties['language_id']); $this->m_interview->setProperty('fk_moderator_user_id', $this->m_properties['moderator_user_id']); $this->m_interview->setProperty('fk_guest_user_id', $this->m_properties['guest_user_id']); $this->m_interview->setProperty('title', $this->m_properties['title']); $this->m_interview->setProperty('fk_image_id', $image_id); $this->m_interview->setProperty('description_short', $this->m_properties['description_short']); $this->m_interview->setProperty('description', $this->m_properties['description']); $this->m_interview->setProperty('interview_begin', $this->m_properties['interview_begin']); $this->m_interview->setProperty('interview_end', $this->m_properties['interview_end']); $this->m_interview->setProperty('questions_begin', $this->m_properties['questions_begin']); $this->m_interview->setProperty('questions_end', $this->m_properties['questions_end']); $this->m_interview->setProperty('questions_limit', $this->m_properties['questions_limit']); #$this->m_interview->setProperty('status', $this->m_properties['status']); $this->m_error = ACTION_OK; return true; } else { // create new interview if ($this->m_interview->create( $this->m_properties['language_id'], $this->m_properties['moderator_user_id'], $this->m_properties['guest_user_id'], $this->m_properties['title'], $image_id, $this->m_properties['description_short'], $this->m_properties['description'], $this->m_properties['interview_begin'], $this->m_properties['interview_end'], $this->m_properties['questions_begin'], $this->m_properties['questions_end'], $this->m_properties['questions_limit'] )) { $_REQUEST['f_interview_id'] = $this->m_interview->getProperty('interview_id'); $this->m_error = ACTION_OK; return true; } } return false; }
/** * * removes concrete model's image * @param Image $img * @throws \Exception */ public function removeImage(Image $img) { $img->clearCache(); $storePath = $this->getModule()->getStorePath(); $fileToRemove = $storePath . DIRECTORY_SEPARATOR . $img->filePath; if (preg_match('@\\.@', $fileToRemove) and is_file($fileToRemove)) { unlink($fileToRemove); } $img->delete(); }
$image = Image::get($imageid, $userid); $imagefilename = $image->getProperty('filename'); $imagesq50 = $image->getProperty('sq50'); $imagesq150 = $image->getProperty('sq150'); $imagesq300 = $image->getProperty('sq300'); $imagesq500 = $image->getProperty('sq500'); $dataowneruserid = $image->getProperty('dataowneruserid'); if ($userisowner == Database::DBFALSE && $userisadmin == Database::DBFALSE) { header("Location: logout"); exit; } if ($userisowner == Database::DBTRUE && $dataowneruserid != $userid) { header("Location: logout"); exit; } Image::delete($imageid, $userid); unlink(PHOTODIR . $imagefilename); unlink(PHOTODIR . $imagesq50); unlink(PHOTODIR . $imagesq150); unlink(PHOTODIR . $imagesq300); unlink(PHOTODIR . $imagesq500); $formmessage = 'Image deleted.'; $formmessageclass = 'red'; } catch (Exception $e) { $formmessage = $e->getMessage(); $formmessageclass = 'red'; } } else { header("Location: logout"); exit; }
/** * Delete product images from database * * @return bool success */ public function deleteImages() { $result = Db::getInstance()->ExecuteS(' SELECT `id_image` FROM `' . _DB_PREFIX_ . 'image` WHERE `id_product` = ' . (int) $this->id); $status = true; if ($result) { foreach ($result as $row) { $image = new Image($row['id_image']); $status &= $image->delete(); } } return $status; }
private function deleteImage($values) { $retval = false; if ($values['thumbnail']) { $image = new Image($values['thumbnail'], $this->plugin->getContentPath(true)); $image->delete(); $retval = true; } if ($values['image']) { $image = new Image($values['image'], $this->plugin->getContentPath(true)); $image->delete(); $retval = true; } return $retval; }
private function handlePOST_deleteMedia($request_data) { global $error, $error_msg; // echo "<pre>".print_r($request_data,1)."</pre>"; // deleting media if (!empty($request_data['media_id'])) { $id = $request_data['media_id']; try { if ($request_data['type'] == 'Images') { $new_image = new Image(); $new_image->content_id = $id; $new_image->parent_collection_id = !empty($request_data['gid']) ? $request_data['gid'] : -1; $new_image->delete($id); $success_delete = TRUE; $error_msg = 2004; } if ($request_data['type'] == 'Audios') { $new_image = new Audio(); $new_image->content_id = $id; $new_image->delete($id); $success_delete = TRUE; $error_msg = 2005; } if ($request_data['type'] == 'Videos') { $new_image = new TekVideo(); $new_image->content_id = $id; $new_image->delete_video($id); $success_delete = TRUE; $error_msg = 2006; } } catch (PAException $e) { $error_msg = "{$e->message}"; $error = TRUE; } } }
/** * Test deleting an image that does not exist * * @expectedException PDOException **/ public function testDeleteInvalidImage() { //Count the number of rows and save it for later $numRows = $this->getConnection()->getRowCount("image"); //Create an image and try to delete it without first inserting it $image = new Image(null, $this->profile->getProfileId(), $this->VALID_IMAGETYPE, $this->VALID_IMAGEFILENAME, $this->VALID_IMAGETEXT, $this->VALID_IMAGEDATE); $image->delete($this->getPDO()); }
$user_image->setImageType('jpeg'); $user_image->scale(130, 170); //Ordnerspeicherung if ($gPreferences['profile_photo_storage'] == 1) { $user_image->copyToFile(null, SERVER_PATH . '/adm_my_files/item_photos/' . $getItemId . '_new.jpg'); } else { //Foto in PHP-Temp-Ordner übertragen $user_image->copyToFile(null, $_FILES['userfile']['tmp_name'][0]); // Foto aus PHP-Temp-Ordner einlesen $user_image_data = fread(fopen($_FILES['userfile']['tmp_name'][0], 'r'), $_FILES['userfile']['size'][0]); // Zwischenspeichern des neuen Fotos in der Session $gCurrentSession->setValue('ses_binary', $user_image_data); $gCurrentSession->save(); } //Image-Objekt löschen $user_image->delete(); if ($getItemId == $gCurrentUser->getValue('inv_id')) { $headline = $gL10n->get('PRO_EDIT_MY_PROFILE_PICTURE'); } else { $headline = $gL10n->get('PRO_EDIT_PROFILE_PIC_FROM', $inventory->getValue('FIRST_NAME'), $inventory->getValue('LAST_NAME')); } // create html page object $page = new HtmlPage($headline); $page->addJavascript('$("#btn_cancel").click(function() { self.location.href=\'' . $g_root_path . '/adm_program/modules/inventory/item_photo_edit.php?mode=dont_save&inv_id=' . $getItemId . '\'; });', true); // show form $form = new HtmlForm('show_new_profile_picture_form', $g_root_path . '/adm_program/modules/inventory/item_photo_edit.php?mode=save&inv_id=' . $getItemId, $page); $form->addCustomContent($gL10n->get('PRO_CURRENT_PICTURE'), '<img class="imageFrame" src="item_photo_show.php?inv_id=' . $getItemId . '" alt="' . $gL10n->get('PRO_CURRENT_PICTURE') . '" />'); $form->addCustomContent($gL10n->get('PRO_NEW_PICTURE'), '<img class="imageFrame" src="item_photo_show.php?inv_id=' . $getItemId . '&new_photo=1" alt="' . $gL10n->get('PRO_NEW_PICTURE') . '" />'); $form->addLine();
/** * This function should be called when an image is uploaded. It will save * the image to the appropriate place on the disk, create a thumbnail for it, * and create a database entry for the file. * * @param array $p_fileVar * <pre> * The variable from the $_FILES array. The array specifies the following: * $a["name"] = original name of the file. * $a["type"] = the MIME type of the file, e.g. image/gif * $a["tmp_name"] = the temporary storage location on disk of the file * $a["size"] = size of the file, in bytes (not required) * $a["error"] = 0 (zero) if there was no error * </pre> * * @param array $p_attributes * Optional attributes which are stored in the database. * Indexes can be the following: 'Description', 'Photographer', 'Place', 'Date' * * @param int $p_userId * The user who uploaded the file. * * @param int $p_id * If the image already exists and we just want to update it, specify the * current image ID here. * * @return mixed * The Image object that was created or updated on success, * return PEAR_Error on error. */ public static function OnImageUpload($p_fileVar, $p_attributes, $p_userId = null, $p_id = null, $p_isLocalFile = false) { global $Campsite; if (function_exists("camp_load_translation_strings")) { camp_load_translation_strings("api"); } if (!is_array($p_fileVar)) { return new PEAR_Error("Invalid arguments given to Image::OnImageUpload()"); } // Verify its a valid image file. $imageInfo = @getimagesize($p_fileVar['tmp_name']); if ($imageInfo === false) { return new PEAR_Error(getGS("The file uploaded is not an image.")); } $extension = Image::__ImageTypeToExtension($imageInfo[2]); // Check if image & thumbnail directories are writable. $imageDir = $Campsite['IMAGE_DIRECTORY']; $thumbDir = $Campsite['THUMBNAIL_DIRECTORY']; if (!file_exists($imageDir) || !is_writable($imageDir)) { return new PEAR_Error(camp_get_error_message(CAMP_ERROR_WRITE_DIR, $imageDir), CAMP_ERROR_WRITE_DIR); } if (!file_exists($thumbDir) || !is_writable($thumbDir)) { return new PEAR_Error(camp_get_error_message(CAMP_ERROR_WRITE_DIR, $thumbDir), CAMP_ERROR_WRITE_DIR); } // Are we updating or creating? if (!is_null($p_id)) { // Updating the image $image = new Image($p_id); $image->update($p_attributes, false); // Remove the old image & thumbnail because // the new file may have a different file extension. if (file_exists($image->getImageStorageLocation())) { unlink($image->getImageStorageLocation()); } if (file_exists($image->getThumbnailStorageLocation())) { unlink($image->getThumbnailStorageLocation()); } } else { // Creating the image $image = new Image(); $image->create($p_attributes); $image->setProperty('TimeCreated', 'NULL', true, true); $image->setProperty('LastModified', 'NULL', true, true); } $image->setProperty('Location', 'local', false); // If we are using PHP version >= 4.3 if (isset($imageInfo['mime'])) { $image->setProperty('ContentType', $imageInfo['mime'], false); } else { $image->setProperty('ContentType', $p_fileVar['type'], false); } if (!is_null($p_userId)) { $image->setProperty('UploadedByUser', $p_userId, false); } if (!isset($p_attributes['Date'])) { $image->setProperty('Date', 'NOW()', true, true); } $target = $image->generateImageStorageLocation($extension); $thumbnail = $image->generateThumbnailStorageLocation($extension); $image->setProperty('ImageFileName', basename($target), false); $image->setProperty('ThumbnailFileName', basename($thumbnail), false); try { if ($p_isLocalFile) { if (!copy($p_fileVar['tmp_name'], $target)) { throw new Exception(camp_get_error_message(CAMP_ERROR_CREATE_FILE, $target), CAMP_ERROR_CREATE_FILE); } } else { if (!rename($p_fileVar['tmp_name'], $target)) { throw new Exception(camp_get_error_message(CAMP_ERROR_CREATE_FILE, $target), CAMP_ERROR_CREATE_FILE); } } chmod($target, 0644); $createMethodName = Image::__GetImageTypeCreateMethod($imageInfo[2]); if ($createMethodName != null) { $imageHandler = $createMethodName($target); if ($imageHandler == false) { throw new Exception(camp_get_error_message(CAMP_ERROR_UPLOAD_FILE, $p_fileVar['name']), CAMP_ERROR_UPLOAD_FILE); } $thumbnailImage = Image::ResizeImage($imageHandler, $Campsite['THUMBNAIL_MAX_SIZE'], $Campsite['THUMBNAIL_MAX_SIZE'], true, $imageInfo[2]); if (PEAR::isError($thumbnailImage)) { throw new Exception($thumbnailImage->getMessage(), $thumbnailImage->getCode()); } $result = Image::SaveImageToFile($thumbnailImage, $thumbnail, $imageInfo[2]); if (PEAR::isError($result)) { throw new Exception($result->getMessage(), $result->getCode()); } chmod($thumbnail, 0644); } elseif ($Campsite['IMAGEMAGICK_INSTALLED']) { $cmd = $Campsite['THUMBNAIL_COMMAND'].' '.$target.' '.$thumbnail; system($cmd); if (file_exists($thumbnail)) { chmod($thumbnail, 0644); } else { throw new Exception(camp_get_error_message(CAMP_ERROR_CREATE_FILE, $thumbnail), CAMP_ERROR_CREATE_FILE); } } else { throw new Exception(getGS("Image type $1 is not supported.", image_type_to_mime_type($p_imageType))); } } catch (Exception $ex) { if (file_exists($target)) { @unlink($target); } if (file_exists($thumbnail)) { @unlink($thumbnail); } if (is_null($p_id)) { $image->delete(); } return new PEAR_Error($ex->getMessage(), $ex->getCode()); } $image->commit(); $logtext = getGS('The image "$1" ($2) has been added.', $image->m_data['Description'], $image->m_data['Id']); Log::Message($logtext, null, 41); return $image; } // fn OnImageUpload
public function postProcess($token = NULL) { global $currentIndex; /* Add a new product */ if (Tools::isSubmit('submitAddproduct') or Tools::isSubmit('submitAddproductAndStay')) { if ($this->tabAccess['add'] === '1') { $this->submitAddproduct($token); } elseif (Tools::getValue('id_product') and $this->tabAccess['edit'] === '1') { $this->submitAddproduct($token); } else { $this->_errors[] = Tools::displayError('You do not have permission to add anything here.'); } } /* Delete a product in the download folder */ if (Tools::getValue('deleteVirtualProduct')) { if ($this->tabAccess['delete'] === '1') { $this->deleteVirtualProduct(); } else { $this->_errors[] = Tools::displayError('You do not have permission to delete anything here.'); } } elseif (Tools::isSubmit('submitAttachments')) { if ($this->tabAccess['edit'] === '1') { if ($id = intval(Tools::getValue($this->identifier))) { if (Attachment::attachToProduct($id, $_POST['attachments'])) { Tools::redirectAdmin($currentIndex . '&id_product=' . $id . '&conf=4&add' . $this->table . '&tabs=6&token=' . ($token ? $token : $this->token)); } } } } elseif (isset($_GET['duplicate' . $this->table])) { if ($this->tabAccess['add'] === '1') { if (Validate::isLoadedObject($product = new Product(intval(Tools::getValue('id_product'))))) { $id_product_old = $product->id; unset($product->id); unset($product->id_product); $product->indexed = 0; if ($product->add() and Category::duplicateProductCategories($id_product_old, $product->id) and ($combinationImages = Product::duplicateAttributes($id_product_old, $product->id)) !== false and Product::duplicateAccessories($id_product_old, $product->id) and Product::duplicateFeatures($id_product_old, $product->id) and Product::duplicateQuantityDiscount($id_product_old, $product->id) and Pack::duplicate($id_product_old, $product->id) and Product::duplicateCustomizationFields($id_product_old, $product->id) and Product::duplicateTags($id_product_old, $product->id)) { if (!Tools::getValue('noimage') and !Image::duplicateProductImages($id_product_old, $product->id, $combinationImages)) { $this->_errors[] = Tools::displayError('an error occurred while copying images'); } else { Hook::addProduct($product); Search::indexation(false); Tools::redirectAdmin($currentIndex . '&id_category=' . intval(Tools::getValue('id_category')) . '&conf=19&token=' . ($token ? $token : $this->token)); } } else { $this->_errors[] = Tools::displayError('an error occurred while creating object'); } } } else { $this->_errors[] = Tools::displayError('You do not have permission to add anything here.'); } } elseif ($id_image = intval(Tools::getValue('id_image')) and Validate::isUnsignedId($id_image) and Validate::isLoadedObject($image = new Image($id_image))) { if ($this->tabAccess['edit'] === '1') { /* Delete product image */ if (isset($_GET['deleteImage'])) { $image->delete(); deleteImage($image->id_product, $image->id); if (!Image::getCover($image->id_product)) { $first_img = Db::getInstance()->getRow(' SELECT `id_image` FROM `' . _DB_PREFIX_ . 'image` WHERE `id_product` = ' . intval($image->id_product)); Db::getInstance()->Execute(' UPDATE `' . _DB_PREFIX_ . 'image` SET `cover` = 1 WHERE `id_image` = ' . intval($first_img['id_image'])); } @unlink(dirname(__FILE__) . '/../../img/tmp/product_' . $image->id_product . '.jpg'); @unlink(dirname(__FILE__) . '/../../img/tmp/product_mini_' . $image->id_product . '.jpg'); Tools::redirectAdmin($currentIndex . '&id_product=' . $image->id_product . '&id_category=' . intval(Tools::getValue('id_category')) . '&add' . $this->table . '&tabs=1' . '&token=' . ($token ? $token : $this->token)); } elseif (isset($_GET['editImage'])) { if ($image->cover) { $_POST['cover'] = 1; } $languages = Language::getLanguages(); foreach ($languages as $language) { if (isset($image->legend[$language['id_lang']])) { $_POST['legend_' . $language['id_lang']] = $image->legend[$language['id_lang']]; } } $_POST['id_image'] = $image->id; $this->displayForm($token ? $token : $this->token); } elseif (isset($_GET['coverImage'])) { Image::deleteCover($image->id_product); $image->cover = 1; if (!$image->update()) { $this->_errors[] = Tools::displayError('Impossible to change the product cover'); } else { $productId = intval(Tools::getValue('id_product')); @unlink(dirname(__FILE__) . '/../../img/tmp/product_' . $productId . '.jpg'); @unlink(dirname(__FILE__) . '/../../img/tmp/product_mini_' . $productId . '.jpg'); Tools::redirectAdmin($currentIndex . '&id_product=' . $image->id_product . '&id_category=' . intval(Tools::getValue('id_category')) . '&addproduct&tabs=1' . '&token=' . ($token ? $token : $this->token)); } } elseif (isset($_GET['imgPosition']) and isset($_GET['imgDirection'])) { $image->positionImage(intval(Tools::getValue('imgPosition')), intval(Tools::getValue('imgDirection'))); Tools::redirectAdmin($currentIndex . '&id_product=' . $image->id_product . '&id_category=' . intval(Tools::getValue('id_category')) . '&add' . $this->table . '&tabs=1&token=' . ($token ? $token : $this->token)); } } else { $this->_errors[] = Tools::displayError('You do not have permission to edit anything here.'); } } elseif (Tools::isSubmit('submitProductAttribute')) { if (Validate::isLoadedObject($product = new Product(intval(Tools::getValue('id_product'))))) { if (!isset($_POST['attribute_quantity']) or $_POST['attribute_quantity'] == NULL) { $this->_errors[] = Tools::displayError('attribute quantity is required'); } if (!isset($_POST['attribute_price']) or $_POST['attribute_price'] == NULL) { $this->_errors[] = Tools::displayError('attribute price is required'); } if (!isset($_POST['attribute_combinaison_list']) or !sizeof($_POST['attribute_combinaison_list'])) { $this->_errors[] = Tools::displayError('you must add at least one attribute'); } if (!sizeof($this->_errors)) { if (!isset($_POST['attribute_wholesale_price'])) { $_POST['attribute_wholesale_price'] = 0; } if (!isset($_POST['attribute_price_impact'])) { $_POST['attribute_price_impact'] = 0; } if (!isset($_POST['attribute_weight_impact'])) { $_POST['attribute_weight_impact'] = 0; } if (!isset($_POST['attribute_ecotax'])) { $_POST['attribute_ecotax'] = 0; } if (Tools::getValue('attribute_default')) { $product->deleteDefaultAttributes(); } // Change existing one if ($id_product_attribute = intval(Tools::getValue('id_product_attribute'))) { if ($this->tabAccess['edit'] === '1') { if ($product->productAttributeExists($_POST['attribute_combinaison_list'], $id_product_attribute)) { $this->_errors[] = Tools::displayError('This attribute already exists.'); } else { $product->updateProductAttribute($id_product_attribute, Tools::getValue('attribute_wholesale_price'), Tools::getValue('attribute_price') * Tools::getValue('attribute_price_impact'), Tools::getValue('attribute_weight') * Tools::getValue('attribute_weight_impact'), Tools::getValue('attribute_ecotax'), Tools::getValue('attribute_quantity'), Tools::getValue('id_image_attr'), Tools::getValue('attribute_reference'), Tools::getValue('attribute_supplier_reference'), Tools::getValue('attribute_ean13'), Tools::getValue('attribute_default'), Tools::getValue('attribute_location')); } } else { $this->_errors[] = Tools::displayError('You do not have permission to add anything here.'); } } else { if ($this->tabAccess['add'] === '1') { if ($product->productAttributeExists($_POST['attribute_combinaison_list'])) { $this->_errors[] = Tools::displayError('This combination already exists.'); } else { $id_product_attribute = $product->addCombinationEntity(Tools::getValue('attribute_wholesale_price'), Tools::getValue('attribute_price') * Tools::getValue('attribute_price_impact'), Tools::getValue('attribute_weight') * Tools::getValue('attribute_weight_impact'), Tools::getValue('attribute_ecotax'), Tools::getValue('attribute_quantity'), Tools::getValue('id_image_attr'), Tools::getValue('attribute_reference'), Tools::getValue('attribute_supplier_reference'), Tools::getValue('attribute_ean13'), Tools::getValue('attribute_default'), Tools::getValue('attribute_location')); } } else { $this->_errors[] = Tools::displayError('You do not have permission to') . '<hr>' . Tools::displayError('edit something here.'); } } if (!sizeof($this->_errors)) { $product->addAttributeCombinaison($id_product_attribute, Tools::getValue('attribute_combinaison_list')); $product->checkDefaultAttributes(); } if (!sizeof($this->_errors)) { Tools::redirectAdmin($currentIndex . '&id_product=' . $product->id . '&id_category=' . intval(Tools::getValue('id_category')) . '&add' . $this->table . '&tabs=2&token=' . ($token ? $token : $this->token)); } } } } elseif (isset($_GET['deleteProductAttribute'])) { if ($this->tabAccess['delete'] === '1') { if ($id_product = intval(Tools::getValue('id_product')) and Validate::isUnsignedId($id_product) and Validate::isLoadedObject($product = new Product($id_product))) { $product->deleteAttributeCombinaison(intval(Tools::getValue('id_product_attribute'))); $product->checkDefaultAttributes(); Tools::redirectAdmin($currentIndex . '&add' . $this->table . '&id_category=' . intval(Tools::getValue('id_category')) . '&tabs=2&id_product=' . $product->id . '&token=' . ($token ? $token : $this->token)); } else { $this->_errors[] = Tools::displayError('impossible to delete attribute'); } } else { $this->_errors[] = Tools::displayError('You do not have permission to delete here.'); } } elseif (Tools::isSubmit('submitProductFeature')) { if ($this->tabAccess['edit'] === '1') { if (Validate::isLoadedObject($product = new Product(intval(Tools::getValue('id_product'))))) { // delete all objects $product->deleteFeatures(); // add new objects $languages = Language::getLanguages(); foreach ($_POST as $key => $val) { if (preg_match("/^feature_([0-9]+)_value/i", $key, $match)) { if ($val) { $product->addFeaturesToDB($match[1], $val); } else { if ($default_value = $this->checkFeatures($languages, $match[1])) { $id_value = $product->addFeaturesToDB($match[1], 0, 1, $language['id_lang']); foreach ($languages as $language) { if ($cust = Tools::getValue('custom_' . $match[1] . '_' . $language['id_lang'])) { $product->addFeaturesCustomToDB($id_value, $language['id_lang'], $cust); } else { $product->addFeaturesCustomToDB($id_value, $language['id_lang'], $default_value); } } } } } } if (!sizeof($this->_errors)) { Tools::redirectAdmin($currentIndex . '&id_product=' . $product->id . '&id_category=' . intval(Tools::getValue('id_category')) . '&add' . $this->table . '&tabs=3&token=' . ($token ? $token : $this->token)); } } else { $this->_errors[] = Tools::displayError('product must be created before adding features'); } } $this->_errors[] = Tools::displayError('You do not have permission to edit anything here.'); } elseif (Tools::isSubmit('submitQuantityDiscount')) { $_POST['tabs'] = 5; if ($this->tabAccess['add'] === '1') { if (Validate::isLoadedObject($product = new Product(intval(Tools::getValue('id_product'))))) { if (!($id_discount_type = intval(Tools::getValue('id_discount_type')))) { $this->_errors[] = Tools::displayError('discount type not selected'); } else { if (!($quantity_discount = intval(Tools::getValue('quantity_discount')))) { $this->_errors[] = Tools::displayError('quantity is required'); } else { if (!($value_discount = floatval(Tools::getValue('value_discount')))) { $this->_errors[] = Tools::displayError('value is required'); } else { $qD = new QuantityDiscount(); $qD->id_product = $product->id; $qD->id_discount_type = $id_discount_type; $qD->quantity = $quantity_discount; $qD->value = $value_discount; if ($qD->add() and !sizeof($this->_errors) and $qD->validateFields()) { Tools::redirectAdmin($currentIndex . '&id_product=' . $product->id . '&id_category=' . intval(Tools::getValue('id_category')) . '&add' . $this->table . '&tabs=5&conf=3&token=' . ($token ? $token : $this->token)); } $this->_errors[] = Tools::displayError('an error occurred while creating object'); } } } } else { $this->_errors[] = Tools::displayError('product must be created before adding quantity discounts'); } } else { $this->_errors[] = Tools::displayError('You do not have permission to add anything here.'); } } elseif (isset($_GET['deleteQuantityDiscount'])) { if ($this->tabAccess['delete'] === '1') { if (Validate::isLoadedObject($product = new Product(intval(Tools::getValue('id_product'))))) { if (Validate::isLoadedObject($qD = new QuantityDiscount(intval(Tools::getValue('id_quantity_discount'))))) { $qD->delete(); if (!sizeof($this->_errors)) { Tools::redirectAdmin($currentIndex . '&id_product=' . $product->id . '&id_category=' . intval(Tools::getValue('id_category')) . '&add' . $this->table . '&tabs=5&conf=1&token=' . ($token ? $token : $this->token)); } } else { $this->_errors[] = Tools::displayError('not a valid quantity discount'); } } else { $this->_errors[] = Tools::displayError('product must be created before delete quantity discounts'); } $qD = new QuantityDiscount(); } else { $this->_errors[] = Tools::displayError('You do not have permission to delete here.'); } } elseif (Tools::isSubmit('submitCustomizationConfiguration')) { if ($this->tabAccess['edit'] === '1') { if (Validate::isLoadedObject($product = new Product(intval(Tools::getValue('id_product'))))) { if (!$product->createLabels(intval($_POST['uploadable_files']) - intval($product->uploadable_files), intval($_POST['text_fields']) - intval($product->text_fields))) { $this->_errors[] = Tools::displayError('an error occured while creating customization fields'); } if (!sizeof($this->_errors) and !$product->updateLabels()) { $this->_errors[] = Tools::displayError('an error occured while updating customization'); } $product->uploadable_files = intval($_POST['uploadable_files']); $product->text_fields = intval($_POST['text_fields']); $product->customizable = (intval($_POST['uploadable_files']) > 0 or intval($_POST['text_fields']) > 0) ? 1 : 0; if (!sizeof($this->_errors) and !$product->update()) { $this->_errors[] = Tools::displayError('an error occured while updating customization configuration'); } if (!sizeof($this->_errors)) { Tools::redirectAdmin($currentIndex . '&id_product=' . $product->id . '&id_category=' . intval(Tools::getValue('id_category')) . '&add' . $this->table . '&tabs=4&token=' . ($token ? $token : $this->token)); } } else { $this->_errors[] = Tools::displayError('product must be created before adding customization possibilities'); } } else { $this->_errors[] = Tools::displayError('You do not have permission to edit anything here.'); } } elseif (Tools::isSubmit('submitProductCustomization')) { if ($this->tabAccess['edit'] === '1') { if (Validate::isLoadedObject($product = new Product(intval(Tools::getValue('id_product'))))) { foreach ($_POST as $field => $value) { if (strncmp($field, 'label_', 6) == 0 and !Validate::isLabel($value)) { $this->_errors[] = Tools::displayError('label fields are invalid'); } } if (!sizeof($this->_errors) and !$product->updateLabels()) { $this->_errors[] = Tools::displayError('an error occured while updating customization'); } if (!sizeof($this->_errors)) { Tools::redirectAdmin($currentIndex . '&id_product=' . $product->id . '&id_category=' . intval(Tools::getValue('id_category')) . '&add' . $this->table . '&tabs=4&token=' . ($token ? $token : $this->token)); } } else { $this->_errors[] = Tools::displayError('product must be created before adding customization possibilities'); } } else { $this->_errors[] = Tools::displayError('You do not have permission to edit anything here.'); } } elseif (isset($_GET['delete' . $this->table])) { if ($this->tabAccess['delete'] === '1') { if (Validate::isLoadedObject($product = new Product(intval(Tools::getValue('id_product'))))) { if (!$this->deleteImage($product->id)) { $this->_errors[] = Tools::displayError('an error occurred during product image deletion'); } if ($product->delete()) { Tools::redirectAdmin($currentIndex . '&id_category=' . intval(Tools::getValue('id_category')) . '&conf=1&token=' . ($token ? $token : $this->token)); } $this->_errors[] = Tools::displayError('an error occurred during product deletion'); } } else { $this->_errors[] = Tools::displayError('You do not have permission to delete here.'); } } else { parent::postProcess(true); } }
} // read inventory data and show error if inventory doesn't exists $gInventoryFields = new InventoryFields($gDb, $gCurrentOrganization->getValue('org_id')); $inventory = new Inventory($gDb, $gInventoryFields, $getItemId); if ($inventory->getValue('inv_id') == 0) { $gMessage->show($gL10n->get('SYS_INVALID_PAGE_VIEW')); } //Foto aus adm_my_files if ($gPreferences['profile_photo_storage'] == 1 && $getNewPhoto == 0) { if (file_exists(SERVER_PATH . '/adm_my_files/item_photos/' . $getItemId . '.jpg')) { $picpath = SERVER_PATH . '/adm_my_files/item_photos/' . $getItemId . '.jpg'; } $image = new Image($picpath); } elseif ($gPreferences['profile_photo_storage'] == 0 && $getNewPhoto == 0) { if (strlen($inventory->getValue('inv_photo')) != NULL) { $image = new Image(); $image->setImageFromData($inventory->getValue('inv_photo')); } else { $image = new Image($picpath); } } elseif ($gPreferences['profile_photo_storage'] == 1 && $getNewPhoto == 1) { $picpath = SERVER_PATH . '/adm_my_files/item_photos/' . $getItemId . '_new.jpg'; $image = new Image($picpath); } elseif ($gPreferences['profile_photo_storage'] == 0 && $getNewPhoto == 1) { $image = new Image(); $image->setImageFromData($gCurrentSession->getValue('ses_binary')); } header('Content-Type: ' . $image->getMimeType()); $image->copyToBrowser(); $image->delete();
/** * Stores any image files from a post request * * The files may be uploaded or chosen in the file browser. * Each file is moved to the given target path with a uniquid() * prepended to the file name; the original name is stored temporarily * only in the session. * If possible, the corresponding Image object is updated. If not, * a new one is created and stored. * The original file name, type, Image ID and ordinal value are stored * in the session under $_SESSION['image'][<field_name>]. * @param string $target_folder_path The target folder path for * uploaded images only * @return integer The Image ID if all images have been * processed successfully, * false if errors occurred, * or the empty string if nothing changed */ static function processPostFiles($target_folder_path) { //DBG::log("Image::processPostFiles($target_folder_path): Entered<br />"); // Cases: // If present, pick the path, ID, ord and type from the session, // overwrite with those from the post. // - Post with a file upload (remember that this requires a multipart // encoded form): // Fields: id, ord, type, file // - For those with valid file upload parameters (no error): // insert or update the file and image. // - For those with invalid parameters (error): // - If there's no ID, ignore it // - If ID and ord are valid, but the src has been posted empty, // delete the file and image. // - Post with image selection from the file browser: // Fields: id, ord, type src // - If the src is present, try to get id and ord // - If the src is valid, either update or insert the image // - if the src is empty, but id and ord are valid, // delete the image and file // Collect all posted images from file upload and post $arrName = array(); if (is_array($_FILES)) { $arrName = array_keys($_FILES); } $name = ''; if (is_array($_POST)) { $match = array(); foreach (array_keys($_POST) as $name) { if (!preg_match('/^(\\w+)_src$/', $name, $match)) { continue; } if (!in_array($match[1], $arrName)) { $arrName[] = $match[1]; } } } //DBG::log("Image::processPostFiles($target_folder_path): Made name array ".var_export($arrName, true)); // Remember paths, so for deleted Images, the file can be removed $arrPath = array(); $arrPathDeleted = array(); $image_id = $name && !empty($_SESSION['image'][$name]['id']) ? $_SESSION['image'][$name]['id'] : false; // The image ID //DBG::log("Image::processPostFiles(): Image ID $image_id"); $objImage = false; $result = ''; // No change //DBG::log("Image::processPostFiles(): Collected image field names: ".var_export($arrName, true)."FILES: ".var_export($_FILES, true)."POST: ".var_export($_POST, true)); // Process all images found foreach ($arrName as $name) { // The code analyzer insists that "$changed is never used". // I know better -- ignore it. $changed = false; //DBG::log("Image::processPostFiles(): Processing image field name: $name<br />"); $image_name = false; // The image original name $image_src = false; // The image path $image_ord = false; // The image ordinal value $image_type = false; // The image type key // Try to get the image object coordinates from the session, // in the ['image'][$name] branch, ... if (isset($_SESSION['image'][$name]['src'])) { $image_src = $_SESSION['image'][$name]['src']; } // if (!empty($_SESSION['image'][$name]['id'])) // $image_id = $_SESSION['image'][$name]['id']; if (isset($_SESSION['image'][$name]['ord'])) { $image_ord = $_SESSION['image'][$name]['ord']; } if (isset($_SESSION['image'][$name]['type'])) { $image_type = $_SESSION['image'][$name]['type']; } // ...or get them from the post. // There may be fields with the name plus suffix // These override the session parameters. if (isset($_FILES[$name])) { $image_name = $_FILES[$name]['name']; } if (isset($_POST[$name . '_src'])) { $image_src = $_POST[$name . '_src']; } if (!empty($_POST[$name . '_id'])) { $image_id = $_POST[$name . '_id']; } if (isset($_POST[$name . '_ord'])) { $image_ord = $_POST[$name . '_ord']; } if (isset($_POST[$name . '_type'])) { $image_type = $_POST[$name . '_type']; } //DBG::log("Image::processPostFiles(): Got parameters for $name: image_name $image_name, image_src $image_src, image_id $image_id, image_ord $image_ord, image_type $image_type<br />"); // Upload valid images and update the parameters $objImage = self::getById($image_id, $image_ord); if (!$objImage) { //DBG::log("Image::processPostFiles(): Created new Image (ID $image_id, ord $image_ord)<br />"); $objImage = new Image($image_ord, $image_id); } // else { //DBG::log("Image::processPostFiles(): Loaded Image ID $image_id: ".var_export($objImage, true)."<br />") ; // } // The image original name is only set when uploading images if ($image_name) { //DBG::log("Image::processPostFiles(): Image to be uploaded, deleting old Image<br />"); // $objImage->delete(); // $objImage->setPath(''); // Uploads must go to the target folder $image_src = $target_folder_path . '/' . $image_name; if (!File::upload_file_http($name, $image_src, self::MAXIMUM_UPLOAD_FILE_SIZE, Filetype::MIMETYPE_IMAGES_WEB)) { // For failed uploads, do not change anything //DBG::log("Image::processPostFiles(): Uploading failed<br />"); $result = false; // Keep the current Image on failure continue; } // Remember the path of the previous Image, if any. if ($objImage->path) { $arrPathDeleted[] = $objImage->path; } //DBG::log("Image::processPostFiles(): Uploading completed successfully<br />"); } // Delete the image if the src has been posted, but is empty // if ($objImage->getPath() && $image_src === '') { // Delete the image if the src is empty //DBG::log("Image::processPostFiles(): Path is $objImage->path<br />"); if (empty($image_src)) { //DBG::log("Image::processPostFiles(): Deleting $objImage->path<br />"); unset($_SESSION['image'][$name]); // Remember the path of the deleted Image, if any. if ($objImage->path) { $arrPathDeleted[] = $objImage->path; } // TODO: Records should not have to be deleted if the path is empty $objImage->delete(); continue; } // Remember the path of the new or existing Image $arrPath[] = $image_src; //DBG::log("Image::processPostFiles(): Valid image ".$objImage->path." (posted: $image_src)"); // The Image is valid if ($image_src != $objImage->path) { //DBG::log("Image::processPostFiles(): Path has been changed from ".$objImage->path." to $image_src"); $objImage->setPath($image_src); if (File::exists($image_src)) { //DBG::log("Image::processPostFiles(): File $image_src exists, austosizing...<br />"); $objImage->autoSize(); } $changed = true; } if ($image_type !== false && $image_type != $objImage->imagetype_key) { //DBG::log("Image::processPostFiles(): Imagetype has been changed from ".$objImage->imagetype_key." to $image_type<br />"); $objImage->setImagetypeKey($image_type); $changed = true; } // TODO: File type // $objImage->setFiletypeKey(''); if ($changed && $objImage->path) { //DBG::log("Image::processPostFiles(): Image has been changed, storing...<br />"); if ($objImage->store()) { //DBG::log("Image::processPostFiles(): Image has been stored successfully<br />"); $image_id = $objImage->id; // The original name is never stored with the image, just kept // for reference as long as the session is alive if ($image_name) { $_SESSION['image'][$name]['name'] = $image_name; } $_SESSION['image'][$name]['src'] = $objImage->path; $_SESSION['image'][$name]['id'] = $image_id; $_SESSION['image'][$name]['ord'] = $objImage->ord; $_SESSION['image'][$name]['type'] = $objImage->imagetype_key; //DBG::log("Image::processPostFiles(): Successfully stored image $name, ID ".$objImage->id); if ($result === '') { $result = true; } //DBG::log("Image::processPostFiles(): Temp result ".var_export($result, true)); // Resize and create a thumbnail with the Imagetype settings $objImage->resize(); //DBG::log("Image::processPostFiles(): After resize: ".var_export($objImage, true)."<br />"); } else { //DBG::log("Image::processPostFiles(): Failed storing $image_src<br />"); $result = false; } } //DBG::log("Image::processPostFiles(): Finished: ".var_export($objImage, true)."<br />"); } // Finally, try to delete obsolete image files whose records have // been deleted. // Mind that the same file could be referenced in more than one record, // thus we need to remove those from the paths to be deleted that are. $arrPathToDelete = array_diff($arrPathDeleted, $arrPath); //DBG::log("Image::processPostFiles(): Paths present: ".var_export($arrPath, true)); //DBG::log("Image::processPostFiles(): Paths deleted: ".var_export($arrPathDeleted, true)); //DBG::log("Image::processPostFiles(): Paths difference: ".var_export($arrPathToDelete, true)); foreach ($arrPathToDelete as $path) { //DBG::log("Image::processPostFiles(): Deleting file $path"); // Ignore errors File::delete_file($path); File::delete_file(self::getThumbnailPath($path)); } //DBG::log("Image::processPostFiles(): Result ".var_export($result, true).", image ID $image_id<br />"); $result = $result === true ? $image_id : $result; //DBG::log("Image::processPostFiles(): Result ".var_export($result, true).", image ID $image_id<br />"); //DBG::log("Image::processPostFiles(): Session: ".var_export($_SESSION['image'], true)."<br />"); return $result; }
/** * postProcess handle every checks before saving products information * * @param mixed $token * @return void */ public function postProcess($token = null) { global $cookie, $currentIndex; // Add a new product if (Tools::isSubmit('submitAddproduct') || Tools::isSubmit('submitAddproductAndStay') || Tools::isSubmit('submitAddProductAndPreview')) { if (Tools::getValue('id_product') && $this->tabAccess['edit'] === '1' || $this->tabAccess['add'] === '1' && !Tools::isSubmit('id_product')) { $this->submitAddproduct($token); } else { $this->_errors[] = Tools::displayError('You do not have permission to add here.'); } } /* Delete a product in the download folder */ if (Tools::getValue('deleteVirtualProduct')) { if ($this->tabAccess['delete'] === '1') { $this->deleteVirtualProduct(); } else { $this->_errors[] = Tools::displayError('You do not have permission to delete here.'); } } elseif (Tools::isSubmit('submitAddAttachments')) { if ($this->tabAccess['add'] === '1') { $languages = Language::getLanguages(false); $is_attachment_name_valid = false; foreach ($languages as $language) { $attachment_name_lang = Tools::getValue('attachment_name_' . (int) $language['id_lang']); if (strlen($attachment_name_lang) > 0) { $is_attachment_name_valid = true; } if (!Validate::isGenericName(Tools::getValue('attachment_name_' . (int) $language['id_lang']))) { $this->_errors[] = Tools::displayError('Invalid Name'); } elseif (Tools::strlen(Tools::getValue('attachment_name_' . (int) $language['id_lang'])) > 32) { $this->_errors[] = Tools::displayError('Name is too long'); } if (!Validate::isCleanHtml(Tools::getValue('attachment_description_' . (int) $language['id_lang']))) { $this->_errors[] = Tools::displayError('Invalid description'); } } if (!$is_attachment_name_valid) { $this->_errors[] = Tools::displayError('Attachment Name Required'); } if (empty($this->_errors)) { if (isset($_FILES['attachment_file']) && is_uploaded_file($_FILES['attachment_file']['tmp_name'])) { if ($_FILES['attachment_file']['size'] > Configuration::get('PS_ATTACHMENT_MAXIMUM_SIZE') * 1024 * 1024) { $this->_errors[] = $this->l('File too large, maximum size allowed:') . ' ' . Configuration::get('PS_ATTACHMENT_MAXIMUM_SIZE') * 1024 . ' ' . $this->l('kb') . '. ' . $this->l('File size you\'re trying to upload is:') . number_format($_FILES['attachment_file']['size'] / 1024, 2, '.', '') . $this->l('kb'); } else { do { $uniqid = sha1(microtime()); } while (file_exists(_PS_DOWNLOAD_DIR_ . $uniqid)); if (!copy($_FILES['attachment_file']['tmp_name'], _PS_DOWNLOAD_DIR_ . $uniqid)) { $this->_errors[] = $this->l('File copy failed'); } @unlink($_FILES['attachment_file']['tmp_name']); } } elseif ((int) $_FILES['attachment_file']['error'] === 1) { $max_upload = (int) ini_get('upload_max_filesize'); $max_post = (int) ini_get('post_max_size'); $upload_mb = min($max_upload, $max_post); $this->_errors[] = $this->l('the File') . ' <b>' . $_FILES['attachment_file']['name'] . '</b> ' . $this->l('exceeds the size allowed by the server, this limit is set to') . ' <b>' . $upload_mb . $this->l('Mb') . '</b>'; } if (empty($this->_errors) && isset($uniqid)) { $attachment = new Attachment(); foreach ($languages as $language) { if (isset($_POST['attachment_name_' . (int) $language['id_lang']])) { $attachment->name[(int) $language['id_lang']] = pSQL($_POST['attachment_name_' . (int) $language['id_lang']]); } if (isset($_POST['attachment_description_' . (int) $language['id_lang']])) { $attachment->description[(int) $language['id_lang']] = pSQL($_POST['attachment_description_' . (int) $language['id_lang']]); } } $attachment->file = $uniqid; $attachment->mime = $_FILES['attachment_file']['type']; $attachment->file_name = pSQL($_FILES['attachment_file']['name']); if (empty($attachment->mime) or Tools::strlen($attachment->mime) > 128) { $this->_errors[] = Tools::displayError('Invalid file extension'); } if (!Validate::isGenericName($attachment->file_name)) { $this->_errors[] = Tools::displayError('Invalid file name'); } if (Tools::strlen($attachment->file_name) > 128) { $this->_errors[] = Tools::displayError('File name too long'); } if (!sizeof($this->_errors)) { $attachment->add(); Tools::redirectAdmin($currentIndex . '&id_product=' . (int) Tools::getValue($this->identifier) . '&id_category=' . (int) Tools::getValue('id_category') . '&addproduct&conf=4&tabs=6&token=' . ($token ? $token : $this->token)); } else { $this->_errors[] = Tools::displayError('Invalid file'); } } } } else { $this->_errors[] = Tools::displayError('You do not have permission to add here.'); } } elseif (Tools::isSubmit('submitAttachments')) { if ($this->tabAccess['edit'] === '1') { if ($id = (int) Tools::getValue($this->identifier)) { if (Attachment::attachToProduct($id, $_POST['attachments'])) { Tools::redirectAdmin($currentIndex . '&id_product=' . (int) $id . (isset($_POST['id_category']) ? '&id_category=' . (int) $_POST['id_category'] : '') . '&conf=4&add' . $this->table . '&tabs=6&token=' . ($token ? $token : $this->token)); } } } } elseif (isset($_GET['duplicate' . $this->table])) { if ($this->tabAccess['add'] === '1') { if (Validate::isLoadedObject($product = new Product((int) Tools::getValue('id_product')))) { $id_product_old = $product->id; unset($product->id); unset($product->id_product); $product->indexed = 0; $product->active = 0; if ($product->add() and Category::duplicateProductCategories($id_product_old, $product->id) and ($combinationImages = Product::duplicateAttributes($id_product_old, $product->id)) !== false and GroupReduction::duplicateReduction($id_product_old, $product->id) and Product::duplicateAccessories($id_product_old, $product->id) and Product::duplicateFeatures($id_product_old, $product->id) and Product::duplicateSpecificPrices($id_product_old, $product->id) and Pack::duplicate($id_product_old, $product->id) and Product::duplicateCustomizationFields($id_product_old, $product->id) and Product::duplicateTags($id_product_old, $product->id) and Product::duplicateDownload($id_product_old, $product->id)) { if ($product->hasAttributes()) { Product::updateDefaultAttribute($product->id); } if (!Tools::getValue('noimage') and !Image::duplicateProductImages($id_product_old, $product->id, $combinationImages)) { $this->_errors[] = Tools::displayError('An error occurred while copying images.'); } else { Hook::addProduct($product); Search::indexation(false, $product->id); Tools::redirectAdmin($currentIndex . '&id_category=' . (!empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1') . '&conf=19&token=' . ($token ? $token : $this->token)); } } else { $this->_errors[] = Tools::displayError('An error occurred while creating object.'); } } } else { $this->_errors[] = Tools::displayError('You do not have permission to add here.'); } } elseif (isset($_GET['status']) and Tools::getValue($this->identifier)) { if ($this->tabAccess['edit'] === '1') { if (Validate::isLoadedObject($object = $this->loadObject())) { if ($object->toggleStatus()) { Tools::redirectAdmin($currentIndex . '&conf=5' . (($id_category = !empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1' and Tools::getValue('id_product')) ? '&id_category=' . $id_category : '') . '&token=' . $token); } else { $this->_errors[] = Tools::displayError('An error occurred while updating status.'); } } else { $this->_errors[] = Tools::displayError('An error occurred while updating status for object.') . ' <b>' . $this->table . '</b> ' . Tools::displayError('(cannot load object)'); } } else { $this->_errors[] = Tools::displayError('You do not have permission to edit here.'); } } elseif (isset($_GET['delete' . $this->table])) { if ($this->tabAccess['delete'] === '1') { if (Validate::isLoadedObject($object = $this->loadObject()) and isset($this->fieldImageSettings)) { // check if request at least one object with noZeroObject if (isset($object->noZeroObject) and sizeof($taxes = call_user_func(array($this->className, $object->noZeroObject))) <= 1) { $this->_errors[] = Tools::displayError('You need at least one object.') . ' <b>' . $this->table . '</b><br />' . Tools::displayError('You cannot delete all of the items.'); } else { $id_category = Tools::getValue('id_category'); $category_url = empty($id_category) ? '' : '&id_category=' . $id_category; if ($this->deleted) { $object->deleteImages(); $object->deleted = 1; if ($object->update()) { Tools::redirectAdmin($currentIndex . '&conf=1&token=' . ($token ? $token : $this->token) . $category_url); } } elseif ($object->delete()) { Tools::redirectAdmin($currentIndex . '&conf=1&token=' . ($token ? $token : $this->token) . $category_url); } $this->_errors[] = Tools::displayError('An error occurred during deletion.'); } } else { $this->_errors[] = Tools::displayError('An error occurred while deleting object.') . ' <b>' . $this->table . '</b> ' . Tools::displayError('(cannot load object)'); } } else { $this->_errors[] = Tools::displayError('You do not have permission to delete here.'); } } elseif (Tools::getValue('submitDel' . $this->table)) { if ($this->tabAccess['delete'] === '1') { if (isset($_POST[$this->table . 'Box'])) { $object = new $this->className(); if (isset($object->noZeroObject) and (sizeof(call_user_func(array($this->className, $object->noZeroObject))) <= 1 or sizeof($_POST[$this->table . 'Box']) == sizeof(call_user_func(array($this->className, $object->noZeroObject))))) { $this->_errors[] = Tools::displayError('You need at least one object.') . ' <b>' . $this->table . '</b><br />' . Tools::displayError('You cannot delete all of the items.'); } else { $result = true; if ($this->deleted) { foreach (Tools::getValue($this->table . 'Box') as $id) { $toDelete = new $this->className($id); $toDelete->deleted = 1; $result = $result and $toDelete->update(); } } else { $result = $object->deleteSelection(Tools::getValue($this->table . 'Box')); } if ($result) { $id_category = Tools::getValue('id_category'); $category_url = empty($id_category) ? '' : '&id_category=' . $id_category; Tools::redirectAdmin($currentIndex . '&conf=2&token=' . $token . $category_url); } $this->_errors[] = Tools::displayError('An error occurred while deleting selection.'); } } else { $this->_errors[] = Tools::displayError('You must select at least one element to delete.'); } } else { $this->_errors[] = Tools::displayError('You do not have permission to delete here.'); } } elseif ($id_image = (int) Tools::getValue('id_image') and Validate::isUnsignedId($id_image) and Validate::isLoadedObject($image = new Image($id_image))) { /* PrestaShop demo mode */ if (_PS_MODE_DEMO_) { $this->_errors[] = Tools::displayError('This functionnality has been disabled.'); return; } /* PrestaShop demo mode*/ if ($this->tabAccess['edit'] === '1') { /* Delete product image */ if (isset($_GET['deleteImage'])) { $image->delete(); if (!Image::getCover($image->id_product)) { $first_img = Db::getInstance()->getRow(' SELECT `id_image` FROM `' . _DB_PREFIX_ . 'image` WHERE `id_product` = ' . (int) $image->id_product); Db::getInstance()->Execute(' UPDATE `' . _DB_PREFIX_ . 'image` SET `cover` = 1 WHERE `id_image` = ' . (int) $first_img['id_image']); } @unlink(_PS_TMP_IMG_DIR_ . '/product_' . $image->id_product . '.jpg'); @unlink(_PS_TMP_IMG_DIR_ . '/product_mini_' . $image->id_product . '.jpg'); Tools::redirectAdmin($currentIndex . '&id_product=' . $image->id_product . '&id_category=' . (!empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1') . '&add' . $this->table . '&tabs=1' . '&token=' . ($token ? $token : $this->token)); } elseif (isset($_GET['editImage'])) { if ($image->cover) { $_POST['cover'] = 1; } $languages = Language::getLanguages(false); foreach ($languages as $language) { if (isset($image->legend[$language['id_lang']])) { $_POST['legend_' . $language['id_lang']] = $image->legend[$language['id_lang']]; } } $_POST['id_image'] = $image->id; $this->displayForm(); } elseif (isset($_GET['coverImage'])) { Image::deleteCover($image->id_product); $image->cover = 1; if (!$image->update()) { $this->_errors[] = Tools::displayError('Cannot change the product cover'); } else { $productId = (int) Tools::getValue('id_product'); @unlink(_PS_TMP_IMG_DIR_ . '/product_' . $productId . '.jpg'); @unlink(_PS_TMP_IMG_DIR_ . '/product_mini_' . $productId . '.jpg'); Tools::redirectAdmin($currentIndex . '&id_product=' . $image->id_product . '&id_category=' . (!empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1') . '&addproduct&tabs=1' . '&token=' . ($token ? $token : $this->token)); } } elseif (isset($_GET['imgPosition']) and isset($_GET['imgDirection'])) { $image->positionImage((int) Tools::getValue('imgPosition'), (int) Tools::getValue('imgDirection')); Tools::redirectAdmin($currentIndex . '&id_product=' . $image->id_product . '&id_category=' . (!empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1') . '&add' . $this->table . '&tabs=1&token=' . ($token ? $token : $this->token)); } } else { $this->_errors[] = Tools::displayError('You do not have permission to edit here.'); } } elseif (Tools::isSubmit('submitProductAttribute')) { if (Validate::isLoadedObject($product = new Product((int) Tools::getValue('id_product')))) { if (!isset($_POST['attribute_price']) or $_POST['attribute_price'] == NULL) { $this->_errors[] = Tools::displayError('Attribute price required.'); } if (!isset($_POST['attribute_combinaison_list']) or !sizeof($_POST['attribute_combinaison_list'])) { $this->_errors[] = Tools::displayError('You must add at least one attribute.'); } if (!sizeof($this->_errors)) { if (!isset($_POST['attribute_wholesale_price'])) { $_POST['attribute_wholesale_price'] = 0; } if (!isset($_POST['attribute_price_impact'])) { $_POST['attribute_price_impact'] = 0; } if (!isset($_POST['attribute_weight_impact'])) { $_POST['attribute_weight_impact'] = 0; } if (!isset($_POST['attribute_ecotax'])) { $_POST['attribute_ecotax'] = 0; } if (Tools::getValue('attribute_default')) { $product->deleteDefaultAttributes(); } // Change existing one if ($id_product_attribute = (int) Tools::getValue('id_product_attribute')) { if ($this->tabAccess['edit'] === '1') { if ($product->productAttributeExists($_POST['attribute_combinaison_list'], $id_product_attribute)) { $this->_errors[] = Tools::displayError('This attribute already exists.'); } else { $product->updateProductAttribute($id_product_attribute, Tools::getValue('attribute_wholesale_price'), Tools::getValue('attribute_price') * Tools::getValue('attribute_price_impact'), Tools::getValue('attribute_weight') * Tools::getValue('attribute_weight_impact'), Tools::getValue('attribute_unity') * Tools::getValue('attribute_unit_impact'), Tools::getValue('attribute_ecotax'), false, Tools::getValue('id_image_attr'), Tools::getValue('attribute_reference'), Tools::getValue('attribute_supplier_reference'), Tools::getValue('attribute_ean13'), Tools::getValue('attribute_default'), Tools::getValue('attribute_location'), Tools::getValue('attribute_upc'), Tools::getValue('attribute_minimal_quantity')); if ($id_reason = (int) Tools::getValue('id_mvt_reason') and (int) Tools::getValue('attribute_mvt_quantity') > 0 and $id_reason > 0) { $reason = new StockMvtReason((int) $id_reason); $qty = Tools::getValue('attribute_mvt_quantity') * $reason->sign; if (!$product->addStockMvt($qty, $id_reason, (int) $id_product_attribute, NULL, $cookie->id_employee)) { $this->_errors[] = Tools::displayError('An error occurred while updating qty.'); } } Hook::updateProductAttribute((int) $id_product_attribute); } } else { $this->_errors[] = Tools::displayError('You do not have permission to add here.'); } } else { if ($this->tabAccess['add'] === '1') { if ($product->productAttributeExists($_POST['attribute_combinaison_list'])) { $this->_errors[] = Tools::displayError('This combination already exists.'); } else { $id_product_attribute = $product->addCombinationEntity(Tools::getValue('attribute_wholesale_price'), Tools::getValue('attribute_price') * Tools::getValue('attribute_price_impact'), Tools::getValue('attribute_weight') * Tools::getValue('attribute_weight_impact'), Tools::getValue('attribute_unity') * Tools::getValue('attribute_unit_impact'), Tools::getValue('attribute_ecotax'), Tools::getValue('attribute_quantity'), Tools::getValue('id_image_attr'), Tools::getValue('attribute_reference'), Tools::getValue('attribute_supplier_reference'), Tools::getValue('attribute_ean13'), Tools::getValue('attribute_default'), Tools::getValue('attribute_location'), Tools::getValue('attribute_upc'), Tools::getValue('attribute_minimal_quantity')); } } else { $this->_errors[] = Tools::displayError('You do not have permission to') . '<hr>' . Tools::displayError('Edit here.'); } } if (!sizeof($this->_errors)) { $product->addAttributeCombinaison($id_product_attribute, Tools::getValue('attribute_combinaison_list')); $product->checkDefaultAttributes(); } if (!sizeof($this->_errors)) { if (!$product->cache_default_attribute) { Product::updateDefaultAttribute($product->id); } Tools::redirectAdmin($currentIndex . '&id_product=' . $product->id . '&id_category=' . (!empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1') . '&add' . $this->table . '&tabs=3&token=' . ($token ? $token : $this->token)); } } } } elseif (Tools::isSubmit('deleteProductAttribute')) { if ($this->tabAccess['delete'] === '1') { if ($id_product = (int) Tools::getValue('id_product') and Validate::isUnsignedId($id_product) and Validate::isLoadedObject($product = new Product($id_product))) { $product->deleteAttributeCombinaison((int) Tools::getValue('id_product_attribute')); $product->checkDefaultAttributes(); $product->updateQuantityProductWithAttributeQuantity(); if (!$product->hasAttributes()) { $product->cache_default_attribute = 0; $product->update(); } else { Product::updateDefaultAttribute($id_product); } Tools::redirectAdmin($currentIndex . '&add' . $this->table . '&id_category=' . (!empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1') . '&tabs=3&id_product=' . $product->id . '&token=' . ($token ? $token : $this->token)); } else { $this->_errors[] = Tools::displayError('Cannot delete attribute'); } } else { $this->_errors[] = Tools::displayError('You do not have permission to delete here.'); } } elseif (Tools::isSubmit('deleteAllProductAttributes')) { if ($this->tabAccess['delete'] === '1') { if ($id_product = (int) Tools::getValue('id_product') and Validate::isUnsignedId($id_product) and Validate::isLoadedObject($product = new Product($id_product))) { $product->deleteProductAttributes(); $product->updateQuantityProductWithAttributeQuantity(); if ($product->cache_default_attribute) { $product->cache_default_attribute = 0; $product->update(); } Tools::redirectAdmin($currentIndex . '&add' . $this->table . '&id_category=' . (!empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1') . '&tabs=3&id_product=' . $product->id . '&token=' . ($token ? $token : $this->token)); } else { $this->_errors[] = Tools::displayError('Cannot delete attributes'); } } else { $this->_errors[] = Tools::displayError('You do not have permission to delete here.'); } } elseif (Tools::isSubmit('defaultProductAttribute')) { if (Validate::isLoadedObject($product = new Product((int) Tools::getValue('id_product')))) { $product->deleteDefaultAttributes(); $product->setDefaultAttribute((int) Tools::getValue('id_product_attribute')); Tools::redirectAdmin($currentIndex . '&add' . $this->table . '&id_category=' . (!empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1') . '&tabs=3&id_product=' . $product->id . '&token=' . ($token ? $token : $this->token)); } else { $this->_errors[] = Tools::displayError('Cannot make default attribute'); } } elseif (Tools::isSubmit('submitProductFeature')) { if ($this->tabAccess['edit'] === '1') { if (Validate::isLoadedObject($product = new Product((int) Tools::getValue('id_product')))) { // delete all objects $product->deleteFeatures(); // add new objects $languages = Language::getLanguages(false); foreach ($_POST as $key => $val) { if (preg_match('/^feature_([0-9]+)_value/i', $key, $match)) { if ($val) { $product->addFeaturesToDB($match[1], $val); } else { if ($default_value = $this->checkFeatures($languages, $match[1])) { $id_value = $product->addFeaturesToDB($match[1], 0, 1, (int) $language['id_lang']); foreach ($languages as $language) { if ($cust = Tools::getValue('custom_' . $match[1] . '_' . (int) $language['id_lang'])) { $product->addFeaturesCustomToDB($id_value, (int) $language['id_lang'], $cust); } else { $product->addFeaturesCustomToDB($id_value, (int) $language['id_lang'], $default_value); } } } } } } if (!sizeof($this->_errors)) { Tools::redirectAdmin($currentIndex . '&id_product=' . (int) $product->id . '&id_category=' . (!empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1') . '&add' . $this->table . '&tabs=4&conf=4&token=' . ($token ? $token : $this->token)); } } else { $this->_errors[] = Tools::displayError('Product must be created before adding features.'); } } $this->_errors[] = Tools::displayError('You do not have permission to edit here.'); } elseif (Tools::isSubmit('submitPricesModification')) { $_POST['tabs'] = 5; if ($this->tabAccess['edit'] === '1') { $id_specific_prices = Tools::getValue('spm_id_specific_price'); $id_shops = Tools::getValue('spm_id_shop'); $id_currencies = Tools::getValue('spm_id_currency'); $id_countries = Tools::getValue('spm_id_country'); $id_groups = Tools::getValue('spm_id_group'); $prices = Tools::getValue('spm_price'); $from_quantities = Tools::getValue('spm_from_quantity'); $reductions = Tools::getValue('spm_reduction'); $reduction_types = Tools::getValue('spm_reduction_type'); $froms = Tools::getValue('spm_from'); $tos = Tools::getValue('spm_to'); foreach ($id_specific_prices as $key => $id_specific_price) { if ($this->_validateSpecificPrice($id_shops[$key], $id_currencies[$key], $id_countries[$key], $id_groups[$key], $prices[$key], $from_quantities[$key], $reductions[$key], $reduction_types[$key], $froms[$key], $tos[$key])) { $specificPrice = new SpecificPrice((int) $id_specific_price); $specificPrice->id_shop = (int) $id_shops[$key]; $specificPrice->id_currency = (int) $id_currencies[$key]; $specificPrice->id_country = (int) $id_countries[$key]; $specificPrice->id_group = (int) $id_groups[$key]; $specificPrice->price = (double) $prices[$key]; $specificPrice->from_quantity = (int) $from_quantities[$key]; $specificPrice->reduction = (double) ($reduction_types[$key] == 'percentage' ? $reductions[$key] / 100 : $reductions[$key]); $specificPrice->reduction_type = !$reductions[$key] ? 'amount' : $reduction_types[$key]; $specificPrice->from = !$froms[$key] ? '0000-00-00 00:00:00' : $froms[$key]; $specificPrice->to = !$tos[$key] ? '0000-00-00 00:00:00' : $tos[$key]; if (!$specificPrice->update()) { $this->_errors = Tools::displayError('An error occurred while updating the specific price.'); } } } if (!sizeof($this->_errors)) { Tools::redirectAdmin($currentIndex . '&id_product=' . (int) Tools::getValue('id_product') . '&id_category=' . (!empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1') . '&update' . $this->table . '&tabs=2&token=' . ($token ? $token : $this->token)); } } else { $this->_errors[] = Tools::displayError('You do not have permission to add here.'); } } elseif (Tools::isSubmit('submitPriceAddition')) { if ($this->tabAccess['add'] === '1') { $id_product = (int) Tools::getValue('id_product'); $id_shop = Tools::getValue('sp_id_shop'); $id_currency = Tools::getValue('sp_id_currency'); $id_country = Tools::getValue('sp_id_country'); $id_group = Tools::getValue('sp_id_group'); $price = Tools::getValue('sp_price'); $from_quantity = Tools::getValue('sp_from_quantity'); $reduction = (double) Tools::getValue('sp_reduction'); $reduction_type = !$reduction ? 'amount' : Tools::getValue('sp_reduction_type'); $from = Tools::getValue('sp_from'); $to = Tools::getValue('sp_to'); if ($this->_validateSpecificPrice($id_shop, $id_currency, $id_country, $id_group, $price, $from_quantity, $reduction, $reduction_type, $from, $to)) { $specificPrice = new SpecificPrice(); $specificPrice->id_product = $id_product; $specificPrice->id_shop = (int) $id_shop; $specificPrice->id_currency = (int) $id_currency; $specificPrice->id_country = (int) $id_country; $specificPrice->id_group = (int) $id_group; $specificPrice->price = (double) $price; $specificPrice->from_quantity = (int) $from_quantity; $specificPrice->reduction = (double) ($reduction_type == 'percentage' ? $reduction / 100 : $reduction); $specificPrice->reduction_type = $reduction_type; $specificPrice->from = !$from ? '0000-00-00 00:00:00' : $from; $specificPrice->to = !$to ? '0000-00-00 00:00:00' : $to; if (!$specificPrice->add()) { $this->_errors = Tools::displayError('An error occurred while updating the specific price.'); } else { Tools::redirectAdmin($currentIndex . (Tools::getValue('id_category') ? '&id_category=' . Tools::getValue('id_category') : '') . '&id_product=' . $id_product . '&add' . $this->table . '&tabs=2&conf=3&token=' . ($token ? $token : $this->token)); } } } else { $this->_errors[] = Tools::displayError('You do not have permission to add here.'); } } elseif (Tools::isSubmit('deleteSpecificPrice')) { if ($this->tabAccess['delete'] === '1') { if (!($obj = $this->loadObject())) { return; } if (!($id_specific_price = Tools::getValue('id_specific_price')) or !Validate::isUnsignedId($id_specific_price)) { $this->_errors[] = Tools::displayError('Invalid specific price ID'); } else { $specificPrice = new SpecificPrice((int) $id_specific_price); if (!$specificPrice->delete()) { $this->_errors[] = Tools::displayError('An error occurred while deleting the specific price'); } else { Tools::redirectAdmin($currentIndex . (Tools::getValue('id_category') ? '&id_category=' . Tools::getValue('id_category') : '') . '&id_product=' . $obj->id . '&add' . $this->table . '&tabs=2&conf=1&token=' . ($token ? $token : $this->token)); } } } else { $this->_errors[] = Tools::displayError('You do not have permission to delete here.'); } } elseif (Tools::isSubmit('submitSpecificPricePriorities')) { if (!($obj = $this->loadObject())) { return; } if (!($priorities = Tools::getValue('specificPricePriority'))) { $this->_errors[] = Tools::displayError('Please specify priorities'); } elseif (Tools::isSubmit('specificPricePriorityToAll')) { if (!SpecificPrice::setPriorities($priorities)) { $this->_errors[] = Tools::displayError('An error occurred while updating priorities.'); } else { Tools::redirectAdmin($currentIndex . '&id_product=' . $obj->id . '&add' . $this->table . '&tabs=2&conf=4&token=' . ($token ? $token : $this->token)); } } elseif (!SpecificPrice::setSpecificPriority((int) $obj->id, $priorities)) { $this->_errors[] = Tools::displayError('An error occurred while setting priorities.'); } else { Tools::redirectAdmin($currentIndex . (Tools::getValue('id_category') ? '&id_category=' . Tools::getValue('id_category') : '') . '&id_product=' . $obj->id . '&add' . $this->table . '&tabs=2&conf=4&token=' . ($token ? $token : $this->token)); } } elseif (Tools::isSubmit('submitCustomizationConfiguration')) { if ($this->tabAccess['edit'] === '1') { if (Validate::isLoadedObject($product = new Product((int) Tools::getValue('id_product')))) { if (!$product->createLabels((int) $_POST['uploadable_files'] - (int) $product->uploadable_files, (int) $_POST['text_fields'] - (int) $product->text_fields)) { $this->_errors[] = Tools::displayError('An error occurred while creating customization fields.'); } if (!sizeof($this->_errors) and !$product->updateLabels()) { $this->_errors[] = Tools::displayError('An error occurred while updating customization.'); } $product->uploadable_files = (int) $_POST['uploadable_files']; $product->text_fields = (int) $_POST['text_fields']; $product->customizable = ((int) $_POST['uploadable_files'] > 0 or (int) $_POST['text_fields'] > 0) ? 1 : 0; if (!sizeof($this->_errors) and !$product->update()) { $this->_errors[] = Tools::displayError('An error occurred while updating customization configuration.'); } if (!sizeof($this->_errors)) { Tools::redirectAdmin($currentIndex . '&id_product=' . $product->id . '&id_category=' . (!empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1') . '&add' . $this->table . '&tabs=5&token=' . ($token ? $token : $this->token)); } } else { $this->_errors[] = Tools::displayError('Product must be created before adding customization possibilities.'); } } else { $this->_errors[] = Tools::displayError('You do not have permission to edit here.'); } } elseif (Tools::isSubmit('submitProductCustomization')) { if ($this->tabAccess['edit'] === '1') { if (Validate::isLoadedObject($product = new Product((int) Tools::getValue('id_product')))) { foreach ($_POST as $field => $value) { if (strncmp($field, 'label_', 6) == 0 and !Validate::isLabel($value)) { $this->_errors[] = Tools::displayError('Label fields are invalid'); } } if (!sizeof($this->_errors) and !$product->updateLabels()) { $this->_errors[] = Tools::displayError('An error occurred while updating customization.'); } if (!sizeof($this->_errors)) { Tools::redirectAdmin($currentIndex . '&id_product=' . $product->id . '&id_category=' . (!empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1') . '&add' . $this->table . '&tabs=5&token=' . ($token ? $token : $this->token)); } } else { $this->_errors[] = Tools::displayError('Product must be created before adding customization possibilities.'); } } else { $this->_errors[] = Tools::displayError('You do not have permission to edit here.'); } } elseif (isset($_GET['position'])) { if ($this->tabAccess['edit'] !== '1') { $this->_errors[] = Tools::displayError('You do not have permission to edit here.'); } elseif (!Validate::isLoadedObject($object = $this->loadObject())) { $this->_errors[] = Tools::displayError('An error occurred while updating status for object.') . ' <b>' . $this->table . '</b> ' . Tools::displayError('(cannot load object)'); } if (!$object->updatePosition((int) Tools::getValue('way'), (int) Tools::getValue('position'))) { $this->_errors[] = Tools::displayError('Failed to update the position.'); } else { Tools::redirectAdmin($currentIndex . '&' . $this->table . 'Orderby=position&' . $this->table . 'Orderway=asc&conf=5' . (($id_category = !empty($_REQUEST['id_category']) ? $_REQUEST['id_category'] : '1') ? '&id_category=' . $id_category : '') . '&token=' . Tools::getAdminTokenLite('AdminCatalog')); } } else { parent::postProcess(true); } }