public function action() { // подготавливаю данные $country = HD::find($this->country)->getField('name'); $town = HDtown::find($this->town)->getField('name'); $datetime = $this->date->format('Y-m-d') . ' ' . $this->time; // получаю данные Дизайна Человека $extractor = new \app\modules\HumanDesign\calculate\YourHumanDesignRu(); $data = $extractor->calc(new \DateTime($datetime), $country, $town); // сохраняю картинку $url = new \cs\services\Url($data->image); $path = new SitePath('/upload/HumanDesign'); $path->add([Yii::$app->user->id, 8, $url->getExtension()]); $path->write($url->read()); $data->image = $path->getPath(); // обновляю пользовтельские данные /** @var \app\models\User $user */ $user = Yii::$app->user->identity; $fields = ['human_design' => $data->getJson(), 'birth_date' => $this->date->format('Y-m-d'), 'birth_time' => $this->time . ':00', 'birth_country' => $this->country, 'birth_town' => $this->town]; $user->update($fields); return true; }
/** * AJAX * Удаляет дизайн человека * * @return string */ public function actionProfile_human_design_delete() { /** @var \app\models\User $user */ $user = Yii::$app->user->identity; $hd = $user->getHumanDesign(); $path = new SitePath($hd->getImage()); $path->deleteFile(); $user->update(['human_design' => null]); return self::jsonSuccess(); }
/** * Выбирает все картинки копирует в папку назначения заменяет в $content и возвращает * * @param \simple_html_dom | string $content контент * @param SitePath | string $destination путь к папке назначения, она должна существовать * * @return string */ public static function copyImages($content, $destination) { if ($content == '') { return ''; } if (!$content instanceof \simple_html_dom) { require_once Yii::getAlias('@csRoot/services/simplehtmldom_1_5/simple_html_dom.php'); $content = str_get_html($content); } foreach ($content->find('img') as $element) { $imagePath = new SitePath($element->attr['src']); // картинка не содержит путь назначения? if (!Str::isContain($element->attr['src'], $destination->getPath())) { $urlInfo = parse_url($element->attr['src']); if (ArrayHelper::getValue($urlInfo, 'scheme', '') == '') { try { $destinationFile = $destination->cloneObject()->add($imagePath->getFileName()); self::resizeImage($imagePath->getPathFull(), $destinationFile->getPathFull()); $element->attr['src'] = $destinationFile->getPath(); } catch (\Exception $e) { Yii::warning($e->getMessage(), 'gs\\HtmlContent\\copyImages'); } } else { // картинка на внешнем сервере, пока ничего не делаем } } } return $content->root->outertext(); }
/** * Сохраняет картинку по формату * * @param \cs\services\File $file * @param \cs\services\SitePath $destination * @param array $field * @param array | false $format => [ * 3000, * 3000, * FileUpload::MODE_THUMBNAIL_OUTBOUND * 'isExpandSmall' => true, * ] , * * @return \cs\services\SitePath */ private static function saveImage($file, $destination, $format, $field) { if ($format === false || is_null($format)) { $file->save($destination->getPathFull()); return $destination; } $widthFormat = 1; $heightFormat = 1; if (is_numeric($format)) { // Обрезать квадрат $widthFormat = $format; $heightFormat = $format; } else { if (is_array($format)) { $widthFormat = $format[0]; $heightFormat = $format[1]; } } // generate a thumbnail image $mode = ArrayHelper::getValue($format, 2, self::MODE_THUMBNAIL_CUT); if ($file->isContent()) { $image = Image::getImagine()->load($file->content); } else { $image = Image::getImagine()->open($file->path); } if (ArrayHelper::getValue($format, 'isExpandSmall', true)) { $image = self::expandImage($image, $widthFormat, $heightFormat, $mode); } $quality = ArrayHelper::getValue($field, 'widget.1.options.quality', 80); $options = ['quality' => $quality]; $image->thumbnail(new Box($widthFormat, $heightFormat), $mode)->save($destination->getPathFull(), $options); return $destination; }
/** * @param self $folder * @param string $fileName новое название файла, по умолчанию берется имя из себя * * @return self файл назначения * @throws \Exception */ public function copyToFolder($folder, $fileName = null) { if (is_null($fileName)) { $fileName = $this->getFileName(); } $ret = $folder->cloneObject(); $ret->add($fileName); @copy($this->getPathFull(), $ret->getPathFull()); return $ret; }
/** * Выбирает все картинки копирует в папку назначения заменяет в $content и возвращает * * @param \simple_html_dom | string $content контент * @param SitePath | string $destination путь к папке назначения, она должна существовать * @param bool $isCopyFromRemoteHost копировать с внешних источников картинки? * * @return string */ public static function copyImages2($content, $destination, $isCopyFromRemoteHost = false) { if ($content == '') { return ''; } // выбираю все изображения из контента $start = 0; $ret = []; do { $pos = Str::pos('src="/upload/HtmlContent/', $content, $start); if ($pos === false) { break; } $end = Str::pos('"', $content, $pos + 5); $src = Str::sub($content, $pos + 5, $end - $pos - 5); $ret[] = $src; $start = $end; } while (true); foreach ($ret as $src) { $imagePath = new SitePath($src); // картинка не содержит путь назначения? if (!Str::isContain($src, $destination->getPath())) { try { $destinationFile = $destination->cloneObject()->add($imagePath->getFileName()); self::resizeImage($imagePath->getPathFull(), $destinationFile->getPathFull()); $content = Str::replace('src="' . $src . '"', 'src="' . $destinationFile->getPath() . '"', $content); } catch (\Exception $e) { Yii::warning($e->getMessage(), 'gs\\HtmlContent\\copyImages'); } } } return $content; }