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);
        }
    }
예제 #2
0
 public function ajaxProcessaddProductImage()
 {
     self::$currentIndex = 'index.php?tab=AdminProducts';
     $product = new Product((int) Tools::getValue('id_product'));
     $legends = Tools::getValue('legend');
     if (!is_array($legends)) {
         $legends = (array) $legends;
     }
     if (!Validate::isLoadedObject($product)) {
         $files = array();
         $files[0]['error'] = Tools::displayError('Cannot add image because product creation failed.');
     }
     $image_uploader = new HelperImageUploader('file');
     $image_uploader->setAcceptTypes(array('jpeg', 'gif', 'png', 'jpg'))->setMaxSize($this->max_image_size);
     $files = $image_uploader->process();
     foreach ($files as &$file) {
         $image = new Image();
         $image->id_product = (int) $product->id;
         $image->position = Image::getHighestPosition($product->id) + 1;
         foreach ($legends as $key => $legend) {
             if (!empty($legend)) {
                 $image->legend[(int) $key] = $legend;
             }
         }
         if (!Image::getCover($image->id_product)) {
             $image->cover = 1;
         } else {
             $image->cover = 0;
         }
         if (($validate = $image->validateFieldsLang(false, true)) !== true) {
             $file['error'] = Tools::displayError($validate);
         }
         if (isset($file['error']) && (!is_numeric($file['error']) || $file['error'] != 0)) {
             continue;
         }
         if (!$image->add()) {
             $file['error'] = Tools::displayError('Error while creating additional image');
         } else {
             if (!($new_path = $image->getPathForCreation())) {
                 $file['error'] = Tools::displayError('An error occurred during new folder creation');
                 continue;
             }
             $error = 0;
             if (!ImageManager::resize($file['save_path'], $new_path . '.' . $image->image_format, null, null, 'jpg', false, $error)) {
                 switch ($error) {
                     case ImageManager::ERROR_FILE_NOT_EXIST:
                         $file['error'] = Tools::displayError('An error occurred while copying image, the file does not exist anymore.');
                         break;
                     case ImageManager::ERROR_FILE_WIDTH:
                         $file['error'] = Tools::displayError('An error occurred while copying image, the file width is 0px.');
                         break;
                     case ImageManager::ERROR_MEMORY_LIMIT:
                         $file['error'] = Tools::displayError('An error occurred while copying image, check your memory limit.');
                         break;
                     default:
                         $file['error'] = Tools::displayError('An error occurred while copying image.');
                         break;
                 }
                 continue;
             } else {
                 $imagesTypes = ImageType::getImagesTypes('products');
                 foreach ($imagesTypes as $imageType) {
                     if (!ImageManager::resize($file['save_path'], $new_path . '-' . stripslashes($imageType['name']) . '.' . $image->image_format, $imageType['width'], $imageType['height'], $image->image_format)) {
                         $file['error'] = Tools::displayError('An error occurred while copying image:') . ' ' . stripslashes($imageType['name']);
                         continue;
                     }
                 }
             }
             unlink($file['save_path']);
             //Necesary to prevent hacking
             unset($file['save_path']);
             Hook::exec('actionWatermark', array('id_image' => $image->id, 'id_product' => $product->id));
             if (!$image->update()) {
                 $file['error'] = Tools::displayError('Error while updating status');
                 continue;
             }
             // Associate image to shop from context
             $shops = Shop::getContextListShopID();
             $image->associateTo($shops);
             $json_shops = array();
             foreach ($shops as $id_shop) {
                 $json_shops[$id_shop] = true;
             }
             $file['status'] = 'ok';
             $file['id'] = $image->id;
             $file['position'] = $image->position;
             $file['cover'] = $image->cover;
             $file['legend'] = $image->legend;
             $file['path'] = $image->getExistingImgPath();
             $file['shops'] = $json_shops;
             @unlink(_PS_TMP_IMG_DIR_ . 'product_' . (int) $product->id . '.jpg');
             @unlink(_PS_TMP_IMG_DIR_ . 'product_mini_' . (int) $product->id . '_' . $this->context->shop->id . '.jpg');
         }
     }
     die(Tools::jsonEncode(array($image_uploader->getName() => $files)));
 }
