fire() public static method

Fire an event and call the listeners.
public static fire ( string | object $event, mixed $payload = [], boolean $halt = false ) : array | null
$event string | object
$payload mixed
$halt boolean
return array | null
 public function postIndex()
 {
     $input = Input::only('first_name', 'last_name', 'email', 'username', 'password', 'domain_id');
     $domain_id = Cookie::get('domain_hash') ? Cookie::get('domain_hash') : 'NULL';
     $rules = array('first_name' => 'required|min:1', 'email' => 'required|email|unique:users,email,NULL,id,deleted_at,NULL,domain_id,' . $domain_id, 'username' => 'required|min:3|must_alpha_num|unique:users,username,NULL,id,deleted_at,NULL,domain_id,' . $domain_id, 'password' => 'required|min:6');
     $v = Validator::make($input, $rules);
     if ($v->fails()) {
         return Output::push(array('path' => 'register', 'errors' => $v, 'input' => TRUE));
     }
     $profile = new Profile(array('first_name' => $input['first_name'], 'last_name' => $input['last_name'], 'website' => ''));
     $profile->save();
     $user = new User(array('domain_id' => Cookie::get('domain_hash') ? Cookie::get('domain_hash') : NULL, 'email' => $input['email'], 'username' => $input['username'], 'password' => Hash::make($input['password']), 'status' => Cookie::get('domain_hash') ? 4 : 3));
     $user->profile()->associate($profile);
     $user->save();
     if ($user->id) {
         if ($user->status == 4) {
             $this->add_phone_number($user->id);
         }
         $cookie = Cookie::forget('rndext');
         $confirmation = App::make('email-confirmation');
         $confirmation->send($user);
         Mail::send('emails.register', array('new_user' => $input['username']), function ($message) {
             $message->from(Config::get('mail.from.address'), Config::get('mail.from.name'))->to(Input::get('email'))->subject(_('New user registration'));
         });
         Event::fire('logger', array(array('account_register', array('id' => $user->id, 'username' => $user->username), 2)));
         //			return Output::push(array(
         //				'path' => 'register',
         //				'messages' => array('success' => _('You have registered successfully')),
         //				));
         return Redirect::to('register')->with('success', _('You have registered successfully'))->withCookie($cookie);
     } else {
         return Output::push(array('path' => 'register', 'messages' => array('fail' => _('Fail to register')), 'input' => TRUE));
     }
 }
 public function onLogin()
 {
     $account = Auth::user()->account;
     $account->last_login = Carbon::now()->toDateTimeString();
     $account->save();
     Event::fire('user.refresh');
 }
 /**
  * Fires an event.
  * @param Boolean $allow Determines if the event is allowed to fire.
  * @param String $event Name of the event to fire.
  * @param [String => Mixed] $opts
  * @param [String => Mixed] $extra Additional options.
  */
 protected function fire($allow, $event, array $opts, array $extra)
 {
     if ($allow) {
         \Event::fire(ltrim($this->model, '\\') . '.' . $event, [array_merge($opts, $extra)]);
     }
     return $allow;
 }
 /**
  * Store a newly created conversation in storage.
  *
  * @return Response
  */
 public function store()
 {
     $rules = array('users' => 'required|array', 'body' => 'required');
     $validator = Validator::make(Input::only('users', 'body'), $rules);
     if ($validator->fails()) {
         return Response::json(['success' => false, 'result' => $validator->messages()]);
     }
     // Create Conversation
     $params = array('created_at' => new DateTime(), 'name' => str_random(30), 'author_id' => Auth::user()->id);
     $conversation = Conversation::create($params);
     $conversation->users()->attach(Input::get('users'));
     $conversation->users()->attach(array(Auth::user()->id));
     // Create Message
     $params = array('conversation_id' => $conversation->id, 'body' => Input::get('body'), 'user_id' => Auth::user()->id, 'created_at' => new DateTime());
     $message = Message::create($params);
     // Create Message Notifications
     $messages_notifications = array();
     foreach (Input::get('users') as $user_id) {
         array_push($messages_notifications, new MessageNotification(array('user_id' => $user_id, 'read' => false, 'conversation_id' => $conversation->id)));
         // Publish Data To Redis
         $data = array('room' => $user_id, 'message' => array('conversation_id' => $conversation->id));
         Event::fire(ChatConversationsEventHandler::EVENT, array(json_encode($data)));
     }
     $message->messages_notifications()->saveMany($messages_notifications);
     return Redirect::route('chat.index', array('conversation', $conversation->name));
 }
