Beispiel #1
0
/**
 * May be set as exception handler, i.e. set_exception_handler('alkemann\h2l\handleError');
 *
 * @param \Throwable $e
 */
function handleError(\Throwable $e)
{
    if ($e instanceof \alkemann\h2l\exceptions\InvalidUrl) {
        Log::info("InvalidUrl: " . $e->getMessage());
        echo (new Error(404, $e->getMessage()))->render();
        return;
    }
    if ($e instanceof \Exception) {
        Log::error(get_class($e) . ": " . $e->getMessage());
    } elseif ($e instanceof \Error) {
        Log::alert(get_class($e) . ": " . $e->getMessage());
    }
    if (DEBUG && isset($e->xdebug_message)) {
        header("Content-type: text/html");
        echo '<table>' . $e->xdebug_message . '</table><br>';
        dbp('xdebug_message');
        d($e);
    } elseif (DEBUG) {
        header("Content-type: text/html");
        echo '<h1>' . $e->getMessage() . '</h1>';
        d($e);
    } else {
        (new Error(500, $e->getMessage()))->render();
    }
}
 /**
  * Fetch the collection of site permissions.
  *
  * @return \Illuminate\Database\Eloquent\Collection
  */
 protected function getPermissions()
 {
     try {
         return Permission::with('roles')->get();
     } catch (\Exception $e) {
         \Log::alert('No se pudo registrar los permisos');
         return [];
     }
 }
Beispiel #3
0
 /**
  * Execute the console command.
  *
  * @return mixed
  */
 public function handle()
 {
     \Log::alert('Refresh tweets');
     $tweet = UpcomingTweet::where('end', '<', date('Y-m-d H:i:s'))->first();
     if ($tweet != null) {
         $tweet->delete();
         $newTweet = UpcomingTweet::orderBy('id', 'asc')->first();
         $newTweet->end = date('Y-m-d H:i:s', strtotime('+ 1 hour'));
         $newTweet->save();
     }
 }
 public function terminate($request, $response)
 {
     if (!\App::runningInConsole() && \App::bound('veer') && app('veer')->isBooted()) {
         $timeToLoad = empty(app('veer')->statistics['loading']) ? 0 : app('veer')->statistics['loading'];
         if ($timeToLoad > config('veer.loadingtime')) {
             \Log::alert('Slowness detected: ' . $timeToLoad . ': ', app('veer')->statistics());
             info('Queries: ', \DB::getQueryLog());
         }
         \Veer\Jobs\TrackingUser::run();
         (new \Veer\Commands\HttpQueueWorkerCommand(config('queue.default')))->handle();
     }
 }
 /**
  * Execute the console command.
  *
  * @return mixed
  */
 public function fire()
 {
     Log::alert('Executed Cron Job to send weekly mail for pending karma note and meeting requests.');
     $KarmaNotePending = "";
     $KarmaNotePending = Meetingrequest::whereIn('status', array('pending', 'accepted'))->get();
     if (!empty($KarmaNotePending)) {
         $test_id = "";
         $test_id = Adminoption::Where('option_name', '=', 'Test User Emails')->first();
         $test_user_id = $getfintrorecords = array();
         if (!empty($test_id)) {
             $test_user_id = explode(',', $test_id->option_value);
         }
         $introducer = $giver = $receiver = $connidgiver = '';
         foreach ($KarmaNotePending as $key => $value) {
             $diffDate = KarmaHelper::dateDiff(date("Y-m-d H:i:s"), $value->created_at);
             if (isset($value->user_id_giver)) {
                 $giver = in_array($value->user_id_giver, $test_user_id);
             }
             if (isset($value->user_id_receiver)) {
                 $receiver = in_array($value->user_id_receiver, $test_user_id);
             }
             if (isset($value->connection_id_giver)) {
                 $connidgiver = in_array($value->connection_id_giver, $test_user_id);
             }
             if (isset($value->user_id_introducer)) {
                 $introducer = in_array($value->user_id_introducer, $test_user_id);
             }
             if ($giver != 1 && $receiver != 1 && $connidgiver != 1 && $introducer != 1) {
                 if ($diffDate->days > 7) {
                     $meetingtimezone = $value->meetingtimezone;
                     $meetingdatetime = $value->meetingdatetime;
                     $user_id_giver = $value->user_id_giver;
                     $user_id_receiver = $value->user_id_receiver;
                     $meetingId = $value->id;
                     $status = $value->status;
                     $CurrentTimeWithZone = KarmaHelper::calculateTime($meetingtimezone);
                     if ($CurrentTimeWithZone > $meetingdatetime && $status == 'accepted') {
                         Queue::push('MessageSender', array('type' => '4', 'user_id_giver' => $user_id_giver, 'user_id_receiver' => $user_id_receiver, 'meetingId' => $meetingId));
                     }
                     if ($status == 'pending') {
                         //echo"<pre>";print_r($value->id);echo"</pre>";
                         if (isset($value->user_id_giver)) {
                             Queue::push('MessageSender', array('type' => '1', 'user_id_giver' => $user_id_giver, 'user_id_receiver' => $user_id_receiver, 'meetingId' => $meetingId));
                         } else {
                             Queue::push('MessageSender', array('type' => '2', 'user_id_giver' => $value->connection_id_giver, 'user_id_receiver' => $user_id_receiver, 'meetingId' => $meetingId));
                         }
                     }
                 }
             }
         }
     }
 }
