Esempio n. 1
0
 protected function checkUploadAction()
 {
     $uploadedFile = Input::file('file_data');
     if (!Request::isMethod('POST') || !is_object($uploadedFile)) {
         return;
     }
     $validationRules = [];
     /*
      * Validate file types
      */
     if (count($this->fileTypes)) {
         $mimes = trim(implode(',', (array) $this->fileTypes));
         $mimes = str_replace('.', '', $mimes);
         // ['mimes:png,jpg,jpeg'];
         if ($mimes != '*') {
             $validationRules[] = 'mimes:' . $mimes;
         }
     }
     $validation = Validator::make(['file_data' => $uploadedFile], ['file_data' => $validationRules]);
     if ($validation->fails()) {
         throw new ValidationException($validation);
     }
     if (!$uploadedFile->isValid()) {
         throw new ApplicationException(sprintf('File %s is not valid.', $uploadedFile->getClientOriginalName()));
     }
     $file = new File();
     $file->data = $uploadedFile;
     $file->is_public = true;
     $file->save();
     $this->model->{$this->attribute}()->add($file, $this->getSessionKey());
     return ['id' => $file->id, 'path' => $file->getPath()];
 }
Esempio n. 2
0
 /**
  * Save the first image result from Google.
  *
  * @param string $query  Search query
  * @param int    $height Resize height
  * @param int    $width  Resize width
  * @param string $path   Path to store the image (will use temp as default)
  *
  * @return System\Models\File|void Created file object
  */
 public static function search($query, $height = 300, $width = 300, $path = null)
 {
     // Prepare the query
     $query = urlencode($query);
     // Prepare path
     $path = $path ?: tempnam(sys_get_temp_dir(), 'image');
     // Use Google Image
     $results = file_get_contents('https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=' . $query);
     if ($results && ($json = json_decode($results, true))) {
         foreach ($json['responseData']['results'] as $image) {
             if (isset($image['url'])) {
                 // Retrive the image
                 $url = $image['url'];
                 $content = @file_get_contents($url);
                 if (!$content) {
                     break;
                 }
                 // Save the image
                 $file_path = $path . basename($url);
                 file_put_contents($file_path, $content);
                 // Resize
                 Resizer::open($file_path)->resize($height, $width)->save($file_path, 100);
                 // Create File object
                 $file = new File();
                 $file->data = $file_path;
                 $file->save();
                 return $file;
             }
         }
     }
 }
 public function run()
 {
     $categories = [['name' => 'Мебель', 'slug' => 'furniture'], ['name' => 'Посуда', 'slug' => 'dishes'], ['name' => 'Аксессуары', 'slug' => 'accessories'], ['name' => 'Кольца', 'slug' => 'rings'], ['name' => 'Заколки', 'slug' => 'hairpins'], ['name' => 'Серьги', 'slug' => 'earrings']];
     $data = [['title' => 'Доска-подставка под горячее', 'content' => ['description' => 'Осина, склейка. Обработка — масло', 'price' => '1000', 'tags' => ['подносы', 'деревяннаяпосуда']], 'categories' => ['dishes'], 'images' => ['cooking_boards_1.jpg', 'cooking_boards_2.jpg']], ['title' => 'Ложки-близняшки', 'content' => ['description' => 'Липа', 'price' => '1000', 'tags' => ['ложкидеревянные', 'деревяннаяпосуда']], 'categories' => ['dishes'], 'images' => ['spoon_1.jpg', 'spoon_2.jpg', 'spoon_3.jpg']], ['title' => 'Серьги «Треугольник»', 'content' => ['description' => 'Орех, хир. сталь', 'price' => '1000', 'tags' => ['серьгиручнойработы', 'серьгииздерева', 'серрежки', 'минимализм']], 'categories' => ['accessories', 'earrings'], 'images' => ['treugolnik_001.jpg']], ['title' => 'Серия сержек «Супрематизм»', 'content' => ['description' => 'Орех, хир. сталь', 'price' => '1000', 'tags' => ['серьгиручнойработы', 'серьгииздерева', 'сережки']], 'categories' => ['accessories', 'earrings'], 'images' => ['kvadro.jpg', 'lisichkini_usgki_1.jpg', 'lisichkini_usgki_2.jpg', 'suprematizm_1.jpg']], ['title' => 'Серьги «Параллелепипед»', 'content' => ['description' => 'Клён, хир. сталь', 'price' => '1000', 'tags' => ['серьгиручнойработы', 'серьгииздерева', 'сережки', 'клен']], 'categories' => ['accessories', 'earrings'], 'images' => ['parallelepiped_1.jpg', 'parallelepiped_2.jpg']], ['title' => 'Серьги «Палочки»', 'content' => ['description' => 'Венге, клён, хир. сталь', 'price' => 'Цена', 'tags' => ['серьгиручнойработы', 'серьгииздерева', 'сережки', 'палочки']], 'categories' => ['accessories', 'earrings'], 'images' => ['palochki.jpg']], ['title' => 'Серьги «Лодочки»', 'content' => ['description' => 'Клён, хир. сталь', 'price' => 'Цена', 'tags' => []], 'categories' => ['accessories', 'earrings'], 'images' => ['lodochki_1.jpg', 'lodochki_2.jpg']], ['title' => 'Серьги «Квадрат»', 'content' => ['description' => 'Орех, хир. сталь', 'price' => '1000', 'tags' => ['серьгиручнойработы', 'серьгииздерева', 'сережки']], 'categories' => ['accessories', 'earrings'], 'images' => ['kvadrat.jpg']], ['title' => 'Серьги «Круг»', 'content' => ['description' => 'Орех, хир. сталь', 'price' => '1000', 'tags' => ['серьгиручнойработы', 'серьгииздерева', 'сережки']], 'categories' => ['accessories', 'earrings'], 'images' => ['krug_1.jpg', 'krug_2.jpg']], ['title' => 'Серьги «Корельская берёза»', 'content' => ['description' => 'Корельская берёза, хир. сталь', 'price' => '1000', 'tags' => ['серьгиручнойработы', 'серьгииздерева', 'сережки']], 'categories' => ['accessories', 'earrings'], 'images' => ['korelskai_bereza_1.jpg', 'korelskai_bereza_2.jpg', 'korelskai_bereza_3.jpg']], ['title' => 'Серьги «Конус»', 'content' => ['description' => 'Орех, хир. сталь', 'price' => '1000', 'tags' => ['серьгиручнойработы', 'серьгииздерева', 'сережки', 'гвоздики']], 'categories' => ['accessories', 'earrings'], 'images' => ['konus_1.jpg', 'konus_2.jpg']], ['title' => 'Серьги «Кленовая коллекция»', 'content' => ['description' => 'Клён, хир. сталь', 'price' => '1000', 'tags' => ['серьгиручнойработы', 'серьгииздерева', 'сережки', 'клен']], 'categories' => ['accessories', 'earrings'], 'images' => ['klen_collection_kolos.jpg']], ['title' => 'Серьги из серии «Геометрия»', 'content' => ['description' => 'Орех, хир. сталь', 'price' => '1000', 'tags' => ['серьгиручнойработы', 'серьгииздерева', 'сережки']], 'categories' => ['accessories', 'earrings'], 'images' => ['geometry_collection_1.jpg', 'geometry_collection_2.jpg']], ['title' => 'Заколка декоративная «Анна»', 'content' => ['description' => 'Красное дерево', 'price' => '1000', 'tags' => ['шпильки', 'деревянныешпильки', 'заколкидляволос', 'заколки', 'заколкииздерева']], 'categories' => ['accessories', 'hairpins'], 'images' => ['anna_kolos.jpg', 'anna_kolos_02.jpg']], ['title' => 'Заколка «Ушки»', 'content' => ['description' => 'Переклейка, венге шпон', 'price' => '1000', 'tags' => ['шпильки', 'деревянныешпильки', 'заколкидляволос', 'заколки', 'заколкииздерева']], 'categories' => ['accessories', 'hairpins'], 'images' => ['shpilky_kolos_01.jpg']], ['title' => 'Заколка «Спутник»', 'content' => ['description' => 'Русский орех', 'price' => '1000', 'tags' => ['шпильки', 'деревянныешпильки', 'заколкидляволос', 'заколки', 'заколкииздерева']], 'categories' => ['accessories', 'hairpins'], 'images' => ['sputnik.jpg', 'sputnik_02.jpg', 'sputnik_03.jpg', 'sputnik_04.jpg']], ['title' => 'Заколка «Биоформа»', 'content' => ['description' => 'Ольха', 'price' => '1000', 'tags' => ['шпильки', 'деревянныешпильки', 'заколкидляволос', 'заколки', 'заколкииздерева']], 'categories' => ['accessories', 'hairpins'], 'images' => ['bio_03.jpg', 'bio_01.jpg', 'bio_02.jpg']], ['title' => 'Кольцо «Грани»', 'content' => ['description' => 'Русский орех, масло', 'price' => '1000', 'tags' => ['кольцо', 'кольцоиздерева', 'граненоекольцо', 'орех', 'дерево']], 'categories' => ['accessories', 'rings'], 'images' => ['grani_001.jpg']], ['title' => 'Кольцо «Костет»', 'content' => ['description' => 'Дуб, масло', 'price' => '1000', 'tags' => ['кольцоиздерева', 'костет', 'костетиздерева', 'дерево', 'дизайнспб', 'дуб']], 'categories' => ['accessories', 'rings'], 'images' => ['ring_kostet_01.jpg', 'ring_kostet_02.jpg', 'ring_kostet_03.jpg']], ['title' => 'Кольца на мизинец', 'content' => ['description' => 'Различные породы деревьев', 'price' => '700', 'tags' => ['кольцоиздерева', 'кольцорунойработы', 'дерево', 'дизайнспб']], 'categories' => ['accessories', 'rings'], 'images' => ['mizinec_001.jpg', 'mizinec_grange_001.jpg', 'mizinec_grange_002.jpg', 'mizinec_tiger_eye.jpg']], ['title' => 'Кольцо «Ольха большая»', 'content' => ['description' => 'Ольха, масло', 'price' => '1000', 'tags' => ['кольцоиздерева', 'кольцоназаказ', 'ольха', 'дизайнспб']], 'categories' => ['accessories', 'rings'], 'images' => ['olxa_001.jpg', 'olxa_002.jpg']], ['title' => 'Кольцо «Ольха круглая»', 'content' => ['description' => 'Ольха, масло', 'price' => '1000', 'tags' => ['кольцоиздерева', 'ольха', 'дизайнспб']], 'categories' => ['accessories', 'rings'], 'images' => ['olxa_kruglai_001.jpg', 'olxa_kruglai_002.jpg']], ['title' => 'Кольцо «Перстень»', 'content' => ['description' => 'Орех, масло', 'price' => '1000', 'tags' => ['кольцоиздерева', 'орех', 'дизайнспб']], 'categories' => ['accessories', 'rings'], 'images' => ['persten_001.jpg', 'persten_002.jpg', 'persten_003.jpg']], ['title' => 'Кольцо «Точечка»', 'content' => ['description' => 'Клен + вставка венге, воск', 'price' => '1000', 'tags' => ['кольцоиздерева', 'точка', 'минимализм', 'дизайниздерева']], 'categories' => ['accessories', 'rings'], 'images' => ['tochechka_001.jpg', 'tochechka_002.jpg', 'tochechka_003.jpg', 'tochechka_004.jpg']], ['title' => 'Кольцо «Тоннель»', 'content' => ['description' => 'Орех, масло', 'price' => '1000', 'tags' => ['кольцоиздерева', 'большоекольцо', 'украшенияручнойработы', 'минимализм', 'хипстота']], 'categories' => ['accessories', 'rings'], 'images' => ['tonnel_001.jpg', 'tonnel_002.jpg', 'tonnel_003.jpg', 'tonnel_004.jpg']], ['title' => 'Кольцо «Трио»', 'content' => ['description' => 'Дуб, масло', 'price' => '1000', 'tags' => ['треугольник', 'круг', 'квадрат', 'триптих', 'трио', 'дуб', 'супрематизм']], 'categories' => ['accessories', 'rings'], 'images' => ['trio_001.jpg', 'trio_002.jpg', 'trio_003.jpg']], ['title' => 'Кольцо «Twix»', 'content' => ['description' => 'Клен и Орех, масло', 'price' => '1000', 'tags' => ['кольцоиздерева', 'twix', 'сладкаяпарочка', 'диптих', 'коллекцияколец']], 'categories' => ['accessories', 'rings'], 'images' => ['twix_black_01.jpg', 'twix_black_02.jpg', 'twix_black_03.jpg', 'twix_collection.jpg', 'twix_whit_01.jpg', 'twix_whit_02.jpg', 'twix_whit_03.jpg', 'twix_whit_04.jpg']], ['title' => 'Кольцо «Усеченный цилиндр»', 'content' => ['description' => 'Ольха, масло', 'price' => '1000', 'tags' => ['кольцоиздерева', 'ручнаработа', 'кольцоручнойработы', 'дизайн']], 'categories' => ['accessories', 'rings'], 'images' => ['usechennii_cilindr_001.jpg', 'usechennii_cilindr_002.jpg']], ['title' => 'Кольцо «Вставка венге»', 'content' => ['description' => 'Клен + вставка шпона венге', 'price' => '1000', 'tags' => ['кольцоиздерева']], 'categories' => ['accessories', 'rings'], 'images' => ['spon_vstavka_kolos.jpg']], ['title' => 'Кольцо «Хребет»', 'content' => ['description' => 'Осина, масло', 'price' => '1000', 'tags' => ['кольцоиздерева', 'осина', 'дизайниздерева', 'минимализм', 'ручнаяработа']], 'categories' => ['accessories', 'rings'], 'images' => ['xrebet_001.jpg', 'xrebet_002.jpg']], ['title' => 'Кольцо «Зебра»', 'content' => ['description' => 'Клен + вставка шпона венге, масло', 'price' => '1000', 'tags' => ['кольцоиздерева', 'зебра', 'клен', 'венге', 'украшениеиздерева', 'дизайн']], 'categories' => ['accessories', 'rings'], 'images' => ['zebra_001.jpg', 'zebra_002.jpg']]];
     foreach ($categories as $key => $category) {
         Category::create($category);
     }
     foreach ($data as $product) {
         if (array_key_exists('images', $product)) {
             $images = $product['images'];
             unset($product['images']);
         }
         if (array_key_exists('categories', $product)) {
             $categories = $product['categories'];
             unset($product['categories']);
         }
         if (array_key_exists('tags', $product['content'])) {
             $tags = $product['content']['tags'];
             unset($product['content']['tags']);
         }
         $product['published'] = true;
         $product['published_at'] = date('Y-m-d H:i:s', rand(strtotime('2015-01-01'), strtotime('2015-09-01')));
         $model = Product::create($product);
         foreach ($categories as $slug) {
             $category = '';
             $category = Category::where('slug', '=', $slug)->first();
             // print_r($category);
             if (!is_null($category)) {
                 $model->categories()->add($category, null);
             }
         }
         foreach ($tags as $name) {
             $tag = '';
             $tag = Tag::where('name', '=', $name)->first();
             // print_r($category);
             if (is_null($tag)) {
                 $tag = Tag::create(['name' => $name]);
             }
             if (!is_null($tag)) {
                 $model->tags()->add($tag, null);
             }
         }
         foreach ($images as $key => $image) {
             $filePath = "./storage/app/images/" . $image;
             if (!file_exists($filePath)) {
                 echo 'File ' . $filePath . ' not exists.' . "\n";
                 continue;
             }
             $file = new File();
             $file->fromFile($filePath);
             $file['title'] = $model->title;
             $file['description'] = $model->content['description'];
             $model->featured_images()->save($file, null);
             // if ($key == 0) {
             //     $model->cover()->save($file, null);
             // }
         }
     }
 }
 public function run()
 {
     $driver = Driver::firstOrCreate(['name' => 'U.S. Postal Service', 'type' => 'shipping', 'class' => 'Bedard\\USPS\\Classes\\USPS', 'is_configurable' => true, 'is_default' => false]);
     $logo = new File();
     $logo->fromFile(plugins_path('bedard/usps/assets/images/usps.png'));
     $logo->save();
     $driver->image()->add($logo);
 }