Example #5
0
 public function put_update()
 {
     $post_modules = Input::get('modules');
     $group_id = Input::get('group_id');
     $action = Input::get('btnAction');
     $post_rules = Input::get('module_roles');
     if (isset($group_id) and !empty($group_id) and ctype_digit($group_id)) {
         Permission::update_permissions($group_id, $post_rules, $post_modules);
         Event::fire('mwi.permissions_updated', array('modules' => $post_modules, 'group_id' => $group_id));
         $this->data['message'] = __('permissions::lang.Permissions were successfully updated')->get(ADM_LANG);
         $this->data['message_type'] = 'success';
         if ($action == 'save') {
             return Redirect::to(ADM_URI . '/permissions/' . $group_id . '/edit')->with($this->data);
         } else {
             // 'save_exit' action
             return Redirect::to(ADM_URI . '/groups')->with($this->data);
         }
     } else {
         // module id's and group_id not posted
         // no changes made
         if ($action == 'save') {
             return Redirect::to(ADM_URI . '/permissions/group/' . $group_id)->with($this->data);
         } else {
             // 'save_exit' action
             return Redirect::to(ADM_URI . '/groups')->with($this->data);
         }
     }
 }
 public function handle(UserUpdateCommand $command)
 {
     $user = User::find($command->getAuthState()->actingUserId);
     $user->email = $command->email;
     $user->save();
     \Event::fire(new UserUpdatedEvent($user));
 }
 public function login()
 {
     $rules = array('rut' => 'required|between:8,9|alpha_num|rut|exist_rut');
     $validator = Validator::make(Input::all(), $rules);
     if ($validator->fails()) {
         if (Request::ajax()) {
             return json_encode('ERROR');
         }
         return Redirect::back()->withErrors($validator->messages())->withInput();
     }
     Event::fire('carga_cliente', array(Input::get('rut')));
     $ultima_respuesta = Event::fire('ya_respondio')[0];
     if (!is_null($ultima_respuesta)) {
         $msg = array('data' => array('type' => 'warning', 'title' => Session::get('user_name'), 'text' => 'En el actual periodo, ya registramos tus respuestas con fecha <b>' . $ultima_respuesta->format('d-m-Y') . '</b> a las <b>' . $ultima_respuesta->toTimeString() . '</b>, ¿Deseas actualizar esta información?'), 'options' => array(HTML::link('#', 'NO', array('class' => 'col-xs-4 col-sm-4 col-md-3 btn btn-default btn-lg text-uppercase', 'id' => 'btn_neg')), HTML::link('encuestas', 'SÍ', array('class' => 'col-xs-4 col-sm-4 col-md-3 btn btn-hot btn-lg text-uppercase pull-right'))));
         if (Request::ajax()) {
             return json_encode($msg);
         }
         return View::make('messages')->with('msg', $msg);
     } else {
         if (Request::ajax()) {
             return json_encode('OK');
         }
         return Redirect::to('encuestas');
     }
 }