Beispiel #6
0
 /**
  * Performs user authentication.
  *
  * @param $username
  * @param $password
  *
  * @return bool
  * @throws BadRequestException
  */
 public function authenticate($username, $password)
 {
     if (empty($username) || empty($password)) {
         throw new BadRequestException('No username and/or password provided.');
     }
     $this->userDn = $this->getUserDn($username);
     try {
         $auth = ldap_bind($this->connection, $this->userDn, $password);
     } catch (\Exception $e) {
         \Log::alert('Failed to authenticate using LDAP. ' . $e->getMessage());
         $auth = false;
     }
     $this->authenticated = $auth;
     return $auth;
 }
 /**
  * Execute the console command.
  *
  * @return mixed
  */
 public function fire()
 {
     //get test users id
     $getUser = KarmaHelper::getTestUsers();
     //print_r($getUser);die;
     if (!empty($getUser)) {
         foreach ($getUser as $key => $value) {
             $helper = User::find($value);
             if (!empty($helper)) {
                 $helper->karmascore = 0;
                 $helper->save();
             }
         }
     }
     Log::alert('Updated test user Karma score.');
 }
 /**
  * Execute the console command.
  *
  * @return mixed
  */
 public function fire()
 {
     Log::alert('Executed Cron Job');
     $KarmaNotePending = Meetingrequest::where('status', '=', 'confirmed')->where('cronjobflag', '=', '0')->get();
     if (!empty($KarmaNotePending)) {
         foreach ($KarmaNotePending as $key => $value) {
             $meetingtimezone = $value->meetingtimezone;
             $meetingdatetime = $value->meetingdatetime;
             $user_id_giver = $value->user_id_giver;
             $user_id_receiver = $value->user_id_receiver;
             $meetingId = $value->id;
             $CurrentTimeWithZone = KarmaHelper::calculateTime($meetingtimezone);
             //echo "<pre>";print_r($meetingdatetime);echo "</pre>";
             //echo "<pre>";print_r($meetingdatetime);echo "</pre>";die();
             if ($CurrentTimeWithZone > $meetingdatetime) {
                 $diffDate = KarmaHelper::dateDiff($CurrentTimeWithZone, $meetingdatetime);
                 $diffDate = $diffDate->days * 24 + $diffDate->h;
                 $EmailTriggerTime = Adminoption::where('option_name', '=', 'KarmaNote Email Trigger Time')->first();
                 if (!empty($EmailTriggerTime)) {
                     $EmailTriggerTime = $EmailTriggerTime->toArray();
                     $EmailTriggerTime = $EmailTriggerTime['option_value'];
                 } else {
                     $EmailTriggerTime = '24';
                 }
                 if ($diffDate >= $EmailTriggerTime) {
                     //$date = Carbon::now()->addMinutes(5);
                     Queue::push('MessageSender', array('type' => '4', 'user_id_giver' => $user_id_giver, 'user_id_receiver' => $user_id_receiver, 'meetingId' => $meetingId));
                     $Meetingrequest = Meetingrequest::find($meetingId);
                     $Meetingrequest->cronjobflag = '1';
                     $Meetingrequest->status = 'over';
                     $Meetingrequest->save();
                     DB::table('users_mykarma')->where('entry_id', '=', $meetingId)->update(array('status' => 'over', 'unread_flag' => 'true', 'entry_updated_on' => Carbon::now()));
                     $messageData = new Message();
                     $messageData->request_id = $meetingId;
                     $messageData->sender_id = $user_id_giver;
                     $messageData->giver_id = $user_id_giver;
                     $messageData->receiver_id = $user_id_receiver;
                     $messageData->message_type = 'system';
                     $messageText = 'Meeting should be over now.';
                     $messageData->messageText = $messageText;
                     $messageData->save();
                     //Queue::push('UpdateUser', array('id' => $user_id,'result' => $result));
                 }
             }
         }
     }
 }
Beispiel #9
0
 public function __construct($dsn = '', $username = '', $password = '')
 {
     if (null !== ($dumpLocation = config('df.db.freetds.dump'))) {
         if (!putenv("TDSDUMP={$dumpLocation}")) {
             \Log::alert('Could not write environment variable for TDSDUMP location.');
         }
     }
     if (null !== ($dumpConfLocation = config('df.db.freetds.dumpconfig'))) {
         if (!putenv("TDSDUMPCONFIG={$dumpConfLocation}")) {
             \Log::alert('Could not write environment variable for TDSDUMPCONFIG location.');
         }
     }
     if (null !== ($confLocation = config('df.db.freetds.sqlanywhere'))) {
         if (!putenv("FREETDSCONF={$confLocation}")) {
             \Log::alert('Could not write environment variable for FREETDSCONF location.');
         }
     }
     parent::__construct($dsn, $username, $password);
 }
 /**
  * 受け取ったイベントの内容を実行する
  *
  * @param  MonitorableInterface  $event
  * @return void
  */
 public function handle(CardTaskKicked $event)
 {
     // 実行中リストへ移動
     $url = 'https://trello.com/1/cards/' . $event->id . '/idList' . '?key=' . env('TRELLO_KEY') . '&token=' . env('TRELLO_TOKEN') . '&value=' . env('TRELLO_BATCH_EXECUTING_LIST');
     $updatedCard = $this->putter->put($url);
     // コマンド実行、実行コード(通常正常時0)が返ってくる
     $result = $this->executor->execute($event->task);
     // エラーの場合のみ、コメントとして実行結果を追加
     if ($result !== 0) {
         // メッセージをログしておく
         \Log::alert($this->executor->getMessage());
         // コメント長の制限は1から16384だが、文字数かバイト数か不明
         // そのためコメント長は未チェック
         $url = 'https://trello.com/1/cards/' . $event->id . '/actions/comments' . '?key=' . env('TRELLO_KEY') . '&token=' . env('TRELLO_TOKEN') . '&text=' . urlencode($this->executor->getMessage());
         $updatedCard = $this->poster->post($url);
     }
     // 実行を終えたので、待機リストへ移動
     $url = 'https://trello.com/1/cards/' . $event->id . '/idList' . '?key=' . env('TRELLO_KEY') . '&token=' . env('TRELLO_TOKEN') . '&value=' . env('TRELLO_BATCH_WAIT_STACK_LIST');
     $updatedCard = $this->putter->put($url);
 }
