Inheritance: extends Markzero\Mvc\AppModel
Ejemplo n.º 1
1
 public function upload($article_id)
 {
     $accessToken = Yii::$app->params['accessToken'];
     $dbxClient = new dbx\Client($accessToken, "PHP-Example/1.0");
     $accountInfo = $dbxClient->getAccountInfo();
     if ($this->validate()) {
         $image_name = Yii::$app->security->generateRandomString();
         $this->file->saveAs('uploads/' . $image_name . '.' . $this->file->extension);
         $file_name = 'uploads/' . $image_name . '.' . $this->file->extension;
         $f = fopen("{$file_name}", "rb");
         $result = $dbxClient->uploadFile("/{$image_name}" . '.' . $this->file->extension, dbx\WriteMode::add(), $f);
         fclose($f);
         $src = $dbxClient->createShareableLink($result['path']);
         $src[strlen($src) - 1] = '1';
         $image = new Image();
         $image->image_name = $image_name . '.' . $this->file->extension;
         $image->image_article = $article_id;
         $image->image_src_big = $src;
         //small
         $file_name = 'uploads/' . $image_name . '.' . $this->file->extension;
         $resizedFile = 'uploads/small_' . $image_name . '.' . $this->file->extension;
         smart_resize_image($file_name, null, 0, 100, true, $resizedFile, false, false, 100);
         $f = fopen("{$resizedFile}", "rb");
         $result = $dbxClient->uploadFile("/small_" . "{$image_name}" . '.' . $this->file->extension, dbx\WriteMode::add(), $f);
         fclose($f);
         $src = $dbxClient->createShareableLink($result['path']);
         $src[strlen($src) - 1] = '1';
         $image->image_src_small = $src;
         $image->save();
         unlink($file_name);
         unlink($resizedFile);
         return true;
     } else {
         return false;
     }
 }
Ejemplo n.º 2
0
 /**
  * Calculate p-hash and save image
  * @param string $file
  * @throws Exception
  * @return Image
  */
 public static function importImage($file)
 {
     try {
         $fileInfo = pathinfo($file);
         $model = new Image();
         $model->md5 = md5_file($file);
         $model->phash = self::getPHash($file);
         $model->path = sprintf('%s/%s.%s', substr($model->md5, 0, 2), $model->md5, $fileInfo['extension']);
         $model->previewPath = sprintf('%s/%s_preview.%s', substr($model->md5, 0, 2), $model->md5, $fileInfo['extension']);
         if ($model->save()) {
             $dstImage = Yii::getAlias('@app/web/uploads') . '/' . $model->path;
             $dstPath = dirname($dstImage);
             if (!is_dir($dstPath)) {
                 mkdir($dstPath, 0777, true);
             }
             if (!file_exists($dstImage)) {
                 copy($file, $dstImage);
                 Imagine::thumbnail($file, 300, 300)->save(Yii::getAlias('@app/web/uploads') . '/' . $model->previewPath, ['format' => 'jpg', 'quality' => 90]);
             }
             return $model;
         } else {
             return null;
         }
     } catch (\Exception $e) {
     }
     return null;
 }
Ejemplo n.º 3
0
 public static function storage(Image $image, $file, $storage_id = 1)
 {
     $url = ImageStorage::upload($file, $storage_id);
     if ($url) {
         $image->increaseCopyCount();
         return static::create(['image_id' => $image->id, 'url' => $url, 'storage_id' => $storage_id]);
     }
     return false;
 }
Ejemplo n.º 4
0
 /**
  * Store a newly created resource in storage.
  *
  * @param  \Illuminate\Http\Request  $request
  * @return \Illuminate\Http\Response
  */
 public function store(Request $request)
 {
     $image = new Image();
     $imageName = substr(md5(rand()), 0, 7) . '.' . $request->file('image')->getClientOriginalExtension();
     $request->file('image')->move(base_path() . '/public/img/', $imageName);
     $image->file_name = $imageName;
     $image->save();
     return Redirect::route('image.index');
 }