Esempio n. 5
0
 public function onAvatarUpdate()
 {
     $file = new File();
     $file->data = Input::file('avatar');
     $file->save();
     $this->AvaUser->avatar()->add($file);
     return Redirect::intended($this->pageUrl($this->property('redirect')));
 }
Esempio n. 6
0
 private function processFileUploadPhoto($id, $uploadedFile)
 {
     $file = new System\Models\File();
     $file->data = $uploadedFile;
     $file->save();
     $mhs = PendaftaranWisuda::find($id);
     $mhs->photo_ijazah()->add($file);
 }
Esempio n. 7
0
 private function processFileUpload($id, $uploadedFile)
 {
     $file = new System\Models\File();
     $file->data = $uploadedFile;
     $file->save();
     $mhs = IdentitasMahasiswa::find($id);
     $mhs->photo()->add($file);
 }
Esempio n. 8
0
 private function assignImages($model, $fileData)
 {
     if (array_key_exists($model->slug, $fileData)) {
         $images = $fileData[$model->slug];
         // print_r($images);
         echo $model->slug . " [";
         // echo get_class($model) . "\n";
         if (!is_array($images)) {
             return;
         }
         foreach ($images as $key => $filePath) {
             if (!is_array($filePath)) {
                 $pathinfo = pathinfo($filePath);
                 $check = File::where('attachment_id', '=', $model->id)->where('attachment_type', '=', get_class($model))->where('file_name', '=', $pathinfo['basename'])->first();
                 if (!is_null($check)) {
                     // echo $filePath . " ";
                     // echo filemtime($filePath) . " ";
                     // echo $check->updated_at->timestamp . "\n";
                     if (filemtime($filePath) > $check->updated_at->timestamp) {
                         // echo "File " . $filePath . " is Newer. Update!" . "\n";
                         echo "^";
                         $check->delete();
                     } else {
                         echo "~";
                         continue;
                     }
                 } else {
                     // echo "File " . $filePath . " is New. Create!" . "\n";
                     echo "+";
                 }
                 $file = new File();
                 $file->fromFile($filePath);
                 switch ($key) {
                     case 'cover':
                         $model->cover()->save($file, null, ['title' => $model->title]);
                         break;
                     default:
                         echo ' Image ' . $filePath . ' not saved.' . "\n";
                         break;
                 }
             }
         }
         echo "]\n";
     } else {
         // preg_match_all('#<img.+?src="(.+?)"#', $model->content, $matches);
         // // $images = $matches[1];
         // $images = array_filter($matches[1], function ($value) {
         //     return !preg_match('#^https?\:\/\/#', $value);
         // });
         // if (count($images) != 0) {
         //     $filePath = $images[0];
         //     // echo $model->title . " -- " . $filePath . "\n";
         //     $file = new File();
         //     $file->fromFile("./" . $filePath);
         //     $model->cover()->save($file, null, ['title' => $model->title]);
         // }
     }
 }
