/**
  * Show the search result for finding contributors.
  *
  * @return \Illuminate\Http\Response
  */
 public function searchContributor(Request $requests)
 {
     $contributor = new Contributor();
     $id_contributor = $requests->get('contributor_id');
     $contributors = $contributor->search(Input::get('query'), 12, true, $id_contributor);
     return response()->json(['request_id' => uniqid(), 'status' => 'success', 'timestamp' => Carbon::now(), 'contributors' => $contributors]);
 }
 /**
  * Registering gcm into related contributor.
  *
  * @param Request $request
  * @return mixed
  */
 public function registerGcm(Request $request)
 {
     $contributor = new Contributor();
     $userId = $request->input('id');
     if ($userId != null && $userId != 0) {
         $contributor->registerGcmToken($userId, $request->input('gcm_token'));
     }
     return response()->json(['request_id' => uniqid(), 'status' => 'success', 'message' => $request->input('gcm_token'), 'timestamp' => Carbon::now()]);
 }
 /**
  * Display a administrator dashboard.
  *
  * @return \Illuminate\Http\Response
  */
 public function index()
 {
     $activities = Activity::with('contributor')->paginate(8);
     $statistics = ['ARTICLES' => Article::count(), 'MEMBERS' => Contributor::count(), 'CATEGORIES' => Subcategory::count(), 'MESSAGES' => Message::count(), 'FEEDBACK' => Feedback::count(), 'VISITORS' => (int) Visitor::sum('unique')];
     $visitors = Visitor::take(10)->get();
     return view('admin.dashboard.index', compact('activities', 'statistics', 'visitors'));
 }
 /**
  * Stop following specified contributor.
  *
  * @param Request $request
  * @return \Illuminate\Http\Response
  */
 public function unfollow(Request $request)
 {
     $contributor_id = $request->input('contributor_id');
     $following_id = $request->input('following_id');
     $follower = Follower::whereContributorId($contributor_id)->whereFollowing($following_id)->first();
     if (count($follower) > 0) {
         $contributor = Contributor::findOrFail($contributor_id)->name;
         $following = Contributor::findOrFail($following_id)->name;
         if ($follower->delete()) {
             return response()->json(['request_id' => uniqid(), 'status' => 'success', 'message' => $contributor . ' is stop following ' . $following, 'timestamp' => Carbon::now()]);
         }
         return response()->json(['request_id' => uniqid(), 'status' => 'failure', 'message' => Lang::get('alert.database.generic'), 'timestamp' => Carbon::now()], 500);
     }
     return response()->json(['request_id' => uniqid(), 'status' => 'denied', 'message' => 'You has not followed this contributor before', 'timestamp' => Carbon::now()], 400);
 }
 /**
  * Bootstrap any application services.
  *
  * @return void
  */
 public function boot()
 {
     $visitor = new Visitor();
     $visitor->checkVisitor();
     $this->app->singleton('site_settings', function () {
         $settings = Setting::all();
         $keys = array();
         foreach ($settings as $setting) {
             $keys[$setting->key] = $setting->value;
         }
         return $keys;
     });
     View::share('site_settings', app('site_settings'));
     $this->app->singleton('site_menus', function () {
         $categories = Category::all();
         return $categories;
     });
     View::share('site_menus', app('site_menus'));
     $this->app->singleton('site_statistic', function () {
         $article = Article::whereStatus('published')->count();
         $member = Contributor::whereStatus('activated')->count();
         return ['article' => $article, 'member' => $member];
     });
     View::share('site_statistic', app('site_statistic'));
     Validator::extend('check_password', function ($attribute, $value, $parameter) {
         if (count($parameter) > 0 && $parameter[0] == 'admin') {
             return Hash::check($value, Auth::guard('admin')->user()->getAuthPassword());
         }
         return Hash::check($value, Auth::user()->getAuthPassword());
     });
     Blade::directive('datetime', function ($expression) {
         return "<?php echo with{$expression}->format('d/m/Y H:i'); ?>";
     });
     Blade::directive('simpledate', function ($expression) {
         return "<?php echo with{$expression}->format('d M Y'); ?>";
     });
     Blade::directive('fulldate', function ($expression) {
         return "<?php echo with{$expression}->format('d F Y'); ?>";
     });
     Blade::directive('datetime', function ($expression) {
         return "<?php echo with{$expression}->format('d F Y h:m A'); ?>";
     });
 }
