protected function step()
 {
     $image_model = new shopProductImagesModel();
     $create_thumbnails = waRequest::post('create_thumbnails');
     $chunk_size = 50;
     if ($create_thumbnails) {
         $chunk_size = 10;
     }
     $sizes = wa('shop')->getConfig()->getImageSizes();
     $images = $image_model->getAvailableImages($this->data['offset'], $chunk_size);
     foreach ($images as $i) {
         if ($this->data['product_id'] != $i['product_id']) {
             sleep(0.2);
             $this->data['product_id'] = $i['product_id'];
             $this->data['product_count'] += 1;
         }
         try {
             $path = shopImage::getThumbsPath($i);
             if (!waFiles::delete($path)) {
                 throw new waException(sprintf(_w('Error when delete thumbnails for image %d'), $i['id']));
             }
             if ($create_thumbnails) {
                 shopImage::generateThumbs($i, $sizes);
             }
             $this->data['image_count'] += 1;
             // image count - count of successful progessed images
         } catch (Exception $e) {
             $this->error($e->getMessage());
         }
         $this->data['offset'] += 1;
     }
 }
 private function stepImportImage()
 {
     /**
      * @var shopProductImagesModel $model
      */
     static $model;
     if (!is_array($this->data['map'][self::STAGE_IMAGE]) && $this->data['map'][self::STAGE_IMAGE]) {
         $this->data['map'][self::STAGE_IMAGE] = array($this->data['map'][self::STAGE_IMAGE]);
     }
     if ($file = reset($this->data['map'][self::STAGE_IMAGE])) {
         if (!$model) {
             $model = new shopProductImagesModel();
         }
         //TODO store image id & if repeated - skip it
         $target = 'new';
         $u = @parse_url($file);
         $_is_url = false;
         if (!$u || !(isset($u['scheme']) && isset($u['host']) && isset($u['path']))) {
         } elseif (in_array($u['scheme'], array('http', 'https', 'ftp', 'ftps'))) {
             $_is_url = true;
         } else {
             $target = 'skip';
             $file = null;
             $this->error(sprintf('Unsupported file source protocol', $u['scheme']));
         }
         $search = array('product_id' => $this->data['map'][self::STAGE_PRODUCT], 'ext' => pathinfo($file, PATHINFO_EXTENSION));
         try {
             $name = preg_replace('@[^a-zA-Zа-яА-Я0-9\\._\\-]+@', '', basename(urldecode($file)));
             if ($_is_url) {
                 $pattern = sprintf('@/(%d)/images/(\\d+)/\\2\\.(\\d+(x\\d+)?)\\.([^\\.]+)$@', $search['product_id']);
                 if (preg_match($pattern, $file, $matches)) {
                     $image = array('product_id' => $matches[1], 'id' => $matches[2], 'ext' => $matches[5]);
                     if (strpos($file, shopImage::getUrl($image, $matches[3])) !== false && $model->getByField($image)) {
                         #skip local file
                         $target = 'skip';
                         $file = null;
                     }
                 }
                 if ($file) {
                     waFiles::upload($file, $file = wa()->getTempPath('csv/upload/images/' . waLocale::transliterate($name, 'en_US')));
                 }
             } elseif ($file) {
                 $file = $this->data['upload_path'] . $file;
             }
             if ($file && file_exists($file)) {
                 if ($image = waImage::factory($file)) {
                     $search['original_filename'] = $name;
                     $data = array('product_id' => $this->data['map'][self::STAGE_PRODUCT], 'upload_datetime' => date('Y-m-d H:i:s'), 'width' => $image->width, 'height' => $image->height, 'size' => filesize($file), 'original_filename' => $name, 'ext' => pathinfo($file, PATHINFO_EXTENSION));
                     if ($exists = $model->getByField($search)) {
                         $data = array_merge($exists, $data);
                         $thumb_dir = shopImage::getThumbsPath($data);
                         $back_thumb_dir = preg_replace('@(/$|$)@', '.back$1', $thumb_dir, 1);
                         $paths[] = $back_thumb_dir;
                         waFiles::delete($back_thumb_dir);
                         // old backups
                         if (file_exists($thumb_dir)) {
                             if (!(waFiles::move($thumb_dir, $back_thumb_dir) || waFiles::delete($back_thumb_dir)) && !waFiles::delete($thumb_dir)) {
                                 throw new waException(_w("Error while rebuild thumbnails"));
                             }
                         }
                     }
                     $image_changed = false;
                     /**
                      * TODO move it code into product core method
                      */
                     /**
                      * Extend add/update product images
                      * Make extra workup
                      * @event image_upload
                      */
                     $event = wa()->event('image_upload', $image);
                     if ($event) {
                         foreach ($event as $result) {
                             if ($result) {
                                 $image_changed = true;
                                 break;
                             }
                         }
                     }
                     if (empty($data['id'])) {
                         $image_id = $data['id'] = $model->add($data);
                     } else {
                         $image_id = $data['id'];
                         $target = 'update';
                         $model->updateById($image_id, $data);
                     }
                     if (!$image_id) {
                         throw new waException("Database error");
                     }
                     $image_path = shopImage::getPath($data);
                     if (file_exists($image_path) && !is_writable($image_path) || !file_exists($image_path) && !waFiles::create($image_path)) {
                         $model->deleteById($image_id);
                         throw new waException(sprintf("The insufficient file write permissions for the %s folder.", substr($image_path, strlen($this->getConfig()->getRootPath()))));
                     }
                     if ($image_changed) {
                         $image->save($image_path);
                         /**
                          * @var shopConfig $config
                          */
                         $config = $this->getConfig();
                         if ($config->getOption('image_save_original') && ($original_file = shopImage::getOriginalPath($data))) {
                             waFiles::copy($file, $original_file);
                         }
                     } else {
                         waFiles::copy($file, $image_path);
                     }
                     $this->data['processed_count'][self::STAGE_IMAGE][$target]++;
                 } else {
                     $this->error(sprintf('Invalid image file', $file));
                 }
             } elseif ($file) {
                 $this->error(sprintf('File %s not found', $file));
                 $target = 'skip';
                 $this->data['processed_count'][self::STAGE_IMAGE][$target]++;
             } else {
                 $this->data['processed_count'][self::STAGE_IMAGE][$target]++;
             }
         } catch (Exception $e) {
             $this->error($e->getMessage());
             //TODO skip on repeated error
         }
         array_shift($this->data['map'][self::STAGE_IMAGE]);
         ++$this->data['current'][self::STAGE_IMAGE];
         if ($_is_url) {
             waFiles::delete($file);
         }
     }
     return true;
 }
 public function execute()
 {
     $id = waRequest::post('id', null, waRequest::TYPE_INT);
     if (!$id) {
         throw new waException("Can't restore image");
     }
     $product_images_model = new shopProductImagesModel();
     $image = $product_images_model->getById($id);
     if (!$image) {
         throw new waException("Can't restore image");
     }
     // check rights
     $product_model = new shopProductModel();
     if (!$product_model->checkRights($image['product_id'])) {
         throw new waException(_w("Access denied"));
     }
     $original_image_path = shopImage::getOriginalPath($image);
     if (!wa('shop')->getConfig()->getOption('image_save_original') || !file_exists($original_image_path)) {
         throw new waException("Can't restore image. Original image doesn't exist");
     }
     $image_path = shopImage::getPath($image);
     $paths = array();
     try {
         $backup_image_path = preg_replace('/(\\.[^\\.]+)$/', '.backup$1', $image_path);
         if (!waFiles::move($image_path, $backup_image_path)) {
             throw new waException("Error while restore. Operation canceled");
         }
         $paths[] = $backup_image_path;
         if (!waFiles::move($original_image_path, $image_path)) {
             if (!waFiles::move($backup_image_path, $image_path)) {
                 throw new waException("Error while restore. Current file corupted but backuped");
             }
             throw new waException("Error while restore. Operation canceled");
         }
         $data = $this->getData($image_path);
         $product_images_model->updateById($id, $data);
         $image = array_merge($image, $data);
         $thumb_dir = shopImage::getThumbsPath($image);
         $back_thumb_dir = preg_replace('@(/$|$)@', '.back$1', $thumb_dir, 1);
         $paths[] = $back_thumb_dir;
         waFiles::delete($back_thumb_dir);
         // old backups
         if (!(waFiles::move($thumb_dir, $back_thumb_dir) || waFiles::delete($back_thumb_dir)) && !waFiles::delete($thumb_dir)) {
             throw new waException(_w("Error while rebuild thumbnails"));
         }
         /**
          * @var shopConfig $config
          */
         $config = $this->getConfig();
         try {
             shopImage::generateThumbs($image, $config->getImageSizes());
         } catch (Exception $e) {
             waLog::log($e->getMessage());
         }
         $this->response = $image;
         $edit_datetime_ts = strtotime($image['edit_datetime']);
         $this->response['url_big'] = shopImage::getUrl($image, $config->getImageSize('big')) . '?' . $edit_datetime_ts;
         $this->response['url_crop'] = shopImage::getUrl($image, $config->getImageSize('crop')) . '?' . $edit_datetime_ts;
         foreach ($paths as $path) {
             waFiles::delete($path);
         }
     } catch (Exception $e) {
         foreach ($paths as $path) {
             waFiles::delete($path);
         }
         throw $e;
     }
 }
 public function execute()
 {
     $id = waRequest::get('id', null, waRequest::TYPE_INT);
     if (!$id) {
         throw new waException("Unknown image");
     }
     $direction = waRequest::post('direction', 'left', waRequest::TYPE_STRING_TRIM);
     if (!isset($this->angles[$direction])) {
         throw new waException("Can't rotate image");
     }
     $product_images_model = new shopProductImagesModel();
     $image = $product_images_model->getById($id);
     if (!$image) {
         throw new waException("Unknown image");
     }
     // check rights
     $product_model = new shopProductModel();
     if (!$product_model->checkRights($image['product_id'])) {
         throw new waException(_w("Access denied"));
     }
     $image_path = shopImage::getPath($image);
     $paths = array();
     try {
         $result_image_path = preg_replace('/(\\.[^\\.]+)$/', '.result$1', $image_path);
         $backup_image_path = preg_replace('/(\\.[^\\.]+)$/', '.backup$1', $image_path);
         $paths[] = $result_image_path;
         if ($this->rotate($image_path, $result_image_path, $this->angles[$direction])) {
             $count = 0;
             while (!file_exists($result_image_path) && ++$count < 5) {
                 sleep(1);
             }
             if (!file_exists($result_image_path)) {
                 throw new waException(_w("Error while rotate. I/O error"));
             }
             if (!waFiles::move($image_path, $backup_image_path)) {
                 throw new waException(_w("Error while rotate. Operation canceled"));
             }
             $paths[] = $backup_image_path;
             if (!waFiles::move($result_image_path, $image_path)) {
                 if (!waFiles::move($backup_image_path, $image_path)) {
                     throw new waException(_w("Error while rotate. Original file corupted but backuped"));
                 }
                 throw new waException(_w("Error while rotate. Operation canceled"));
             }
             $datetime = date('Y-m-d H:i:s');
             $data = array('edit_datetime' => $datetime, 'width' => $image['height'], 'height' => $image['width']);
             $product_images_model->updateById($id, $data);
             $image = array_merge($image, $data);
             $thumb_dir = shopImage::getThumbsPath($image);
             $back_thumb_dir = preg_replace('@(/$|$)@', '.back$1', $thumb_dir, 1);
             $paths[] = $back_thumb_dir;
             waFiles::delete($back_thumb_dir);
             if (!(waFiles::move($thumb_dir, $back_thumb_dir) || waFiles::delete($back_thumb_dir)) && !waFiles::delete($thumb_dir)) {
                 throw new waException(_w("Error while rebuild thumbnails"));
             }
             $config = $this->getConfig();
             try {
                 shopImage::generateThumbs($image, $config->getImageSizes());
             } catch (Exception $e) {
                 waLog::log($e->getMessage());
             }
             $this->response = $image;
             $edit_datetime_ts = strtotime($image['edit_datetime']);
             $this->response['url_big'] = shopImage::getUrl($image, $config->getImageSize('big')) . '?' . $edit_datetime_ts;
             $this->response['url_crop'] = shopImage::getUrl($image, $config->getImageSize('crop')) . '?' . $edit_datetime_ts;
         }
         foreach ($paths as $path) {
             waFiles::delete($path);
         }
     } catch (Exception $e) {
         foreach ($paths as $path) {
             waFiles::delete($path);
         }
         throw $e;
     }
 }
Exemplo n.º 5
0
 /**
  * Delete one image
  * @param int $id ID of image
  */
 public function delete($id)
 {
     $id = (int) $id;
     if (!$id) {
         return false;
     }
     $image = $this->getById($id);
     if (!$image) {
         return false;
     }
     $product_id = $image['product_id'];
     // first of all try delete files from disk
     waFiles::delete(shopImage::getThumbsPath($image));
     waFiles::delete(shopImage::getPath($image));
     waFiles::delete(shopImage::getOriginalPath($image));
     if (!$this->deleteById($id)) {
         return false;
     }
     // first image for this product is main image for this product
     $main_image = $this->query("SELECT id AS image_id, ext FROM {$this->table} WHERE product_id = {$product_id} ORDER BY sort LIMIT 1")->fetchAssoc();
     if (!$main_image) {
         $main_image = array('image_id' => null, 'ext' => null);
     }
     $product_model = new shopProductModel();
     $product_model->updateById($product_id, $main_image);
     // make NULL image_id for that skus of this product which have image_id equals this image ID
     $this->exec("\n            UPDATE `shop_product_skus` SET image_id = NULL\n            WHERE product_id = {$product_id} AND image_id = {$id}\n        ");
     return true;
 }