public function execute()
 {
     $id = waRequest::post('id', null, waRequest::TYPE_INT);
     if (!$id) {
         throw new waException("Can't rotate photo");
     }
     $direction = waRequest::post('direction', 'left', waRequest::TYPE_STRING_TRIM);
     if (isset($this->derection_angles[$direction])) {
         $photo_model = new photosPhotoModel();
         $photo_rights_model = new photosPhotoRightsModel();
         $photo = $photo_model->getById($id);
         if (!$photo_rights_model->checkRights($photo, true)) {
             throw new waException(_w("You don't have sufficient access rights"));
         }
         $photo_path = photosPhoto::getPhotoPath($photo);
         $paths = array();
         try {
             $image = new photosImage($photo_path);
             $result_photo_path = preg_replace('/(\\.[^\\.]+)$/', '.result$1', $photo_path);
             $backup_photo_path = preg_replace('/(\\.[^\\.]+)$/', '.backup$1', $photo_path);
             $paths[] = $result_photo_path;
             $result = $image->rotate($this->derection_angles[$direction])->save($result_photo_path);
             if ($result) {
                 $count = 0;
                 while (!file_exists($result_photo_path) && ++$count < 5) {
                     sleep(1);
                 }
                 if (!file_exists($result_photo_path)) {
                     throw new waException("Error while rotate. I/O error");
                 }
                 $paths[] = $backup_photo_path;
                 if (waFiles::move($photo_path, $backup_photo_path)) {
                     if (!waFiles::move($result_photo_path, $photo_path)) {
                         if (!waFiles::move($backup_photo_path, $photo_path)) {
                             throw new waException("Error while rotate. Original file corupted but backuped");
                         }
                         throw new waException("Error while rotate. Operation canceled");
                     } else {
                         $edit_datetime = date('Y-m-d H:i:s');
                         $data = array('edit_datetime' => $edit_datetime, 'width' => $photo['height'], 'height' => $photo['width']);
                         $photo_model->updateById($id, $data);
                         $photo = array_merge($photo, $data);
                         $thumb_dir = photosPhoto::getPhotoThumbDir($photo);
                         $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("Error while rebuild thumbnails");
                         }
                     }
                     $photo['thumb'] = photosPhoto::getThumbInfo($photo, photosPhoto::getThumbPhotoSize());
                     $photo['thumb_big'] = photosPhoto::getThumbInfo($photo, photosPhoto::getBigPhotoSize());
                     $photo['thumb_middle'] = photosPhoto::getThumbInfo($photo, photosPhoto::getMiddlePhotoSize());
                     $original_photo_path = photosPhoto::getOriginalPhotoPath($photo);
                     if (wa('photos')->getConfig()->getOption('save_original') && file_exists($original_photo_path)) {
                         $photo['original_exists'] = true;
                     } else {
                         $photo['original_exists'] = false;
                     }
                     $this->response['photo'] = $photo;
                     $this->log('photo_edit', 1);
                     $obligatory_sizes = $this->getConfig()->getSizes();
                     try {
                         photosPhoto::generateThumbs($photo, $obligatory_sizes);
                     } catch (Exception $e) {
                         waLog::log($e->getMessage());
                     }
                 } else {
                     throw new waException("Error while rotate. Operation canceled");
                 }
             }
             foreach ($paths as $path) {
                 waFiles::delete($path);
             }
         } catch (Exception $e) {
             foreach ($paths as $path) {
                 waFiles::delete($path);
             }
             throw $e;
         }
     }
 }
 /**
  * Rename existing theme
  * @param string $id
  * @param array $params
  * @throws waException
  * @return waTheme
  */
 public function move($id, $params = array())
 {
     if ($this->id != $id && (!$this->init('system') || empty($this->info['system']))) {
         self::verify($id);
         $target = wa()->getDataPath("themes/{$id}", true, $this->app, false);
         if (file_exists($target)) {
             throw new waException(sprintf(_ws("Theme %s already exists"), $id));
         }
         self::protect($this->app);
         waFiles::move($this->path, $target);
         $class = get_class($this);
         /**
          * @var waTheme $instance
          */
         $instance = new $class($id, $this->app);
         $instance->init();
         $instance->info['id'] = $id;
         $instance->changed['id'] = true;
         foreach ($params as $param => $value) {
             $instance[$param] = $value;
         }
         $instance->save();
         return $instance;
     } elseif ($this->type == self::ORIGINAL || !empty($this->info['system'])) {
         return $this->copy($id, $params);
     } else {
         foreach ($params as $param => $value) {
             $this[$param] = $value;
         }
         if ($params) {
             $this->save();
         }
         return $this;
     }
 }
 public function execute()
 {
     $this->response = array();
     // Initialize all needed post vars as $vars in current namespace
     foreach (array('x1', 'y1', 'x2', 'y2', 'w', 'h', 'ww', 'orig') as $var) {
         if (null === (${$var} = (int) waRequest::post($var))) {
             // $$ black magic...
             $this->response['error'] = 'wrong parameters';
             return;
         }
     }
     $id = $this->getId();
     $contact = new waContact($id);
     // Path to file we need to crop
     $rand = mt_rand();
     $dir = waContact::getPhotoDir($id, true);
     $filename = wa()->getDataPath("{$dir}{$rand}.original.jpg", true, 'contacts');
     $oldDir = wa()->getDataPath("{$dir}", true, 'contacts');
     $no_old_photo = false;
     if (!$orig) {
         // Delete the old photos if they exist
         if (file_exists($oldDir)) {
             waFiles::delete($oldDir);
             $no_old_photo = true;
         }
         waFiles::create($oldDir);
         // Is there an uploaded file in session?
         $photoEditors = $this->getStorage()->read('photoEditors');
         if (!isset($photoEditors[$id]) || !file_exists($photoEditors[$id])) {
             $this->response['error'] = 'Photo editor session is not found or already expired.';
             return;
         }
         $newFile = $photoEditors[$id];
         // Save the original image in jpeg for future use
         try {
             $img = waImage::factory($newFile)->save($filename);
         } catch (Exception $e) {
             $this->response['error'] = 'Unable to save new file ' . $filename . ' (' . pathinfo($filename, PATHINFO_EXTENSION) . ') as jpeg: ' . $e->getMessage();
             return;
         }
         // Remove uploaded file
         unset($photoEditors[$id]);
         $this->getStorage()->write('photoEditors', $photoEditors);
         unlink($newFile);
     } else {
         // cropping an old file. Move it temporarily to temp dir to delete all cached thumbnails
         $oldFile = wa()->getDataPath("{$dir}{$contact['photo']}.original.jpg", TRUE, 'contacts');
         $tempOldFile = wa()->getTempPath("{$id}/{$rand}.original.jpg", 'contacts');
         waFiles::move($oldFile, $tempOldFile);
         // Delete thumbnails
         if (file_exists($oldDir)) {
             waFiles::delete($oldDir);
         }
         waFiles::create($oldDir);
         // return original image to its proper place
         waFiles::move($tempOldFile, $filename);
     }
     if (!file_exists($filename)) {
         $this->response['error'] = 'Image to crop not found (check directory access rights).';
         return;
     }
     // Crop and save selected area
     $croppedFilename = wa()->getDataPath("{$dir}{$rand}.jpg", TRUE, 'contacts');
     try {
         $img = waImage::factory($filename);
         $scale = $img->width / $ww;
         $img->crop(floor($w * $scale), floor($h * $scale), floor($x1 * $scale), floor($y1 * $scale))->save($croppedFilename);
     } catch (Exception $e) {
         $this->response['error'] = 'Unable to crop an image: ' . $e->getMessage();
         return;
     }
     // Update record in DB for this user
     $contact['photo'] = $rand;
     $contact->save();
     if ($no_old_photo) {
         $old_app = null;
         if (wa()->getApp() !== 'contacts') {
             $old_app = wa()->getApp();
             waSystem::setActive('contacts');
         }
         $this->logAction('photo_add', null, $contact->getId());
         if ($old_app) {
             waSystem::setActive($old_app);
         }
     }
     // Update recent history to reload thumbnail correctly (if not called from personal account)
     if (wa()->getUser()->get('is_user')) {
         $history = new contactsHistoryModel();
         $history->save('/contact/' . $id, null, null, '--');
     }
     $this->response = array('url' => $contact->getPhoto());
 }
 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;
     }
 }
 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 photo");
     }
     $photo_model = new photosPhotoModel();
     $photo_rights_model = new photosPhotoRightsModel();
     $photo = $photo_model->getById($id);
     if (!$photo_rights_model->checkRights($photo, true)) {
         throw new waException("You don't have sufficient access rights");
     }
     $original_photo_path = photosPhoto::getOriginalPhotoPath($photo);
     if (!wa('photos')->getConfig()->getOption('save_original') || !file_exists($original_photo_path)) {
         throw new waException("Can't restore photo. Original photo doesn't exist");
     }
     $paths = array();
     try {
         $photo_path = photosPhoto::getPhotoPath($photo);
         $backup_photo_path = preg_replace('/(\\.[^\\.]+)$/', '.backup$1', $photo_path);
         if (waFiles::move($photo_path, $backup_photo_path)) {
             if (!waFiles::move($original_photo_path, $photo_path)) {
                 if (!waFiles::move($backup_photo_path, $photo_path)) {
                     throw new waException("Error while restore. Current file corupted but backuped");
                 }
                 $paths[] = $backup_photo_path;
                 throw new waException("Error while restore. Operation canceled");
             } else {
                 $image = new photosImage($photo_path);
                 $edit_datetime = date('Y-m-d H:i:s');
                 $data = array('edit_datetime' => $edit_datetime, 'width' => $image->width, 'height' => $image->height);
                 $photo_model->updateById($id, $data);
                 $photo = array_merge($photo, $data);
                 $thumb_dir = photosPhoto::getPhotoThumbDir($photo);
                 $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($thumb_dir)) {
                     throw new waException("Error while rebuild thumbnails");
                 }
                 $photo['original_exists'] = false;
                 $photo['thumb'] = photosPhoto::getThumbInfo($photo, photosPhoto::getThumbPhotoSize());
                 $photo['thumb_big'] = photosPhoto::getThumbInfo($photo, photosPhoto::getBigPhotoSize());
                 $photo['thumb_middle'] = photosPhoto::getThumbInfo($photo, photosPhoto::getMiddlePhotoSize());
                 $sizes = $this->getConfig()->getSizes();
                 try {
                     photosPhoto::generateThumbs($photo, $sizes);
                 } catch (Exception $e) {
                     waLog::log($e->getMessage());
                 }
                 $this->response['photo'] = $photo;
                 $this->log('photo_reverttooriginal', 1);
             }
         } else {
             throw new waException("Error while restore. Operation canceled");
         }
         foreach ($paths as $path) {
             waFiles::delete($path);
         }
     } catch (Exception $e) {
         foreach ($paths as $path) {
             waFiles::delete($path);
         }
         throw $e;
     }
 }
 public function execute()
 {
     $path = $this->getConfig()->getPath('config', 'routing');
     if (file_exists($path)) {
         $routes = (include $path);
     } else {
         $routes = array();
     }
     $domain = siteHelper::getDomain();
     $url = mb_strtolower(rtrim(waRequest::post('url'), '/'));
     if ($url != $domain) {
         $domain_model = new siteDomainModel();
         // domain already exists
         if ($domain_model->getByName($url)) {
             $this->errors = sprintf(_w("Website with a domain name %s is already registered in this Webasyst installation. Delete %s website (Site app > %s > Settings) to be able to use it's domain name for another website."), $url, $url, $url);
             return;
         }
         $domain_model->updateById(siteHelper::getDomainId(), array('name' => $url));
         $routes[$url] = $routes[$domain];
         unset($routes[$domain]);
         // move configs
         $old = $this->getConfig()->getConfigPath('domains/' . $domain . '.php');
         if (file_exists($old)) {
             waFiles::move($old, $this->getConfig()->getConfigPath('domains/' . $url . '.php'));
         }
         $old = wa()->getDataPath('data/' . $domain . '/', true, 'site', false);
         if (file_exists($old)) {
             waFiles::move($old, wa()->getDataPath('data/' . $url . '/', true));
             clearstatcache();
             try {
                 waFiles::delete($old, true);
             } catch (waException $e) {
             }
         }
         $domain = $url;
         siteHelper::setDomain(siteHelper::getDomainId(), $domain);
     }
     // save wa_apps
     $domain_config_path = $this->getConfig()->getConfigPath('domains/' . $domain . '.php');
     if (file_exists($domain_config_path)) {
         $domain_config = (include $domain_config_path);
     } else {
         $domain_config = array();
     }
     $title = waRequest::post('title');
     $style = waRequest::post('background');
     if (!$style || substr($style, 0, 1) == '.') {
         if ($s = $this->saveBackground()) {
             $style = '.' . $s;
         }
     }
     $domain_model = new siteDomainModel();
     $domain_model->updateById(siteHelper::getDomainId(), array('title' => $title, 'style' => $style));
     $save_config = false;
     if ($title) {
         $domain_config['name'] = $title;
         $save_config = true;
     } else {
         if (isset($domain_config['name'])) {
             unset($domain_config['name']);
             $save_config = true;
         }
     }
     waUtils::varExportToFile($routes, $path);
     if (waRequest::post('wa_apps_type')) {
         $apps = waRequest::post('apps');
         if (!$domain_config) {
             // create directory
             waFiles::create($domain_config_path);
         }
         $domain_config['apps'] = array();
         foreach ($apps['url'] as $i => $u) {
             $domain_config['apps'][] = array('url' => $u, 'name' => $apps['name'][$i]);
         }
         $save_config = true;
     } else {
         if (isset($domain_config['apps'])) {
             unset($domain_config['apps']);
             $save_config = true;
         }
     }
     if (waRequest::post('cdn')) {
         $domain_config['cdn'] = waRequest::post('cdn');
         $save_config = true;
     } elseif (!empty($domain_config['cdn'])) {
         unset($domain_config['cdn']);
         $save_config = true;
     }
     // save other settings
     foreach (array('head_js', 'google_analytics') as $key) {
         if (!empty($domain_config[$key]) || waRequest::post($key)) {
             $domain_config[$key] = waRequest::post($key);
             $save_config = true;
         }
     }
     if ($save_config && !waUtils::varExportToFile($domain_config, $domain_config_path)) {
         $this->errors = sprintf(_w('Settings could not be saved due to the insufficient file write permissions for the "%s" folder.'), 'wa-config/apps/site/domains');
     }
     $this->saveFavicon();
     $this->saveTouchicon();
     $this->saveRobots();
     $this->logAction('site_edit');
 }
