예제 #1
0
 /**
  * Save Images from temporary folder to Storage and store it in database
  *
  * @param Item		$item
  * @param Supplier	$supplier
  * @param array		$images
  *
  * @return
  */
 public static function saveImages($item, $supplier, $request)
 {
     // Get the short name of supplier
     $supplier = $supplier->shortname;
     $path = 'pictures/' . $supplier . '/';
     foreach ($request->images['image'] as $image) {
         $picture = Picture::where('path', '=', $path . $image)->first();
         $first_choice = $request->picture == $image ? 1 : 0;
         // If Picture exist in database, check if it's attached to this Item.
         // If Picture don't exist in database, create it and attach it to this Item.
         if ($picture === null) {
             $picture = new Picture(['path' => $path, 'title' => $image]);
             $picture->save();
             $picture->moveImage();
             $item->pictures()->attach($picture->id, ['first_choice' => $first_choice]);
         } elseif ($picture) {
             // If item don't have picture attached, attach it!
             if (!$item->hasPicture($picture->id)) {
                 $item->pictures()->attach($picture->id);
             }
         }
     }
 }
 public function actionCreate()
 {
     $request = Yii::$app->request;
     $userId = $request->post('user_id');
     $token = $request->post('token');
     if (!$this->checkToken($userId, $token)) {
         $this->setHeader(400);
         echo json_encode(array('status' => 0, 'error_code' => 400, 'message' => 'Invalid token'), JSON_PRETTY_PRINT);
         exit;
     }
     $longitude = $request->post('longitude');
     $latitude = $request->post('latitude');
     $data = $request->post('data');
     if (empty($longitude) or empty($latitude)) {
         $this->setHeader(400);
         echo json_encode(array('status' => 0, 'error_code' => 400, 'message' => 'Wrong params'), JSON_PRETTY_PRINT);
         exit;
     }
     if (!is_numeric($longitude) or $longitude <= -180 or $longitude > 180) {
         $this->setHeader(400);
         echo json_encode(array('status' => 0, 'error_code' => 400, 'message' => 'Longitude values must be in the range (-180, 180].'), JSON_PRETTY_PRINT);
         exit;
     }
     if (!is_numeric($latitude) or $latitude < -90 or $latitude > 90) {
         $this->setHeader(400);
         echo json_encode(array('status' => 0, 'error_code' => 400, 'message' => 'Latitude values must be in the range [-90, 90].'), JSON_PRETTY_PRINT);
         exit;
     }
     $sql = "SELECT id FROM node WHERE geom = GeomFromText('Point({$longitude} {$latitude})')";
     $nodeId = Yii::$app->db->createCommand($sql)->queryScalar();
     if (empty($nodeId)) {
         $address = $request->post('addr');
         if (empty($address)) {
             $this->setHeader(400);
             echo json_encode(array('status' => 0, 'error_code' => 400, 'message' => "Address shouldn't be empty."), JSON_PRETTY_PRINT);
             exit;
         }
         $createSql = "INSERT node(geom, addr) VALUES(GeomFromText('Point({$longitude} {$latitude})'), '{$address}')";
         Yii::$app->db->createCommand($createSql)->execute();
         $nodeId = Yii::$app->db->createCommand($sql)->queryScalar();
     }
     $img = $data;
     $save_dir = __DIR__ . '/' . $nodeId . '/';
     if (!file_exists($save_dir)) {
         mkdir($save_dir);
     }
     $fileName = $save_dir . $userId . '_' . time() . '.jpg';
     $fp2 = fopen($fileName, 'w');
     fwrite($fp2, $img);
     fclose($fp2);
     $title = $request->post('title');
     if (empty($title)) {
         $this->setHeader(400);
         echo json_encode(array('status' => 0, 'error_code' => 400, 'message' => "Picture should have a title."), JSON_PRETTY_PRINT);
         exit;
     }
     $model = new Picture();
     $model->node_id = $nodeId;
     $model->user_id = $userId;
     $model->title = $title;
     $model->pic_link = $fileName;
     if ($model->save()) {
         $this->setHeader(200);
         echo json_encode(array('status' => 1, 'data' => ['node_id' => $model->node_id, 'pic_id' => $model->id, 'title' => $model->title]), JSON_PRETTY_PRINT);
         exit;
     } else {
         $this->setHeader(400);
         echo json_encode(array('status' => 0, 'error_code' => 400, 'errors' => $model->errors), JSON_PRETTY_PRINT);
         exit;
     }
 }