Esempio n. 9
0
 private function assignImage($field, $filePath, $model)
 {
     $file = new File();
     $file->fromFile($filePath);
     if (!is_null($model->{$field}) && strtotime($model->{$field}->updated_at) < filemtime($filePath)) {
         echo "Update " . $field . " by file " . $file->getFilename() . "\n";
         $model->{$field}->delete();
         $model->{$field}()->save($file);
     }
 }
 /**
  * @param $username
  *
  * @return string|null
  */
 private function findAvatar($username)
 {
     $library = MediaLibrary::instance();
     $files = $library->listFolderContents($this->imageStoragePath, 'title', 'image');
     foreach ($files as $file) {
         $pathinfo = pathinfo($file->publicUrl);
         if ($pathinfo['filename'] == $username) {
             $file = new File();
             $file->is_public = $this->imagePublic;
             $file->fromFile(base_path() . $pathinfo['dirname'] . '/' . $pathinfo['basename']);
             return $file;
         }
     }
 }
Esempio n. 11
0
 public function boot()
 {
     FileBase::extend(function ($model) {
         $model->hasOne['exif'] = ['Hambern\\Exify\\Models\\Exif', 'delete' => true];
     });
     FileBase::extend(function ($model) {
         $model->bindEvent('model.afterCreate', function () use($model) {
             if (strpos($model->content_type, 'image') !== false) {
                 $reader = Reader::factory(Reader::TYPE_NATIVE);
                 $path = 'http://' . $_SERVER['SERVER_NAME'] . $model->path;
                 $data = $reader->read($path)->getData();
                 foreach ($data as $k => $v) {
                     $fill[snake_case($k)] = $v;
                 }
                 $exif = Exif::make($fill);
                 $model->exif()->save($exif);
             }
         });
         $model->bindEvent('model.beforeDelete', function () use($model) {
             if (strpos($model->content_type, 'image') !== false) {
                 $model->exif()->delete();
             }
         });
     });
 }