示例#8
0
 public function rotate($id, $clockwise = true)
 {
     $photo_rights_model = new photosPhotoRightsModel();
     $photo = $this->getById($id);
     if (!$photo || !$photo_rights_model->checkRights($photo, true)) {
         throw new waException(_w("You don't have sufficient access rights"));
     }
     $photo_path = photosPhoto::getPhotoPath($photo);
     $paths = array();
     try {
         $image = new photosImage($photo_path);
         $result_photo_path = preg_replace('/(\\.[^\\.]+)$/', '.result$1', $photo_path);
         $backup_photo_path = preg_replace('/(\\.[^\\.]+)$/', '.backup$1', $photo_path);
         $paths[] = $result_photo_path;
         $angle = $clockwise ? '90' : '-90';
         $result = $image->rotate($angle)->save($result_photo_path);
         if ($result) {
             $count = 0;
             while (!file_exists($result_photo_path) && ++$count < 5) {
                 sleep(1);
             }
             if (!file_exists($result_photo_path)) {
                 throw new waException("Error while rotate. I/O error");
             }
             $paths[] = $backup_photo_path;
             if (waFiles::move($photo_path, $backup_photo_path)) {
                 if (!waFiles::move($result_photo_path, $photo_path)) {
                     if (!waFiles::move($backup_photo_path, $photo_path)) {
                         throw new waException("Error while rotate. Original file corupted but backuped");
                     }
                     throw new waException("Error while rotate. Operation canceled");
                 } else {
                     $edit_datetime = date('Y-m-d H:i:s');
                     $data = array('edit_datetime' => $edit_datetime, 'width' => $photo['height'], 'height' => $photo['width']);
                     $this->updateById($id, $data);
                     $photo = array_merge($photo, $data);
                     $thumb_dir = photosPhoto::getPhotoThumbDir($photo);
                     $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("Error while rebuild thumbnails");
                     }
                 }
                 $obligatory_sizes = wa('photos')->getConfig()->getSizes();
                 try {
                     photosPhoto::generateThumbs($photo, $obligatory_sizes);
                 } catch (Exception $e) {
                     waLog::log($e->getMessage());
                 }
             } else {
                 throw new waException("Error while rotate. Operation canceled");
             }
         }
         foreach ($paths as $path) {
             waFiles::delete($path);
         }
     } catch (Exception $e) {
         foreach ($paths as $path) {
             waFiles::delete($path);
         }
         throw $e;
     }
 }
 protected function finish($filename)
 {
     $result = !!$this->getRequest()->post('cleanup');
     try {
         if ($result) {
             if (wa()->getEnv() == 'backend') {
                 $this->logAction('catalog_export', array('type' => 'YML'));
             }
             $file = $this->getTempPath();
             $target = $this->data['path']['offers'];
             if ($this->data['processed_count']['product']) {
                 if (file_exists($file)) {
                     waFiles::delete($target);
                     waFiles::move($file, $target);
                 }
                 shopYandexmarketPlugin::path('shops.dtd');
                 if (wa()->getEnv() == 'backend') {
                     $this->validate();
                 }
             } else {
                 $this->error('Не выгружено ни одного товарного предложения, файл не обновлен');
                 $this->error(var_export($this->data, true));
             }
         }
     } catch (Exception $ex) {
         $this->error($ex->getMessage());
     }
     $this->info();
     return $result;
 }