예제 #3
0
 public function actionUpload($key = null)
 {
     $readyPicsCount = Picture::find()->where(['state' => 'ready'])->count();
     $lastPictures = Picture::find()->where(['state' => 'ready'])->orderBy('updated ASC')->limit(50)->offset($readyPicsCount - 50)->all();
     $avgPictureTime = 0;
     if (count($lastPictures) > 1) {
         $summ = 0;
         for ($i = 1; $i < count($lastPictures); $i++) {
             $diff = strtotime($lastPictures[$i]->updated) - strtotime($lastPictures[$i - 1]->updated);
             $summ += $diff;
         }
         $avgPictureTime = intval($summ / (count($lastPictures) - 1));
     }
     $readyTime = $avgPictureTime * Picture::find()->where(['state' => 'new'])->count();
     $myPictureDP = new ActiveDataProvider(['query' => Picture::find()->where(['state' => 'new', 'ip' => Yii::$app->getRequest()->getUserIP()]), 'sort' => false]);
     $lastPending = Picture::find()->where(['state' => 'pending'])->orderBy('id DESC')->one();
     if ($lastPending == null) {
         $lastPending = Picture::find()->where(['state' => 'ready'])->orderBy('id DESC')->one();
     }
     $pendingPicsCount = Picture::find()->where(['state' => 'new'])->count();
     $algorithms = [];
     $algos = Algorithm::find()->orderBy('count DESC')->all();
     foreach ($algos as $algo) {
         if (count($algorithms) == 0) {
             $algorithms[$algo->getPrimaryKey()] = $algo->name . ' (default, ' . $algo->count . ' pics)';
         } else {
             $algorithms[$algo->getPrimaryKey()] = $algo->name . ' (' . $algo->count . ' pics)';
         }
     }
     $viewData = ['readyTime' => $readyTime, 'myPictureDP' => $myPictureDP, 'avgPictureTime' => $avgPictureTime, 'lastPendingId' => $lastPending->id, 'pendingPicsCount' => $pendingPicsCount, 'algorithms' => $algorithms, 'algos' => $algos];
     $priority = 0;
     if ($key != null) {
         $keyModel = Key::find()->where(['value' => $key])->andWhere('used < count')->one();
         if ($keyModel == null) {
             throw new HttpException(404, "Bad key");
         }
         $priority = $keyModel->priority;
         $viewData['key'] = $keyModel;
     }
     $model = new UploadForm();
     if ($model->load(Yii::$app->request->post())) {
         $image = UploadedFile::getInstance($model, 'image');
         $model->image = $image;
         if ($model->validate() && $model->check()) {
             $size = getimagesize($image->tempName);
             list($width, $height, $type) = $size;
             if ($type == IMAGETYPE_JPEG) {
                 $img = imagecreatefromjpeg($image->tempName);
             } else {
                 if ($type == IMAGETYPE_PNG) {
                     $img = imagecreatefrompng($image->tempName);
                 } else {
                     throw new HttpException(400, 'Bad image');
                 }
             }
             $srcName = Helper::gen_uuid() . '.jpg';
             $filename = \Yii::$app->basePath . '/web/images/' . $srcName;
             $k = 650;
             if (!($width <= $k && $height <= $k)) {
                 $minSide = (int) (min($width, $height) * $k / max($width, $height));
                 list($newWidth, $newHeight) = $width > $height ? [$k, $minSide] : [$minSide, $k];
                 $newImage = imagecreatetruecolor($newWidth, $newHeight);
                 imagecopyresampled($newImage, $img, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
                 imagejpeg($newImage, $filename, 100);
             } else {
                 imagejpeg($img, $filename, 100);
             }
             $hash = sha1(file_get_contents($filename));
             $count = Picture::find()->where(['hash' => $hash, 'algorithmId' => $model->algoId])->all();
             if (count($count) > 0) {
                 unlink($filename);
                 $first = $count[0];
                 Yii::$app->getSession()->setFlash('success', 'This image was already submitted.');
                 return $this->redirect('/picture/' . $first->getPrimaryKey());
             }
             $algo = Algorithm::find()->where(['id' => $model->algoId])->one();
             $picture = new Picture();
             $picture->email = $model->email;
             $picture->ip = \Yii::$app->getRequest()->getUserIP();
             $picture->source = $srcName;
             $picture->output = null;
             $picture->state = 'new';
             $picture->hash = $hash;
             $picture->status = 0;
             $picture->priority = $priority;
             $picture->algorithm = $algo->name;
             $picture->algorithmId = $model->algoId;
             $picture->save();
             $algo->count += 1;
             $algo->save();
             if (!empty($keyModel)) {
                 $keyModel->used += 1;
                 $keyModel->save();
                 \Yii::$app->getSession()->setFlash('success', 'Your image were successfully uploaded. Converted image will be ready <b>ASAP</b> and sent on your email. Thank you!');
             } else {
                 \Yii::$app->getSession()->setFlash('success', 'Your image were successfully uploaded. Converted image will be ready after ~' . Helper::formatHourAndMin($readyTime) . ' and sent on your email. Thank you!');
             }
             return $this->redirect('/picture/' . $picture->getPrimaryKey());
         }
     }
     $viewData['model'] = $model;
     return $this->render('upload', $viewData);
 }