Example #8
0
 public function action_index()
 {
     $settings = new Settings();
     $settings->add_setting(new Setting_Preferences($this->user));
     $settings->add_setting(new Setting_Profile($this->user));
     $settings->add_setting(new Setting_Account($this->user));
     // Run the events.
     Event::fire('user.settings', array($this->user, $settings));
     if ($this->request->method() == HTTP_Request::POST) {
         $setting = $settings->get_by_id($this->request->post('settings-tab'));
         if ($setting) {
             $post = $this->request->post();
             $validation = $setting->get_validation($post);
             if ($validation->check()) {
                 try {
                     $setting->save($post);
                     Hint::success('Updated ' . $setting->title . '!');
                 } catch (ORM_Validation_Exception $e) {
                     Hint::error($e->errors('models'));
                 }
             } else {
                 Hint::error($validation->errors());
             }
         } else {
             Hint::error('Invalid settings id!');
         }
     }
     $this->view = new View_User_Settings();
     $this->view->settings = $settings;
 }
 /**
  * Display a listing of the resource.
  *
  * @return Response
  */
 public function index()
 {
     $key = Input::get('key');
     $deliverydate = Input::get('date');
     $dev = \Device::where('key', '=', $key)->first();
     $model = $this->model;
     $merchants = $model->where('group_id', '=', 4)->get();
     //print_r($merchants);
     //die();
     for ($n = 0; $n < count($merchants); $n++) {
         $or = new \stdClass();
         foreach ($merchants[$n] as $k => $v) {
             $nk = $this->underscoreToCamelCase($k);
             $or->{$nk} = is_null($v) ? '' : $v;
         }
         $or->extId = $or->id;
         unset($or->id);
         //$or->boxList = $this->boxList('delivery_id',$or->deliveryId,$key);
         //$or->boxObjects = $this->boxList('delivery_id',$or->deliveryId, $key , true);
         $merchants[$n] = $or;
     }
     $actor = $key;
     \Event::fire('log.api', array($this->controller_name, 'get', $actor, 'logged out'));
     return $merchants;
     //
 }
Example #10
0
 /**
  * Find a model by its primary key.
  *
  * @param mixed $id
  * @param array $columns
  *
  * @return \Illuminate\Database\Eloquent\Model|static|null
  */
 public function find($id, $columns = array('*'))
 {
     Event::fire('before.find', array($this));
     $result = parent::find($id, $columns);
     Event::fire('after.find', array($this));
     return $result;
 }
 /**
  * Handle the event.
  *
  * @param  OpenBattleVideoConverted  $event
  * @return void
  */
 public function handle(OpenBattleVideoConverted $event)
 {
     Log::info('Updating OpenBattle', ['battle' => $event->battle->id, 'phase' => $event->battle->phase]);
     $event->battle[$event->videoColumn] = $event->videoFilename;
     // Set beat id
     if ($event->battle->phase == 1) {
         $event->battle['beat' . $event->rapperNumber . '_id'] = $event->beatId;
         // Go to phase 2 if both 1st rounds are uploaded
         if ($event->battle->hasFirstRounds()) {
             Log::debug('Updating OpenBattle: changing phase (before)', ['battle' => $event->battle->id, 'phase' => $event->battle->phase]);
             $event->battle->setPhaseAttribute(2);
             Log::debug('Updating OpenBattle: changing phase (after)', ['battle' => $event->battle->id, 'phase' => $event->battle->phase]);
         }
     } else {
         if ($event->battle->phase == 2 && $event->battle->hasAllRounds()) {
             // note: battle done, concat video, create battle, delete open battle - maybe need to do this when conversion is done
             // input files in filesystem
             $infiles = array();
             $infiles[] = Storage::disk('videos')->getAdapter()->applyPathPrefix($event->battle->rapper1_round1);
             $infiles[] = Storage::disk('videos')->getAdapter()->applyPathPrefix($event->battle->rapper2_round1);
             $infiles[] = Storage::disk('videos')->getAdapter()->applyPathPrefix($event->battle->rapper2_round2);
             $infiles[] = Storage::disk('videos')->getAdapter()->applyPathPrefix($event->battle->rapper1_round2);
             // new video file name
             $this->outfilename = '' . $event->battle->id . '.mp4';
             $outfile = Storage::disk('videos')->getAdapter()->applyPathPrefix($this->outfilename);
             // concatenates the videos, converts the OpenBattle to a Battle and deletes the old video files
             \Event::fire(new VideoWasUploaded($outfile, $infiles, false, new OpenBattleCompleted($event->battle, $this->outfilename)));
         }
     }
     $event->battle->save();
 }
