/**
  * Execute the console command.
  *
  * @return mixed
  */
 public function handle()
 {
     $this->info("Clearing permissions... \n");
     // Delete old data
     $response = Action::deleteAllData();
     null !== $response ? $this->error("\n" . $response . "\n") : null;
     $this->info("Permissions cleared... \n");
     try {
         $routeData = $this->getRouteData();
         $roles = Role::all();
         DB::beginTransaction();
         foreach ($routeData as $action => $uri) {
             $action = new Action(['uri' => $uri, 'action' => $action]);
             $action->save();
             $this->savePermissions($roles, $action);
             $this->comment("Added action " . $action->action . "\n");
         }
         $cache = $this->getCacheInstance(['permissions']);
         $cache->flush();
         DB::commit();
     } catch (\Exception $e) {
         DB::rollBack();
         $this->error("\n" . $e->getMessage() . "\n");
     }
 }
 public function update(Request $request, $id)
 {
     $departamento = $request->input('departamento');
     if ($departamento != '0') {
         try {
             DB::beginTransaction();
             $usuario = User::find($id);
             $empleado = $usuario->empleado;
             $empleado->nombre = Str::upper($request->input('nombre'));
             $empleado->apellido_paterno = Str::upper($request->input('apellido_paterno'));
             $empleado->apellido_materno = Str::upper($request->input('apellido_materno'));
             $empleado->save();
             $usuario->username = Str::upper($request->input('username'));
             $usuario->password = bcrypt($request->input('password'));
             $usuario->rol_id = $request->input('departamento');
             $usuario->save();
             DB::commit();
             return redirect()->route('usuario.index');
         } catch (QueryException $e) {
             echo $e;
             DB::rollBack();
             return redirect()->route('usuario.edit', $id);
         }
     } else {
         return redirect()->route('usuario.edit', $id);
     }
 }
 public function clear(Request $request)
 {
     $post = $request->all();
     $comment = $post['comment'];
     $value = $post['amount'];
     $student = $post['regNo'];
     $clearedAt = $post['signedAt'];
     $clearedBy = $post['signedBy'];
     $comment = preg_replace('/[^A-Za-z0-9 _]/', '', $comment);
     $value = preg_replace('/[^0-9]/', '', $value);
     DB::beginTransaction();
     $submit = DB::update("UPDATE charge\n            INNER JOIN comments ON charge.students_studentNo = comments.students_studentNo\n            INNER JOIN cleared_at ON charge.students_studentNo = cleared_at.students_studentNo\n            INNER JOIN cleared_by ON charge.students_studentNo = cleared_by.students_studentNo\n            SET\n            charge.cafeteria_value = '{$value}',\n            charge.queueFlag = charge.queueFlag + 1,\n            comments.cafeteria = '{$comment}',\n            cleared_at.cafeteria_cleared_at = '{$clearedAt}',\n            cleared_by.cafeteria_cleared_by = '{$clearedBy}'\n\n            WHERE charge.students_studentNo = '{$student}'\n            AND comments.students_studentNo = '{$student}'\n            AND cleared_at.students_studentNo = '{$student}'\n            AND cleared_by.students_studentNo='{$student}' ");
     if ($submit) {
         DB::commit();
     } else {
         DB::rollBack();
     }
     // $admin = DB::table('departments')
     //         ->join('administrators','departments.administrator','=','administrators.admin_id')
     //         ->select('administrators.email')->where('departments.department_name','=','Library')
     //         ->pluck('email');
     //Send Mail
     // Mail::send('mails.clear', ['student' => $student ], function($message) use($admin){
     //     $message->to($admin)->from('*****@*****.**', 'Strathmore University')->subject('Clearance');
     // });
     return redirect('/cafeteria');
 }
 /**
  * Handle the event.
  *
  * @param CurrencyMessageReceivedEvent
  * @return void
  */
 public function handle(CurrencyMessageReceivedEvent $event)
 {
     $timePlaced = new \DateTime($event->message->time_placed);
     $rate = MonthlyRate::where('year', $timePlaced->format('Y'))->where('month', $timePlaced->format('m'))->where('currency_from', $event->message->getAttribute('currency_from'))->where('currency_to', $event->message->getAttribute('currency_to'))->get()->first();
     if (is_null($rate)) {
         $rate = new MonthlyRate();
         $rate->tot_messages = 1;
         $rate->currency_from = $event->message->getAttribute('currency_from');
         $rate->currency_to = $event->message->getAttribute('currency_to');
         $rate->sum_rate = $event->message->getAttribute('rate');
         $rate->month = $timePlaced->format('m');
         $rate->year = $timePlaced->format('Y');
     } else {
         $rate->tot_messages++;
         $rate->sum_rate += $event->message->getAttribute('rate');
     }
     DB::beginTransaction();
     try {
         $rate->save();
         $key = $rate->currency_from . '-' . $rate->currency_to;
         $message = [$key => ['rate' => $rate->avg_rate, 'month' => $rate->month]];
         // Push message in redis to be displayed in the frontend
         $this->pushToSocket($message);
         DB::commit();
     } catch (\ErrorException $e) {
         DB::rollBack();
         // Throw the exception again to signal an error
         // in the processing
         throw $e;
     } catch (\Exception $e) {
         DB::rollBack();
         throw $e;
     }
 }
 /**
  * Creates an activity
  *
  * @param null|array $data
  * @return null|ActivityModel
  */
 public function create($data = null)
 {
     DB::beginTransaction();
     try {
         if (is_null($data)) {
             throw new NullDataException('The data array is required!');
         }
         foreach ($data as $k => $v) {
             if (!in_array($k, $this->fields)) {
                 throw new CreateActivityException('Please add the correct fields!');
             }
         }
         if (count(array_keys($data)) != count($this->fields)) {
             throw new CreateActivityException('The number of given data is different than required!');
         }
         $this->checkFields($data);
         $activity = ActivityModel::create($data);
         DB::commit();
         return $activity;
     } catch (NullDataException $e) {
         DB::rollBack();
         return $e;
     } catch (CreateActivityException $e) {
         DB::rollBack();
         return $e;
     }
 }
 public function saveTrackerEntry(Request $request)
 {
     // return $request->all();
     $validator = Validator::make($request->all(), ['desc' => 'required|min:5', 'time' => 'required|numeric', 'tags' => 'required', 'project_id' => 'required']);
     if ($request->input('project_id') == 'Select Project') {
         Session::flash('flash_error', 'You need to select the project');
         return redirect()->back()->withInput();
     }
     if ($validator->fails()) {
         return redirect()->back()->withErrors($validator)->withInput();
     }
     try {
         DB::beginTransaction();
         $project = Project::with('client')->find($request->input('project_id'));
         $entry = TimeEntry::create(['desc' => $request->input('desc'), 'user_id' => Auth::user()->id, 'project_id' => $project->id, 'project_name' => $project->name, 'client_name' => $project->client->name, 'time' => $request->input('time')]);
         // adding the entry of the ticket with tags mapping table
         foreach ($request->input('tags') as $key => $value) {
             DB::table('taggables')->insert(['tag_id' => $value, 'taggable_id' => $entry->id, 'taggable_type' => 'ticket', 'created_at' => Carbon::now(), 'updated_at' => Carbon::now()]);
         }
         if ($request->input('estimate_id')) {
             DB::table('time_entry_estimates')->insert(['time_entry_id' => $entry->id, 'estimate_id' => $request->input('estimate_id'), 'created_at' => Carbon::now(), 'updated_at' => Carbon::now()]);
             DB::update("UPDATE estimates SET hours_consumed = hours_consumed + :hours WHERE id = :id", ['hours' => $request->input('time'), 'id' => $request->input('estimate_id')]);
         }
         DB::commit();
         Session::flash('flash_message', 'Entry saved');
         return redirect('time-tracker');
     } catch (\PDOException $e) {
         DB::rollBack();
         abort(403, 'Data was not saved. Try again' . $e->getMessage());
     }
 }