Esempio n. 12
0
 public function get($code = null)
 {
     try {
         if (!$code) {
             throw new ApplicationException('Missing code');
         }
         $parts = explode('!', base64_decode($code));
         if (count($parts) < 2) {
             throw new ApplicationException('Invalid code');
         }
         list($id, $hash) = $parts;
         if (!($file = FileModel::find((int) $id))) {
             throw new ApplicationException('Unable to find file');
         }
         $verifyCode = self::getUniqueCode($file);
         if ($code != $verifyCode) {
             throw new ApplicationException('Invalid hash');
         }
         echo $file->output();
         exit;
     } catch (Exception $ex) {
     }
     /*
      * Fall back on Cms controller
      */
     return App::make('Cms\\Classes\\Controller')->setStatusCode(404)->run('/404');
 }
Esempio n. 13
0
 /**
  * Create file from path, save it and return File object
  *
  * @param $path
  * @param $public
  *
  * @return File
  */
 protected function getSavedFile($path, $public = true)
 {
     $file = new File();
     $file->is_public = $public;
     $file->fromFile($path);
     $file->save();
     return $file;
 }
Esempio n. 14
0
 public function testDeleteFlagSoftDeleteModel()
 {
     Model::unguard();
     $user = SoftDeleteUser::create(['name' => 'Stevie', 'email' => '*****@*****.**']);
     Model::reguard();
     $user->avatar()->create(['data' => base_path() . '/tests/fixtures/plugins/database/tester/assets/images/avatar.png']);
     $this->assertNotNull($user->avatar);
     $avatarId = $user->avatar->id;
     $user->delete();
     $this->assertNotNull(FileModel::find($avatarId));
 }