Example #12
0
 /**
  * Execute the console command.
  *
  * @return void
  */
 public function fire()
 {
     // Fire event before the Cron jobs will be executed
     \Event::fire('cron.collectJobs');
     $report = Cron::run();
     if ($report['inTime'] === -1) {
         $inTime = -1;
     } else {
         if ($report['inTime']) {
             $inTime = 'true';
         } else {
             $inTime = 'false';
         }
     }
     // Get Laravel version
     $laravel = app();
     $version = $laravel::VERSION;
     if ($version < '5.2') {
         // Create table for old Laravel versions.
         $table = $this->getHelperSet()->get('table');
         $table->setHeaders(array('Run date', 'In time', 'Run time', 'Errors', 'Jobs'));
         $table->addRow(array($report['rundate'], $inTime, round($report['runtime'], 4), $report['errors'], count($report['crons'])));
     } else {
         // Create table for new Laravel versions.
         $table = new \Symfony\Component\Console\Helper\Table($this->getOutput());
         $table->setHeaders(array('Run date', 'In time', 'Run time', 'Errors', 'Jobs'))->setRows(array(array($report['rundate'], $inTime, round($report['runtime'], 4), $report['errors'], count($report['crons']))));
     }
     // Output table.
     $table->render($this->getOutput());
 }
 /**
  * Register any other events for your application.
  *
  * @param  \Illuminate\Contracts\Events\Dispatcher  $events
  * @return void
  */
 public function boot(DispatcherContract $events)
 {
     parent::boot($events);
     User::deleting(function ($user) {
         \Event::fire(new UserWasDeleted($user->id));
     });
 }
Example #14
0
 /**
  * Write a message to the log file.
  *
  * <code>
  *		// Write an "error" message to the log file
  *		Log::write('error', 'Something went horribly wrong!');
  *
  *		// Write an "error" message using the class' magic method
  *		Log::error('Something went horribly wrong!');
  *
  *		// Log an arrays data
  *		Log::write('info', array('name' => 'Sawny', 'passwd' => '1234', array(1337, 21, 0)), true);
  *      //Result: Array ( [name] => Sawny [passwd] => 1234 [0] => Array ( [0] => 1337 [1] => 21 [2] => 0 ) )
  *      //If we had omit the third parameter the result had been: Array
  * </code>
  *
  * @param  string  $type
  * @param  string  $message
  * @return void
  */
 public static function write($type, $message, $pretty_print = false)
 {
     $message = $pretty_print ? print_r($message, true) : $message;
     // If there is a listener for the log event, we'll delegate the logging
     // to the event and not write to the log files. This allows for quick
     // swapping of log implementations for debugging.
     if (Event::listeners('laravel.log')) {
         Event::fire('laravel.log', array($type, $message));
     }
     $trace = debug_backtrace();
     foreach ($trace as $item) {
         if (isset($item['class']) and $item['class'] == __CLASS__) {
             continue;
         }
         $caller = $item;
         break;
     }
     $function = $caller['function'];
     if (isset($caller['class'])) {
         $class = $caller['class'] . '::';
     } else {
         $class = '';
     }
     $message = static::format($type, $class . $function . ' - ' . $message);
     File::append(path('storage') . 'logs/' . date('Y-m-d') . '.log', $message);
 }
Example #15
0
 /**
  * @Post("/publish")
  * @Middleware("admin")
  *
  * Admin publishes the menu.
  * 
  */
 public function publishMenus()
 {
     $week = \Input::get('week');
     Menu::where('week', $week)->update(['published' => true]);
     \Event::fire(new MenuWasPublished(Menu::where('week', $week)->first()));
     return Menu::with(['menuFoods', 'menuFoods.menu', 'menuFoods.food'])->where('week', $week)->get();
 }
Example #16
0
 /**
  * Creates a new user.
  * 
  * @param array $data
  * @return App\User $user
  */
 public function createNewUser($data)
 {
     $verification_token = str_random(50);
     $user = User::create([$this->getUsernameColumnAndField() => $data[$this->getUsernameColumnAndField()], $this->getPasswordColumnAndField() => bcrypt($data[$this->getPasswordColumnAndField()]), 'verification_token' => $verification_token]);
     Event::fire(new UserRegistered($user));
     return $user;
 }