Beispiel #7
0
 /**
  * Creates a type
  *
  * @param null|array $data
  * @return null|TypeModel
  */
 public function create($data = null)
 {
     DB::beginTransaction();
     try {
         if (is_null($data)) {
             throw new NullDataException('The data array is required!');
         }
         foreach ($data as $k => $v) {
             if (!in_array($k, $this->fields)) {
                 throw new CreateTypeException('Please add the correct fields!');
             }
         }
         if (count(array_keys($data)) != count($this->fields)) {
             throw new CreateTypeException('The number of given data is different than required!');
         }
         if (TypeModel::whereName($data['name'])->first()) {
             throw new CreateTypeException('The type name already exists!');
         }
         $type = TypeModel::create($data);
         DB::commit();
         return $type;
     } catch (NullDataException $e) {
         DB::rollBack();
         return $e;
     } catch (CreateTypeException $e) {
         DB::rollBack();
         return $e;
     }
 }
 /**
  * @param Request $request
  * @return array|\Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
  */
 public function uploadFile(Request $request)
 {
     try {
         try {
             DB::beginTransaction();
             $file = 'file';
             if ($request->has('filename')) {
                 $file = $request->input('filename');
             }
             $files = $request->file($file);
             if (!is_array($files)) {
                 $files[] = $request->file($file);
             }
             foreach ($files as $f) {
                 $extArr = explode("/", $f->getClientMimeType());
                 $mimeType = $f->getClientMimeType();
                 $fileSize = $f->getClientSize();
                 $originalFilename = $f->getClientOriginalName();
                 $type = 'local';
                 // check with the file extention
                 if ($extArr) {
                     $ext = $extArr[1];
                 }
                 if (!$ext) {
                     return false;
                 }
                 $fileName = uniqid() . "." . $ext;
                 if (!file_exists($this->filePath)) {
                     mkdir($this->filePath, 0777, true);
                 }
                 $f->move($this->filePath, $fileName);
                 $filePath = $this->filePath . $fileName;
                 // if the designation is s3. Upload
                 if ($request->input('destination') == 's3') {
                     $uploadPath = $request->input('path') . '/' . $fileName;
                     $type = 's3';
                     $s3 = Storage::disk('s3');
                     $s3->put($uploadPath, file_get_contents($filePath), 'public');
                     unlink($filePath);
                     $filePath = $this->s3Prefix . $uploadPath;
                 }
                 $file = File::create(['file_name' => $fileName, 'mime_type' => $mimeType, 'file_size' => $fileSize, 'file_path' => $filePath, 'client_file_name' => $originalFilename, 'type' => $type]);
                 $responseArr[] = $file;
             }
             DB::commit();
             return $responseArr;
         } catch (FileException $e) {
             return response($e->getMessage(), 500);
         }
     } catch (Exception $e) {
         DB::rollBack();
         return response('There were some errors uploading files', 500);
     }
 }
 /**
  * Run the request filter.
  *
  * @param  \Illuminate\Http\Request  $request
  * @param  \Closure  $next
  * @return mixed
  */
 public function handle($request, Closure $next)
 {
     DB::beginTransaction();
     try {
         $response = $next($request);
     } catch (Exception $e) {
         DB::rollBack();
         throw $e;
     }
     DB::commit();
     EventStore::publishQueue();
     return $response;
 }
Beispiel #10
0
 /**
  * Delete all data in the table
  */
 public static function deleteAllData()
 {
     self::all()->each(function ($action) {
         try {
             DB::beginTransaction();
             $action->delete();
             DB::commit();
             return;
         } catch (Exception $e) {
             DB::rollBack();
             return $e->getMessage();
         }
     });
 }
Beispiel #11
0
 public function deleteAlbum($id)
 {
     DB::beginTransaction();
     try {
         $albumImageTable = new AlbumImage();
         $albumImageTable->deleteAlbumImages($id);
         $this->where("id", "=", $id)->delete();
         DB::commit();
         return 1;
     } catch (Exception $e) {
         print_r($e);
         DB::rollBack();
         return 0;
     }
 }