Esempio n. 15
0
 /**
  * Add image size information.
  *
  * @param  \Symfony\Component\HttpFoundation\File\UploadedFile  $uploadedFile
  * @return  File
  */
 public function fromPost($uploadedFile)
 {
     if (!is_null($uploadedFile)) {
         parent::fromPost($uploadedFile);
         if ($this->isImage() && $this->hasFile($this->disk_name)) {
             list($width, $height) = getimagesize($uploadedFile->getRealPath());
             $width and $this->image_width = $width;
             $height and $this->image_height = $height;
         }
     }
     return $this;
 }
Esempio n. 16
0
 public function loadUserInfo()
 {
     $peopleWithAvatars = [];
     $avatars = Avatar::where('attachment_type', 'RainLab\\User\\Models\\User')->where('field', 'avatar')->get();
     foreach ($avatars as $avatr) {
         $this->avatars[$avatr->attachment_id] = ['t600' => $avatr->getThumb(600, 600), 't200' => $avatr->getThumb(200, 200), 'filename' => $avatr->filename];
         $peopleWithAvatars[] = $avatr->attachment_id;
     }
     // Set Pagination parameters
     $this->perPage = $this->property('PicsPerPage', 12);
     $this->currentPage = input('page', 1);
     $sort3 = null;
     /*
      * Sorting
      */
     switch ($this->sort) {
         case 'last':
             $sort1 = 'surname';
             $sort2 = 'name';
             break;
         case 'given':
             $sort1 = 'name';
             $sort2 = 'surname';
             break;
         default:
             $sort1 = 'primary_usergroup';
             $sort2 = 'surname';
             $sort3 = 'name';
     }
     $people = user::wherein('id', $peopleWithAvatars)->orderBy($sort1)->orderBy($sort2);
     if ($sort3) {
         $people->orderBy($sort3);
     }
     $this->people = $people->paginate($this->perPage, $this->currentPage);
     /*
      * Pagination
      */
     if ($this->people) {
         $queryArr = [];
         $queryArr['sort'] = $this->sort;
         $queryArr['page'] = '';
         $paginationUrl = Request::url() . '?' . http_build_query($queryArr);
         if ($this->currentPage > ($this->lastPage = $this->people->lastPage()) && $this->currentPage > 1) {
             return Redirect::to($paginationUrl . $this->lastPage);
         }
         $this->firstItem = $this->people->firstItem();
         $this->lastItem = $this->people->lastItem();
         $this->total = $this->people->total();
         $this->paginationUrl = $paginationUrl;
     }
     return $this->people;
 }
Esempio n. 17
0
 public function formAfterDelete($model)
 {
     $fields = json_decode($model->fields);
     foreach ($fields as $value) {
         if (\Str::startsWith($value, 'attachment::')) {
             $id = explode('::', $value)[1];
             $file = \System\Models\File::find($id);
             if ($file) {
                 $file->delete();
             }
         }
     }
 }
 private function assignImages($model, $fileData)
 {
     if (array_key_exists($model->slug, $fileData)) {
         $images = $fileData[$model->slug];
         echo $model->slug . " [";
         foreach ($images as $key => $filePath) {
             if (!is_array($filePath)) {
                 $pathinfo = pathinfo($filePath);
                 $check = File::where('attachment_id', '=', $model->id)->where('attachment_type', '=', get_class($model))->where('file_name', '=', $pathinfo['basename'])->first();
                 if (!is_null($check)) {
                     if (filemtime($filePath) > $check->updated_at->timestamp) {
                         echo "^";
                         $check->delete();
                     } else {
                         echo "~";
                         continue;
                     }
                 } else {
                     echo "+";
                 }
                 $file = new File();
                 $file->fromFile($filePath);
                 switch ($key) {
                     case 'logo_color':
                         $model->logo_color()->save($file, null, ['title' => $model->title]);
                         break;
                     case 'logo_bw':
                         $model->logo_bw()->save($file, null, ['title' => $model->title]);
                         break;
                     default:
                         echo ' Image ' . $filePath . ' not saved.' . "\n";
                         break;
                 }
             }
         }
         echo "]\n";
     }
 }