예제 #3
0
 public function copyImage($id_product, $id_image, $method = 'auto')
 {
     $image = new Image($id_image);
     if (!($new_path = $image->getPathForCreation())) {
         return array('error' => Tools::displayError('An error occurred during new folder creation'));
     }
     if (!($tmpName = tempnam(_PS_TMP_IMG_DIR_, 'PS')) || !$this->upload($tmpName)) {
         return array('error' => Tools::displayError('An error occurred during the image upload'));
     } elseif (!ImageManager::resize($tmpName, $new_path . '.' . $image->image_format)) {
         return array('error' => Tools::displayError('An error occurred while copying image.'));
     } elseif ($method == 'auto') {
         $imagesTypes = ImageType::getImagesTypes('products');
         foreach ($imagesTypes as $imageType) {
             /*
             	$theme = (Shop::isFeatureActive() ? '-'.$imageType['id_theme'] : '');
             	if (!ImageManager::resize($tmpName, $new_path.'-'.stripslashes($imageType['name']).$theme.'.'.$image->image_format, $imageType['width'], $imageType['height'], $image->image_format))
             		return array('error' => Tools::displayError('An error occurred while copying image:').' '.stripslashes($imageType['name']));
             */
             if (!ImageManager::resize($tmpName, $new_path . '-' . stripslashes($imageType['name']) . '.' . $image->image_format, $imageType['width'], $imageType['height'], $image->image_format)) {
                 return array('error' => Tools::displayError('An error occurred while copying image:') . ' ' . stripslashes($imageType['name']));
             }
         }
     }
     unlink($tmpName);
     Hook::exec('actionWatermark', array('id_image' => $id_image, 'id_product' => $id_product));
     if (!$image->update()) {
         return array('error' => Tools::displayError('Error while updating status'));
     }
     $img = array('id_image' => $image->id, 'position' => $image->position, 'cover' => $image->cover, 'name' => $this->getName(), 'legend' => $image->legend);
     return array('success' => $img);
 }
예제 #4
0
$articleObj = new Article($f_language_selected, $f_article_number);

if (!$g_user->hasPermission('ChangeImage') && !$g_user->hasPermission('AttachImageToArticle')) {
	camp_html_add_msg(getGS("You do not have the right to change image information."));
	camp_html_goto_page(camp_html_article_url($articleObj, $f_language_id, 'edit.php'));
}

$imageObj = new Image($f_image_id);

if (!is_null($f_image_description) && $g_user->hasPermission('ChangeImage')) {
	$attributes = array();
	$attributes['Description'] = $f_image_description;
	$attributes['Photographer'] = $f_image_photographer;
	$attributes['Place'] = $f_image_place;
	$attributes['Date'] = $f_image_date;
	$imageObj->update($attributes);
}

if ($g_user->hasPermission('AttachImageToArticle')) {
	if (is_numeric($f_image_template_id) && ($f_image_template_id > 0)) {
		$articleImageObj = new ArticleImage($f_article_number, $f_image_id);
		$updated = $articleImageObj->setTemplateId($f_image_template_id);
		if ($updated == false) {
			camp_html_add_msg(getGS("Image number '$1' already exists", $f_image_template_id));
			camp_html_goto_page($backLink);
		}
	}
}

camp_html_add_msg(getGS("Image '$1' updated.", $imageObj->getDescription()), "ok");
 public function ajaxProcessUpdateCover()
 {
     Image::deleteCover((int) Tools::getValue('id_product'));
     $img = new Image((int) Tools::getValue('id_image'));
     $img->cover = 1;
     @unlink(_PS_TMP_IMG_DIR_ . 'product_' . (int) $img->id_product . '.jpg');
     @unlink(_PS_TMP_IMG_DIR_ . 'product_mini_' . (int) $img->id_product . '_' . $this->context->shop->id . '.jpg');
     if ($img->update()) {
         $this->jsonConfirmation($this->_conf[26]);
     } else {
         $this->jsonError(Tools::displayError('An error occurred while attempting to move this picture.'));
     }
 }