Ejemplo n.º 5
0
 /**
  * @param $imgProps
  * @param $src
  * @param $imageToLoad
  * @throws ImageAlreadyExistsException
  * @throws ImageNotFoundException
  */
 private function saveImage(array $imgProps, $src, Image $imageToLoad)
 {
     if (file_exists(ROOT . $src)) {
         throw new ImageAlreadyExistsException("Image " . pathinfo($src, PATHINFO_BASENAME) . " already exists");
     }
     $imageToLoad->saveAs(ROOT . $src, $imgProps['height'], $imgProps['width']);
     if (!file_exists(ROOT . $src)) {
         throw new ImageNotFoundException("Unable to save image " . ROOT . $src);
     }
 }
Ejemplo n.º 6
0
 public function init()
 {
     $this->layout = 'client_layout';
     $imagesModel = new Image();
     $this->logo = $imagesModel->getProfilePhoto();
     $profile = $this->findModel(Yii::$app->user->id);
     $this->first_name = $profile->firstname;
     $this->last_name = $profile->lastname;
     $this->userModules = UsersModules::getUsersModules();
     parent::init();
     // custom initialization code goes here
 }
Ejemplo n.º 7
0
 public function actionIndex()
 {
     $currentPsychologistId = Yii::$app->user->id;
     $profile = $this->findModel($currentPsychologistId);
     /*       $directions = new Directions();
             $problems = new Problems();*/
     $imagesModel = new Image();
     if ($profile->load(Yii::$app->request->post())) {
         if ($profile->save()) {
             return $this->render('index', ['profileModel' => $profile, 'message' => 'Профиль успешно обновлён', 'imagesModel' => $imagesModel, 'logo' => $imagesModel->getProfilePhoto()]);
         }
     } else {
         return $this->render('index', ['profileModel' => $profile, 'imagesModel' => $imagesModel]);
     }
 }
Ejemplo n.º 8
0
 public function run()
 {
     DB::table('images')->delete();
     Image::create(['file_name' => 'first.jpg']);
     Image::create(['file_name' => 'second.jpg']);
     Image::create(['file_name' => 'third.jpg']);
 }
Ejemplo n.º 9
0
 public static function saveByFile($uploadedFileInstance)
 {
     if ($uploadedFileInstance !== null) {
         $i = new Image();
         $rnd = rand(0, 99999);
         $fileName = $rnd . '_' . $uploadedFileInstance->name;
         $localPath = '/files/' . $fileName;
         $filePath = Yii::$app->basePath . $localPath;
         $uploadedFileInstance->saveAs($filePath);
         $i->source = $localPath;
         if ($i->save()) {
             return $i;
         }
     }
     return null;
 }
Ejemplo n.º 10
0
 public function defaultPhoto()
 {
     if (empty($this->default_photo)) {
         return \Theme::asset()->img('theme/images/photo/default-album.png');
     }
     return \Image::url($this->default_photo, 600);
 }
Ejemplo n.º 11
0
 public function attachImage($id, $media_id)
 {
     $product = $this->model->find($id);
     $media = Image::find($media_id);
     $product->images()->save($media);
     return true;
 }