示例#10
0
    protected function create($app_id, $path, $params = array())
    {
        $report = '';
        if (!file_exists($path)) {
            $path .= '/';
            mkdir($path);
            mkdir($path . 'css');
            touch($path . 'css/' . $app_id . '.css');
            mkdir($path . 'js');
            touch($path . 'js/' . $app_id . '.js');
            mkdir($path . 'img');
            // lib
            mkdir($path . 'lib');
            waFiles::protect($path . 'lib');
            mkdir($path . 'lib/actions');
            // backend controller
            mkdir($path . 'lib/actions/backend');
            // api
            if (isset($params['api'])) {
                mkdir($path . 'lib/api');
                if ($params['api'] !== true) {
                    mkdir($path . 'lib/api/' . $params['api']);
                } else {
                    mkdir($path . 'lib/api/v1');
                }
            }
            // cli
            if (isset($params['cli'])) {
                mkdir($path . 'lib/cli');
            }
            mkdir($path . 'lib/classes');
            mkdir($path . 'lib/models');
            // config
            mkdir($path . 'lib/config');
            // app description
            $app = array('name' => empty($params['name']) ? ucfirst($app_id) : $params['name'], 'icon' => 'img/' . $app_id . '.gif', 'version' => $version = empty($params['version']) ? '0.1' : $params['version'], 'vendor' => $vendor = empty($params['vendor']) ? '--' : $params['vendor']);
            if (isset($params['frontend'])) {
                $app['frontend'] = true;
                if (isset($params['themes'])) {
                    $app['themes'] = true;
                }
                $routing = array('*' => 'frontend');
                waUtils::varExportToFile($routing, $path . 'lib/config/routing.php');
                // frontend controller
                mkdir($path . 'lib/actions/frontend');
            }
            // plugins
            if (isset($params['plugins'])) {
                $app['plugins'] = true;
                mkdir($path . 'plugins');
            }
            waUtils::varExportToFile($app, $path . 'lib/config/app.php');
            // templates
            mkdir($path . 'templates');
            waFiles::protect($path . 'templates');
            mkdir($path . 'templates/actions');
            mkdir($path . 'templates/actions/backend');
            // backend template
            if (isset($params['frontend'])) {
                // frontend template
                mkdir($path . 'templates/actions/frontend');
            }
            // locale
            mkdir($path . 'locale');
            waFiles::protect($path . 'locale');
            if (isset($params['frontend']) && isset($params['themes'])) {
                // themes
                mkdir($path . 'themes');
                mkdir($path . 'themes/default');
                $theme = new waTheme('default', $app_id, true);
                $theme->name = 'Default theme';
                $theme->description = 'Auto generated default theme';
                $theme->vendor = $vendor;
                $theme->system = 1;
                $theme->addFile('index.html', 'Frontend index file');
                touch($path . 'themes/default/index.html');
                $theme->addFile('default.css', 'Frontend CSS file');
                touch($path . 'themes/default/default.css');
                $theme->version = $version;
                $theme->save();
                waFiles::move($theme->path . '/theme.xml', $path . 'themes/default/theme.xml');
            }
            $report .= <<<REPORT
App with id "{$app_id}" created!

Useful commands:
    #generate app's database description file db.php
    php wa.php generateDb {$app_id}

    #generate app's locale files
    php wa-system/locale/locale.php {$app_id}
REPORT;
            if (isset($params['plugins'])) {
                $report .= "\n\n" . <<<REPORT
    #create a plugin with specified 'plugin_id' for your app
    php wa.php createPlugin {$app_id} plugin_id
REPORT;
            }
            //TODO add hint about compress command
        } else {
            $report .= <<<REPORT
App with id "{$app_id}" already exists.
REPORT;
        }
        print $report . "\n";
    }
