示例#1
0
/**
 * shopp_add_image
 *
 * Add an image by filename, and associate with a user defined context.  Requires full path to the file on your filesystem, or a correct relative path for the scripts current working directory.
 *
 * @api
 * @since 1.2
 *
 * @param int $id Object id to attach the image asset to.
 * @param string $context the object type the image asset will be attached to.  This can be product or category
 * @param string $file Full or correct relative path to the image file.
 * @return mixed false on failure, int image asset id on success.
 **/
function shopp_add_image($id, $context, $file)
{
    if (empty($id) || empty($context) || empty($file)) {
        shopp_debug(__FUNCTION__ . " failed: One or more missing parameters.");
        return false;
    }
    if (!is_file($file) || !is_readable($file)) {
        shopp_debug(__FUNCTION__ . " failed for file {$file}: File missing or unreadable.");
    }
    if ('product' == $context) {
        $Object = new ShoppProduct($id);
        $Image = new ProductImage();
    } else {
        if ('category' == $context) {
            $Object = new ProductCategory($id);
            $Image = new CategoryImage();
        } else {
            shopp_debug(__FUNCTION__ . " failed for file {$file}: Invalid context {$context}.");
            return false;
        }
    }
    if (empty($Object->id)) {
        shopp_debug(__FUNCTION__ . " failed for file {$file}: Unable to find a {$context} with id {$id}.");
        return false;
    }
    $Image->parent = $id;
    $Image->type = "image";
    $Image->name = "original";
    $Image->filename = basename($file);
    list($Image->width, $Image->height, $Image->mime, $Image->attr) = getimagesize($file);
    $Image->mime = image_type_to_mime_type($Image->mime);
    $Image->size = filesize($file);
    if (!$Image->unique()) {
        shopp_debug(__FUNCTION__ . " failed for file {$file}: Too many images exist with this name.");
        return false;
    }
    $Image->store($file, 'file');
    $Image->save();
    if ($Image->id) {
        return $Image->id;
    }
    shopp_debug(__FUNCTION__ . " failed for file {$file}.");
    return false;
}