Esempio n. 19
0
 protected function checkUploadPostback()
 {
     if (!post('X_BLOG_IMAGE_UPLOAD')) {
         return;
     }
     $uploadedFileName = null;
     try {
         $uploadedFile = Input::file('file');
         if ($uploadedFile) {
             $uploadedFileName = $uploadedFile->getClientOriginalName();
         }
         $validationRules = ['max:' . File::getMaxFilesize()];
         $validationRules[] = 'mimes:jpg,jpeg,bmp,png,gif';
         $validation = Validator::make(['file_data' => $uploadedFile], ['file_data' => $validationRules]);
         if ($validation->fails()) {
             throw new ValidationException($validation);
         }
         if (!$uploadedFile->isValid()) {
             throw new SystemException(Lang::get('cms::lang.asset.file_not_valid'));
         }
         $fileRelation = $this->model->content_images();
         $file = new File();
         $file->data = $uploadedFile;
         $file->is_public = true;
         $file->save();
         $fileRelation->add($file, $this->sessionKey);
         $result = ['file' => $uploadedFileName, 'path' => $file->getPath()];
         $response = Response::make()->setContent($result);
         $response->send();
         die;
     } catch (Exception $ex) {
         $message = $uploadedFileName ? Lang::get('cms::lang.asset.error_uploading_file', ['name' => $uploadedFileName, 'error' => $ex->getMessage()]) : $ex->getMessage();
         $result = ['error' => $message, 'file' => $uploadedFileName];
         $response = Response::make()->setContent($result);
         $response->send();
         die;
     }
 }
 /**
  * Sample pdf layouts
  */
 public function run()
 {
     PDFLayout::insert([['name' => 'Invoice', 'code' => 'renatio::invoice', 'content_html' => File::get(__DIR__ . '/layouts/invoice.htm'), 'content_css' => File::get(__DIR__ . '/layouts/style_invoice.css'), 'created_at' => Carbon::now()]]);
     $file = FileModel::where(['field' => 'background_img', 'attachment_id' => 1])->first();
     if (!is_object($file)) {
         FileModel::insert([['disk_name' => '55428b6d4425d031778535.jpg', 'file_name' => 'invoice.jpg', 'file_size' => '47454', 'content_type' => 'image/jpeg', 'field' => 'background_img', 'attachment_id' => 1, 'attachment_type' => 'Renatio\\DynamicPDF\\Models\\PDFLayout']]);
     }
     $storage_dir = storage_path('app/uploads/public/554/28b/6d4');
     $file = $storage_dir . '/55428b6d4425d031778535.jpg';
     if (!File::exists($file)) {
         File::makeDirectory($storage_dir, 0755, true);
         File::copy('plugins/renatio/dynamicpdf/assets/images/invoice.jpg', $file);
     }
 }
Esempio n. 21
0
 /**
  * Execute the console command.
  * @return void
  */
 public function fire()
 {
     $base_path = base_path('');
     $this->info('Dependencies installing begins here! (plugin:install)');
     // DEPENDENCIES
     foreach (['RainLab.Translate', 'Flynsarmy.IdeHelper', 'BnB.ScaffoldTranslation', 'October.Drivers', 'RainLab.GoogleAnalytics', 'Genius.StorageClear'] as $required) {
         $this->info('Installing: ' . $required);
         Artisan::call("plugin:install", ['name' => $required]);
     }
     $this->info('Dependencies installed!');
     // THEME
     $this->info('Installing: oc-genius-theme');
     system("cd '{$base_path}' && git clone https://github.com/estudiogenius/oc-genius-theme themes/genius");
     Theme::setActiveTheme('genius');
     // ELIXIR
     $this->info('Installing: oc-genius-elixir');
     system("cd '{$base_path}' && git clone https://github.com/estudiogenius/oc-genius-elixir plugins/genius/elixir");
     // FORMS
     $this->info('Installing: oc-genius-forms');
     system("cd '{$base_path}' && git clone https://github.com/estudiogenius/oc-genius-forms plugins/genius/forms");
     // BACKUP
     $this->info('Installing: oc-genius-backup');
     system("cd '{$base_path}' && git clone https://github.com/estudiogenius/oc-genius-backup plugins/genius/backup");
     // GOOGLE ANALYTICS
     $this->info('Initial setup: AnalytcsSettings');
     if (!AnalytcsSettings::get('project_name')) {
         AnalytcsSettings::create(['project_name' => 'API Project', 'client_id' => '979078159189-8afk8nn2las4vk1krbv8t946qfk540up.apps.googleusercontent.com', 'app_email' => '*****@*****.**', 'profile_id' => '112409305', 'tracking_id' => 'UA-29856398-24', 'domain_name' => 'retrans.srv.br'])->gapi_key()->add(File::create(['data' => plugins_path('genius/base/assets/genius-analytics.p12')]));
     }
     // EMAIL
     $this->info('Initial setup: MailSettings');
     if (!MailSettings::get('mandrill_secret')) {
         MailSettings::create(['send_mode' => 'mandrill', 'sender_name' => 'Genius Soluções Web', 'sender_email' => '*****@*****.**', 'mandrill_secret' => 't27R2C15NPnZ8tzBrIIFTA']);
     }
     // BRAND
     $this->info('Initial setup: BrandSettings');
     if (!BrandSettings::get('app_init')) {
         BrandSettings::create(['app_name' => 'Genius Soluções Web', 'app_tagline' => 'powered by Genius', "primary_color_light" => "#e67e22", "primary_color_dark" => "#d35400", "secondary_color_light" => "#34495e", "secondary_color_dark" => "#2b3e50", "custom_css" => "", 'app_init' => true])->logo()->add(File::create(['data' => plugins_path('genius/base/assets/genius-logo.png')]));
     }
     // USUARIO BASE
     $this->info('Initial setup: User');
     $user = User::find(1);
     if (!$user->last_name) {
         $user->update(['first_name' => 'Genius', 'last_name' => 'Soluções Web', 'login' => 'genius', 'email' => '*****@*****.**', 'password' => 'genius', 'password_confirmation' => 'genius']);
         $user->avatar()->add(File::create(['data' => plugins_path('genius/base/assets/genius-avatar.jpg')]));
     }
     $this->info('Genius.Base is ready to rock!');
     $this->info('');
     $this->info('For Laravel Elixir setup run: php artisan elixir:init');
 }