示例#11
0
$path = $this->getPath('plugins');
$root = $this->getRootPath();
if (!file_exists($root . '/.svn') && !file_exists($root . '/.git')) {
    $plugin_types = array('shipping', 'payment');
    foreach ($plugin_types as $type) {
        $base_path = $path . '/' . $type . '/';
        foreach (waFiles::listdir($path . '/' . $type) as $plugin) {
            if (preg_match('/[A-Z]/', $plugin)) {
                try {
                    $plugin_path = $base_path . $plugin;
                    $file_name = $plugin_path . '/lib/' . $plugin . ucfirst($type) . '.class.php';
                    $plugin = strtolower($plugin);
                    $dest_file_name = $plugin_path . '/lib/' . $plugin . ucfirst($type) . '.class.php';
                    $dest_plugin_path = $base_path . $plugin;
                    waFiles::move($file_name, $dest_file_name);
                    waFiles::move($plugin_path, $dest_plugin_path);
                } catch (Exception $e) {
                    waLog::log($e->getMessage());
                }
            }
        }
        foreach (waFiles::listdir($path . '/' . $type) as $plugin) {
            if (preg_match('/[A-Z]/', $plugin)) {
                $plugin_path = $base_path . $plugin;
                try {
                    waFiles::delete($plugin_path);
                } catch (Exception $e) {
                    waLog::log($e->getMessage());
                }
            }
        }
 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;
     }
 }