Beispiel #12
0
 /**
  * Register a user
  *
  * @param Registration $request
  *
  * @return mixed
  */
 public function handleRegister(Registration $request)
 {
     DB::beginTransaction();
     try {
         $user = User::create($request->all());
         $user->assignRole(config('users.default'));
         auth()->login($user);
         event(new UserRegistered(auth()->user()));
     } catch (\Exception $exception) {
         DB::rollBack();
         return redirect(route('auth.register'))->with('errors', $exception->getMessage());
     }
     DB::commit();
     return redirect(route('home'))->with('message', 'Your account has been created.');
 }
 public function store(Request $request, $id)
 {
     $compra = Compra::find($id);
     $saldo = [];
     foreach ($compra->compra_itens as $key => $it) {
         if ($it->quantidade > $request->item[$key]['quantidade']) {
             $saldo[$key]['produto_id'] = $it->produto_id;
             $saldo[$key]['preco_compra'] = $it->preco_compra;
             $saldo[$key]['quantidade'] = $it->quantidade - $request->item[$key]['quantidade'];
         }
     }
     $new_compra = new Compra();
     if (count($saldo) > 0) {
         $new_compra->fornecedor_id = $compra->fornecedor_id;
         $new_compra->user_id = Auth::user()->id;
         $new_compra->data_compra = date('d/m/Y');
         $new_compra->save();
         foreach ($saldo as $s) {
             $it = new CompraItem();
             $it->compra_id = $new_compra->id;
             $it->produto_id = $s['produto_id'];
             $it->quantidade = $s['quantidade'];
             $it->save();
         }
     }
     DB::beginTransaction();
     try {
         foreach ($request->item as $item) {
             $p = Produto::find($item['produto_id']);
             $p->estoque += $item['quantidade'];
             $p->save();
         }
         $compra->status = 2;
         $compra->save();
         DB::commit();
     } catch (\Exception $e) {
         DB::rollBack();
         throw $e;
     }
     if ($this->reenviaEmail($new_compra)) {
         flash()->success('Confirmação de compra efetuada com sucesso e e-mail com itens que faltaram reenviado para o fornecedor');
     } else {
         flash()->success('Confirmação de compra efetuada com sucesso, mas email não foi enviado, envie o mesmo manualmente.');
     }
     return redirect()->route('compras.index');
 }
 /**
  * Store a newly created resource in storage.
  *
  * @return Response
  */
 public function store(Request $request)
 {
     // DB::transaction(function(){
     try {
         DB::beginTransaction();
         $comprobante_compra = $request->get('comprobante_compra');
         $comprobante_servicio = $request->get('comprobante_servicio');
         // dd($comprobante_servicio);
         foreach ($comprobante_compra as $key1 => $value1) {
             $asociar = new AsociarComprobante();
             $asociar->id_comprobanteVenta = $value1['id_comprobanteVenta'];
             $asociar->id_comprobanteCompra = $value1['id_comprobanteCompra'];
             $asociar->id_producto = $value1['id_producto'];
             $asociar->precio_compra = $value1['precio_compra'];
             $asociar->cantidad_compra = $value1['cantidad_compra'];
             $asociar->precio_venta = $value1['precio_venta'];
             $asociar->cantidad_venta = $value1['cantidad_venta'];
             $asociar->save();
             $id_cabecera = $asociar->id;
             $compra = ComprobanteDetalleCompra::find($value1['id_comprobanteDetalleCompra']);
             $compra->indicador_asociado = 'false';
             $compra->save();
             foreach ($comprobante_servicio as $key2 => $value2) {
                 if ($value1['id_producto'] == $value2['id_producto']) {
                     $AsociarComprobante = AsociarComprobante::find($id_cabecera);
                     $AsociarComprobante->id_comprobanteServicio = $value2['id_comprobanteServicio'];
                     $AsociarComprobante->precio_servicio = $value2['precio_servicio'];
                     $AsociarComprobante->cantidad_servicio = $value2['cantidad_servicio'];
                     $AsociarComprobante->save();
                     $servicio = ComprobanteDetalleServicio::find($value2['id_comprobanteDetalleServicio']);
                     $servicio->indicador_asociado = 'false';
                     $servicio->save();
                 }
             }
         }
         DB::commit();
         return \Response::json(array('datos' => 'correcto'));
     } catch (Exception $e) {
         DB::rollBack();
     }
 }
 public function store(Request $request)
 {
     $destino = $request->input('destino');
     $ruta_id = $request->input('ruta');
     if ($ruta_id > 0) {
         try {
             DB::beginTransaction();
             $nuevodestino = new Destino();
             $nuevodestino->destino = $destino;
             $nuevodestino->ruta_id = $ruta_id;
             $nuevodestino->save();
             DB::commit();
             return redirect()->route('destino.index');
         } catch (QueryException $ex) {
             DB::rollBack();
             return redirect()->route('destino.create');
         }
     } else {
         return redirect()->route('destino.create');
     }
 }
 public function saveUser(Request $request)
 {
     $validator = Validator::make($request->all(), ['name' => 'required|min:5', 'email' => 'required|unique:users,email', 'dob' => 'required', 'employee_id' => 'required', 'joining_date' => 'required', 'role' => 'required', 'password' => 'required|min:5']);
     if ($validator->fails()) {
         return redirect()->back()->withErrors($validator)->withInput();
     }
     try {
         DB::beginTransaction();
         $user = User::create(['name' => $request->input('name'), 'email' => $request->input('email'), 'dob' => $request->input('dob'), 'employee_id' => $request->input('employee_id'), 'joining_date' => $request->input('joining_date'), 'password' => Hash::make($request->input('password'))]);
         foreach ($request->input('role') as $roleId) {
             DB::table('roles_users')->insert(['user_id' => $user->id, 'role_id' => $roleId, 'created_at' => Carbon::now(), 'updated_at' => Carbon::now()]);
         }
         Session::flash('flash_message', 'User was created');
         DB::commit();
     } catch (\PDOException $e) {
         DB::rollBack();
         Session::flash('flash_error', 'User was not created');
         \Log::info(print_r($e->getMessage(), 1));
         return redirect()->back()->withErrors($validator)->withInput();
     }
     return redirect()->back();
 }