예제 #6
0
    /**
     * 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);
        }
    }
예제 #7
0
 /**
  * Approve action
  */
 public function approveAction()
 {
     $this->getHelper('contextSwitch')->addActionContext('approve', 'json')->initContext();
     $parameters = $this->getRequest()->getParams();
     if ($parameters['type'] == 'image') {
         $image = new Image($parameters['id']);
         $image->update(array('Status' => 'approved'));
         $user_id = $image->getUploadingUserId();
         $user = $this->_helper->service('user')->find($user_id);
         $this->_helper->service->getService('dispatcher')->notify('image.approved', new GenericEvent($this, array('user' => $user)));
     }
     if ($parameters['type'] == 'document') {
         $document = new Attachment($parameters['id']);
         $document->update(array('Status' => 'approved'));
         $user_id = $document->getUploadingUserId();
         $user = $this->_helper->service('user')->find($user_id);
         $this->_helper->service->getService('dispatcher')->notify('document.approved', new GenericEvent($this, array('user' => $user)));
     }
 }
 public function ajaxProcessUpdateCover()
 {
     Image::deleteCover((int) Tools::getValue('id_product'));
     $img = new Image((int) Tools::getValue('id_image'));
     $img->cover = 1;
     @unlink(_PS_TMP_IMG_DIR_ . 'product_' . (int) $img->id_product . '.jpg');
     @unlink(_PS_TMP_IMG_DIR_ . 'product_mini_' . (int) $img->id_product . '.jpg');
     if ($img->update()) {
         $this->jsonConfirmation($this->_conf[26]);
     } else {
         $this->jsonError(Tools::displayError('Error on moving picture'));
     }
 }