Example #17
0
 public function sendInvoice(Invoice $invoice)
 {
     $invoice->load('invitations', 'client', 'account');
     $entityType = $invoice->getEntityType();
     $view = 'invoice';
     $subject = trans("texts.{$entityType}_subject", ['invoice' => $invoice->invoice_number, 'account' => $invoice->account->getDisplayName()]);
     foreach ($invoice->invitations as $invitation) {
         if (!$invitation->user->email) {
             return false;
         }
         if (!$invitation->contact->email) {
             return false;
         }
         $invitation->sent_date = \Carbon::now()->toDateTimeString();
         $invitation->save();
         $data = ['entityType' => $entityType, 'link' => $invitation->getLink(), 'clientName' => $invoice->client->getDisplayName(), 'accountName' => $invoice->account->getDisplayName(), 'contactName' => $invitation->contact->getDisplayName(), 'invoiceAmount' => Utils::formatMoney($invoice->amount, $invoice->client->currency_id), 'emailFooter' => $invoice->account->email_footer, 'showNinjaFooter' => !$invoice->account->isPro()];
         $fromEmail = $invitation->user->email;
         $fromName = $invitation->user->getDisplayName();
         $this->sendTo($invitation->contact->email, $fromEmail, $fromName, $subject, $view, $data);
         Activity::emailInvoice($invitation);
     }
     if (!$invoice->isSent()) {
         $invoice->invoice_status_id = INVOICE_STATUS_SENT;
         $invoice->save();
     }
     \Event::fire('invoice.sent', $invoice);
 }
Example #18
0
 public function ajaxAdminLogin()
 {
     $input = Input::all();
     $data = ['email' => $input['email'], 'password' => $input['password']];
     //Rules to validate the incoming username and password
     $rules = ['email' => 'required', 'password' => 'required'];
     $validator = Validator::make($input, $rules);
     //if validator fails then move to this block
     if ($validator->fails()) {
         $output['status'] = 'error';
         //Check if login is from lock screen or from login page
         $output['msg'] = Session::get("lock") != 1 ? 'Ambos campos requereidos' : 'Password Invalido/Requerido';
     } else {
         if (Auth::admin()->attempt($data, true)) {
             $event = Event::fire('auth.login', Auth::admin()->get());
             Session::put('lock', '0');
             //Reset the lock screen session;
             $output['status'] = 'success';
             $output['msg'] = 'Ingreso Exitoso';
         } else {
             $output['status'] = 'error';
             //Check if login is from lock screen or from login page
             $output['msg'] = Session::get("lock") != 1 ? 'Credenciales Erroneas' : 'Password Invalido';
         }
     }
     return Response::json($output, 200);
 }
Example #19
0
 /**
  * Start a big file download on Laravel Framework 4.0 / 4.1
  * Source (originally for Laravel 3.*) : http://stackoverflow.com/questions/15942497/why-dont-large-files-download-easily-in-laravel
  * @param  string $path    Path to the big file
  * @param  string $name    Name of the file (used in Content-disposition header)
  * @param  array  $headers Some extra headers
  */
 public function sendFile($path, $name = null, array $headers = array())
 {
     if (is_null($name)) {
         $name = basename($path);
     }
     $file = new \Symfony\Component\HttpFoundation\File\File($path);
     $mime = $file->getMimeType();
     // Prepare the headers
     $headers = array_merge(array('Content-Description' => 'File Transfer', 'Content-Type' => $mime, 'Content-Transfer-Encoding' => 'binary', 'Expires' => 0, 'Cache-Control' => 'must-revalidate, post-check=0, pre-check=0', 'Pragma' => 'public', 'Content-Length' => \File::size($path), 'Content-Disposition' => 'attachment; filename=' . $name), $headers);
     $response = new \Symfony\Component\HttpFoundation\Response('', 200, $headers);
     // If there's a session we should save it now
     if (\Config::get('session.driver') !== '') {
         \Session::save();
     }
     session_write_close();
     if (ob_get_length()) {
         ob_end_clean();
     }
     $response->sendHeaders();
     // Read the file
     if ($file = fopen($path, 'rb')) {
         while (!feof($file) and connection_status() == 0) {
             print fread($file, 1024 * 8);
             flush();
         }
         fclose($file);
     }
     // Finish off, like Laravel would
     \Event::fire('laravel.done', array($response));
     $response->send();
 }