Beispiel #17
0
 public function updateData($data, $floor, $status, $id)
 {
     DB::beginTransaction();
     try {
         $data['updated_at'] = date("Y-m-d H:i:s");
         $res = $this->where("id", "=", $id)->update($data);
         if (count($floor) > 0) {
             $projectFloorPlansTable = new ProjectFloorPlans();
             $projectFloorPlansTable->insertData($floor, $id);
         }
         if (count($status) > 0) {
             $projectStatusTable = new ProjectStatus();
             $projectStatusTable->insertData($status, $id);
         }
         DB::commit();
         return 1;
     } catch (Exception $e) {
         print_r($e);
         DB::rollBack();
         return 0;
     }
 }
 public function deleteUser(Request $request, Response $response)
 {
     $validator = Validator::make($request->all(), ['id' => 'required|numeric']);
     if ($validator->fails()) {
         $response->header(Constants::RESPONSE_HEADER, "\"id\" query parameter is required and must contain number as value.");
         $response->setStatusCode(Response::HTTP_UNPROCESSABLE_ENTITY);
         return $response;
     }
     DB::beginTransaction();
     $userId = $request->input("id");
     $isUserDeleted = User::find($userId)->delete();
     if ($isUserDeleted === false) {
         DB::rollBack();
         $response->header(Constants::RESPONSE_HEADER, "Failed to delete user.");
         $response->setStatusCode(Response::HTTP_INTERNAL_SERVER_ERROR);
         return $response;
     }
     DB::commit();
     $response->header("Content-Type", "application/json");
     $response->header(Constants::RESPONSE_HEADER, "Successfully deleted user.");
     $response->setStatusCode(201);
     return $response;
 }
 /**
  * Stores resources in storage.
  *
  * @param  \Illuminate\Http\Request $request
  * @return \Illuminate\Http\Response
  */
 public function store(Request $request)
 {
     Log::debug("STORE CALLED .. ENV:" . env('APP_ENV') . " TOKEN:" . env('PIPEDRVIE_API_TOKEN'));
     //starting transaction for DB queries, if one of organizations fails, I will roll it back
     DB::beginTransaction();
     //saving to our DB in recursion loop (creating all daughters)
     $result = $this->saveOrganization($request->all());
     if (is_a($result, 'App\\Organization')) {
         //since I won't be able to roll back requests to pipedrive api, I use separate method to save data to pipedrive
         //at least at this point I am sure that all data passed all internal validation and stored in our DB
         if ($this->saveOrganizationToPipedrive($request->all())) {
             $success = true;
             DB::commit();
         } else {
             $success = false;
             DB::rollBack();
         }
     } else {
         $success = false;
         DB::rollBack();
     }
     return Response::json(compact('result', 'success'));
 }
 /**
  * Obsluga formularza rejestracji uzytkownika
  *
  * @param  \Illuminate\Http\Request  $request
  * @return \Illuminate\Http\Response
  */
 public function signup(Request $request)
 {
     $this->validate($request, ['name' => 'required|min:2|max:28|username|unique:users', 'email' => 'required|email|max:255|unique:users', 'password' => 'required|confirmed|min:3', 'human' => 'required']);
     DB::beginTransaction();
     try {
         $email = $request->input('email');
         $user = User::create(['name' => $request->input('name'), 'email' => $email, 'password' => bcrypt($request->input('password'))]);
         $actkey = Actkey::create(['actkey' => str_random(), 'user_id' => $user->id]);
         // taki format linku zachowany jest ze wzgledu na wsteczna kompatybilnosc.
         // z czasem mozemy zmienic ten format aby wskazywal na /User/Confirm/Email/<id>/<actkey>
         $url = route('user.email') . '?id=' . $user->id . '&actkey=' . $actkey->actkey;
         Mail::queue('emails.signup', ['url' => $url], function ($message) use($email) {
             $message->to($email);
             $message->subject('Dziękujemy za rejestrację. Potwierdź autentyczność swojego adresu e-mail');
         });
         Auth::login($user, true);
         stream(Stream_Create::class, new Stream_Person());
         DB::commit();
     } catch (\Exception $e) {
         DB::rollBack();
         throw $e;
     }
     return redirect()->intended(route('home'));
 }
 /**
  * Load records from file.
  *
  * @return Response
  */
 public function loadRecords(Request $request)
 {
     $validator = Validator::make($request->all(), ['file' => 'required'], ['required' => 'No file provided']);
     if ($validator->fails()) {
         return redirect()->back()->withInput()->withErrors($validator);
     } else {
         $contents = file($request->file('file')->getRealPath());
         try {
             DB::beginTransaction();
             $properties = ['full_name', 'email', 'text'];
             foreach ($contents as $lineNumber => $line) {
                 $gbr = new GuestBookRecord(array_combine($properties, explode(';', $line)));
                 $gbr->save();
             }
             DB::commit();
             return redirect()->back();
         } catch (\Exception $e) {
             DB::rollBack();
             $message = 'Invalid data provided at line ' . ($lineNumber + 1) . " ('{$line}')";
             $messageBag = new MessageBag(['content' => $message]);
             return redirect()->back()->withErrors($messageBag);
         }
     }
 }
 /**
  * Store the message received from the api call
  * POST /messages
  * @return Response
  */
 public function store(Request $request)
 {
     if ($request->isJson()) {
         $input = $this->formatInput($request->all());
         $validator = $this->getValidationFactory()->make($input, ['userId' => 'required', 'currencyFrom' => 'required', 'currencyTo' => 'required', 'amountSell' => 'required', 'amountBuy' => 'required', 'rate' => 'required', 'timePlaced' => 'required', 'originatingCountry' => 'required']);
         if ($validator->fails()) {
             $response = response()->json($validator->errors()->getMessages(), 400);
         } else {
             DB::beginTransaction();
             try {
                 $message = new CurrencyMessage();
                 $request = (object) $input;
                 $message->user_id = $request->userId;
                 $message->currency_from = $request->currencyFrom;
                 $message->currency_to = $request->currencyTo;
                 $message->amount_sell = $request->amountSell;
                 $message->amount_buy = $request->amountBuy;
                 $message->rate = $request->rate;
                 $message->country_origin = $request->originatingCountry;
                 $message->time_placed = $request->timePlaced;
                 // Save all the messages, in case something is wrong and the
                 // statistics need to be recalculated
                 $message->save();
                 Event::fire(new CurrencyMessageReceived($message));
                 $response = response()->make(null, 201);
                 DB::commit();
             } catch (\Exception $e) {
                 DB::rollBack();
                 $response = response()->make($e->getMessage(), 500);
             }
         }
         return $response;
     } else {
         throw new BadRequestHttpException('This method accepts json requests.');
     }
 }
 public function addUserTags()
 {
     $request = Request::capture();
     $token = $request->input('token');
     $tags = $request->input('tags');
     if ($tags == null) {
         return Utility::response_format(Utility::RESPONSE_CODE_Error, '', '标签不能为空');
     }
     $userId = AuthController::getUserIdByToken($token);
     if ($userId == null) {
         return Utility::response_format(Utility::RESPONSE_CODE_AUTH_ERROR, '', '认证失败');
     }
     DB::beginTransaction();
     try {
         $array = explode(',', $tags);
         $result = UserTags::where('user_id', $userId)->delete();
         foreach ($array as $tag) {
             $result = UserTags::create(['user_id' => $userId, 'tag_id' => $tag]);
         }
         DB::commit();
         return Utility::response_format(Utility::RESPONSE_CODE_SUCCESS, '', '添加成功');
     } catch (Exception $e) {
         DB::rollBack();
         return Utility::response_format(Utility::RESPONSE_CODE_DB_ERROR, '', $e->getMessage());
     }
 }
 public function saveTicketConversation(Request $request)
 {
     $ticketId = $request->input('ticketId');
     $comment = $request->input('comment');
     try {
         DB::beginTransaction();
         $comment = new Comment();
         $comment->comment = $request->input('comment');
         $comment->user_id = Auth::user()->id;
         $comment->parent_id = 0;
         $comment->status = 1;
         $comment->save();
         DB::table('commentables')->insert(['comment_id' => $comment->id, 'commentable_id' => $ticketId, 'commentable_type' => 'App\\Ticket']);
         $attachments = $request->input('attachments');
         if ($attachments) {
             foreach ($attachments as $key => $attachment) {
                 $attachmentInsert[] = ['file_id' => $attachment['id'], 'fileable_id' => $comment->id, 'fileable_type' => 'App\\Comment'];
             }
             DB::table('fileables')->insert($attachmentInsert);
         }
         DB::commit();
         return response(['data' => $this->getCommentsData($ticketId)], 200);
     } catch (\PDOException $e) {
         DB::rollBack();
     }
 }
 public function publishAnswer()
 {
     $request = Request::capture();
     $token = $request->input('token');
     $content = $request->input('content');
     $questionId = $request->input('questionId');
     $brief = $request->input('brief');
     $pictures = $request->input('picids');
     if ($content == null) {
         return Utility::response_format(Utility::RESPONSE_CODE_Error, '', '内容不能为空');
     }
     $userId = AuthController::getUserIdByToken($token);
     if ($userId == null) {
         return Utility::response_format(Utility::RESPONSE_CODE_AUTH_ERROR, '', '认证失败');
     }
     DB::beginTransaction();
     try {
         $answer = Answer::create(['answer_content' => $content, 'answer_brief' => $brief, 'user_id' => $userId, 'question_id' => $questionId, 'answer_time' => time()]);
         if ($pictures != null) {
             $picArray = explode(',', $pictures);
             foreach ($picArray as $pic) {
                 AnswerPictures::create(['answer_id' => $answer->id, 'pic_id' => $pic]);
             }
         }
         DB::commit();
         return Utility::response_format(Utility::RESPONSE_CODE_SUCCESS, '', '发布成功');
     } catch (Exception $e) {
         DB::rollBack();
         return Utility::response_format(Utility::RESPONSE_CODE_DB_ERROR, '', $e->getMessage());
     }
 }
 /**
  * Performs the actual processing
  */
 protected function doProcessing()
 {
     $this->prepareProcessContext();
     // initialization process pipeline
     $initSteps = $this->initProcessSteps();
     if (!empty($initSteps)) {
         $this->context = app(Pipeline::class)->send($this->context)->through($initSteps)->then(function (ProcessContextInterface $context) {
             return $context;
         });
         $this->afterInitSteps();
     }
     // main pipeline (actual processing)
     $steps = $this->processSteps();
     if ($this->databaseTransaction) {
         DB::beginTransaction();
     }
     try {
         $this->context = app(Pipeline::class)->send($this->context)->through($steps)->then(function (ProcessContextInterface $context) {
             if ($this->databaseTransaction) {
                 DB::commit();
             }
             return $context;
         });
     } catch (Exception $e) {
         if ($this->databaseTransaction) {
             DB::rollBack();
         }
         $this->onExceptionInPipeline($e);
         throw $e;
     }
     $this->afterPipeline();
     $this->populateResult();
 }
 /**
  * @param Request $request
  * @return $this|\Illuminate\Http\RedirectResponse
  */
 public function loadFromFile(Request $request)
 {
     $validator = Validator::make($request->all(), ['file' => 'required'], ['required' => 'No file provided']);
     if ($validator->fails()) {
         return redirect()->back()->withErrors($validator);
     } else {
         $contents = file($request->file('file')->getRealPath());
         try {
             DB::beginTransaction();
             foreach ($contents as $lineNumber => $line) {
                 $record = array_combine(['subject', 'text', 'created_at'], str_getcsv($line));
                 $recordsValidator = Validator::make($record, BlogRecordRequest::getValidationRules());
                 if ($recordsValidator->fails()) {
                     throw new \Exception();
                 } else {
                     $br = new BlogRecord($record);
                     $br->save();
                 }
             }
             DB::commit();
             return redirect()->back();
         } catch (\Exception $e) {
             DB::rollBack();
             return redirect()->back()->withErrors(new MessageBag(['Line number' => $lineNumber]));
         }
     }
 }