Beispiel #11
0
 /**
  * {@inheritdoc}
  */
 public function authenticate($username, $password)
 {
     if (empty($username) || empty($password)) {
         throw new BadRequestException('No username and/or password provided.');
     }
     $accountSuffix = $this->getAccountSuffix();
     try {
         $preAuth = ldap_bind($this->connection, $username . '@' . $accountSuffix, $password);
         if ($preAuth) {
             $this->userDn = $this->getUserDn($username, 'samaccountname');
             $auth = ldap_bind($this->connection, $this->userDn, $password);
         } else {
             $auth = false;
         }
     } catch (\Exception $e) {
         \Log::alert('Failed to authenticate with AD server using LDAP. ' . $e->getMessage());
         $auth = false;
     }
     $this->authenticated = $auth;
     return $auth;
 }
 /**
  * @return array
  * @throws \Exception
  */
 protected function getPath()
 {
     try {
         $cors = \DB::table('cors_config')->whereRaw('enabled = 1')->get();
     } catch (\Exception $e) {
         if ($e instanceof QueryException || $e instanceof \PDOException) {
             \Log::alert('Could not get cors config from DB - ' . $e->getMessage());
             return [];
         } else {
             throw $e;
         }
     }
     $path = [];
     if (!empty($cors)) {
         $path = [];
         foreach ($cors as $p) {
             $cc = new CorsConfig(['id' => $p->id, 'path' => $p->path, 'origin' => $p->origin, 'header' => $p->header, 'method' => $p->method, 'max_age' => $p->max_age, 'enabled' => $p->enabled]);
             $path[$cc->path] = ["allowedOrigins" => explode(',', $cc->origin), "allowedHeaders" => explode(',', $cc->header), "allowedMethods" => $cc->method, "maxAge" => $cc->max_age];
         }
     }
     return $path;
 }
Beispiel #13
0
 /**
  * Execute the console command.
  *
  * @return void
  */
 public function fire()
 {
     if ($this->confirm('Are you sure you wish to restore to factory defaults? [y/N] ', false)) {
         /**
          * Execute the migration tasks here, meaning that we only have to keep the migrations
          *  up to date and the rest should just work :)
          */
         $app_path = str_replace('/app/commands', '', dirname(__FILE__));
         // We now need to delete all configuration files from the Nginx configuration directory
         $cleanup = new NginxConfig();
         $existing_rules = Rule::all();
         foreach ($existing_rules as $rule) {
             //$cleanup->readConfig($filename)
             $cleanup->setHostheaders($rule->hostheader);
             $cleanup->deleteConfig(Setting::getSetting('nginxconfpath') . '/' . $cleanup->serverNameToFileName() . '.enabled.conf');
         }
         // We now re-build the database using the migrations...
         $execute = new Executer();
         $execute->setApplication('php')->addArgument($app_path . '/artisan')->addArgument('migrate:refresh')->addArgument('--seed')->execute();
         // and then restart the daemon as otherwise Nginx will continue to proxy traffic...
         $cleanup->reloadConfig();
         // We now generate a new API key..
         $genkey = new Executer();
         $genkey->setApplication('php')->addArgument($app_path . '/artisan')->addArgument('turbine:generatekey')->execute();
         /**
          *  Users can uncommet this code block if they want verbose factory resets!
          *
          * foreach ($execute->resultAsArray() as $outputline) {
          *    $this->info($outputline); - Users can uncommet this if they want verbose factory resets!
          * }
          *
          */
         Log::alert('Factory settings restored from the console');
         $this->info('Factory settings restored and a new API key has been generated!');
     } else {
         $this->error('User cancelled!');
     }
 }
Beispiel #14
0
 public function __construct($dsn = '', $username = '', $password = '')
 {
     if (substr(PHP_OS, 0, 3) == 'WIN') {
         // MS SQL Server on Windows
         $this->pdoClass = 'DreamFactory\\Core\\Database\\Mssql\\SqlsrvPdoAdapter';
     } else {
         if (null !== ($dumpLocation = config('df.db.freetds.dump'))) {
             if (!putenv("TDSDUMP={$dumpLocation}")) {
                 \Log::alert('Could not write environment variable for TDSDUMP location.');
             }
         }
         if (null !== ($dumpConfLocation = config('df.db.freetds.dumpconfig'))) {
             if (!putenv("TDSDUMPCONFIG={$dumpConfLocation}")) {
                 \Log::alert('Could not write environment variable for TDSDUMPCONFIG location.');
             }
         }
         if (null !== ($confLocation = config('df.db.freetds.sqlsrv'))) {
             if (!putenv("FREETDSCONF={$confLocation}")) {
                 \Log::alert('Could not write environment variable for FREETDSCONF location.');
             }
         }
     }
     parent::__construct($dsn, $username, $password);
 }
Beispiel #15
0
 /**
  * Actiovation account
  */
 public function getActivation($code = null)
 {
     if (Session::get('activated')) {
         return View::make(Config::get('larauth::views.activation'));
     }
     if (Input::get('code')) {
         $code = Input::get('code');
     }
     if ($code) {
         try {
             $user = Sentry::findUserByActivationCode($code);
             $user->attemptActivation($code);
             // добавляем пользователя в группы
             foreach (Config::get('larauth::append_groups') as $group) {
                 try {
                     $oGroup = Sentry::findGroupByName($group);
                 } catch (\Cartalyst\Sentry\Groups\GroupNotFoundException $e) {
                     Log::alert("Попытка добавдения пользователя :user_email в несуществующую группу :group", ['user_email' => $user->email, 'group' => $group]);
                 }
                 $user->addGroup($oGroup);
             }
             $data = ['email' => $user->email, 'password' => Cache::pull(md5($user->email)), 'subject' => trans('larauth::larauth.registration_success')];
             $this->sendMail(Config::get('larauth::views.mail_registration'), $data);
             return Redirect::route('larauth.activation')->with('activated', TRUE);
         } catch (Cartalyst\Sentry\Users\UserNotFoundException $e) {
             return Redirect::route('larauth.activation')->with('error', trans('larauth::larauth.wrong_activation_code'));
         }
     }
     return View::make(Config::get('larauth::views.activation'), ['error' => Session::get('error'), 'code' => $code]);
 }