Example #20
0
 /**
  * View users profile
  */
 public function action_index()
 {
     $id = $this->request->param('id');
     $user = ORM::factory('User', $id);
     if (!$user->loaded()) {
         throw HTTP_Exception::Factory('404', 'No such user');
     }
     $container = new Tabs();
     $about = new Tab('About me');
     $about->add_content(new Tab_Text($user->get_property('about')));
     $about->add_content(new Tab_Text($user->get_property('signature')));
     $container->add_tab($about);
     Event::fire('user.profile_tabs', array($user, $container));
     $this->view = new View_User_Profile();
     $this->view->user = $user;
     $this->view->tabs = $container->render();
     /*
     // @TODO, This belongs to the pet module, better to use events?
     $pets = ORM::factory('User_Pet')
     	->where('user_id', '=', $user->id)
     	->order_by('active', 'desc');
     
     $paginate = Paginate::factory($pets)
     	->execute();
     
     $this->view = new View_User_Profile;
     $this->view->pagination = $paginate->render();
     $this->view->profile_user = $user;
     // $this->view->pets = ORM::factory('User_Pet')->where('user_id', '=', $user->id)->order_by('active', 'desc')->find_all()->as_array();
     $this->view->pets = $paginate->result();
     */
 }
 public function render()
 {
     $params = array($this->_pageID, &$this->_data);
     ptc_log($params, 'Website metatags are been compiled!', \App::option('website.debug_category') . ' Action');
     if ($this->_callback) {
         ptc_log($params, 'Website metatags is beeing fired!', \App::option('website.debug_category') . ' Action');
         \Event::fire('metatags.callback', $params);
     }
     if (empty($this->_data)) {
         return null;
     }
     $tag = null;
     foreach ($this->_data as $k => $v) {
         if (!$v) {
             continue;
         }
         $v = preg_replace('/\\s+/', ' ', $v);
         if ('title' === $k) {
             $tag .= "\t" . '<title>' . trim($v) . '</title>' . "\n";
         } else {
             if (0 === strpos(strtolower($k), 'og:')) {
                 $tag .= "\t" . '<meta property="' . $k . '" content="' . trim($v) . '">' . "\n";
             } else {
                 $tag .= "\t" . '<meta name="' . $k . '" content="' . trim($v) . '">' . "\n";
             }
         }
     }
     return $tag;
 }
Example #22
0
 /**
  * Bootstrap the application events.
  *
  * @return void
  */
 public function boot()
 {
     \Event::fire('press.mount', []);
     if (\App::runningInConsole()) {
         $this->consoleSetup();
     }
 }
Example #23
0
 public function makeImages($imagePath, $filePath = NULL, $rename = NULL, $config = NULL)
 {
     $results = null;
     $image = $this->imageManager->make($imagePath);
     $filename = $rename !== NULL ? $rename : pathinfo($imagePath)['filename'];
     foreach ($this->imageSizes as $type => $size) {
         $tempImage = clone $image;
         $height = $size[0];
         $width = $size[1];
         // prevent possible upsizing maintain aspect ratio
         $tempImage->resize($width, $height, function ($constraint) {
             $constraint->aspectRatio();
             $constraint->upsize();
         });
         $tempImage->encode($this->imageFormat);
         $tempFilename = $filename . '_' . $type . '.' . $this->imageFormat;
         $tempPath = $filePath !== NULL ? $filePath . '/' . $tempFilename : $tempFilename;
         $saved_image = $this->path->put($tempPath, $tempImage);
         $results[$type] = $this->pathPrefix . '/' . $tempPath;
         unset($tempImage);
     }
     $data = ['output' => $results, 'source' => $imagePath];
     // used with Laravel to fire event
     if (defined('LARAVEL_START')) {
         \Event::fire('resizer', [$data]);
     }
     return ['status' => 'ok', 'data' => $data, 'message' => 'Everything is okay!'];
 }