Esempio n. 22
0
 public function testDeleteFlagDeleteModel()
 {
     Model::unguard();
     $user = User::create(['name' => 'Stevie', 'email' => '*****@*****.**']);
     Model::reguard();
     $this->assertEmpty($user->photos);
     $user->photos()->create(['data' => base_path() . '/tests/fixtures/plugins/database/tester/assets/images/avatar.png']);
     $user->reloadRelations();
     $this->assertNotEmpty($user->photos);
     $photo = $user->photos->first();
     $this->assertNotNull($photo);
     $photoId = $photo->id;
     $user->delete();
     $this->assertNull(FileModel::find($photoId));
 }
 private function assignImages($model, $fileData)
 {
     if (array_key_exists($model->slug, $fileData)) {
         $images = $fileData[$model->slug];
         // print_r($images);
         echo $model->slug . " [";
         // echo get_class($model) . "\n";
         foreach ($images as $key => $filePath) {
             if (!is_array($filePath)) {
                 $pathinfo = pathinfo($filePath);
                 $check = File::where('attachment_id', '=', $model->id)->where('attachment_type', '=', get_class($model))->where('file_name', '=', $pathinfo['basename'])->first();
                 if (!is_null($check)) {
                     // echo $filePath . " ";
                     // echo filemtime($filePath) . " ";
                     // echo $check->updated_at->timestamp . "\n";
                     if (filemtime($filePath) > $check->updated_at->timestamp) {
                         // echo "File " . $filePath . " is Newer. Update!" . "\n";
                         echo "^";
                         $check->delete();
                     } else {
                         echo "~";
                         continue;
                     }
                 } else {
                     // echo "File " . $filePath . " is New. Create!" . "\n";
                     echo "+";
                 }
                 $file = new File();
                 $file->fromFile($filePath);
                 // $file->save();
                 $model->images()->save($file, null, ['title' => $model->title]);
             }
         }
         echo "]\n";
     }
 }
 /**
  * Execute the console command.
  * @return void
  */
 public function fire()
 {
     // remove files without related register...
     $this->info(trans('genius.storageclear::lang.clear.seeking.files'));
     $allFiles = Storage::allFiles('uploads');
     $count = 0;
     $total = count($allFiles);
     foreach ($allFiles as $file) {
         if (!File::where('disk_name', basename($file))->first(['id'])) {
             Storage::delete($file);
             $count++;
         }
     }
     $this->info(trans('genius.storageclear::lang.clear.removed.files', compact('count', 'total')));
     // remove registers without file...
     $this->info(trans('genius.storageclear::lang.clear.seeking.registers'));
     $allFiles = File::all(['id', 'disk_name', 'attachment_type', 'attachment_id', 'is_public']);
     $count = 0;
     $total = $allFiles->count();
     foreach ($allFiles as $file) {
         if (!Storage::exists($file->getDiskPath())) {
             $file->delete();
             $count++;
         } else {
             $class = $file->attachment_type;
             if (!$class || !class_exists($class) || !$class::find($file->attachment_id)) {
                 $file->delete();
                 $count++;
             }
         }
     }
     $this->info(trans('genius.storageclear::lang.clear.removed.registers', compact('count', 'total')));
     // deletar pastas vazias
     $this->info(trans('genius.storageclear::lang.clear.seeking.directories'));
     $allFolders = array_reverse(Storage::allDirectories('uploads'));
     $count = 0;
     $total = count($allFolders);
     foreach ($allFolders as $directory) {
         if (!Storage::allFiles($directory)) {
             Storage::deleteDirectory($directory);
             $count++;
         }
     }
     $this->info(trans('genius.storageclear::lang.clear.removed.directories', compact('count', 'total')));
 }
 /**
  * Locates a file model based on the unique code.
  * @param $code string
  * @return System\Models\File
  */
 protected function findFileObject($code)
 {
     if (!$code) {
         throw new ApplicationException('Missing code');
     }
     $parts = explode('!', base64_decode($code));
     if (count($parts) < 2) {
         throw new ApplicationException('Invalid code');
     }
     list($id, $hash) = $parts;
     if (!($file = FileModel::find((int) $id))) {
         throw new ApplicationException('Unable to find file');
     }
     $verifyCode = self::getUniqueCode($file);
     if ($code != $verifyCode) {
         throw new ApplicationException('Invalid hash');
     }
     return $file;
 }