Beispiel #16
0
    $raw_settings = Settings::all();
    $settings = new StdClass();
    foreach ($raw_settings as $raw_setting) {
        $settings->{$raw_setting->key} = json_decode($raw_setting->value);
    }
    $view->with('settings', $settings);
    $view->with('uni_department_id', User::getUniDepartment());
    $view->with('uni_company_id', User::getUniCompany());
});
Route::get('/', 'AuthController@getLogin');
Route::post('/log-errors', function () {
    $inputJSON = file_get_contents('php://input');
    $input = json_decode($inputJSON, TRUE);
    //convert JSON into array
    Log::alert("See below");
    Log::alert($input);
});
/*
Route::get('/setup', 'DashboardController@getSetup');
Route::post('/setup', 'DashboardController@postSetup');
*/
Route::get('/clean-everything', 'DashboardController@cleanDB');
Route::get('/activities/all', 'DashboardController@allActivities');
Route::get('/users/all', 'DashboardController@allUsers');
Route::get('/profile', 'AuthController@profile');
Route::get('/login', 'AuthController@getLogin');
Route::get('/register', 'AuthController@getRegister');
Route::get('/forgot-password', 'AuthController@getForgotPassword');
Route::get('/reset/{email}/{code}', 'AuthController@getReset');
Route::get('/activate/{user_id}/{activation_code}', 'AuthController@activateUser');
Route::get('/facebook', 'AuthController@signInWithFacebook');
Beispiel #17
0
 /** Redirect user
  *
  * Redirect user to another page (or event)
  *
  * @param string $event
  *	Name of event to redirect to (use 'back' to redirect one event back, 
  *	'this' to redirect to the current event and 'default' to redirect to 
  *	default start page)
  * @param bool|array|int $gets
  *	GET parameters for redirect or number of events to go back
  *
  */
 public function redirect($event, $gets = false)
 {
     // TODO: Prevent internal runs from redirecting
     // get loop
     $loop = $this->Input->get('loop');
     // get module and event
     if ($event === 'back') {
         // go back to page in history
         // get back-time
         $time = ($gets === false or !is_numeric($gets)) ? 1 : $gets;
         // create link
         $link = '?back=' . $time;
     } elseif ($event === 'default') {
         // set default-event
         $link = '?event=$$$showIndex';
     } elseif ($event === 'this') {
         // redirect to current page
         // get parameters
         $gets = $this->Input->getRaw(true);
         // sum up GET-parameters
         $url_gets = '';
         $to_skip = array('loop', '$$$hid', 'back');
         foreach ($gets as $index => $value) {
             if (in_array($index, $to_skip)) {
                 continue;
             }
             $url_gets .= '&' . $index . '=' . $value;
         }
         // get link
         $link = '?' . substr($url_gets, 1);
     } elseif ($gets === true) {
         // redirect to address given in $event
         $link = $event;
     } elseif (!empty($event)) {
         // get module and event from its parameters
         $gets = ($gets === false or !is_array($gets)) ? array() : $gets;
         $gets['event'] = $event;
         // sum up GET-parameters
         $url_gets = '';
         foreach ($gets as $index => $value) {
             $url_gets .= '&' . $index . '=' . $value;
         }
         // get redirect-path
         $link = '?' . substr($url_gets, 1);
     } else {
         // event doesn't exist
         $this->Log->alert('error', '{CLASS__TSUNIC__PAGE_NOT_FOUND}');
         $link = '?back=1';
     }
     // loop-prevention
     if (!empty($loop) and $loop >= 6) {
         $this->Log->log(3, "TSunic: Redirect failed!");
         $this->throwError('Redirect failed!');
     } elseif (!is_numeric($loop)) {
         $loop = 0;
     }
     $loop++;
     $link .= '&loop=' . $loop;
     // check, if ajax
     if ($this->isAjax()) {
         // TODO
         echo '<redirect>' . $link . '</redirect>';
     } else {
         // redirect and exit
         $this->Log->log(6, "TSunic::redirect: redirecting to {$link}");
         header('Location:' . $link);
     }
     exit;
 }
Beispiel #18
0
 public static function logException(\Exception $exception)
 {
     \Log::alert($exception->__toString());
 }
 public function bitpayRequest($orderId, $grandTotal, $billing)
 {
     $config = Config::get('bitcoins');
     $url = $config['bitpay_url'];
     $apiKey = $config['bitpay_api_key'];
     $post = array('orderID' => $orderId, 'price' => $grandTotal, 'currency' => 'USD', 'itemDesc' => 'KodeInfo Checkout Invoice', 'notificationEmail' => '*****@*****.**', 'notificationURL' => $config['bitpay_notify_url'], 'physical' => true, 'fullNotifications' => true, 'buyerName' => $billing->name, 'buyerAddress1' => $billing->address, 'buyerAddress2' => '', 'buyerCity' => $billing->city, 'buyerState' => $billing->state, 'buyerZip' => $billing->zip, 'buyerEmail' => $billing->email, 'buyerPhone' => $billing->phone);
     $post = json_encode($post);
     $length = strlen($post);
     $basic_auth = base64_encode($apiKey);
     $context_options = array("http" => array("method" => "POST", "header" => "Content-type: application/json\r\n" . "Content-Length: {$length}\r\n" . "Authorization: Basic {$basic_auth}\r\n"));
     $context_options["http"]["content"] = $post;
     $context = stream_context_create($context_options);
     $response = file_get_contents($url, false, $context);
     $decodeResponse = json_decode($response);
     if (empty($decodeResponse)) {
         Log::alert(Request::all());
         throw new \Exception("Unable to process payment contact customer support");
     } else {
         return $decodeResponse;
     }
 }