Example #24
0
 public function edit($user)
 {
     $save = $this->user->createOrUpdate($user->id);
     $errors = $save->errors();
     Event::fire('controller.user.edit', array($user));
     return count($errors->all()) == 0 ? Api::to(array('success', Lang::get('admin/users/messages.edit.success'))) ?: Redirect::to('admin/users/' . $user->id . '/edit')->with('success', Lang::get('admin/users/messages.edit.success')) : (Api::to(array('error', Lang::get('admin/users/messages.edit.error'))) ?: Redirect::to('admin/users/' . $user->id . '/edit')->withErrors($errors));
 }
Example #25
0
 /**
  * @return mixed
  */
 public function ajaxLogin()
 {
     if (Request::ajax()) {
         $output = [];
         $input = Input::all();
         $data = ['email' => $input['email'], 'password' => $input['password'], 'estado' => 'activo'];
         //Reglas de los Campos de Email y Password
         $rules = ['email' => 'required|email', 'password' => 'required'];
         $validator = Validator::make($input, $rules);
         //Verificacion previa de los campos, antes de la Autenticacion
         if ($validator->fails()) {
             $output['status'] = 'error';
             $output['msg'] = $validator->getMessageBag()->toArray();
         }
         $data = ['email' => $input['email'], 'password' => $input['password'], 'estado' => 'activo'];
         // Check if  exists in database with the credentials of not
         if (Auth::personales()->attempt($data)) {
             $event = Event::fire('auth.login', Auth::personales()->get());
             $output['status'] = 'success';
             $output['msg'] = Lang::get('messages.loginSuccess');
             return Response::json($output, 200);
         }
         // For Blocked Users
         $data['estado'] = 'inactive';
         if (Auth::personales()->validate($data)) {
             $output['status'] = 'error';
             $output['msg'] = ['error' => Lang::get('messages.loginBlocked')];
         } else {
             $output['status'] = 'error';
             $output['msg'] = ['error' => Lang::get('messages.loginInvalid')];
         }
         return Response::json($output, 200);
     }
 }