예제 #9
0
	/**
	 * Download the remote file and save it to disk, create a thumbnail for it,
	 * and create a database entry for the file.
	 *
	 * @param string $p_url
	 *		The remote location of the file. ("http://...");
	 *
	 * @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 ID of the user who uploaded the image.
	 *
	 * @param int $p_id
	 *		If you are updating an image, specify its ID here.
	 *
	 * @return mixed
	 * 		Return an Image object on success, return a PEAR_Error otherwise.
	 */
	public static function OnAddRemoteImage($p_url, $p_attributes,
	                                        $p_userId = null, $p_id = null)
	{
		global $Campsite;
		if (function_exists("camp_load_translation_strings")) {
			camp_load_translation_strings("api");
		}

		// Check if thumbnail directory is 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);
		}

		$client = new HTTP_Client();
	    $client->get($p_url);
	    $response = $client->currentResponse();
	    if ($response['code'] != 200) {
	    	return new PEAR_Error(getGS("Unable to fetch image from remote server."));
	    }
	    foreach ($response['headers'] as $headerName => $value) {
	    	if (strtolower($headerName) == "content-type") {
	    		$ContentType = $value;
	    		break;
	    	}
	    }

        // Check content type
        if (!preg_match('/image/', $ContentType)) {
            // wrong URL
            return new PEAR_Error(getGS('URL "$1" is invalid or is not an image.', $p_url));
        }

    	// Save the file
        $tmpname = $Campsite['TMP_DIRECTORY'].'img'.md5(rand());
        if (is_writable($Campsite['TMP_DIRECTORY'])) {
	        if ($tmphandle = fopen($tmpname, 'w')) {
	            fwrite($tmphandle, $response['body']);
	            fclose($tmphandle);
	        }
        } else {
	    	return new PEAR_Error(camp_get_error_message(CAMP_ERROR_CREATE_FILE, $tmpname), CAMP_ERROR_CREATE_FILE);
	    }

        // Check if it is really an image file
        $imageInfo = getimagesize($tmpname);
        if ($imageInfo === false) {
        	unlink($tmpname);
            return new PEAR_Error(getGS('URL "$1" is not an image.', $cURL));
        }

        // content-type = image
        if (!is_null($p_id)) {
        	// Updating the image
        	$image = new Image($p_id);
        	$image->update($p_attributes);
	    	// Remove the old image & thumbnail because
	    	// the new file might have a different file extension.
	    	if (file_exists($image->getImageStorageLocation())) {
				if (is_writable(dirname($image->getImageStorageLocation()))) {
		    		unlink($image->getImageStorageLocation());
				} else {
	    			return new PEAR_Error(camp_get_error_message(CAMP_ERROR_DELETE_FILE, $image->getImageStorageLocation()), CAMP_ERROR_DELETE_FILE);
				}
	    	}
	    	if (file_exists($image->getThumbnailStorageLocation())) {
				if (is_writable(dirname($image->getThumbnailStorageLocation()))) {
		    		unlink($image->getThumbnailStorageLocation());
				} else {
	    			return new PEAR_Error(camp_get_error_message(CAMP_ERROR_DELETE_FILE, $image->getThumbnailStorageLocation()), CAMP_ERROR_DELETE_FILE);
				}
	    	}
        } else {
        	// Creating the image
        	$image = new Image();
        	$image->create($p_attributes);
        	$image->setProperty('TimeCreated', 'NULL', true, true);
        	$image->setProperty('LastModified', 'NULL', true, true);
        }
        if (!isset($p_attributes['Date'])) {
        	$image->setProperty('Date', 'NOW()', true, true);
        }
        $image->setProperty('Location', 'remote', false);
        $image->setProperty('URL', $p_url, false);
	    if (isset($imageInfo['mime'])) {
	    	$image->setProperty('ContentType', $imageInfo['mime'], false);
	    }

        // Remember who uploaded the image
        if (!is_null($p_userId)) {
			$image->setProperty('UploadedByUser', $p_userId, false);
        }

        if ($Campsite['IMAGEMAGICK_INSTALLED']) {
		    // Set thumbnail file name
		    $extension = Image::__ImageTypeToExtension($imageInfo[2]);
		    $thumbnail = $image->generateThumbnailStorageLocation($extension);
		    $image->setProperty('ThumbnailFileName', basename($thumbnail), false);

		    if (!is_writable(dirname($image->getThumbnailStorageLocation()))) {
            	return new PEAR_Error(camp_get_error_message(CAMP_ERROR_CREATE_FILE, $image->getThumbnailStorageLocation()), CAMP_ERROR_CREATE_FILE);
		    }

		    // Create the thumbnail
            $cmd = $Campsite['THUMBNAIL_COMMAND'].' '
            	. $tmpname . ' ' . $image->getThumbnailStorageLocation();
            system($cmd);
            if (file_exists($image->getThumbnailStorageLocation())) {
            	chmod($image->getThumbnailStorageLocation(), 0644);
            }
        }
        unlink($tmpname);
        $image->commit();

		$logtext = getGS('The image $1 has been added.',
						$image->m_data['Description']." (".$image->m_data['Id'].")");
		Log::Message($logtext, null, 41);

	    return $image;
	} // fn OnAddRemoteImage
예제 #10
0
 /**
  * Test inserting an image, editing it, then updating it
  **/
 public function testUpdateValidImage()
 {
     //Count the number of rows and save it for later
     $numRows = $this->getConnection()->getRowCount("image");
     //Create a new image and insert it into MySQL
     $image = new Image(null, $this->profile->getProfileId(), $this->VALID_IMAGETYPE, $this->VALID_IMAGEFILENAME, $this->VALID_IMAGETEXT, $this->VALID_IMAGEDATE);
     $image->insert($this->getPDO());
     //Edit the image and update it
     $image->setImageText($this->VALID_IMAGETEXT2);
     $image->update($this->getPDO());
     //Grab data from MySQL and ensure fields match expectations
     $pdoImage = Image::getImageByImageId($this->getPDO(), $image->getImageId());
     $this->assertEquals($numRows + 1, $this->getConnection()->getRowCount("image"));
     $this->assertEquals($pdoImage->getImageProfileId(), $this->profile->getProfileId());
     $this->assertEquals($pdoImage->getImageType(), $this->VALID_IMAGETYPE);
     $this->assertEquals($pdoImage->getImageFileName(), $this->VALID_IMAGEFILENAME);
     $this->assertEquals($pdoImage->getImageText(), $this->VALID_IMAGETEXT2);
     $this->assertEquals($pdoImage->getImageDate(), $this->VALID_IMAGEDATE);
 }