Ejemplo n.º 12
0
 public function deleteMe()
 {
     $path = $this->path;
     $slug = $this->slug;
     \Image::delete($path);
     //lets take our time to delete likes and comments
     app('App\\Repositories\\CommentRepository')->deleteByType('photo', $this->id);
     app('App\\Repositories\\LikeRepository')->deleteByType('photo', $this->id);
     //if post is attached lets delete the pic
     if ($this->post_id) {
         app('App\\Repositories\\PostRepository')->delete($this->post_id);
     }
     $this->delete();
     $split = explode('-', $slug);
     if (count($split) > 1) {
         list($name, $id) = $split;
         if (isset($id)) {
             $album = app('App\\Repositories\\PhotoAlbumRepository')->get($id);
             if (!empty($album)) {
                 if ($album->default_photo == $path) {
                     $lastPhoto = app('App\\Repositories\\PhotoRepository')->lastPhoto($slug);
                     if ($lastPhoto) {
                         $album->default_photo = $lastPhoto->path;
                     } else {
                         $album->default_photo = '';
                     }
                     $album->save();
                 }
             }
         }
     }
 }
 /**
  * Get all of the products of a given Breeder
  *
  * @param  Breeder      $breeder
  * @return Collection
  */
 public function forBreeder(Breeder $breeder)
 {
     $products = $breeder->products()->where('status', 'requested')->get();
     $reservations = $breeder->reservations()->get();
     $items = [];
     // Include all "requested" products
     foreach ($products as $product) {
         if ($product->quantity == 0) {
             continue;
         }
         $itemDetail = [];
         $itemDetail['uuid'] = (string) Uuid::uuid4();
         $itemDetail['id'] = $product->id;
         $itemDetail['reservation_id'] = 0;
         $itemDetail['img_path'] = '/images/product/' . Image::find($product->primary_img_id)->name;
         $itemDetail['breeder_id'] = $product->breeder_id;
         $itemDetail['farm_province'] = FarmAddress::find($product->farm_from_id)->province;
         $itemDetail['name'] = $product->name;
         $itemDetail['type'] = $product->type;
         $itemDetail['age'] = $this->computeAge($product->birthdate);
         $itemDetail['breed'] = $this->transformBreedSyntax(Breed::find($product->breed_id)->name);
         $itemDetail['quantity'] = $product->quantity;
         $itemDetail['adg'] = $product->adg;
         $itemDetail['fcr'] = $product->fcr;
         $itemDetail['bft'] = $product->backfat_thickness;
         $itemDetail['status'] = $product->status;
         $itemDetail['customer_id'] = 0;
         $itemDetail['customer_name'] = '';
         $itemDetail['date_needed'] = '';
         $itemDetail['special_request'] = '';
         array_push($items, (object) $itemDetail);
     }
     // Include "reserved" / "paid" / "on_delivery" / "sold" products
     foreach ($reservations as $reservation) {
         $product = Product::find($reservation->product_id);
         $itemDetail = [];
         $itemDetail['uuid'] = (string) Uuid::uuid4();
         $itemDetail['id'] = $product->id;
         $itemDetail['reservation_id'] = $reservation->id;
         $itemDetail['img_path'] = '/images/product/' . Image::find($product->primary_img_id)->name;
         $itemDetail['breeder_id'] = $product->breeder_id;
         $itemDetail['farm_province'] = FarmAddress::find($product->farm_from_id)->province;
         $itemDetail['name'] = $product->name;
         $itemDetail['type'] = $product->type;
         $itemDetail['age'] = $this->computeAge($product->birthdate);
         $itemDetail['breed'] = $this->transformBreedSyntax(Breed::find($product->breed_id)->name);
         $itemDetail['quantity'] = $reservation->quantity;
         $itemDetail['adg'] = $product->adg;
         $itemDetail['fcr'] = $product->fcr;
         $itemDetail['bft'] = $product->backfat_thickness;
         $itemDetail['status'] = $reservation->order_status;
         $itemDetail['customer_id'] = $reservation->customer_id;
         $itemDetail['customer_name'] = Customer::find($reservation->customer_id)->users()->first()->name;
         $itemDetail['date_needed'] = $this->transformDateSyntax($reservation->date_needed);
         $itemDetail['special_request'] = $reservation->special_request;
         array_push($items, (object) $itemDetail);
     }
     // dd($items);
     return collect($items)->toJson();
 }
 /**
  * Execute the console command.
  *
  * @return mixed
  */
 public function handle()
 {
     $this->output->progressStart();
     $offset = 0;
     $media = Media::with('mediaType', 'scan', 'scan.specimen', 'scan.museum', 'scan.author', 'scan.animalGroup')->limit(self::BATCH_LIMIT)->offset($offset)->get()->toArray();
     while (!empty($media)) {
         foreach ($media as $key => $mediaArray) {
             $media[$key] = $this->flattenNested($mediaArray, true);
         }
         $this->output->progressAdvance(self::BATCH_LIMIT);
         $this->search->insertDocuments($media);
         $offset += self::BATCH_LIMIT;
         $media = Media::with('mediaType', 'scan', 'scan.specimen', 'scan.museum', 'scan.author', 'scan.animalGroup')->limit(self::BATCH_LIMIT)->offset($offset)->get()->toArray();
     }
     $offset = 0;
     $images = Image::with('scan', 'scan.specimen', 'scan.museum', 'scan.author', 'scan.animalGroup')->limit(self::BATCH_LIMIT)->offset($offset)->get()->toArray();
     while (!empty($images)) {
         foreach ($images as $key => $image) {
             $images[$key] = $this->flattenNested($image, true);
         }
         $this->output->progressAdvance(self::BATCH_LIMIT);
         $this->search->insertDocuments($images);
         $offset += self::BATCH_LIMIT;
         $images = Image::with('scan', 'scan.specimen', 'scan.museum', 'scan.author', 'scan.animalGroup')->limit(self::BATCH_LIMIT)->offset($offset)->get()->toArray();
     }
     $this->output->progressFinish();
 }