Beispiel #20
0
 /**
  * Pindah Adjustment ke Approval List
  *
  * @param       $adjid
  * @param       $adjnumber
  * @param array $itemAdj
  *
  * @throws \Exception
  * @return \Illuminate\Database\Eloquent\Model|static
  */
 public function moveAdjustmentToApproval($adjid, $adjnumber, array $itemAdj)
 {
     $adjustment = $this->oAdjustment()->findOrFail($adjid);
     if (!$adjustment) {
         $msg = 'Adjustment Id tidak diketemukan ';
         Log::alert($msg, ['time' => time(), 'class' => __CLASS__]);
         throw new \Exception($msg);
     }
     $trxnumber_adjustment = $adjustment->trxnumber;
     $id_adjustment = $adjustment->id;
     if ($trxnumber_adjustment !== $adjnumber) {
         $msg = 'Adjustment Number tidak cocok';
         Log::alert($msg, ['time' => time(), 'class' => __CLASS__ . '::' . __FUNCTION__]);
         throw new \Exception($msg);
     }
     $Adjitems = $this->oAdjustment()->getItem();
     /*Transaksi Number Adjustment */
     /*Prefix Approval*/
     $prefix_approval = $this->getPrefix();
     /*Transaksi Number Approval*/
     $trxnumber_approval = $prefix_approval . $trxnumber_adjustment;
     $uuid = $this->createUuid($trxnumber_approval);
     $newApproval = $this->create(['trxnumber' => $trxnumber_approval, 'adj_id' => $id_adjustment, 'uuid' => $uuid, 'status' => 1, 'createby_id' => $this->getUid(), 'lastupdateby_id' => $this->getUid()]);
     $approvalItem = $this->getItems();
     foreach ($itemAdj as $itemtoapprove) {
         /*Item Record Adjustment*/
         $item = $Adjitems->find($itemtoapprove);
         if (!$item) {
             /*Jika Item Id tidak ada Laporkan ke Log*/
             Log::critical('Adjustment dengan ID ' . $itemtoapprove . ' gagal dimasukan karena Id tidak diketemukan');
         } else {
             /*Jika Adjustment Item ada */
             $approvalItem->create(['product_id' => $item->product_id, 'adj_id' => $adjustment->id, 'adj_item' => $item->id, 'apr_id' => $newApproval->id, 'status' => 1, 'trxnumber' => $trxnumber_approval, 'uuid' => $uuid, 'createby_id' => $this->getUid(), 'lastupdateby_id' => $this->getUid()]);
             $item->status = 5;
             $item->save();
         }
     }
     /*Setup Status Adjustment menjadi sudah diajukan */
     $adjustment->status = 5;
     $adjustment->save();
     return $newApproval;
 }
 public function fire()
 {
     //fetch all users
     $getusers = DB::table('users')->select(array('users.*'))->where('users.userstatus', '=', 'approved')->orderBy('created_at', 'DESC')->get();
     //process for the records found
     if (!empty($getusers)) {
         $queryOfferHelp = array();
         foreach ($getusers as $user_info) {
             $diffDate = KarmaHelper::dateDiff(date("Y-m-d H:i:s"), $user_info->created_at);
             if ($diffDate->days > -1) {
                 $user_id = $user_info->id;
                 $location = $user_info->location;
                 /*$myKarmaDataOfInCompleteState= DB::select(DB::raw("SELECT COUNT( * ) AS AGGREGATE FROM  `users_mykarma` WHERE  `status` =  'completed' AND  `user_id` =".$user_id." AND  created_at > DATE_SUB(NOW(), INTERVAL 1 DAY)"));
                 		$myKarmaDataOfInCompleteState= DB::select(DB::raw("SELECT COUNT( * ) AS AGGREGATE FROM  `users_mykarma` WHERE  `status` !=  'completed' AND  `user_id` =".$user_id." AND  created_at > DATE_SUB(NOW(), INTERVAL 1 DAY)"));*/
                 $myKarmaDataOfCompleteState = Mykarma::where('status', '=', 'completed')->where('user_id', '=', $user_id)->where('unread_flag', '=', 'true')->where('created_at', '>=', Carbon::now()->subDay(1))->count();
                 $myKarmaDataOfInCompleteState = Mykarma::where('status', '!=', 'completed')->where('user_id', '=', $user_id)->where('entry_type', '=', 'Meeting')->where('unread_flag', '=', 'true')->where('created_at', '>=', Carbon::now()->subDay(1))->count();
                 $myKarmaDataOfQuery = Mykarma::where('user_id', '=', $user_id)->where('entry_type', '=', 'Query')->get();
                 foreach ($myKarmaDataOfQuery as $key => $value) {
                     $allQuery[] = $value->entry_id;
                 }
                 if (!empty($allQuery)) {
                     $queryOfferHelp = Mykarma::whereIn('entry_id', $allQuery)->where('users_role', '=', 'OfferedHelp')->where('unread_flag', '=', 'true')->where('created_at', '>=', Carbon::now()->subDay(1))->count();
                 }
                 // fetch user connections on KC
                 $getUserConnection = KarmaHelper::getUserConnection($user_id, $location);
                 $user_connection_onkc = 0;
                 if (!empty($getUserConnection)) {
                     foreach ($getUserConnection as $key => $value) {
                         if (isset($value->con_user_id)) {
                             $user_connection_onkc++;
                         }
                     }
                 }
                 // fetch pending karmanote requests
                 $totalPendingRequest = 0;
                 $PendingRequest = array();
                 $PendingRequest = KarmaHelper::getPendingKarmaNotes($user_info->id);
                 if (!empty($PendingRequest)) {
                     $totalPendingRequest = count($PendingRequest);
                 }
                 //fetch pending KM requests only received no read no unread
                 $totalReceivedRequest = 0;
                 $GiverInMeeting = User::find($user_info->id)->Giver()->where('status', 'pending')->orderBy('updated_at', 'DESC')->get();
                 if (!empty($GiverInMeeting)) {
                     $totalReceivedRequest = count($GiverInMeeting);
                 }
                 //fetch pending karma intros
                 $totalintroductionInitiated = 0;
                 $IntroducerInitiated = User::find($user_info->id)->Introducer;
                 if (!empty($IntroducerInitiated)) {
                     foreach ($IntroducerInitiated as $key => $value) {
                         $value['user_id_receiver'] = User::find($value['user_id_receiver'])->toArray();
                         if (!empty($value['user_id_giver'])) {
                             $value['user_id_giver'] = User::find($value['user_id_giver'])->toArray();
                         } else {
                             $value['user_id_giver'] = Connection::find($value['connection_id_giver'])->toArray();
                         }
                         if ($value->status == 'pending') {
                             $totalintroductionInitiated++;
                         }
                     }
                 }
                 // fetch queries that have been posted in the last 7 days within common groups including both public & private.
                 $Usergroup = User::find($user_info->id)->Groups;
                 $All_groups = '';
                 $group_question = 0;
                 $totagroupquestion = 0;
                 $yesterday = Carbon::now()->subDays(1);
                 $one_week_ago = Carbon::now()->subWeeks(1);
                 if (!$Usergroup->isEmpty()) {
                     foreach ($Usergroup as $key => $value) {
                         $All_groups[] = $value->id;
                     }
                     if (!empty($All_groups)) {
                         $group_question = DB::table('group_questions')->join('questions', 'group_questions.question_id', '=', 'questions.id')->select(array('questions.id'))->whereIn('group_questions.group_id', $All_groups)->where('questions.user_id', '!=', $user_info->id)->where('questions.queryStatus', '=', 'open')->where('questions.created_at', '>=', $one_week_ago)->where('questions.created_at', '<=', $yesterday)->orderBy('questions.created_at', 'DESC')->groupBy('question_id')->get();
                         if (!empty($group_question)) {
                             $totagroupquestion = count($group_question);
                         }
                     }
                 }
                 // fetch weekly suggestion option value set from admin
                 $weekly_suggestion = "KarmaNote";
                 $weekly_suggestion = Adminoption::Where("option_name", "=", "Weekly Suggestion")->select("option_value")->first();
                 if (!empty($weekly_suggestion)) {
                     $weekly_suggestion = $weekly_suggestion->option_value;
                 }
                 $getkcUser = $getsuggestion = array();
                 if ($weekly_suggestion == "KarmaMeeting") {
                     // fetch a random users on KC platform with a common group of logged in user
                     $getkcUser = KarmaHelper::fetchUserGroup($user_id);
                     if (!empty($getkcUser)) {
                         $getkcUser = $getkcUser[0];
                     }
                 } else {
                     // fetch a user connection either KC or NON KC
                     $getsuggestion = KarmaHelper::getUserConnection($user_id, $location);
                     //get test users id
                     $getUser = KarmaHelper::getTestUsers();
                     if (!empty($getsuggestion)) {
                         foreach ($getsuggestion as $key => $value) {
                             $test_match = in_array($value->con_user_id, $getUser);
                             if ($value->con_user_id != "" && $test_match != 1) {
                                 $getKc = DB::table('users as u')->select(array('u.userstatus', 'u.id', 'u.fname', 'u.lname', 'u.linkedinurl', 'u.piclink', 'u.headline', 'u.email', 'u.karmascore', 'u.location'))->where('u.id', '=', $value->con_user_id)->where('u.userstatus', '=', 'approved')->get();
                                 if (!empty($getKc)) {
                                     $value->networkid = $getKc;
                                 }
                             }
                         }
                         $getsuggestion = $getsuggestion[array_rand($getsuggestion)];
                     }
                 }
                 //fetch random 5 unique notes
                 $getKarmanote = "";
                 $getKarmanote = KarmaHelper::getKarmanote();
                 $type = 19;
                 $meetingIncomplete = $myKarmaDataOfInCompleteState;
                 $meetingComplete = $myKarmaDataOfCompleteState;
                 $offeredHelp = $queryOfferHelp;
                 $user_id = $user_id;
                 $user_connection_onkc = $user_connection_onkc;
                 $totalPendingRequest = $totalPendingRequest;
                 $totalReceivedRequest = $totalReceivedRequest;
                 $totalintroductionInitiated = $totalintroductionInitiated;
                 $totagroupquestion = $totagroupquestion;
                 $getsuggestion = $getsuggestion;
                 $getkcUser = $getkcUser;
                 $getKarmanote = $getKarmanote;
                 // call a function to send email
                 if ($meetingIncomplete > 0 || $meetingComplete > 0 || $offeredHelp > 0) {
                     $sendLinkedinMessage = MessageHelper::dailyUpdateMykarmaScreen($type, $user_id, $meetingIncomplete, $meetingComplete, $offeredHelp, $user_connection_onkc, $totalPendingRequest, $totalReceivedRequest, $totalintroductionInitiated, $totagroupquestion, $getsuggestion, $getkcUser, $getKarmanote);
                 }
                 /*Queue::push('MessageSender@MyKarmaDailyUpdateScreen',array('type' =>19,'meetingIncomplete'=>$myKarmaDataOfInCompleteState,'meetingComplete'=>$myKarmaDataOfCompleteState,'offeredHelp'=>$queryOfferHelp,'user_id' => $user_id,'user_connection_onkc'=>$user_connection_onkc,'totalPendingRequest' => $totalPendingRequest,'totalReceivedRequest'=>$totalReceivedRequest,'totalintroductionInitiated'=>$totalintroductionInitiated,'totagroupquestion'=>$totagroupquestion,'getsuggestion'=>$getsuggestion,'getkcUser'=>$getkcUser,'getKarmanote'=>$getKarmanote));*/
             }
         }
         //endforeach
     }
     // endif
     Log::alert('Executed Daily Cron Job');
 }
 /**
  * Execute the console command.
  *
  * @return mixed
  */
 public function fire()
 {
     Log::alert('Executed Cron Job to update user data daily.');
     $getusers = DB::table('users')->select(array('users.*'))->where('users.userstatus', '=', 'approved')->orderBy('created_at', 'DESC')->get();
     if (!empty($getusers)) {
         foreach ($getusers as $user_info) {
             $diffDate = KarmaHelper::dateDiff(date("Y-m-d H:i:s"), $user_info->profileupdatedate);
             if ($diffDate->days < 60) {
                 $user_data = User::find($user_info->id);
                 $token = $user_data->token;
                 //$result = json_decode(file_get_contents("https://api.linkedin.com/v1/people/~:(id,first-name,last-name,skills,headline,summary,industry,member-url-resources,picture-urls::(original),location,public-profile-url,email-address)?format=json&oauth2_access_token=$token"));
                 $curl_handle = curl_init();
                 curl_setopt($curl_handle, CURLOPT_URL, 'https://api.linkedin.com/v1/people/~:(id,first-name,last-name,skills,headline,summary,industry,member-url-resources,picture-urls::(original),location,public-profile-url,email-address)?format=json&oauth2_access_token=$token');
                 curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 2);
                 curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
                 curl_setopt($curl_handle, CURLOPT_USERAGENT, 'Your application name');
                 $result = curl_exec($curl_handle);
                 curl_close($curl_handle);
                 $publicProfileUrl = "";
                 if (isset($result->id)) {
                     $InsTag = KarmaHelper::insertUsertag($user_data, $result);
                     // Close insertUserConnection due to linkedIn changes
                     //$InsConnection = KarmaHelper::insertUserConnection($user_data);
                     $InsConnection = KarmaHelper::updateUserProfile($user_info->id, $result);
                     //update user profile details
                     if (!isset($result->publicProfileUrl) || $result->publicProfileUrl == '') {
                         $publicProfileUrl = $result->siteStandardProfileRequest['url'];
                     } else {
                         $publicProfileUrl = $result->publicProfileUrl;
                     }
                     $imageurl = "";
                     if (isset($result->pictureUrls->values[0])) {
                         $imageurl = $result->pictureUrls->values[0];
                     }
                     $user = User::find($user_info->id);
                     $user->email = $result->emailAddress;
                     if (isset($imageurl)) {
                         $user->piclink = $imageurl;
                     }
                     if (isset($result->summary)) {
                         $user->summary = $result->summary;
                     }
                     if (!empty($result->location)) {
                         $user->location = $result->location->name;
                     }
                     if (isset($result->industry)) {
                         $user->industry = $result->industry;
                     }
                     if (isset($result->headline)) {
                         $user->headline = $result->headline;
                     }
                     if ($publicProfileUrl != "") {
                         $user->linkedinurl = $publicProfileUrl;
                     }
                     $user->profileupdatedate = date('Y-m-d H:i:s');
                     $user->save();
                 }
                 sleep('2');
             }
         }
     }
 }
 /**
  * Execute the console command.
  *
  * @return mixed
  */
 public function fire()
 {
     Log::alert('testing ');
 }