예제 #11
0
 /**
  * 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;
     $translator = \Zend_Registry::get('container')->getService('translator');
     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($translator->trans("The file uploaded is not an image.", array(), 'api'));
     }
     $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);
             }
         }
         self::chmod($target, 0644);
         $createMethodName = Image::__GetImageTypeCreateMethod($imageInfo[2]);
         if (!isset($createMethodName)) {
             throw new Exception($translator->trans("Image type \$1 is not supported.", array('$1' => image_type_to_mime_type($p_imageType)), 'api'));
         }
         $imageHandler = $createMethodName($target);
         if (!$imageHandler) {
             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']);
         $thumbnailImage->save($thumbnail, array('format' => $extension));
         self::chmod($thumbnail, 0644);
     } 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());
     }
     $user = Zend_Registry::get('container')->getService('user')->getCurrentUser();
     if ($user && $user->isAdmin()) {
         $image->m_data['Status'] = 'approved';
         $image->m_data['Source'] = 'local';
     }
     $image->commit();
     return $image;
 }
예제 #12
0
require_once $GLOBALS['g_campsiteDir'] . '/classes/ImageSearch.php';
require_once $GLOBALS['g_campsiteDir'] . '/classes/Log.php';
$translator = \Zend_Registry::get('container')->getService('translator');
if (!SecurityToken::isValid()) {
    camp_html_display_error($translator->trans('Invalid security token!'));
    exit;
}
// check input
$f_image_id = Input::Get('f_image_id', 'int', 0);
$f_image_description = Input::Get('f_image_description');
$f_image_photographer = Input::Get('f_image_photographer');
$f_image_place = Input::Get('f_image_place');
$f_image_date = Input::Get('f_image_date');
$f_image_status = Input::Get('f_image_status');
//$f_image_url = Input::Get('f_image_url', 'string', '', true);
if (!Input::IsValid() || $f_image_id <= 0) {
    camp_html_goto_page("/{$ADMIN}/media-archive/index.php");
}
$imageObj = new Image($f_image_id);
if (!$g_user->hasPermission('ChangeImage')) {
    camp_html_goto_page("/{$ADMIN}/logout.php");
}
$updateArray = array('Description' => $f_image_description, 'Photographer' => $f_image_photographer, 'Place' => $f_image_place, 'Date' => $f_image_date, 'Status' => $f_image_status, 'photographer_url' => Input::Get('f_photographer_url'));
//if (!empty($f_image_url)) {
//	$updateArray['URL'] = $f_image_url;
//}
$imageObj->update($updateArray);
$cacheService = \Zend_Registry::get('container')->getService('newscoop.cache');
$cacheService->clearNamespace('image');
camp_html_add_msg($translator->trans("Image updated.", array(), 'media_archive'), "ok");
camp_html_goto_page("/{$ADMIN}/media-archive/edit.php?f_image_id={$f_image_id}");
예제 #13
0
 public function createImage()
 {
     $image = new Image();
     $image->fill(Input::get('formdata'));
     $image->save();
     $image->sortorder = $image->id;
     $image->update();
     $html = View::make('projects.imageadmin')->withImage($image)->render();
     return $this->success(['html' => $html], 'It worked');
 }
예제 #14
0
파일: Image.php 프로젝트: nidzix/Newscoop
 /**
  * Download the remote file and save it to disk, create a thumbnail for it,
  * and create a database entry for the file.
  *
  * @param string $p_url
  *		The remote location of the file. ("http://...");
  *
  * @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 ID of the user who uploaded the image.
  *
  * @param int $p_id
  *		If you are updating an image, specify its ID here.
  *
  * @return mixed
  * 		Return an Image object on success, return a PEAR_Error otherwise.
  */
 public static function OnAddRemoteImage($p_url, $p_attributes, $p_userId = null, $p_id = null)
 {
     global $Campsite;
     if (function_exists("camp_load_translation_strings")) {
         camp_load_translation_strings("api");
     }
     // Check if thumbnail directory is 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);
     }
     // fetch headers
     $headers = get_headers($p_url, TRUE);
     if (strpos($headers[0], '200 OK') === FALSE) {
         return new PEAR_Error(getGS("Unable to fetch image from remote server."));
     }
     // get type
     $ContentType = $headers['Content-Type'];
     // Check content type
     if (strpos($ContentType, 'image') === FALSE) {
         // wrong URL
         return new PEAR_Error(getGS('URL "$1" is invalid or is not an image.', $p_url));
     }
     // check path
     if (!is_writable($Campsite['TMP_DIRECTORY'])) {
         return new PEAR_Error(camp_get_error_message(CAMP_ERROR_CREATE_FILE, $tmpname), CAMP_ERROR_CREATE_FILE);
     }
     // save image
     $tmpname = $Campsite['TMP_DIRECTORY'] . 'img' . md5(uniqid());
     file_put_contents($tmpname, file_get_contents($p_url));
     // Check if it is really an image file
     $imageInfo = getimagesize($tmpname);
     if ($imageInfo === false) {
         unlink($tmpname);
         return new PEAR_Error(getGS('URL "$1" is not an image.', $cURL));
     }
     // content-type = image
     if (!is_null($p_id)) {
         // Updating the image
         $image = new Image($p_id);
         $image->update($p_attributes);
         // Remove the old image & thumbnail because
         // the new file might have a different file extension.
         if (file_exists($image->getImageStorageLocation())) {
             if (is_writable(dirname($image->getImageStorageLocation()))) {
                 unlink($image->getImageStorageLocation());
             } else {
                 return new PEAR_Error(camp_get_error_message(CAMP_ERROR_DELETE_FILE, $image->getImageStorageLocation()), CAMP_ERROR_DELETE_FILE);
             }
         }
         if (file_exists($image->getThumbnailStorageLocation())) {
             if (is_writable(dirname($image->getThumbnailStorageLocation()))) {
                 unlink($image->getThumbnailStorageLocation());
             } else {
                 return new PEAR_Error(camp_get_error_message(CAMP_ERROR_DELETE_FILE, $image->getThumbnailStorageLocation()), CAMP_ERROR_DELETE_FILE);
             }
         }
     } else {
         $image = new Image();
         $image->create($p_attributes);
         $image->setProperty('TimeCreated', 'NULL', true, true);
         $image->setProperty('LastModified', 'NULL', true, true);
     }
     if (!isset($p_attributes['Date'])) {
         $image->setProperty('Date', 'NOW()', true, true);
     }
     $image->setProperty('Location', 'remote', false);
     $image->setProperty('URL', $p_url, false);
     if (isset($imageInfo['mime'])) {
         $image->setProperty('ContentType', $imageInfo['mime'], false);
     }
     // Remember who uploaded the image
     if (!is_null($p_userId)) {
         $image->setProperty('UploadedByUser', $p_userId, false);
     }
     // create thumbnail
     $extension = Image::__ImageTypeToExtension($imageInfo[2]);
     $thumbnail = $image->generateThumbnailStorageLocation($extension);
     $image->setProperty('ThumbnailFileName', basename($thumbnail), false);
     if (!is_writable(dirname($thumbnail))) {
         return new PEAR_Error(camp_get_error_message(CAMP_ERROR_CREATE_FILE, $image->getThumbnailStorageLocation()), CAMP_ERROR_CREATE_FILE);
     }
     $createMethodName = Image::__GetImageTypeCreateMethod($imageInfo[2]);
     if (!isset($createMethodName)) {
         throw new Exception(getGS("Image type \$1 is not supported.", image_type_to_mime_type($ContentType)));
     }
     $imageHandler = $createMethodName($tmpname);
     if (!$imageHandler) {
         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']);
     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());
     }
     if (file_exists($thumbnail)) {
         self::chmod($thumbnail, 0644);
     }
     unlink($tmpname);
     $image->commit();
     return $image;
 }