Ejemplo n.º 15
0
 /**
  * Get data formatted for JSON output
  *
  * @param Array $attach Optional: sub-resources to attach to the base data, if available. Possible values: options, images, custom_fields
  * @return Array $output The formatted data
  */
 public function getOutput($attach = [])
 {
     $output = array('id' => $this->id, 'name' => $this->name, 'sku' => $this->sku, 'description' => $this->description, 'price' => $this->price, 'cost_price' => $this->cost_price, 'retail_price' => $this->retail_price, 'sale_price' => $this->sale_price, 'calculated_price' => $this->calculated_price, 'warranty' => $this->warranty, 'custom_url' => $this->custom_url);
     if (in_array('options', $attach) && isset($this->_options)) {
         $output['options'] = unserialize($this->_options);
     }
     if (in_array('images', $attach)) {
         $images = Image::where('product_id', $this->id)->get();
         $output['images'] = [];
         if (count($images)) {
             foreach ($images as $image) {
                 $output['images'][] = $image->mapData();
             }
         }
     }
     if (in_array('custom_fields', $attach)) {
         $custom_fields = CustomField::where('product_id', $this->id)->get();
         $output['custom_fields'] = [];
         if (count($custom_fields)) {
             foreach ($custom_fields as $custom_field) {
                 $output['custom_fields'][] = $custom_field->mapData();
             }
         }
     }
     return $output;
 }
Ejemplo n.º 16
0
 public function actionGetPhotoInfoList($sn, $page = 1, $numPerPage = 50, $tagId = 0)
 {
     $start = ($page - 1) * $numPerPage;
     if ($tagId == 0) {
         $imageList = Image::find()->limit($numPerPage)->offset($start)->asArray()->all();
     } else {
         $imageList = Image::find()->leftJoin('image_tag', 'image.id = image_tag.imageId')->where(['image_tag.tagId' => $tagId])->limit($numPerPage)->offset($start)->asArray()->all();
     }
     $imageIdList = [];
     foreach ($imageList as $image) {
         $imageIdList[] = $image['id'];
     }
     //是否收藏
     $favoriteList = Favorite::find()->where(['isDelete' => 0, 'imageId' => $imageIdList])->asArray()->all();
     $favoriteMap = [];
     foreach ($favoriteList as $favorite) {
         $favoriteMap[$favorite['imageId']] = true;
     }
     $output = [];
     //更改链接
     foreach ($imageList as &$image) {
         $t = [];
         $t['id'] = $image['id'];
         $t['url'] = './image/' . Image::getUrlFromResizedFilePath($image['filePath']);
         //            $t['rawUrl'] = './rawImage/'.Image::getUrlFromRawFilePath($image['rawFilePath']);
         $t['thumbnailUrl'] = './image/' . Image::getUrlFromResizedFilePath($image['thumbnailFilePath']);
         $t['isFavorite'] = isset($favoriteMap[$image['id']]) ? true : false;
         $output[] = $t;
     }
     Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
     return ['sn' => $sn, 'data' => $output];
 }
