/**
     * Write the posted image on disk
     *
     * @param string $reception_path
     * @param int $dest_width
     * @param int $dest_height
     * @param array $image_types
     * @param string $parent_path
     * @return bool
     *
     * @throws WebserviceException
     */
    protected function writePostedImageOnDisk($reception_path, $dest_width = null, $dest_height = null, $image_types = null, $parent_path = null)
    {
        if ($this->wsObject->method == 'PUT') {
            if (isset($_FILES['image']['tmp_name']) && $_FILES['image']['tmp_name']) {
                $file = $_FILES['image'];
                if ($file['size'] > $this->imgMaxUploadSize) {
                    throw new WebserviceException(sprintf('The image size is too large (maximum allowed is %d KB)', $this->imgMaxUploadSize / 1000), array(72, 400));
                }
                // Get mime content type
                $mime_type = false;
                if (Tools::isCallable('finfo_open')) {
                    $const = defined('FILEINFO_MIME_TYPE') ? FILEINFO_MIME_TYPE : FILEINFO_MIME;
                    $finfo = finfo_open($const);
                    $mime_type = finfo_file($finfo, $file['tmp_name']);
                    finfo_close($finfo);
                } elseif (Tools::isCallable('mime_content_type')) {
                    $mime_type = mime_content_type($file['tmp_name']);
                } elseif (Tools::isCallable('exec')) {
                    $mime_type = trim(exec('file -b --mime-type ' . escapeshellarg($file['tmp_name'])));
                }
                if (empty($mime_type) || $mime_type == 'regular file') {
                    $mime_type = $file['type'];
                }
                if (($pos = strpos($mime_type, ';')) !== false) {
                    $mime_type = substr($mime_type, 0, $pos);
                }
                // Check mime content type
                if (!$mime_type || !in_array($mime_type, $this->acceptedImgMimeTypes)) {
                    throw new WebserviceException('This type of image format is not recognized, allowed formats are: ' . implode('", "', $this->acceptedImgMimeTypes), array(73, 400));
                } elseif ($file['error']) {
                    throw new WebserviceException('Error while uploading image. Please change your server\'s settings', array(74, 400));
                }
                // Try to copy image file to a temporary file
                if (!($tmp_name = tempnam(_PS_TMP_IMG_DIR_, 'PS')) || !move_uploaded_file($_FILES['image']['tmp_name'], $tmp_name)) {
                    throw new WebserviceException('Error while copying image to the temporary directory', array(75, 400));
                } else {
                    $result = $this->writeImageOnDisk($tmp_name, $reception_path, $dest_width, $dest_height, $image_types, $parent_path);
                }
                @unlink($tmp_name);
                return $result;
            } else {
                throw new WebserviceException('Please set an "image" parameter with image data for value', array(76, 400));
            }
        } elseif ($this->wsObject->method == 'POST') {
            if (isset($_FILES['image']['tmp_name']) && $_FILES['image']['tmp_name']) {
                $file = $_FILES['image'];
                if ($file['size'] > $this->imgMaxUploadSize) {
                    throw new WebserviceException(sprintf('The image size is too large (maximum allowed is %d KB)', $this->imgMaxUploadSize / 1000), array(72, 400));
                }
                require_once _PS_CORE_DIR_ . '/images.inc.php';
                if ($error = ImageManager::validateUpload($file)) {
                    throw new WebserviceException('Image upload error : ' . $error, array(76, 400));
                }
                if (isset($file['tmp_name']) && $file['tmp_name'] != null) {
                    if ($this->imageType == 'products') {
                        $product = new Product((int) $this->wsObject->urlSegment[2]);
                        if (!Validate::isLoadedObject($product)) {
                            throw new WebserviceException('Product ' . (int) $this->wsObject->urlSegment[2] . ' does not exist', array(76, 400));
                        }
                        $image = new Image();
                        $image->id_product = (int) $product->id;
                        $image->position = Image::getHighestPosition($product->id) + 1;
                        if (!Image::getCover((int) $product->id)) {
                            $image->cover = 1;
                        } else {
                            $image->cover = 0;
                        }
                        if (!$image->add()) {
                            throw new WebserviceException('Error while creating image', array(76, 400));
                        }
                        if (!Validate::isLoadedObject($product)) {
                            throw new WebserviceException('Product ' . (int) $this->wsObject->urlSegment[2] . ' does not exist', array(76, 400));
                        }
                        Hook::exec('updateProduct', array('id_product' => (int) $this->wsObject->urlSegment[2]));
                    }
                    // copy image
                    if (!isset($file['tmp_name'])) {
                        return false;
                    }
                    if ($error = ImageManager::validateUpload($file, $this->imgMaxUploadSize)) {
                        throw new WebserviceException('Bad image : ' . $error, array(76, 400));
                    }
                    if ($this->imageType == 'products') {
                        $image = new Image($image->id);
                        if (!(Configuration::get('PS_OLD_FILESYSTEM') && file_exists(_PS_PROD_IMG_DIR_ . $product->id . '-' . $image->id . '.jpg'))) {
                            $image->createImgFolder();
                        }
                        if (!($tmp_name = tempnam(_PS_TMP_IMG_DIR_, 'PS')) || !move_uploaded_file($file['tmp_name'], $tmp_name)) {
                            throw new WebserviceException('An error occurred during the image upload', array(76, 400));
                        } elseif (!ImageManager::resize($tmp_name, _PS_PROD_IMG_DIR_ . $image->getExistingImgPath() . '.' . $image->image_format)) {
                            throw new WebserviceException('An error occurred while copying image', array(76, 400));
                        } else {
                            $images_types = ImageType::getImagesTypes('products');
                            foreach ($images_types as $imageType) {
                                if (!ImageManager::resize($tmp_name, _PS_PROD_IMG_DIR_ . $image->getExistingImgPath() . '-' . stripslashes($imageType['name']) . '.' . $image->image_format, $imageType['width'], $imageType['height'], $image->image_format)) {
                                    $this->_errors[] = Tools::displayError('An error occurred while copying image:') . ' ' . stripslashes($imageType['name']);
                                }
                            }
                        }
                        @unlink($tmp_name);
                        $this->imgToDisplay = _PS_PROD_IMG_DIR_ . $image->getExistingImgPath() . '.' . $image->image_format;
                        $this->objOutput->setFieldsToDisplay('full');
                        $this->output = $this->objOutput->renderEntity($image, 1);
                        $image_content = array('sqlId' => 'content', 'value' => base64_encode(file_get_contents($this->imgToDisplay)), 'encode' => 'base64');
                        $this->output .= $this->objOutput->objectRender->renderField($image_content);
                    } elseif (in_array($this->imageType, array('categories', 'manufacturers', 'suppliers', 'stores'))) {
                        if (!($tmp_name = tempnam(_PS_TMP_IMG_DIR_, 'PS')) || !move_uploaded_file($file['tmp_name'], $tmp_name)) {
                            throw new WebserviceException('An error occurred during the image upload', array(76, 400));
                        } elseif (!ImageManager::resize($tmp_name, $reception_path)) {
                            throw new WebserviceException('An error occurred while copying image', array(76, 400));
                        }
                        $images_types = ImageType::getImagesTypes($this->imageType);
                        foreach ($images_types as $imageType) {
                            if (!ImageManager::resize($tmp_name, $parent_path . $this->wsObject->urlSegment[2] . '-' . stripslashes($imageType['name']) . '.jpg', $imageType['width'], $imageType['height'])) {
                                $this->_errors[] = Tools::displayError('An error occurred while copying image:') . ' ' . stripslashes($imageType['name']);
                            }
                        }
                        @unlink(_PS_TMP_IMG_DIR_ . $tmp_name);
                        $this->imgToDisplay = $reception_path;
                    } elseif ($this->imageType == 'customizations') {
                        $filename = md5(uniqid(rand(), true));
                        $this->imgToDisplay = _PS_UPLOAD_DIR_ . $filename;
                        if (!($tmp_name = tempnam(_PS_TMP_IMG_DIR_, 'PS')) || !move_uploaded_file($file['tmp_name'], $tmp_name)) {
                            throw new WebserviceException('An error occurred during the image upload', array(76, 400));
                        } elseif (!ImageManager::resize($tmp_name, $this->imgToDisplay)) {
                            throw new WebserviceException('An error occurred while copying image', array(76, 400));
                        }
                        $product_picture_width = (int) Configuration::get('PS_PRODUCT_PICTURE_WIDTH');
                        $product_picture_height = (int) Configuration::get('PS_PRODUCT_PICTURE_HEIGHT');
                        if (!ImageManager::resize($this->imgToDisplay, $this->imgToDisplay . '_small', $product_picture_width, $product_picture_height)) {
                            throw new WebserviceException('An error occurred while resizing image', array(76, 400));
                        }
                        @unlink(_PS_TMP_IMG_DIR_ . $tmp_name);
                        $query = 'INSERT INTO `' . _DB_PREFIX_ . 'customized_data` (`id_customization`, `type`, `index`, `value`)
							VALUES (' . (int) $this->wsObject->urlSegment[3] . ', 0, ' . (int) $this->wsObject->urlSegment[4] . ', \'' . $filename . '\')';
                        if (!Db::getInstance()->execute($query)) {
                            return false;
                        }
                    }
                    return true;
                }
            }
        } else {
            throw new WebserviceException('Method ' . $this->wsObject->method . ' is not allowed for an image resource', array(77, 405));
        }
    }
Esempio n. 2
0
 /**
  * Thanks to the (WebserviceOutputBuilder) WebserviceKey::objOutput
  * Method build the output depend on the WebserviceRequest::outputFormat
  * and set HTTP header parameters.
  *
  * @return array with displaying informations (used in the dispatcher).
  */
 protected function returnOutput()
 {
     $return = array();
     // write headers
     $this->objOutput->setHeaderParams('Access-Time', time())->setHeaderParams('X-Powered-By', 'PrestaShop Webservice')->setHeaderParams('PSWS-Version', _PS_VERSION_)->setHeaderParams('Execution-Time', round(microtime(true) - $this->_startTime, 3));
     $return['type'] = strtolower($this->outputFormat);
     // write this header only now (avoid hackers happiness...)
     if ($this->_authenticated) {
         $this->objOutput->setHeaderParams('PSWS-Version', _PS_VERSION_);
     }
     // If Specific Management is asked
     if ($this->objectSpecificManagement instanceof WebserviceSpecificManagementInterface) {
         try {
             $return['content'] = $this->objectSpecificManagement->getContent();
         } catch (WebserviceException $e) {
             if ($e->getType() == WebserviceException::DID_YOU_MEAN) {
                 $this->setErrorDidYouMean($e->getStatus(), $e->getMessage(), $e->getWrongValue(), $e->getAvailableValues(), $e->getCode());
             } elseif ($e->getType() == WebserviceException::SIMPLE) {
                 $this->setError($e->getStatus(), $e->getMessage(), $e->getCode());
             }
         }
     }
     // for use a general output
     if (!$this->hasErrors() && $this->objectSpecificManagement == null) {
         if (empty($this->objects)) {
             try {
                 $return['content'] = $this->objOutput->getResourcesList($this->keyPermissions);
             } catch (WebserviceException $e) {
                 if ($e->getType() == WebserviceException::DID_YOU_MEAN) {
                     $this->setErrorDidYouMean($e->getStatus(), $e->getMessage(), $e->getWrongValue(), $e->getAvailableValues(), $e->getCode());
                 } elseif ($e->getType() == WebserviceException::SIMPLE) {
                     $this->setError($e->getStatus(), $e->getMessage(), $e->getCode());
                 }
             }
         } else {
             try {
                 if (isset($this->urlSegment[1]) && !empty($this->urlSegment[1])) {
                     $type_of_view = WebserviceOutputBuilder::VIEW_DETAILS;
                 } else {
                     $type_of_view = WebserviceOutputBuilder::VIEW_LIST;
                 }
                 if (in_array($this->method, array('PUT', 'POST'))) {
                     $type_of_view = WebserviceOutputBuilder::VIEW_DETAILS;
                     $this->fieldsToDisplay = 'full';
                 }
                 $return['content'] = $this->objOutput->getContent($this->objects, $this->schemaToDisplay, $this->fieldsToDisplay, $this->depth, $type_of_view);
             } catch (WebserviceException $e) {
                 if ($e->getType() == WebserviceException::DID_YOU_MEAN) {
                     $this->setErrorDidYouMean($e->getStatus(), $e->getMessage(), $e->getWrongValue(), $e->getAvailableValues(), $e->getCode());
                 } elseif ($e->getType() == WebserviceException::SIMPLE) {
                     $this->setError($e->getStatus(), $e->getMessage(), $e->getCode());
                 }
             } catch (Exception $e) {
                 $this->setError(500, $e->getMessage(), $e->getCode());
             }
         }
     }
     // if the output is not enable, delete the content
     // the type content too
     if (!$this->_outputEnabled) {
         if (isset($return['type'])) {
             unset($return['type']);
         }
         if (isset($return['content'])) {
             unset($return['content']);
         }
     } elseif (isset($return['content'])) {
         $this->objOutput->setHeaderParams('Content-Sha1', sha1($return['content']));
     }
     // if errors happends when creating returned xml,
     // the usual xml content is replaced by the nice error handler content
     if ($this->hasErrors()) {
         $this->_outputEnabled = true;
         $return['content'] = $this->objOutput->getErrors($this->errors);
     }
     if (!isset($return['content']) || strlen($return['content']) <= 0) {
         $this->objOutput->setHeaderParams('Content-Type', '');
     }
     $return['headers'] = $this->objOutput->buildHeader();
     restore_error_handler();
     return $return;
 }
 /**
  * This must be return a string with specific values as WebserviceRequest expects.
  *
  * @return string
  */
 public function getContent()
 {
     return $this->objOutput->getObjectRender()->overrideContent($this->output);
 }