Beispiel #24
0
/**
 * Log une alerte
 *
 * @param $message
 * @param array $context
 * @return bool
 */
function la($message, $context = [])
{
    return Log::alert($message, $context);
}
 public static function insertUserConnection($user)
 {
     $user_id = $user->id;
     $token = $user->token;
     $user_connection_data = "https://api.linkedin.com/v1/people/~/connections?id,first-name,last-name,headline,summary,industry,member-url-resources,picture-urls::(original),location,public-profile-url,site-standard-profile-request&format=json&oauth2_access_token={$token}";
     //echo $user_connection_data;exit;
     $ch = curl_init($user_connection_data);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
     curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
     curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
     $data = curl_exec($ch);
     curl_close($ch);
     $user_connection = json_decode($data);
     Log::alert('User connection fetch');
     /* for($i=0;$i<count($user_connection->person);$i++)
     		{
     			print_r($user_connection->person[$i]->{'first-name'}); 
     		} */
     //echo "<pre>========="; print_r($user_connection); echo "</pre>========"; die;
     if (!empty($user_connection->values)) {
         $group = new Usersgroup();
         $group->user_id = $user_id;
         $group->group_id = 1;
         $group->save();
         Usersconnection::where('user_id', '=', $user_id)->delete();
         foreach ($user_connection->values as $key => $value) {
             if (!empty($value->id) && $value->id != 'private') {
                 if (!isset($value->publicProfileUrl) || $value->publicProfileUrl == '') {
                     $publicProfileUrl = $value->siteStandardProfileRequest->url;
                 } else {
                     $publicProfileUrl = $value->publicProfileUrl;
                 }
                 $connection = new Connection();
                 $connection = Connection::firstOrCreate(array('networkid' => $value->id));
                 if ($connection['user_id'] != '') {
                     $Connuser = User::find($connection['user_id']);
                     /* $Connuser->fname 				= @$value->firstName;
                     			$Connuser->lname 				= @$value->lastName;*/
                     $Connuser->location = @$value->location->name;
                     $Connuser->industry = @$value->industry;
                     $Connuser->piclink = @$value->pictureUrl;
                     $Connuser->linkedinurl = @$publicProfileUrl;
                     $Connuser->headline = @$value->headline;
                     $Connuser->save();
                 }
                 $connection_id = $connection['id'];
                 $connection = connection::find($connection_id);
                 $connection->networktype = 'linkedin';
                 if ($connection->user_id == '') {
                     $connection->fname = @$value->firstName;
                     $connection->lname = @$value->lastName;
                 }
                 $connection->headline = @$value->headline;
                 $connection->industry = @$value->industry;
                 $connection->location = @$value->location->name;
                 $connection->piclink = @$value->pictureUrl;
                 $connection->linkedinurl = @$publicProfileUrl;
                 $connection->save();
                 $users_connections = new Usersconnection();
                 $users_connections->user_id = $user_id;
                 $users_connections->connection_id = $connection_id;
                 $users_connections->save();
                 $userDetail = User::find($user_id);
                 $userDetail->totalConnectionCount = $user_connection->_total;
                 $userDetail->save();
             }
         }
     }
     $userDetail = User::find($user_id);
     if (empty($userDetail->totalConnectionCount)) {
         $userDetail->totalConnectionCount = 0;
         $userDetail->save();
     }
     $connection = new Connection();
     $connection = Connection::firstOrCreate(array('networkid' => $user['linkedinid']));
     $connection_id = $connection['id'];
     $connection = Connection::find($connection_id);
     $connection->networktype = 'linkedin';
     if ($connection->user_id == '') {
         $connection->fname = @$user['fname'];
         $connection->lname = @$user['lname'];
     }
     $connection->headline = @$user['headline'];
     $connection->industry = @$user['industry'];
     $connection->location = @$user['location'];
     $connection->piclink = @$user['piclink'];
     $connection->linkedinurl = @$user['linkedinurl'];
     $connection->user_id = $user_id;
     $connection->save();
     return true;
 }