示例#13
0
if (file_exists($file)) {
    include($file);
} else {
    header("HTTP/1.0 404 Not Found");
}
');
waFiles::copy(wa()->getAppPath('lib/config/data/.htaccess', 'contacts'), $path . '/.htaccess');
$old_path = wa()->getDataPath('photo', true, 'contacts', false);
if (file_exists($old_path) && is_dir($old_path)) {
    $model = new waModel();
    $all_success = true;
    $contact_ids = $model->query("SELECT id FROM wa_contact WHERE photo > 0")->fetchAll(null, true);
    foreach ($contact_ids as $contact_id) {
        $old_filepath = $old_path . '/' . $contact_id;
        if (file_exists($old_filepath) && is_dir($old_filepath)) {
            $filepath = wa()->getDataPath(waContact::getPhotoDir($contact_id), true, 'contacts');
            try {
                $success = @waFiles::move($old_filepath, $filepath);
                $all_success = $all_success && $success;
            } catch (Exception $e) {
                $all_success = false;
            }
        }
    }
    if ($all_success) {
        try {
            waFiles::delete(wa()->getDataPath('photo', true, 'contacts', false));
        } catch (waException $e) {
        }
    }
}
    protected function create($params = array())
    {
        //TODO layout|ajax|simple mode
        $structure = array("css/{$this->app_id}.css", "js/{$this->app_id}.js", "img/", "img/{$this->app_id}48.png" => $this->root_path . 'wa-content/img/dummy-app-icon-48.png', "img/{$this->app_id}96.png" => $this->root_path . 'wa-content/img/dummy-app-icon-96.png', "lib/", "lib/actions/backend/", "lib/actions/backend/{$this->app_id}Backend.action.php" => $this->getActionCode(), "templates/actions/backend/Backend.html" => $this->getDefaultTemplate(), "lib/classes/", "lib/models/", "lib/config/", "locale/");
        $features = array_map('trim', preg_split('@[,\\s]+@', ifset($params['features'], $this->getDefaults('features'))));
        // api
        if (in_array('api', $features, true)) {
            $structure = array_merge($structure, array("lib/api/v1/"));
        }
        if (in_array('cli', $features, true)) {
            $structure = array_merge($structure, array("lib/cli/", "lib/cli/{$this->app_id}Example.cli.php" => $this->getCliController()));
        }
        $protect = array('lib', 'templates');
        // app description
        $app = array('name' => empty($params['name']) ? ucfirst($this->app_id) : $params['name'], 'icon' => array(48 => "img/{$this->app_id}48.png", 96 => "img/{$this->app_id}96.png"), 'version' => ifempty($params['version'], $this->getDefaults('version')), 'vendor' => ifempty($params['vendor'], $this->getDefaults('vendor')));
        if (isset($params['frontend'])) {
            $app['frontend'] = true;
            if ($params['frontend'] == 'themes') {
                $app['themes'] = true;
            }
            $routing = array('*' => 'frontend');
            $structure['lib/config/routing.php'] = $routing;
            $structure = array_merge($structure, array('lib/actions/frontend/', "lib/actions/frontend/{$this->app_id}Frontend.action.php" => $this->getActionCode('default', false, $app)));
            if (!empty($app['themes'])) {
                $structure = array_merge($structure, array('themes/.htaccess' => '
<FilesMatch "\\.(php\\d*|html?|xml)$">
    Deny from all
</FilesMatch>
', 'themes/default/index.html' => $this->getFrontendTemplate(), 'themes/default/css/default.css'));
            } else {
                $structure = array_merge($structure, array("templates/actions/frontend/Frontend.html" => $this->getFrontendTemplate(), "css/frontend/{$this->app_id}.css"));
            }
        }
        if (isset($params['plugins'])) {
            $structure = array_merge($structure, array("plugins/"));
            $app['plugins'] = true;
        }
        $structure['lib/config/app.php'] = $app;
        $this->createStructure($structure);
        $this->protect($protect);
        if (!empty($app['themes'])) {
            waFiles::delete(wa()->getDataPath('themes/default', true, $this->app_id));
            $theme = new waTheme('default', $this->app_id, true);
            $theme->name = 'Default theme';
            $theme->description = 'Auto generated default theme';
            $theme->vendor = $app['vendor'];
            $theme->version = $app['version'];
            $theme->addFile('index.html', 'Frontend index file');
            $theme->addFile('css/default.css', 'Frontend CSS file');
            $theme->save();
            waFiles::move($theme->path . '/theme.xml', $this->path . 'themes/default/theme.xml');
        }
        if (!isset($params['disable'])) {
            $this->installApp();
            $errors = $this->flushCache();
            if ($errors) {
                print "Error during delete cache files:\n\t" . implode("\n\t", $errors) . "\n";
            }
        }
        return $app;
    }