Ejemplo n.º 17
0
 protected function actionUploadImage()
 {
     if ($this->isPost()) {
         try {
             $file = new Uploader();
             $file->setUploadsDir('/home/rayman/domains/my-blog/App/file/');
             $file->format = ['jpg' => 'image/jpeg', 'png' => 'image/png', 'gif' => 'image/gif'];
             $path = $file->UploadFile();
             $image = new Image();
             $image->image = $path;
             var_dump($image->save());
         } catch (\Exception $e) {
             $this->view->error = $e;
         }
     }
     $this->view->display(__DIR__ . '/../Templates/Form.php');
 }
Ejemplo n.º 18
0
 public function actionDelete($id)
 {
     $request = \Yii::$app->request;
     $ajax = $request->isAjax;
     if (!\app\helpers\Csrf::check()) {
         return $ajax ? json_encode(['success' => false]) : $this->goHome();
     }
     Model::directDelete($id);
     return $ajax ? json_encode(['success' => true]) : $this->redirect(static::URL_TO_INDEX);
 }
Ejemplo n.º 19
0
 public function run()
 {
     DB::table('images')->delete();
     $faker = $this->getFaker();
     $image_list = ["http://i.imgur.com/j3NXQsK.jpg", "http://i.imgur.com/VxmP5AS.jpg", "http://i.imgur.com/IlFQw7c.jpg", "http://i.imgur.com/YFlyOti.jpg", "http://i.imgur.com/wU6f7XT.jpg"];
     for ($i = 0; $i < $this->num_records; $i++) {
         $array = ["url_location" => $image_list[$i % 5], "description" => $this->getFaker()->text];
         Image::create($array);
     }
 }
 public function getServerImages()
 {
     $images = Image::get(['original_name', 'filename']);
     $imageAnswer = [];
     foreach ($images as $image) {
         $imageAnswer[] = ['original' => $image->original_name, 'server' => $image->filename, 'size' => File::size(public_path('images/full_size/' . $image->filename))];
     }
     // http://laravel-image-upload-dropzone.local/public/images/full_size/v1-c26b3.png
     // 'size' => File::size(public_path('images/full_size/' . $image->filename))
     return response()->json(['images' => $imageAnswer]);
 }
 public function handle(StoreUploadedImageCommand $command)
 {
     $intImg = IntImage::make($command->image->getRealPath())->orientate();
     $randomFilename = uniqid();
     $fullPath = 'uploads/' . $randomFilename . '.jpg';
     \Storage::disk('images')->put($fullPath, $intImg->encode('jpg', 75));
     $width = $intImg->width();
     $height = $intImg->height();
     $average = $intImg->resize(1, 1)->pickColor(0, 0, 'rgba');
     $newImage = Image::create(['width' => $width, 'height' => $height, 'mime_type' => 'image/jpeg', 'extension' => '.jpg', 'path' => $fullPath, 'description' => '', 'average_colour' => $average]);
     return $newImage->id;
 }
 public function run()
 {
     if (class_exists('Faker\\Factory')) {
         $faker = Faker\Factory::create();
         $scans = Scan::all()->all();
         $images = ['/img/eusthenopteron_foordi.jpg', '/img/iridotriton_hechti.jpg', '/img/sipalocyon_sp.jpg', '/img/teinolophos_trusleri.jpg'];
         foreach ($scans as $scan) {
             for ($i = 1; $i <= 500; $i++) {
                 Image::create(['filePath' => '/' . $faker->word, 'fileName' => $faker->word . $faker->randomNumber(2) . '.tif', 'fileUrl' => $faker->randomElement($images), 'scanId' => $scan->id]);
             }
         }
     }
 }