Example #26
0
 public function commission($driver, $ipn)
 {
     try {
         \DB::beginTransaction();
         if ($driver->id == $ipn['custom']) {
             // Get the pre-month commissions.
             $sales = new SaleCollection($driver->sales(Carbon::now()->subMonth(), Carbon::now()));
             if ($sales) {
                 $paypalHelper = new PaypalHelper($driver);
                 // get authorized commission payment
                 if ($authorizedCommissionPayment = $paypalHelper->createPaypalFuturePayment($sales->toArray()['totals'])) {
                     // capture authorized commission payment
                     if ($capture = $paypalHelper->capturePaypalPayment($authorizedCommissionPayment)) {
                         if ($authorizedCommissionPayment['id'] == $capture['parent_payment']) {
                             $commission_payment = ['driver_id' => $driver->id, 'commissions' => $authorizedCommissionPayment['transactions'][0]['amount']['total'], 'currency' => $authorizedCommissionPayment['transactions'][0]['amount']['currency'], 'status' => $authorizedCommissionPayment['state'], 'commission_ipn' => $authorizedCommissionPayment, 'commission_payment_id' => $authorizedCommissionPayment['id'], 'capture_id' => $capture['id'], 'capture_created_at' => $capture['create_time'], 'capture_updated_at' => $capture['update_time'], 'capture_status' => $capture['state'], 'capture_ipn' => $capture];
                             if ($commission = EloquentCommissionRepository::create($commission_payment)) {
                                 \DB::commit();
                                 // Todo:: fire notification event the commission paid.
                                 $commission->type = "billing";
                                 \Event::fire('paxifi.notifications.billing', [$commission]);
                                 return $this->setStatusCode(201)->respondWithItem($commission);
                             }
                         }
                     }
                 }
             }
         }
     } catch (\Exception $e) {
         return $this->setStatusCode(400)->respondWithError($e->getMessage());
     }
 }
 public function create()
 {
     $response = array('success' => false);
     if (Request::ajax()) {
         $postData = Input::all();
         $tabletId = $postData['tabletId'];
         $economyValue = (double) $postData['economyValue'];
         $rules = array('tabletId' => array('required', 'not_in:0', 'exists:tablets,id'), 'economyValue' => array('required', 'numeric', 'min:0'));
         $messages = array('tabletId.required' => 'Please select a tablet.', 'tabletId.not_in' => 'Please select a tablet.', 'tabletId.exists' => 'An error occured. Please try later.', 'economyValue.required' => 'Please enter savings value.', 'economyValue.numeric' => 'Savings must be a numeric value. Ex: 90, 3.42', 'economyValue.min' => 'Savings must have a positive value.');
         $validator = Validator::make($postData, $rules, $messages);
         if ($validator->fails()) {
             $messages = $validator->messages();
             $response['tabletMsg'] = $messages->first('tabletId');
             $response['economyValueMsg'] = $messages->first('economyValue');
             return Response::json($response);
         }
         $tablet = Tablet::find($tabletId);
         if ($tablet->id) {
             $initialCurrentSum = $tablet->current_sum;
             $tablet->current_sum = $initialCurrentSum - $economyValue;
             $initialEconomies = $tablet->economies;
             $tablet->economies = $initialEconomies + $economyValue;
             $tablet->save();
             $response['success'] = true;
             Event::fire('economy.create.success', array($economyValue, $tabletId));
         }
     }
     return Response::json($response);
 }
 public function create()
 {
     $response = array('success' => false);
     if (Request::ajax()) {
         $postData = Input::all();
         $predictionId = $postData['predictionId'];
         $expenseValue = $postData['value'];
         $rules = array('predictionId' => array('required', 'not_in:0', 'exists:predictions,id'), 'value' => array('required', 'numeric', 'min:0'));
         $messages = array('predictionId.required' => 'Please select a category.', 'predictionId.not_in' => 'Please select a category.', 'predictionId.exists' => 'An error occured. Please try later.', 'value.required' => 'Please enter expense value.', 'value.numeric' => 'Expense must be a numeric value. Ex: 90, 3.42', 'value.min' => 'Value must be a positive number.');
         $validator = Validator::make($postData, $rules, $messages);
         if ($validator->fails()) {
             $messages = $validator->messages();
             $response['predictionMsg'] = $messages->first('predictionId');
             $response['valueMsg'] = $messages->first('value');
             return Response::json($response);
         }
         $expense = new Expense();
         $expense->prediction_id = $predictionId;
         $expense->value = $expenseValue;
         $expense->save();
         $response['expenseId'] = $expense->id;
         $response['success'] = true;
         Event::fire('expense.create.success', array($expense));
     }
     return Response::json($response);
 }
Example #29
0
 /**
  * Update the specified resource in storage.
  *
  * @param  int  $id
  * @return Response
  */
 public function update($id)
 {
     $input = Input::only('email', 'username', 'password');
     $rules = array('email' => 'required|email|unique:users,email,' . Auth::user()->id . ',id,deleted_at,NULL,status,' . Auth::user()->status . '');
     if ($input['password']) {
         $rules['password'] = '******';
     }
     $v = Validator::make($input, $rules);
     if ($v->fails()) {
         return Output::push(array('path' => 'user', 'errors' => $v, 'input' => TRUE));
     }
     if ($input['password'] && $id && Auth::user()->id == $id) {
         $user = user::find($id);
         //$user->username = $input['username'];
         $user->email = $input['email'];
         if ($input['password']) {
             $user->password = Hash::make($input['password']);
             Event::fire('logger', array(array('account_password_update', array('id' => $id, 'username' => $user->username), 2)));
         }
         $user->save();
         return Output::push(array('path' => 'user', 'errors' => 'Change Password Successfully', 'messages' => array('success', _('User data has been saved')), 'input' => TRUE));
     } else {
         return Output::push(array('path' => 'user', 'errors' => 'Unable to update user', 'messages' => array('fail', _('Unable to update user')), 'input' => TRUE));
     }
 }
Example #30
0
 public function deleteAttribute($attribute)
 {
     \Event::fire('entity_attributes.deleted', $attribute);
     $attribute->delete();
     $coder = new \Cms\Library\Helpers\Coder\EntitiesCoder();
     $coder->codeEntities();
 }