Beispiel #6
0
 /**
  * Retrieve all messages by contributor.
  *
  * @param $contributor_id
  * @return mixed
  */
 public function retrieveMessages($contributor_id)
 {
     /*
      * --------------------------------------------------------------------------
      * Retrieve message list
      * --------------------------------------------------------------------------
      * Select conversation by contributor and find who is the first sender,
      * just select data with marker column which has value 1, if sender is
      * this contributor then is_available_sender must be 1, otherwise
      * is_available_receiver must be 1, this marker as guard that the data
      * is available for the contributor because if the value of marker depends
      * on they are the first sender or not then the message or conversation has
      * been deleted before, and in other situation another user who chat with
      * must keep see the message, because we just update the marker 0 or 1,
      * 0 mean deleted, 1 mean available.
      */
     $sender = "\n            SELECT\n              conversations.message_id AS message_id,\n              sender AS message_sender\n            FROM conversations\n              JOIN (SELECT message_id, MIN(created_at) AS timestamp FROM conversations GROUP BY conversations.message_id) dates_min\n                ON conversations.message_id = dates_min.message_id\n                   AND created_at = dates_min.timestamp\n            WHERE\n              (sender = " . $contributor_id . " OR receiver = " . $contributor_id . ")\n        ";
     $conversation = Conversation::select(DB::raw('
             id,
             conversations.message_id AS message_id,
             IF(sender = ' . $contributor_id . ', receiver, sender) AS interact_with,
             message_sender,
             message,
             conversation_total,
             conversations.created_at AS created_at'))->join(DB::raw('(SELECT message_id, COUNT(*) as conversation_total, MAX(created_at) AS timestamp FROM conversations GROUP BY message_id) dates'), function ($join) {
         $join->on('conversations.message_id', '=', 'dates.message_id');
         $join->on('created_at', '=', 'dates.timestamp');
     })->join(DB::raw('(' . $sender . ') AS first_sender'), 'conversations.message_id', '=', 'first_sender.message_id')->whereRaw('(sender = ' . $contributor_id . ' OR receiver = ' . $contributor_id . ')')->whereRaw('IF(message_sender = ' . $contributor_id . ', is_available_sender, is_available_receiver) = 1 ')->orderBy('conversations.created_at', 'desc');
     /*
      * --------------------------------------------------------------------------
      * Grouping at once
      * --------------------------------------------------------------------------
      * Group the conversation by message_id, it mean same result of group by
      * contributor who talk with then select the partner of conversation,
      * because we just show the opposite of us as contributor.
      * message_sender is the one who sent email first.
      */
     $contributor = Contributor::select(DB::raw("\n                conversations.id, \n                message_id, \n                message_sender, \n                contributors.id AS contributor_id,\n                name, \n                username,\n                avatar,\n                message,\n                conversation_total,\n                conversations.created_at"))->join(DB::raw("({$conversation->toSql()}) AS conversations"), 'conversations.interact_with', '=', 'contributors.id')->orderBy('conversations.created_at', 'desc')->paginate(10);
     return $this->preMessageModifier($contributor);
 }
 /**
  * Update transaction status and send notification to contributor.
  *
  * @param Request $request
  * @param $status
  * @return \Illuminate\Http\RedirectResponse
  */
 public function update(Request $request, $status)
 {
     $result = DB::transaction(function () use($request, $status) {
         $contributor_id = $request->input('contributor_id');
         $transaction_id = $request->input('transaction_id');
         $contributor = Contributor::findOrFail($contributor_id);
         $transaction = $contributor->transactions()->findOrFail($transaction_id);
         try {
             if ($transaction->status != Transaction::STATUS_SUCCESS) {
                 if ($status == Transaction::STATUS_SUCCESS) {
                     $balance = $contributor->balance - $transaction->amount;
                     if ($balance >= 0) {
                         $contributor->balance = $balance;
                         $contributor->save();
                     } else {
                         return redirect()->back()->withErrors(['balance' => 'You have tried to withdraw IDR ' . number_format($transaction->amount, 0, ',', '.'), 'error' => 'Balance of ' . $contributor->name . ' is insufficient (IDR ' . number_format($contributor->balance, 0, ',', '.') . ')', 'reject' => 'Please reject or cancel this transaction']);
                     }
                 }
             }
             $transaction->status = $status;
             if ($transaction->save()) {
                 // notify the contributor
                 Mail::send('emails.receipt', ['transaction' => $transaction, 'contributor' => $contributor], function ($message) use($transaction, $contributor) {
                     $message->from(env('MAIL_ADDRESS', '*****@*****.**'), env('MAIL_NAME', 'Infogue.id'));
                     $message->replyTo('*****@*****.**', env('MAIL_NAME', 'Infogue.id'));
                     $message->to($contributor->email)->subject('Withdrawal status transaction ID ' . $transaction->id . ' is ' . $transaction->status);
                 });
                 return redirect()->back()->with(['status' => $status == 'success' ? 'success' : 'warning', 'message' => "Status transaction ID {$transaction_id} was updated <strong>{$status}</strong>"]);
             } else {
                 return redirect()->back()->withErrors(['error' => Lang::get('alert.error.database')]);
             }
         } catch (\Exception $e) {
             return redirect()->back()->withErrors(['error' => Lang::get('alert.error.transaction')])->withInput();
         }
     });
     return $result;
 }
 /**
  * Send new message to another contributor in storage.
  *
  * @param  \Illuminate\Http\Request $request
  * @return \Illuminate\Http\Response
  */
 public function send(Request $request)
 {
     /*
      * --------------------------------------------------------------------------
      * Create message
      * --------------------------------------------------------------------------
      * Each conversation will handle by one message record as identity, first
      * check if contributor sender or receiver ever make conversation, if they
      * did not then create new one of message.
      */
     $sender = $request->input('contributor_id');
     $receiver = $request->input('receiver_id');
     $lastMessage = $this->conversation->whereSender($sender)->whereReceiver($receiver)->orWhere('sender', $receiver)->whereReceiver($sender)->first();
     if (count($lastMessage) == 0) {
         $message = new Message();
         $message->save();
         $messageId = $message->id;
     } else {
         $messageId = $lastMessage->message_id;
     }
     /*
      * --------------------------------------------------------------------------
      * Create conversation
      * --------------------------------------------------------------------------
      * Populate message id from last conversation or last inserted new message
      * then create the first conversation or continue with last message, check
      * if there is request of attachment, if so then upload it.
      */
     $conversation = new Conversation(['message_id' => $messageId, 'sender' => $sender, 'receiver' => $receiver, 'message' => $request->input('message')]);
     $result = $conversation->save();
     if ($result) {
         $contributorSender = Contributor::findOrFail($sender);
         $contributor = Contributor::findOrFail($receiver);
         if ($contributor->email_message) {
             $this->sendEmailNotification($contributorSender, $contributor, $request->input('message'));
         }
         $conversation->broadcastConversation($contributorSender, $contributor, $request->input('message'));
     }
     return response()->json(['request_id' => uniqid(), 'status' => $result ? 'success' : 'failure', 'timestamp' => Carbon::now()], $result ? 200 : 500);
 }
 /**
  * Update GCM token for registered user so they could control mobile notifications.
  *
  * @param $userId contributor ID
  * @param $gcmToken generated token from google
  */
 public function registerGcmToken($userId, $gcmToken)
 {
     $contributor = Contributor::find($userId);
     if ($contributor != null) {
         $contributor->gcm_token = $gcmToken;
         $contributor->save();
     }
 }
 /**
  * Display a listing of the contributor following.
  *
  * @param Request $requests
  * @param $username
  * @return \Illuminate\Http\Response
  */
 public function following(Request $requests, $username)
 {
     $contributor = $this->contributor->profile($username, false, $requests->get('contributor_id'), true);
     $following = $this->contributor->contributorFollowing($username, $requests->get('contributor_id'), true);
     return $this->responseData($contributor, 'following', $following);
 }
 /**
  * Update the specified contributor in storage.
  *
  * @param  \Illuminate\Http\Request $request
  * @return \Illuminate\Http\Response
  */
 public function update(Request $request)
 {
     $rules = ['avatar' => 'mimes:jpg,jpeg,gif,png|max:1000', 'cover' => 'mimes:jpg,jpeg,gif,png|max:1000'];
     $validator = Validator::make($request->all(), $rules);
     if ($validator->fails()) {
         $failedRules = $validator->failed();
         $validAvatar = isset($failedRules['avatar']);
         $validCover = isset($failedRules['cover']);
         $errorMessage = "Invalid avatar or cover";
         if ($validAvatar && $validCover) {
             $errorMessage = "Cover and Avatar is invalid";
         } else {
             if ($validAvatar) {
                 $errorMessage = "Avatar is invalid";
             } else {
                 if ($validCover) {
                     $errorMessage = "Cover is invalid";
                 }
             }
         }
         $errorMessage .= ", must image and less than 1MB";
         return response()->json(['request_id' => uniqid(), 'status' => 'denied', 'message' => $errorMessage, 'timestamp' => Carbon::now()], 400);
     }
     $contributor = Contributor::findOrFail($request->input('contributor_id'));
     if ($request->has('new_password') && !empty($request->get('new_password'))) {
         $credential = Hash::check($request->input('password'), $contributor->password);
         if (!$credential) {
             return response()->json(['request_id' => uniqid(), 'status' => 'mismatch', 'message' => 'Current password is mismatch', 'timestamp' => Carbon::now()], 401);
         }
     }
     $usernameExist = Contributor::whereUsername($request->input('username'))->where('id', '!=', $contributor->id)->count();
     if ($usernameExist) {
         return response()->json(['request_id' => uniqid(), 'status' => 'denied', 'message' => 'Username has been taken', 'timestamp' => Carbon::now()], 400);
     }
     $emailExist = Contributor::whereEmail($request->input('email'))->where('id', '!=', $contributor->id)->count();
     if ($emailExist) {
         return response()->json(['request_id' => uniqid(), 'status' => 'denied', 'message' => 'Email has been taken', 'timestamp' => Carbon::now()], 400);
     }
     $contributor->name = $request->input('name');
     $contributor->gender = $request->input('gender');
     $contributor->birthday = $request->input('birthday');
     $contributor->location = $request->input('location');
     $contributor->contact = $request->input('contact');
     $contributor->about = $request->input('about');
     $contributor->username = $request->input('username');
     $contributor->email = $request->input('email');
     $image = new Uploader();
     if ($image->upload($request, 'avatar', base_path('public/images/contributors/'), 'avatar_' . $request->input('contributor_id'))) {
         $contributor->avatar = $request->input('avatar');
     }
     if ($image->upload($request, 'cover', base_path('public/images/covers/'), 'cover_' . $request->input('contributor_id'))) {
         $contributor->cover = $request->input('cover');
     }
     $contributor->instagram = $request->input('instagram');
     $contributor->facebook = $request->input('facebook');
     $contributor->twitter = $request->input('twitter');
     $contributor->googleplus = $request->input('googleplus');
     $contributor->email_subscription = $request->input('email_subscription');
     $contributor->email_message = $request->input('email_message');
     $contributor->email_follow = $request->input('email_follow');
     $contributor->email_feed = $request->input('email_feed');
     $contributor->mobile_notification = $request->input('mobile_notification');
     if ($request->has('new_password') && !empty($request->get('new_password'))) {
         $request->merge(['password' => Hash::make($request->input('new_password'))]);
         $contributor->password = $request->input('password');
     }
     $contributor->bank_id = $request->input('bank_id');
     $contributor->account_name = $request->input('account_name');
     $contributor->account_number = $request->input('account_number');
     if ($contributor->save()) {
         return response()->json(['request_id' => uniqid(), 'status' => 'success', 'message' => 'Setting was updated', 'timestamp' => Carbon::now(), 'contributor' => $contributor->profile($contributor->username, false, $request->input('contributor_id'), true)]);
     } else {
         return response()->json(['request_id' => uniqid(), 'status' => 'failure', 'message' => Lang::get('alert.database.generic'), 'timestamp' => Carbon::now()], 500);
     }
 }
 /**
  * Find out accumulation of deferred transaction before, 'deferred transaction' means
  * all withdrawal request which does not proceed yet by admin and contributor's balance
  * never touch (subtracted) so it need to recalculate again before next request comes in.
  *
  * @param $contributor_id
  * @return mixed
  */
 private function getDefferWithdrawal($contributor_id)
 {
     return Contributor::find($contributor_id)->transactions()->whereType(Transaction::TYPE_WITHDRAWAL)->where(function ($query) {
         $query->where('status', '=', Transaction::STATUS_PENDING);
         $query->orWhere('status', '=', Transaction::STATUS_PROCEED);
     })->sum('amount');
 }
 /**
  * Show the search result for finding contributors.
  *
  * @return \Illuminate\Http\Response
  */
 public function searchPeople()
 {
     $contributor = new Contributor();
     $contributor_result = $contributor->search(Input::get('query'), 20);
     $total_result = $contributor_result->total();
     return view('pages.search', compact('contributor_result', 'total_result'));
 }
 /**
  * Update the specified contributor in storage.
  *
  * @param  \Illuminate\Http\Request $request
  * @return \Illuminate\Http\Response
  */
 public function update(Request $request)
 {
     /*
      * --------------------------------------------------------------------------
      * Validating data
      * --------------------------------------------------------------------------
      * Define rules before populating data, check if checkbox is unchecked then
      * gives default value 0, merge notification for date, month, year as
      * birthday, and throw it back if errors occur.
      */
     $user = Auth::user();
     $rules = ['name' => 'required|max:50', 'gender' => 'required|in:male,female,other', 'date' => 'required|max:31', 'month' => 'required|max:12', 'year' => 'required|max:' . (int) Carbon::now()->addYear(-8)->format('Y'), 'location' => 'required|max:30', 'contact' => 'required|max:20', 'about' => 'required|min:15|max:160', 'email_subscription' => 'boolean', 'email_message' => 'boolean', 'email_follow' => 'boolean', 'email_feed' => 'boolean', 'mobile_notification' => 'boolean', 'account_name' => 'max:50', 'account_number' => 'min:7|max:15', 'avatar' => 'mimes:jpg,jpeg,gif,png|max:1000', 'cover' => 'mimes:jpg,jpeg,gif,png|max:1000', 'username' => 'required|alpha_dash|max:20|unique:contributors,username,' . $user->id, 'email' => 'required|email|max:50|unique:contributors,email,' . $user->id, 'new_password' => 'confirmed|min:6'];
     if ($user->vendor == "web" || $user->vendor == "mobile") {
         $rules['password'] = '******';
     }
     if (!$request->has('email_subscription')) {
         $request->merge(['email_subscription' => 0]);
     }
     if (!$request->has('email_message')) {
         $request->merge(['email_message' => 0]);
     }
     if (!$request->has('email_follow')) {
         $request->merge(['email_follow' => 0]);
     }
     if (!$request->has('email_feed')) {
         $request->merge(['email_feed' => 0]);
     }
     if (!$request->has('mobile_notification')) {
         $request->merge(['mobile_notification' => 0]);
     }
     $request->merge(['birthday' => implode('-', Input::only('year', 'month', 'date'))]);
     $validator = Validator::make($request->all(), $rules);
     if ($validator->fails()) {
         $failedRules = $validator->failed();
         $date = isset($failedRules['date']['Required']);
         $month = isset($failedRules['month']['Required']);
         $year = isset($failedRules['year']['Required']);
         if ($date || $month || $year) {
             $validator->errors()->add('birthday', Lang::get('alert.validation.birthday'));
         }
         $this->throwValidationException($request, $validator);
     }
     /*
      * --------------------------------------------------------------------------
      * Populating data and update
      * --------------------------------------------------------------------------
      * Retrieve all data, if avatar or cover input is not empty then try to
      * upload the image and get the filename, if new_password is not empty then
      * the contributor intend to change their password, in the end perform save.
      */
     $contributor = Contributor::findOrFail($user->id);
     $contributor->name = $request->input('name');
     $contributor->gender = $request->input('gender');
     $contributor->birthday = $request->input('birthday');
     $contributor->location = $request->input('location');
     $contributor->contact = $request->input('contact');
     $contributor->about = $request->input('about');
     $contributor->username = $request->input('username');
     $contributor->email = $request->input('email');
     $image = new Uploader();
     if ($image->upload($request, 'avatar', base_path('public/images/contributors/'), 'avatar_' . $contributor->id)) {
         $contributor->avatar = $request->input('avatar');
     }
     if ($image->upload($request, 'cover', base_path('public/images/covers/'), 'cover_' . $contributor->id)) {
         $contributor->cover = $request->input('cover');
     }
     $contributor->instagram = $request->input('instagram');
     $contributor->facebook = $request->input('facebook');
     $contributor->twitter = $request->input('twitter');
     $contributor->googleplus = $request->input('googleplus');
     $contributor->email_subscription = $request->input('email_subscription');
     $contributor->email_message = $request->input('email_message');
     $contributor->email_follow = $request->input('email_follow');
     $contributor->email_feed = $request->input('email_feed');
     $contributor->mobile_notification = $request->input('mobile_notification');
     if ($request->has('new_password') && !empty($request->get('new_password'))) {
         $request->merge(['password' => Hash::make($request->input('new_password'))]);
         $contributor->password = $request->input('password');
     }
     $contributor->bank_id = $request->input('bank');
     $contributor->account_name = $request->input('account_name');
     $contributor->account_number = $request->input('account_number');
     if ($contributor->save()) {
         return redirect(route('account.setting'))->with(['status' => 'success', 'message' => Lang::get('alert.contributor.account')]);
     }
     return redirect()->back()->withErrors(['error' => Lang::get('alert.error.database')]);
 }
 /**
  * Obtain the user information from Twitter.
  *
  * @return Response
  */
 public function handleTwitterProviderCallback()
 {
     /*
      * --------------------------------------------------------------------------
      * Login with twitter
      * --------------------------------------------------------------------------
      * Initiating twitter driver and retrieve authenticate twitter login,
      * check if the user has been registered before, if they doesn't exist
      * create the new one then authenticating them and redirect.
      */
     $user = Socialite::driver('twitter')->user();
     $contributor = Contributor::whereVendor('twitter')->whereToken($user->id);
     if ($contributor->count() == 0) {
         /*
          * --------------------------------------------------------------------------
          * Populate twitter data
          * --------------------------------------------------------------------------
          * Collect the twitter basic data and create new contributor,
          * the data including banner as contributor cover, twitter avatar
          * as contributor avatar and twitter profile.
          */
         $contributor = new Contributor();
         $avatar = file_get_contents($user->avatar_original);
         file_put_contents('images/contributors/twitter-' . $user->id . '.jpg', $avatar);
         $cover = file_get_contents($user->user['profile_banner_url']);
         file_put_contents('images/covers/twitter-' . $user->id . '.jpg', $cover);
         $contributor->token = $user->id;
         $contributor->api_token = str_random(60);
         $contributor->name = $user->name;
         $contributor->username = $user->nickname . '.twitter';
         $contributor->password = Hash::make(uniqid());
         $contributor->email = $user->nickname . '@domain.com';
         $contributor->vendor = 'twitter';
         $contributor->status = 'activated';
         $contributor->location = $user->user['location'];
         $contributor->about = $user->user['description'];
         $contributor->twitter = 'https://twitter.com/' . $user->nickname;
         $contributor->avatar = 'twitter-' . $user->id . '.jpg';
         $contributor->cover = 'twitter-' . $user->id . '.jpg';
         $contributor->save();
         /*
          * --------------------------------------------------------------------------
          * Create register activity
          * --------------------------------------------------------------------------
          * Create new instance of Activity and insert register activity.
          */
         Activity::create(['contributor_id' => $contributor->id, 'activity' => Activity::registerActivity($contributor->username, 'twitter')]);
         $this->sendAdminContributorNotification($contributor);
     }
     Auth::login($contributor->first());
     return redirect()->route('account.stream');
 }
 /**
  * Remove the specified contributor from storage.
  *
  * @param Request $request
  * @param  int $id
  * @return \Illuminate\Http\Response
  */
 public function destroy(Request $request, $id = null)
 {
     /*
      * --------------------------------------------------------------------------
      * Delete contributor
      * --------------------------------------------------------------------------
      * Check if selected variable is not empty then user intends to select multiple
      * rows at once, and prepare the feedback message according the type of
      * deletion action.
      */
     if (!empty(trim($request->input('selected')))) {
         $contributor_ids = explode(',', $request->input('selected'));
         $delete = Contributor::whereIn('id', $contributor_ids)->delete();
         $message = Lang::get('alert.contributor.delete_all', ['count' => $delete]);
     } else {
         $contributor = Contributor::findOrFail($id);
         $message = Lang::get('alert.contributor.delete', ['name' => $contributor->name]);
         $delete = $contributor->delete();
     }
     if ($delete) {
         return redirect(route('admin.contributor.index'))->with(['status' => 'warning', 'message' => $message]);
     } else {
         return redirect()->back()->withErrors(['error' => Lang::get('alert.error.database')]);
     }
 }
 /**
  * Send new message to another contributor in storage.
  *
  * @param  \Illuminate\Http\Request $request
  * @return \Illuminate\Http\Response
  */
 public function send(Request $request)
 {
     /*
      * --------------------------------------------------------------------------
      * Create message
      * --------------------------------------------------------------------------
      * Each conversation will handle by one message record as identity, first
      * check if contributor sender or receiver ever make conversation, if they
      * did not then create new one of message.
      */
     $sender = Auth::user()->id;
     $receiver = (int) $request->input('contributor_id');
     $lastMessage = $this->conversation->whereSender($sender)->whereReceiver($receiver)->orWhere('sender', $receiver)->whereReceiver($sender)->first();
     if (count($lastMessage) == 0) {
         $message = new Message();
         $message->save();
         $messageId = $message->id;
     } else {
         $messageId = $lastMessage->message_id;
     }
     /*
      * --------------------------------------------------------------------------
      * Create conversation
      * --------------------------------------------------------------------------
      * Populate message id from last conversation or last inserted new message
      * then create the first conversation or continue with last message, check
      * if there is request of attachment, if so then upload it.
      */
     $conversation = new Conversation(['message_id' => $messageId, 'sender' => $sender, 'receiver' => $receiver, 'message' => $request->input('message')]);
     if ($conversation->save()) {
         $contributor = Contributor::findOrFail($receiver);
         if ($contributor->email_message) {
             $this->sendEmailNotification(Auth::user(), $contributor, $request->input('message'));
         }
         $conversation->broadcastConversation(Auth::user(), $contributor, $request->input('message'));
         if ($request->has('async') && $request->ajax()) {
             $image = new Uploader();
             if ($image->upload($request, 'attachment', base_path('public/file/'), 'attachment_' . uniqid())) {
                 $attachment = new Attachment();
                 $attachment->conversation_id = $conversation->id;
                 $attachment->file = $request->input('attachment');
                 if (!$attachment->save()) {
                     return false;
                 }
             }
             return 'sent';
         }
         return redirect()->back()->with(['status' => 'success', 'message' => Lang::get('alert.message.send', ['receiver' => $contributor->name])]);
     }
     if ($request->has('async') && $request->ajax()) {
         return false;
     }
     return redirect()->back()->with(['status' => 'danger', 'message' => Lang::get('alert.error.database')]);
 }
 /**
  * Display the specified article.
  *
  * @param  int $slug
  * @return \Illuminate\Http\Response
  */
 public function show($slug)
 {
     /*
      * --------------------------------------------------------------------------
      * Populate single article view
      * --------------------------------------------------------------------------
      * Find published article by slug, build breadcrumb stack, retrieve article
      * author, article tags, related and popular article.
      */
     $article = $this->article->whereSlug($slug)->firstOrFail();
     if ($article->status == 'pending') {
         return view('article.pending', compact('article'));
     }
     if ($article->status == 'published') {
         $category = $article->subcategory->category->category;
         $subcategory = $article->subcategory->subcategory;
         $comments = $article->comments;
         $breadcrumb = ['Archive' => route('article.archive'), $category => route('article.category', [str_slug($category)]), $subcategory => route('article.subcategory', [str_slug($category), str_slug($subcategory)])];
         $previous_article = $this->article->navigateArticle($article->id, 'prev');
         $next_article = $this->article->navigateArticle($article->id, 'next');
         $prev_ref = $previous_article != null ? route('article.show', [$previous_article->slug]) : '#';
         $next_ref = $next_article != null ? route('article.show', [$next_article->slug]) : '#';
         $tags = $article->tags()->get();
         $related = $this->article->related($article->id);
         $popular = $this->article->mostPopular(5);
         $contributor = new Contributor();
         $author = $contributor->profile($article->contributor->username);
         return view('article.article', compact('breadcrumb', 'prev_ref', 'next_ref', 'article', 'author', 'comments', 'tags', 'related', 'popular'));
     } else {
         abort(404);
     }
 }
 /**
  * Update the specified article in storage.
  *
  * @param  \Illuminate\Http\Request $request
  * @param param int $slug
  * @return \Illuminate\Http\Response
  */
 public function update(Request $request, $slug)
 {
     $validator = Validator::make($request->all(), ['featured' => 'mimes:jpg,jpeg,gif,png|max:1000']);
     if ($validator->fails()) {
         return response()->json(['request_id' => uniqid(), 'status' => 'denied', 'message' => "Featured must image and less than 1MB", 'timestamp' => Carbon::now()], 400);
     }
     $articleController = $this;
     $article = Article::whereSlug($slug)->firstOrFail();
     $exist = Article::whereSlug($request->input('slug'))->where('id', '!=', $article->id)->count();
     if ($exist) {
         return response()->json(['request_id' => uniqid(), 'status' => 'denied', 'message' => 'Unique slug has taken', 'timestamp' => Carbon::now()], 400);
     }
     $result = DB::transaction(function () use($request, $article, $articleController) {
         try {
             /*
              * --------------------------------------------------------------------------
              * Populate tags
              * --------------------------------------------------------------------------
              * Sync last tags and new article, extract tags from request, break down 
              * between new tags and tags that available in database, merge new inserted 
              * tag id with available tags id and remove the old which is removed.
              */
             $tag = Tag::whereIn('tag', explode(',', $request->get('tags')));
             $tags_id = $tag->pluck('id')->toArray();
             $available_tags = $tag->pluck('tag')->toArray();
             $new_tags = array_diff(explode(',', $request->get('tags')), $available_tags);
             $article->tags()->sync($tags_id);
             foreach ($new_tags as $tag_label) {
                 $newTag = new Tag();
                 $newTag->tag = $tag_label;
                 $newTag->save();
                 if (!$article->tags->contains($newTag->id)) {
                     $article->tags()->save($newTag);
                 }
             }
             /*
              * --------------------------------------------------------------------------
              * Update the article
              * --------------------------------------------------------------------------
              * Finally populate article data like create process and check if featured
              * need to change and upload the image then update the changes.
              */
             $autoApprove = Setting::whereKey('Auto Approve')->first();
             $content = $article->content;
             $content_update = $request->input('content');
             $status = $request->input('status');
             if ($autoApprove->value) {
                 $content = $request->input('content');
                 $content_update = '';
                 if ($status == 'pending') {
                     $status = 'published';
                 }
             }
             $article->subcategory_id = $request->input('subcategory_id');
             $article->title = $request->input('title');
             $article->slug = $request->input('slug');
             $article->type = $request->input('type');
             $article->content = $content;
             $article->content_update = $content_update;
             $article->excerpt = $request->input('excerpt');
             $article->status = $status;
             $image = new Uploader();
             if ($image->upload($request, 'featured', base_path('public/images/featured/'), 'featured_' . uniqid())) {
                 $article->featured = $request->input('featured');
             }
             $article->save();
             $contributor = Contributor::findOrFail($request->input('contributor_id'));
             Activity::create(['contributor_id' => $contributor->id, 'activity' => Activity::updateArticleActivity($contributor->username, $article->title, $article->slug)]);
             if (!$autoApprove->value) {
                 $articleController->sendAdminArticleNotification($contributor, $article, true);
             }
             return response()->json(['request_id' => uniqid(), 'status' => 'success', 'message' => 'Article was updated', 'auto_approve' => $autoApprove->value, 'timestamp' => Carbon::now()]);
         } catch (\Exception $e) {
             return response()->json(['request_id' => uniqid(), 'status' => 'failure', 'message' => Lang::get('alert.error.transaction'), 'timestamp' => Carbon::now()], 500);
         }
     });
     return $result;
 }
 /**
  * Show reset password view.
  *
  * @param null $token
  * @return $this|\Illuminate\Http\Response
  */
 public function showResetForm($token = null)
 {
     if (is_null($token)) {
         return $this->getEmail();
     }
     /*
      * --------------------------------------------------------------------------
      * Checking password reset request token
      * --------------------------------------------------------------------------
      * Check if user has been creating request for changing their password
      * otherwise throw it 404 error page, then retrieve their profile to make
      * sure they are going to update the correct account.
      */
     $reset = DB::table('password_resets')->whereToken($token)->first();
     if ($reset == null) {
         abort(404);
     }
     $contributor = Contributor::whereEmail($reset->email)->firstOrFail();
     return view('auth.passwords.reset')->with(compact('token', 'contributor'));
 }
 /**
  * Store a relation between 2 contributors.
  *
  * @param  \Illuminate\Http\Request $request
  * @return \Illuminate\Http\Response
  */
 public function follow(Request $request)
 {
     /*
      * --------------------------------------------------------------------------
      * Perform follow request
      * --------------------------------------------------------------------------
      * This operation only for authenticate user, a contributor follow another
      * contributor, populate the data and make sure there is no record following
      * from contributor A to B before then perform insert data.
      */
     if (Auth::check() && $request->ajax()) {
         $contributor_id = Auth::user()->id;
         $following_id = $request->input('id');
         $isFollowing = Follower::whereContributorId($contributor_id)->whereFollowing($following_id)->count();
         if (!$isFollowing) {
             $follower = new Follower();
             $follower->contributor_id = $contributor_id;
             $follower->following = $following_id;
             if ($follower->save()) {
                 $following = Contributor::findOrFail($following_id);
                 /*
                  * --------------------------------------------------------------------------
                  * Create following activity
                  * --------------------------------------------------------------------------
                  * Create new instance of Activity and insert following activity.
                  */
                 Activity::create(['contributor_id' => $contributor_id, 'activity' => Activity::followActivity(Auth::user()->username, $following->username)]);
                 if ($following->email_follow) {
                     $follower->sendEmailNotification(Auth::user(), $following);
                 }
                 return response('success');
             }
             return response('failed', 500);
         }
         return response('success');
     } else {
         return response('restrict', 401);
     }
 }
 /**
  * Delete image by passing contributor id and image id.
  *
  * @param Request $request
  * @return \Illuminate\Http\JsonResponse
  */
 public function delete(Request $request)
 {
     /*
      * the file must be owned by the correspond contributor,
      * and if it exists, just delete.
      */
     $contributor = Contributor::findOrFail($request->input('contributor_id'));
     $image = $contributor->images()->findOrFail($request->input('id'));
     $pathImage = public_path('images/featured/' . $image->source);
     if (File::exists($pathImage)) {
         unlink($pathImage);
     }
     if ($image->delete()) {
         return response()->json(['request_id' => uniqid(), 'status' => 'success', 'message' => Lang::get('alert.image.delete', ['title' => $image->source]), 'timestamp' => Carbon::now()]);
     }
     return response()->json(['request_id' => uniqid(), 'status' => 'failure', 'message' => Lang::get('alert.error.generic'), 'timestamp' => Carbon::now()], 500);
 }