Ejemplo n.º 23
0
 public function actionTest()
 {
     //        $rawFilePath = '/homeNASDownloads/photo_2011-2012/DSC_0155.JPG';
     //        $match = [];
     //        if (preg_match('/\/homeNASDownloads\/photo_[0-9\-]+(.*)/', dirname($rawFilePath), $match)) {
     ////        if (preg_match('/\/homeNASDownloads\/(.*)/i', $rawFilePath, $match)) {
     //            var_dump($match);
     //        }else{
     //            echo "o my god!\n";
     //        }
     $image = Image::find()->where(['id' => 2])->one();
     var_dump($image->tags);
 }
Ejemplo n.º 24
0
 /**
  * Creates data provider instance with search query applied
  *
  * @param array $params
  *
  * @return ActiveDataProvider
  */
 public function search($params)
 {
     $query = Image::find();
     $dataProvider = new ActiveDataProvider(['query' => $query]);
     $this->load($params);
     if (!$this->validate()) {
         // uncomment the following line if you do not want to return any records when validation fails
         // $query->where('0=1');
         return $dataProvider;
     }
     $query->andFilterWhere(['id' => $this->id]);
     $query->andFilterWhere(['like', 'title', $this->title])->andFilterWhere(['like', 'url', $this->url]);
     return $dataProvider;
 }
Ejemplo n.º 25
0
 public function postUpload()
 {
     $form_data = Input::all();
     $validator = Validator::make($form_data, Image::$rules, Image::$messages);
     if ($validator->fails()) {
         return Response::json(['status' => 'error', 'message' => $validator->messages()->first()], 200);
     }
     $photo = $form_data['img'];
     $original_name = $photo->getClientOriginalName();
     $original_name_without_ext = substr($original_name, 0, strlen($original_name) - 4);
     $filename = $this->sanitize($original_name_without_ext);
     $allowed_filename = $this->createUniqueFilename($filename);
     $filename_ext = $allowed_filename . '.jpg';
     $manager = new ImageManager();
     $image = $manager->make($photo)->encode('jpg')->save(env('UPLOAD_PATH') . $filename_ext);
     if (!$image) {
         return Response::json(['status' => 'error', 'message' => 'Server error while uploading'], 200);
     }
     $database_image = new Image();
     $database_image->filename = $allowed_filename;
     $database_image->original_name = $original_name;
     $database_image->save();
     return Response::json(['status' => 'success', 'url' => env('URL') . 'uploads/' . $filename_ext, 'width' => $image->width(), 'height' => $image->height()], 200);
 }
Ejemplo n.º 26
0
 /**
  * Execute the console command.
  *
  * @return mixed
  */
 public function handle()
 {
     $from = date('Y-m-d H:i:s', strtotime($this->argument('from') ?: 'today'));
     $to = date('Y-m-d H:i:s', strtotime($this->argument('to') ?: 'now'));
     while ($images = Image::whereBetween('created_at', [$from, $to])->where('copy_count', '<', ImageStorage::count())->where('copy_count', '>', 0)->take(10)->get()) {
         if ($images->isEmpty()) {
             $this->info('No image to process.');
             break;
         }
         foreach ($images as $image) {
             $image->checkMulti();
             $this->info("Image:{$image->id} processed.");
         }
     }
 }