Beispiel #28
0
 public function postVendorRegister(Request $request)
 {
     try {
         $validator = $this->validator($request->all());
         if ($validator->fails()) {
             $this->throwValidationException($request, $validator);
         }
         DB::beginTransaction();
         // Create User first
         $user = $this->create($request->all(), config('app.role_vendor'));
         // Now validate / create vendor profile
         $data = $request->all();
         $vendorValidator = $this->vendorValidator($data);
         if ($vendorValidator->fails()) {
             $this->throwValidationException($request, $vendorValidator);
         }
         // Attempt to upload the images
         $uploader = new UploadHandler();
         if ($request->hasFile('logo_image_path') && $request->file('logo_image_path')->isValid() && $uploader->isImage($request->file('logo_image_path'))) {
             $newFilename = $uploader->uploadVendorAsset($request->file('logo_image_path'));
             $data['logo_image_path'] = $newFilename;
         }
         if ($request->hasFile('background_image_path') && $request->file('background_image_path')->isValid() && $uploader->isImage($request->file('background_image_path'))) {
             $newFilename = $uploader->uploadVendorAsset($request->file('background_image_path'));
             $data['background_image_path'] = $newFilename;
         }
         $vendor = $this->createVendor($user->id, $data);
         DB::commit();
         \Auth::login($user);
     } catch (\Exception $ex) {
         DB::rollBack();
         throw $ex;
     }
     // Send an email to us to notify of new vendor registration
     try {
         $mailData = ['to' => config('app.vendor_registration_notify_email'), 'from' => $user->email, 'subject' => 'Vendor ' . $user->email . ' has registered', 'body' => 'Vendor sign up: Email:' . $user->email . ', Company Name: ' . $vendor->company_name, 'sendRaw' => true];
         $this->dispatch(new SendEmail($mailData));
     } catch (\Exception $ex) {
         // If email fails do not stop registration from happening
     }
     return redirect($this->redirectPath());
 }