Beispiel #26
0
 /**
  * @return bool
  * @throws \DreamFactory\Core\Exceptions\BadRequestException
  * @throws \Exception
  */
 private function insertData()
 {
     $data = $this->zip->getFromName('data.json');
     $this->zip->deleteName('data.json');
     if (false !== $data) {
         $data = DataFormatter::jsonToArray($data);
         $services = ArrayUtils::get($data, 'service');
         if (!empty($services)) {
             foreach ($services as $service) {
                 $serviceName = ArrayUtils::get($service, 'name');
                 $tables = ArrayUtils::get($service, 'table');
                 foreach ($tables as $table) {
                     $tableName = ArrayUtils::get($table, 'name');
                     $records = ArrayUtils::get($table, 'record');
                     $resource = $this->resourceWrapped ? [$this->resourceWrapper => $records] : [$records];
                     try {
                         ServiceHandler::handleRequest(Verbs::POST, $serviceName, '_table/' . $tableName, [], $resource);
                     } catch (\Exception $e) {
                         if (in_array($e->getCode(), [404, 500])) {
                             throw $e;
                         } else {
                             \Log::alert('Failed to insert data. ' . $e->getMessage());
                         }
                     }
                 }
             }
         } else {
             throw new BadRequestException("Could not create the database tables for this application.\nDatabase service or data not found.");
         }
         return true;
     }
     return false;
 }