Esempio n. 26
0
 /** Usage example: {{ product.image | transparencyThumb(180,180, {color: [255,0,0]}) }}
  * @param File  $originalImage
  * @param       $width
  * @param       $height
  * @param array $opts
  * @return string
  */
 public function transparencyThumb($originalImage, $width, $height, $opts = [])
 {
     if ($originalImage == null) {
         return null;
     }
     $extension = $originalImage->getAttribute('extension');
     if ($extension == 'png' || $extension == 'gif') {
         if (isset($opts['color']) == false) {
             $opts['color'] = [255, 255, 255];
         }
         $appendix = '_trans_tmp_' . implode('-', $opts['color']) . '.jpg';
         $dbDiskName = str_replace('.' . $extension, $appendix, $originalImage->getAttribute('file_name'));
         $dbAttachmentType = $originalImage->getAttribute('attachment_type') . '::transparency';
         $dbFile = File::where('file_name', $dbDiskName)->where('attachment_type', $dbAttachmentType)->first();
         if ($dbFile) {
             return $dbFile->getThumb($width, $height, $opts);
         }
         if ($extension == 'png') {
             $tmpImageData = imagecreatefrompng(base_path() . $originalImage->getPath());
         } else {
             $tmpImageData = imagecreatefromgif(base_path() . $originalImage->getPath());
         }
         $imageWidth = imagesx($tmpImageData);
         $imageHeight = imagesy($tmpImageData);
         $backgroundImg = imagecreatetruecolor($imageWidth, $imageHeight);
         $color = imagecolorallocate($backgroundImg, $opts['color'][0], $opts['color'][1], $opts['color'][2]);
         imagefill($backgroundImg, 0, 0, $color);
         imagecopy($backgroundImg, $tmpImageData, 0, 0, 0, 0, $imageWidth, $imageHeight);
         $tmpImagePath = $originalImage->getTempPath() . '/' . $dbDiskName;
         imagejpeg($backgroundImg, $tmpImagePath);
         imagedestroy($backgroundImg);
         imagedestroy($tmpImageData);
         //return str_replace(base_path(), '', $tmpImagePath);
         $file = File::create(['data' => $tmpImagePath, 'attachment_type' => $dbAttachmentType]);
         return $file->getThumb($width, $height, $opts);
     }
     return $originalImage->getThumb($width, $height, $opts);
 }
Esempio n. 27
0
 /**
  * Checks the current request to see if it is a postback containing a file upload
  * for this particular widget.
  */
 protected function checkUploadPostback()
 {
     if (!($uniqueId = post('X_OCTOBER_FILEUPLOAD')) || $uniqueId != $this->getId()) {
         return;
     }
     try {
         $uploadedFile = Input::file('file_data');
         $validationRules = ['max:' . File::getMaxFilesize()];
         if ($fileTypes = $this->getAcceptedFileTypes()) {
             $validationRules[] = 'mimes:' . $fileTypes;
         }
         $validation = Validator::make(['file_data' => $uploadedFile], ['file_data' => $validationRules]);
         if ($validation->fails()) {
             throw new ValidationException($validation);
         }
         if (!$uploadedFile->isValid()) {
             throw new SystemException('File is not valid');
         }
         $fileRelation = $this->getRelationObject();
         $file = new File();
         $file->data = $uploadedFile;
         $file->is_public = $fileRelation->isPublic();
         $file->save();
         $fileRelation->add($file, $this->sessionKey);
         $file->thumb = $file->getThumb($this->imageWidth, $this->imageHeight, $this->thumbOptions);
         $result = $file;
     } catch (Exception $ex) {
         $result = json_encode(['error' => $ex->getMessage()]);
     }
     header('Content-Type: application/json');
     die($result);
 }
Esempio n. 28
0
 /**
  * Checks the current request to see if it is a postback containing a file upload
  * for this particular widget.
  */
 protected function checkUploadPostback()
 {
     if (!($uniqueId = post('X_OCTOBER_FILEUPLOAD')) || $uniqueId != $this->getId()) {
         return;
     }
     try {
         $uploadedFile = Input::file('file_data');
         $isImage = starts_with($this->getDisplayMode(), 'image');
         $validationRules = ['max:' . File::getMaxFilesize()];
         if ($isImage) {
             $validationRules[] = 'mimes:jpg,jpeg,bmp,png,gif';
         }
         $validation = Validator::make(['file_data' => $uploadedFile], ['file_data' => $validationRules]);
         if ($validation->fails()) {
             throw new ValidationException($validation);
         }
         if (!$uploadedFile->isValid()) {
             throw new SystemException('File is not valid');
         }
         $fileRelation = $this->getRelationObject();
         $file = new File();
         $file->data = $uploadedFile;
         $file->is_public = $fileRelation->isPublic();
         $file->save();
         $fileRelation->add($file, $this->sessionKey);
         $file->thumb = $file->getThumb($this->imageWidth, $this->imageHeight, ['mode' => 'crop']);
         $result = $file;
     } catch (Exception $ex) {
         $result = json_encode(['error' => $ex->getMessage()]);
     }
     die($result);
 }
Esempio n. 29
0
 /**
  *
  * Saves photos with files attached from $file_ids and attaches them to album
  *
  * @param AlbumModel $album
  * @param array $file_ids
  * @param string[] $file_titles arrray of titles
  */
 protected function savePhotos($album, $file_ids, $file_titles)
 {
     $files = File::whereIn('id', $file_ids)->get();
     $photos = array();
     foreach ($files as $file) {
         $photo = new PhotoModel();
         $photo->title = isset($file_titles[$file->id]) ? $file_titles[$file->id] : '';
         $photo->save();
         $photo->image()->save($file);
         $photos[] = $photo;
     }
     $album->photos()->saveMany($photos);
 }
 public function onRemoveAttachment()
 {
     if (($file_id = post('file_id')) && ($file = File::find($file_id))) {
         $this->model->{$this->attribute}()->remove($file, $this->getSessionKey());
     }
 }