Ejemplo n.º 27
0
 /**
  * Creates data provider instance with search query applied
  *
  * @param array $params
  *
  * @return ActiveDataProvider
  */
 public function search($params)
 {
     $query = Image::find();
     // add conditions that should always apply here
     $dataProvider = new ActiveDataProvider(['query' => $query]);
     $this->load($params);
     if (!$this->validate()) {
         // uncomment the following line if you do not want to return any records when validation fails
         // $query->where('0=1');
         return $dataProvider;
     }
     // grid filtering conditions
     $query->andFilterWhere(['like', 'id', $this->id])->andFilterWhere(['like', 'model_name', $this->model_name])->andFilterWhere(['like', 'model_id', $this->model_id])->andFilterWhere(['like', 'file', $this->file])->andFilterWhere(['like', 'path', $this->path])->andFilterWhere(['like', 'link', $this->link])->andFilterWhere(['like', 'author_id', $this->author_id])->andFilterWhere(['like', 'updater_id', $this->updater_id])->andFilterWhere(['like', 'created_at', $this->created_at])->andFilterWhere(['like', 'updated_at', $this->updated_at]);
     return $dataProvider;
 }
Ejemplo n.º 28
0
 /**
  * Creates data provider instance with search query applied
  *
  * @param array $params
  *
  * @return ActiveDataProvider
  */
 public function search($params)
 {
     $query = Image::find();
     $dataProvider = new ActiveDataProvider(['query' => $query]);
     $this->load($params);
     if (!$this->validate()) {
         // uncomment the following line if you do not want to return any records when validation fails
         $query->where('0=1');
         return $dataProvider;
     }
     $query->joinWith(['tags']);
     $query->groupBy(['image.id']);
     $query->andFilterWhere(['image.id' => $this->id, 'owner_id' => $this->owner_id, 'tag.id' => $this->tag_id]);
     $query->andFilterWhere(['like', 'image.name', $this->name])->andFilterWhere(['like', 'url', $this->url]);
     return $dataProvider;
 }
Ejemplo n.º 29
0
 /** 
  * observe image event saved
  * 1. check default image and make sure it's the only default
  * 2. act, accept or refuse
  * 
  * @param $model
  * @return bool
  */
 public function saved($model)
 {
     //1. check default image event
     if (isset($model->imageable_id) && $model->is_default == 1) {
         $images = Image::where('imageable_id', $model->imageable_id)->where('imageable_type', $model->imageable_type)->where('is_default', 1)->where('id', '!=', $model->id)->get();
         foreach ($images as $image) {
             //1a. set is_default to false for other image
             $image->fill(['is_default' => 0]);
             if (!$image->save()) {
                 $model['errors'] = $image->geterror();
                 return false;
             }
         }
     }
     return true;
 }
 public static function uploadImage($nameOfImageInput)
 {
     $message = "";
     $target_dir = DIR_IMAGE_FOLDER;
     $imageId = Image::count() + 1;
     $imageExt = substr($_FILES[$nameOfImageInput]["name"], -4);
     $target_file = $target_dir . basename($imageId . $imageExt);
     $uploadOk = 1;
     $imageFileType = pathinfo($target_file, PATHINFO_EXTENSION);
     // Check if image file is a actual image or fake image
     if (isset($_POST["submit"])) {
         $check = getimagesize($_FILES[$nameOfImageInput]["tmp_name"]);
         if ($check !== false) {
             $uploadOk = 1;
         } else {
             $uploadOk = 0;
         }
     }
     // Check file size
     if ($_FILES[$nameOfImageInput]["size"] > 500000) {
         $message = "Sorry, your file is too large.";
         $uploadOk = 0;
         echo "loi";
         die;
     }
     // Allow certain file formats
     if ($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif") {
         $uploadOk = 0;
         $message = $message . "Not Image file type!";
     }
     // Check if $uploadOk is set to 0 by an error
     if ($uploadOk == 0) {
         Session::put("imageMessage", $message);
         return "";
         // if everything is ok, try to upload file
     } else {
         if (move_uploaded_file($_FILES[$nameOfImageInput]["tmp_name"], $target_file)) {
             Image::create(['id' => $imageId, 'path' => $target_file]);
             echo "";
             return $target_file;
         } else {
             $message = $message . "Cannot upload!";
             Session::put("imageMessage", $message);
             return "";
         }
     }
 }