Beispiel #29
0
 public function update(Request $request)
 {
     $articleResult = Articles::find($request->input('id'));
     if (!$articleResult) {
         return redirect('backend/articles');
     }
     $request->request->set('published_at', Carbon\Carbon::now());
     $this->validate($request, ['title' => 'required', 'content' => 'required', 'published_at' => 'required', 'tags' => 'required']);
     $input = $request->all();
     $articleResult->update($input);
     $raw_tags = array();
     //文章没有修改前的标签
     foreach ($articleResult->tags as $raw_v) {
         $raw_tags[] = $raw_v->tag_name;
     }
     $new_tags = explode(',', ltrim(rtrim(trim($input['tags']), ','), ','));
     $new_tags = array_unique(array_map('trim', $new_tags));
     //修改后的标签
     $tags_inserts = array_diff($new_tags, $raw_tags);
     //需要和文章新增关系标签
     $tags_deletes = array_diff($raw_tags, $new_tags);
     //需要和文章去除关系的标签
     // 		dd($tags_deletes);
     DB::beginTransaction();
     try {
         if (isset($tags_inserts) && count($tags_inserts)) {
             foreach ($tags_inserts as $tags_insert) {
                 if ($tags_insert) {
                     $tag_res = Tags::where('tag_name', $tags_insert)->first();
                     if (!$tag_res) {
                         $articleResult->tags()->saveMany(new Tags(['tag_name' => $tags_insert, 'use_nums' => 1]));
                     } else {
                         $tag_res->use_nums++;
                         $tag_res->save();
                         $tag_res->articles()->attach($articleResult->id);
                     }
                 }
             }
         }
         unset($tag_res);
         if (isset($tags_deletes) && count($tags_deletes)) {
             foreach ($tags_deletes as $tags_delete) {
                 if ($tags_delete) {
                     $tag_res = Tags::where('tag_name', $tags_delete)->first();
                     if ($tag_res) {
                         $tag_res->use_nums--;
                         $tag_res->save();
                         $tag_res->articles()->detach($articleResult->id);
                     }
                 }
             }
         }
         DB::commit();
     } catch (\Exception $e) {
         DB::rollBack();
         dd($e->getMessage());
     }
     return redirect('backend/articles');
 }
 public function checkUserProfileViews($userDetails)
 {
     $instagramScrape = new API\InstagramAPI\Instagram_scrape();
     //        $objInstagramAPI = new API\InstagramAPI\Instagram();
     $instagramUserModel = new Instagram_User();
     $objUsermetaModel = new Usersmeta();
     $objOrderModel = new Order();
     $whereIn = implode(',', array_unique(array_map(function ($v) {
         return $v->ins_user_id;
     }, $userDetails)));
     $insUserStatus = $instagramUserModel->updateUserDetails(['rawQuery' => 'ins_user_id IN(' . $whereIn . ')'], ['cronjob_status' => 0]);
     //replace with 1
     if (!Session::has('FE_in_checkUserProfile')) {
         //FE=Fatal_Error
         $fataErrorData['whereIn'] = $whereIn;
         $fataErrorData['modalObject'] = $instagramUserModel;
         $fataErrorData['functionName'] = 'updateUserDetails';
         $fataErrorData['params'] = 'ins_user_id';
         Session::put('FE_in_checkUserProfile', $fataErrorData);
     }
     try {
         $id = 1;
         foreach ($userDetails as $user) {
             $username = $user->ins_username;
             print_r($id . ' . ');
             print_r($username);
             echo "<br>";
             ++$id;
             $username = $user->ins_username;
             $picsFetchCount = intval($user->pics_fetch_count);
             //            $picsDone = intval($user->pics_done);
             $picLimit = intval($user->pics_limit);
             $dailyPostLimit = intval($user->daily_post_limit);
             $dailyPostDone = intval($user->daily_post_done);
             $lastPostCreatedTime = intval($user->last_post_created_time);
             $firstPost_deliveryTime_day = intval($user->firstpost_delivery_daytime);
             $orderDelay = intval($user->order_delay_flag);
             $endDateTime = intval($user->end_date_time);
             $whereInsUser = ['rawQuery' => 'ins_user_id=?', 'bindParams' => [$user->ins_user_id]];
             // code for reset daily limit every 24 hr. If daily limit cross then stop  autolikes script for next 24 hrs.
             // Daily limit will be automatically reset every 24 hours from the time the user make the first post
             if (intval($user->ig_user_status) == 2 || intval($user->ig_user_status) == 3) {
                 if ($firstPost_deliveryTime_day != 0) {
                     if (time() - $firstPost_deliveryTime_day >= 86400) {
                         //24 hr = 86400 seconds
                         $updatedData23 = ['last_post_created_time' => time(), 'firstpost_delivery_daytime' => time(), 'daily_post_done' => 0, 'ig_user_status' => 2, 'cronjob_status' => 0, 'message' => 'The script is waiting for new post. Searching new post in every 5 minutes!'];
                         $queryResult = $instagramUserModel->updateUserDetails($whereInsUser, $updatedData23);
                     }
                 } else {
                     if (intval($user->ig_user_status) == 3) {
                         $queryResult = $instagramUserModel->updateUserDetails($whereInsUser, ['cronjob_status' => 0]);
                     }
                 }
             }
             // This script will run when autolikes script was stopped due to in-sufficient balance,
             // This code will automatically reset autolikes running script when user add balance in account.
             if (intval($user->ig_user_status) == 3) {
                 if ($user->last_order_total_price != 0) {
                     $accountBalanceDetails = $objUsermetaModel->getUsermetaWhere(['rawQuery' => 'user_id=?', 'bindParams' => [$user->by_user_id]], ['account_bal']);
                     $accountBalance = $accountBalanceDetails->account_bal;
                     if ($accountBalance >= $user->last_order_total_price) {
                         $updatedData3 = ['ig_user_status' => 2, 'cronjob_status' => 0, 'message' => 'The script is waiting for new post. Searching new post in every 5 minutes!'];
                         $queryResult = $instagramUserModel->updateUserDetails($whereInsUser, $updatedData3);
                     }
                 } else {
                     $queryResult = $instagramUserModel->updateUserDetails($whereInsUser, ['cronjob_status' => 0]);
                 }
             }
             $expiredFlag = false;
             if ($endDateTime != 0 && $endDateTime < time()) {
                 if ($user->ig_user_status != 4) {
                     $updatedData = ['ig_user_status' => 4, 'cronjob_status' => 0, 'message' => 'This profile #' . $username . ' has expired. If you wish to continue, increase the end date in edit option. '];
                     $queryResult = $instagramUserModel->updateUserDetails($whereInsUser, $updatedData);
                 } else {
                     $queryResult = $instagramUserModel->updateUserDetails($whereInsUser, ['cronjob_status' => 0]);
                 }
                 $expiredFlag = true;
             } else {
                 if ($user->ig_user_status == 4) {
                     $updatedData = ['ig_user_status' => 2, 'cronjob_status' => 0, 'message' => 'The script is waiting for new post. Searching new post in every 5 minutes!'];
                     $queryResult = $instagramUserModel->updateUserDetails($whereInsUser, $updatedData);
                 }
             }
             if (!$expiredFlag) {
                 if (intval($user->ig_user_status) == 2) {
                     if ($lastPostCreatedTime == 0) {
                         $lastPostCreatedTime = time();
                         $queryResult = $instagramUserModel->updateUserDetails($whereInsUser, ['last_post_created_time' => time()]);
                     }
                     if ($dailyPostLimit > 0) {
                         if ($picsFetchCount < $picLimit) {
                             if ($dailyPostDone < $dailyPostLimit) {
                                 //scrap all the latest post created after the last post created time
                                 $userDetails = [];
                                 //                                    if (intval($user->plan_type) == 0) {// for likes
                                 ////                                        print_r($username); echo"<br>";
                                 //                                        $username = strtolower($username);
                                 ////                                        $userDetails = $objInstagramAPI->UserDetailsByUsernameWithLastPostCreatedTime($username, $user->last_post_created_time);
                                 //                                        $userDetails = $instagramScrape->instagramScrape($username, $lastPostCreatedTime, 'image');
                                 //
                                 ////                                        $userProfileData = $instagramScrape->getInsUserLatestPostDetails($username, $lastPostCreatedTime, $dailyPostLimit, 'image');
                                 //                                    } else if (intval($user->plan_type) == 4) { // for video
                                 $username = strtolower($username);
                                 $userDetails = $instagramScrape->instagramScrape($username, $lastPostCreatedTime, 'video');
                                 //                                        $userProfileData = $instagramScrape->getInsUserLatestPostDetails($username, $lastPostCreatedTime, $dailyPostLimit, 'video');
                                 //                                    }
                                 //                                dd($userProfileData);
                                 if ($userDetails != null) {
                                     // && $userDetails != "Username does not exist" && $userDetails != "user is private"
                                     $latestPostCreatedTime = 0;
                                     $latestPostCreatedTimeFlag = false;
                                     $latestDeliveryLink = '';
                                     $startTime = time();
                                     $userDetails = array_reverse($userDetails, true);
                                     foreach ($userDetails as $key => $value) {
                                         $startTime = time();
                                         $startTime = $orderDelay == 1 ? $startTime + 600 : $startTime;
                                         //600= 10 minutes delay in next order
                                         // get the latest post link and place that link  for autolikes order
                                         if ($dailyPostDone < $dailyPostLimit && $picsFetchCount < $picLimit) {
                                             //add order in order table and then in order-process table
                                             // This code is for placing  autolikes order only (likes orders)
                                             // check if auto comment is set or not
                                             $autoCommentsPrice = 0;
                                             $autoCommentsData = array();
                                             if ($user->autoComments == "YES") {
                                                 $autoCommentsPrice = $user->price_for_autoComments / 1000 * $user->comments_amount;
                                                 $autoCommentsData['plan_id'] = $user->plan_id_for_autoComments;
                                                 $autoCommentsData['by_user_id'] = $user->by_user_id;
                                                 $autoCommentsData['for_user_id'] = $user->ins_user_id;
                                                 $autoCommentsData['ins_url'] = "https://www.instagram.com/p/" . $value['link'] . "/";
                                                 $autoCommentsData['quantity_total'] = $user->comments_amount;
                                                 $autoCommentsData['comment_id'] = $user->custom_comment_id;
                                                 $autoCommentsData['start_time'] = $startTime;
                                                 $autoCommentsData['added_time'] = time();
                                                 $autoCommentsData['updated_time'] = time();
                                                 $autoCommentsData['auto_order_status'] = 1;
                                                 // 1=autolikes order
                                                 $autoCommentsData['status'] = 0;
                                                 // order is in pending state
                                                 $autoCommentsData['price'] = $autoCommentsPrice;
                                                 $autoCommentsData['orders_per_run'] = 0;
                                                 $autoCommentsData['time_interval'] = 0;
                                                 $autoCommentsData['url_type'] = 0;
                                                 // 0=postLink
                                                 $autoCommentsData['order_message'] = 'Order has inserted! This order has a schedule time and it will start after (' . $this->getDateDifference($startTime) . ').Please wait to get it started!';
                                                 // 0=postLink
                                             }
                                             $autoLikesPrice = $user->charge_per_unit / 1000 * $user->likes_per_pic;
                                             $accountBalanceDetails = $objUsermetaModel->getUsermetaWhere(['rawQuery' => 'user_id=?', 'bindParams' => [$user->by_user_id]], ['account_bal']);
                                             $accountBalance = $accountBalanceDetails->account_bal;
                                             $totalPrice = $autoLikesPrice + $autoCommentsPrice;
                                             if ($accountBalance >= $totalPrice) {
                                                 $autoLikesData['plan_id'] = $user->plan_id;
                                                 $autoLikesData['by_user_id'] = $user->by_user_id;
                                                 $autoLikesData['for_user_id'] = $user->ins_user_id;
                                                 //code added and modified by Saurabh
                                                 $autoLikesData['ins_url'] = "https://www.instagram.com/p/" . $value['link'] . "/";
                                                 $autoLikesData['initial_likes_count'] = $value['likes_count'];
                                                 $autoLikesData['initial_followers_count'] = $value['followers_count'];
                                                 $autoLikesData['initial_comments_count'] = $value['comments_count'];
                                                 $autoLikesData['initial_views_count'] = $value['views_count'];
                                                 $autoLikesData['quantity_total'] = $user->likes_per_pic;
                                                 $autoLikesData['start_time'] = $startTime;
                                                 $autoLikesData['added_time'] = time();
                                                 $autoLikesData['updated_time'] = time();
                                                 $autoLikesData['auto_order_status'] = 1;
                                                 // 1=autolikes order
                                                 $autoLikesData['status'] = 0;
                                                 // order is in pending state
                                                 $autoLikesData['price'] = $autoLikesPrice;
                                                 $autoLikesData['orders_per_run'] = 0;
                                                 $autoLikesData['time_interval'] = 0;
                                                 $autoLikesData['url_type'] = 0;
                                                 // 0=postLink
                                                 $autoLikesData['order_message'] = 'Order has inserted! This order has a schedule time and it will start after (' . $this->getDateDifference($startTime) . ').Please wait to get it started!';
                                                 // 0=postLink
                                                 $rollback = false;
                                                 DB::beginTransaction();
                                                 DB::table('usersmeta')->where('user_id', '=', $user->by_user_id)->lockForUpdate()->get();
                                                 $autoLikesOrderInsertedStatus = $objOrderModel->insertOrder($autoLikesData);
                                                 $autoCommentsOrderInsertedStatus = 1;
                                                 if ($user->autoComments == "YES") {
                                                     $autoCommentsOrderInsertedStatus = $objOrderModel->insertOrder($autoCommentsData);
                                                 }
                                                 if ($autoLikesOrderInsertedStatus && $autoCommentsOrderInsertedStatus) {
                                                     $current_bal['account_bal'] = $accountBalance - $totalPrice;
                                                     $orderUpdateBalanceStatus = $objUsermetaModel->updateUsermetaWhere(['rawQuery' => 'user_id=?', 'bindParams' => [$user->by_user_id]], $current_bal);
                                                     if ($orderUpdateBalanceStatus) {
                                                         DB::commit();
                                                     } else {
                                                         $rollback = true;
                                                         DB::rollBack();
                                                     }
                                                 } else {
                                                     $rollback = true;
                                                     DB::rollBack();
                                                 }
                                                 if (!$rollback) {
                                                     //this code runs only when user make the first post (first order is placed).
                                                     if ($firstPost_deliveryTime_day == 0) {
                                                         $data4['firstpost_delivery_daytime'] = time();
                                                         $queryResult = $instagramUserModel->updateUserDetails($whereInsUser, $data4);
                                                     }
                                                     ++$picsFetchCount;
                                                     ++$dailyPostDone;
                                                     $latestPostCreatedTime = $value['created_time'];
                                                     $latestDeliveryLink = "https://www.instagram.com/p/" . $value['link'] . "/";
                                                     $latestPostCreatedTimeFlag = true;
                                                     //modified by saurabh
                                                     $startTime = $orderDelay == 1 ? $startTime + 600 : $startTime;
                                                     // for adding 10 MORE minutes delay in next order // if flag is not set than order will place at instant
                                                     //                                                $startTime += 600;//600= 10 minutes delay in next order placing
                                                 }
                                             } else {
                                                 $data5 = ['cronjob_status' => 0, 'ig_user_status' => 3, 'last_order_total_price' => $totalPrice, 'message' => 'Autolikes script has been stopped for # ' . $user->ins_username . ' due to insufficient balance.'];
                                                 $queryResult = $instagramUserModel->updateUserDetails($whereInsUser, $data5);
                                                 break;
                                             }
                                         }
                                     }
                                     //End of inner foreach loop
                                     // Update details in instagram_users table
                                     if ($latestPostCreatedTimeFlag) {
                                         $data6['pics_fetch_count'] = $picsFetchCount;
                                         $data6['daily_post_done'] = $dailyPostDone;
                                         $data6['last_post_created_time'] = $latestPostCreatedTime;
                                         $data6['last_delivery_link'] = $latestDeliveryLink;
                                         //                                            print_r($data6);
                                         $queryResult = $instagramUserModel->updateUserDetails($whereInsUser, $data6);
                                     }
                                 }
                             }
                         }
                     } else {
                         if ($dailyPostLimit == 0) {
                             if ($picsFetchCount < $picLimit) {
                                 //scrap all the latest post created after the first post created time
                                 $userDetails = [];
                                 //                                if ($user->plan_type == 0) {// for likes
                                 ////                                    $objInstagramAPI = new API\InstagramAPI\Instagram();
                                 ////                                    print_r($username); echo "<br>";
                                 //                                    $username = strtolower($username);
                                 ////                                    $userDetails = $objInstagramAPI->UserDetailsByUsernameWithLastPostCreatedTime($username, $user->last_post_created_time);
                                 //                                    $userDetails = $instagramScrape->instagramScrape($username, $lastPostCreatedTime, "image");
                                 ////                                    dd($userDetails);
                                 ////                                    $userProfileData = (isset($userDetails['instagramUsersData'])) ? $userDetails['instagramUsersData'] : '';
                                 //
                                 //
                                 ////                                    $userDetails = $instagramScrape->getInsUserLatestPostDetails($username, $lastPostCreatedTime, 0, 'image');
                                 ////                                    dd($userDetails['instagramUsersData']);
                                 //                                } else if ($user->plan_type == 4) { // for video
                                 $username = strtolower($username);
                                 $userDetails = $instagramScrape->instagramScrape($username, $lastPostCreatedTime, "video");
                                 //                                    $userDetails = $instagramScrape->getInsUserLatestPostDetails($username, $lastPostCreatedTime, 0, 'video');
                                 //                                }
                                 if ($userDetails != null) {
                                     // && $userDetails != "Username does not exist" && $userDetails != "user is private"
                                     $latestPostCreatedTime = 0;
                                     $latestDeliveryLink = '';
                                     $latestPostCreatedTimeFlag = false;
                                     $startTime = time();
                                     $userDetails = array_reverse($userDetails, true);
                                     foreach ($userDetails as $key => $value) {
                                         $startTime = time();
                                         $startTime = $orderDelay == 1 ? $startTime + 600 : $startTime;
                                         //600= 10 minutes delay in next order
                                         // get the latest post link and place that link  for autolikes order
                                         if ($picsFetchCount < $picLimit) {
                                             //add order in order table and then in order-process table
                                             // This code is for placing  autolikes order only (likes orders)
                                             $autoCommentsPrice = 0;
                                             $autoCommentsData = array();
                                             if ($user->autoComments == "YES") {
                                                 $autoCommentsPrice = $user->price_for_autoComments / 1000 * $user->comments_amount;
                                                 $autoCommentsData['plan_id'] = $user->plan_id_for_autoComments;
                                                 $autoCommentsData['by_user_id'] = $user->by_user_id;
                                                 $autoCommentsData['for_user_id'] = $user->ins_user_id;
                                                 $autoCommentsData['ins_url'] = "https://www.instagram.com/p/" . $value['link'] . "/";
                                                 $autoCommentsData['quantity_total'] = $user->comments_amount;
                                                 $autoCommentsData['comment_id'] = $user->custom_comment_id;
                                                 $autoCommentsData['start_time'] = $startTime;
                                                 $autoCommentsData['added_time'] = time();
                                                 $autoCommentsData['updated_time'] = time();
                                                 $autoCommentsData['auto_order_status'] = 1;
                                                 // 1=autolikes order
                                                 $autoCommentsData['status'] = 0;
                                                 // order is in pending state
                                                 $autoCommentsData['price'] = $autoCommentsPrice;
                                                 $autoCommentsData['orders_per_run'] = 0;
                                                 $autoCommentsData['time_interval'] = 0;
                                                 $autoCommentsData['url_type'] = 0;
                                                 // 0=postLink
                                                 $autoCommentsData['order_message'] = 'Order has inserted! This order has a schedule time and it will start after (' . $this->getDateDifference($startTime) . ').Please wait to get it started!';
                                                 // 0=postLink
                                             }
                                             $autoLikesOrViewsPrice = $user->charge_per_unit / 1000 * $user->likes_per_pic;
                                             //likes_per_pic is same as views per pic
                                             $accountBalanceDetails = $objUsermetaModel->getUsermetaWhere(['rawQuery' => 'user_id=?', 'bindParams' => [$user->by_user_id]], ['account_bal']);
                                             $accountBalance = $accountBalanceDetails->account_bal;
                                             $totalPrice = $autoLikesOrViewsPrice + $autoCommentsPrice;
                                             if ($accountBalance >= $totalPrice) {
                                                 $autoLikesOrViewsData['plan_id'] = $user->plan_id;
                                                 $autoLikesOrViewsData['by_user_id'] = $user->by_user_id;
                                                 $autoLikesOrViewsData['for_user_id'] = $user->ins_user_id;
                                                 $autoLikesOrViewsData['ins_url'] = "https://www.instagram.com/p/" . $value['link'] . "/";
                                                 $autoLikesOrViewsData['initial_likes_count'] = $value['likes_count'];
                                                 $autoLikesOrViewsData['initial_followers_count'] = $value['followers_count'];
                                                 $autoLikesOrViewsData['initial_comments_count'] = $value['comments_count'];
                                                 $autoLikesOrViewsData['initial_views_count'] = $value['views_count'];
                                                 $autoLikesOrViewsData['quantity_total'] = $user->likes_per_pic;
                                                 //likes_per_pic is same as views per pic
                                                 $autoLikesOrViewsData['start_time'] = $startTime;
                                                 $autoLikesOrViewsData['added_time'] = time();
                                                 $autoLikesOrViewsData['updated_time'] = time();
                                                 $autoLikesOrViewsData['auto_order_status'] = 1;
                                                 // 1=autolikes order
                                                 $autoLikesOrViewsData['status'] = 0;
                                                 // order is in pending state
                                                 $autoLikesOrViewsData['price'] = $autoLikesOrViewsPrice;
                                                 $autoLikesOrViewsData['orders_per_run'] = 0;
                                                 $autoLikesOrViewsData['time_interval'] = 0;
                                                 $autoLikesOrViewsData['url_type'] = 0;
                                                 // 0=postLink
                                                 $autoLikesOrViewsData['order_message'] = 'Order has inserted! This order has a schedule time and it will start after (' . $this->getDateDifference($startTime) . ').Please wait to get it started!';
                                                 $rollback = false;
                                                 DB::beginTransaction();
                                                 DB::table('usersmeta')->where('user_id', '=', $user->by_user_id)->lockForUpdate()->get();
                                                 $orderInsertedStatus = $objOrderModel->insertOrder($autoLikesOrViewsData);
                                                 $commentsOrderInsertedStatus = 1;
                                                 if ($user->autoComments == "YES") {
                                                     $commentsOrderInsertedStatus = $objOrderModel->insertOrder($autoCommentsData);
                                                 }
                                                 if ($orderInsertedStatus && $commentsOrderInsertedStatus) {
                                                     $current_bal['account_bal'] = $accountBalance - $totalPrice;
                                                     $orderUpdateBalanceStatus = $objUsermetaModel->updateUsermetaWhere(['rawQuery' => 'user_id=?', 'bindParams' => [$user->by_user_id]], $current_bal);
                                                     if ($orderUpdateBalanceStatus) {
                                                         DB::commit();
                                                     } else {
                                                         $rollback = true;
                                                         DB::rollBack();
                                                     }
                                                 } else {
                                                     $rollback = true;
                                                     DB::rollBack();
                                                 }
                                                 if (!$rollback) {
                                                     //                                            // Update details in instagram_users table
                                                     //                                            $whereInsUser = ['rawQuery' => 'ins_user_id=?', 'bindParams' => [$user->ins_user_id]];
                                                     //                                            $updateInsUserData = [
                                                     //                                                'pics_fetch_count' => ++$picsFetchCount,
                                                     //                                                'daily_post_done' => ++$dailyPostDone,
                                                     //                                                'cronjob_status' => 0,
                                                     //                                                'last_check' => time(),
                                                     ////                                            'last_delivery' => time(),
                                                     ////                                            'last_delivery_link' => $value['link'],
                                                     //                                                'last_post_created_time' => $value['created_time']
                                                     //                                            ];
                                                     //                                            $queryResult = $instagramUserModel->updateUserDetails($whereInsUser, $updateInsUserData);
                                                     //this code is run only when user make the first post (first order is placed).
                                                     if ($firstPost_deliveryTime_day == 0) {
                                                         $data4['firstpost_delivery_daytime'] = time();
                                                         $queryResult = $instagramUserModel->updateUserDetails($whereInsUser, $data4);
                                                     }
                                                     ++$picsFetchCount;
                                                     ++$dailyPostDone;
                                                     $latestPostCreatedTime = $value['created_time'];
                                                     $latestDeliveryLink = "https://www.instagram.com/p/" . $value['link'] . "/";
                                                     $latestPostCreatedTimeFlag = true;
                                                     //modified by saurabh
                                                     // for adding 10 MORE minutes delay in next order, if flag is not set than order will place at instant
                                                     $startTime = $orderDelay == 1 ? $startTime + 600 : $startTime;
                                                     //$startTime += 600;//600= 10 minutes delay in next order placing
                                                 }
                                             } else {
                                                 // insert your custom message here in instagram_users table
                                                 $updateInsUserMessageData = ['cronjob_status' => 0, 'ig_user_status' => 3, 'last_order_total_price' => $totalPrice, 'message' => 'Autolikes script has been stopped for # ' . $user->ins_username . ' due to insufficient balance.'];
                                                 $queryResult = $instagramUserModel->updateUserDetails($whereInsUser, $updateInsUserMessageData);
                                                 break;
                                             }
                                         }
                                     }
                                     //End of inner foreach loop
                                     // Update details in instagram_users table
                                     if ($latestPostCreatedTimeFlag) {
                                         $data6['pics_fetch_count'] = $picsFetchCount;
                                         $data6['daily_post_done'] = $dailyPostDone;
                                         $data6['last_post_created_time'] = $latestPostCreatedTime;
                                         $data6['last_delivery_link'] = $latestDeliveryLink;
                                         //                                        print_r($data6);echo "<br>";
                                         $queryResult = $instagramUserModel->updateUserDetails($whereInsUser, $data6);
                                     }
                                 }
                             }
                         }
                     }
                     $updateInsUserData = ['cronjob_status' => 0, 'last_check' => time()];
                     $queryResult = $instagramUserModel->updateUserDetails($whereInsUser, $updateInsUserData);
                 }
             }
         }
         //End of Outer foreach loop
     } catch (\Exception $e) {
         echo $e->getMessage();
         $insUserStatus = $instagramUserModel->updateUserDetails(['rawQuery' => 'ins_user_id IN(' . $whereIn . ')'], ['cronjob_status' => 0]);
     }
 }