Beispiel #27
0
 /**
  * Log a message with the given level to Monolog logger if one is set and to Laravels build in Logger if it is enabled
  *
  * @static
  * @param  string $level The logger level as string which can be debug, info, notice, warning, error, critival, alert, emergency
  * @param  string $message The message which will be logged to Monolog
  * @throws \InvalidArgumentException if the parameter $level or $message is not of the data type string or if the $level parameter does not match with debug, info, notice, warning, error, critival, alert or emergency
  */
 private static function log($level, $message)
 {
     // Check parameter
     if (!is_string($level) || !is_string($message)) {
         throw new \InvalidArgumentException('Function paramter $level or $message is not of the data type string.');
     }
     // If a Monolog logger object is set, use it
     if (!empty(self::$logger)) {
         // Switch the lower case level string and log the message with the given level
         switch (strtolower($level)) {
             case "debug":
                 self::$logger->addDebug($message);
                 break;
             case "info":
                 self::$logger->addInfo($message);
                 break;
             case "notice":
                 self::$logger->addNotice($message);
                 break;
             case "warning":
                 self::$logger->addWarning($message);
                 break;
             case "error":
                 self::$logger->addError($message);
                 break;
             case "critical":
                 self::$logger->addCritical($message);
                 break;
             case "alert":
                 self::$logger->addAlert($message);
                 break;
             case "emergency":
                 self::$logger->addEmergency($message);
                 break;
             default:
                 throw new \InvalidArgumentException('Invalid log $level parameter with string ' . $level . '.');
         }
     }
     $laravelLogging = self::getConfig('laravelLogging');
     // If Laravel logging is enabled
     if (is_bool($laravelLogging) && $laravelLogging) {
         switch (strtolower($level)) {
             case "debug":
                 \Log::debug($message);
                 break;
             case "info":
                 \Log::info($message);
                 break;
             case "notice":
                 \Log::notice($message);
                 break;
             case "warning":
                 \Log::warning($message);
                 break;
             case "error":
                 \Log::error($message);
                 break;
             case "critical":
                 \Log::critical($message);
                 break;
             case "alert":
                 \Log::alert($message);
                 break;
             case "emergency":
                 \Log::emergency($message);
                 break;
             default:
                 throw new \InvalidArgumentException('Invalid log $level parameter with string ' . $level . '.');
         }
     }
 }