Ejemplo n.º 1
0
 /**
  * updates title and description of an activity
  * @param array    $activityDetails
  * @param Activity $activity
  * @return bool
  */
 public function update(array $activityDetails, Activity $activity)
 {
     try {
         $this->database->beginTransaction();
         $this->stepTwoRepo->update($activityDetails, $activity);
         $this->database->commit();
         $this->logger->info('Step Two Completed!', ['for' => [$activity->title, $activity->description]]);
         $this->logger->activity("activity.step_two_completed", ['activity_id' => $activity->id, 'organization' => $this->auth->user()->organization->name, 'organization_id' => $this->auth->user()->organization->id]);
         return true;
     } catch (Exception $exception) {
         $this->database->rollback();
         $this->logger->error($exception, ['stepTwo' => $activityDetails]);
     }
     return false;
 }
Ejemplo n.º 2
0
function myErrorHandler($errno, $errstr, $errfile, $errline)
{
    if (!class_exists('Log')) {
        require YYUC_LIB . 'sys/log.php';
    }
    $err_msg = "信息:{$errno}。内容:{$errstr},发生在文件{$errfile}的{$errline}行";
    switch ($errno) {
        case E_USER_ERROR:
            Log::error($err_msg);
            if (Conf::$is_developing) {
                echo $err_msg;
            }
            exit(1);
            break;
        case E_USER_WARNING:
            Log::warn($err_msg);
            break;
        case E_USER_NOTICE:
            Log::info($err_msg);
            break;
        default:
            Log::info($err_msg);
            break;
    }
    return true;
}
Ejemplo n.º 3
0
 /**
  * save new activity from wizard
  * @param array $identifier
  * @param       $defaultFieldValues
  * @return bool
  */
 public function store(array $identifier, $defaultFieldValues)
 {
     try {
         $this->database->beginTransaction();
         $result = $this->activityRepo->store($identifier, $defaultFieldValues, $this->auth->user()->organization->id);
         $this->activityRepo->saveDefaultValues($result->id, $defaultFieldValues);
         $this->database->commit();
         $this->logger->info('Activity identifier added!', ['for' => $identifier['activity_identifier']]);
         $this->logger->activity("activity.activity_added", ['identifier' => $identifier['activity_identifier'], 'organization' => $this->auth->user()->organization->name, 'organization_id' => $this->auth->user()->organization->id]);
         return $result;
     } catch (Exception $exception) {
         $this->database->rollback();
         $this->logger->error($exception, ['ActivityIdentifier' => $identifier]);
     }
     return false;
 }
 /**
  * Store a newly created resource in storage.
  *
  * @return Response
  * @throws ImageFailedException
  * @throws \BB\Exceptions\FormValidationException
  */
 public function store()
 {
     $data = \Request::only(['user_id', 'category', 'description', 'amount', 'expense_date', 'file']);
     $this->expenseValidator->validate($data);
     if (\Input::file('file')) {
         try {
             $filePath = \Input::file('file')->getRealPath();
             $ext = \Input::file('file')->guessClientExtension();
             $mimeType = \Input::file('file')->getMimeType();
             $newFilename = \App::environment() . '/expenses/' . str_random() . '.' . $ext;
             Storage::put($newFilename, file_get_contents($filePath), 'public');
             $data['file'] = $newFilename;
         } catch (\Exception $e) {
             \Log::error($e);
             throw new ImageFailedException($e->getMessage());
         }
     }
     //Reformat from d/m/y to YYYY-MM-DD
     $data['expense_date'] = Carbon::createFromFormat('j/n/y', $data['expense_date']);
     if ($data['user_id'] != \Auth::user()->id) {
         throw new \BB\Exceptions\FormValidationException('You can only submit expenses for yourself', new \Illuminate\Support\MessageBag(['general' => 'You can only submit expenses for yourself']));
     }
     $expense = $this->expenseRepository->create($data);
     event(new NewExpenseSubmitted($expense));
     return \Response::json($expense, 201);
 }
Ejemplo n.º 5
0
 /**
  * Render an exception into an HTTP response.
  *
  * @param  \Illuminate\Http\Request  $request
  * @param  \Exception  $e
  * @return \Illuminate\Http\Response
  */
 public function render($request, Exception $e)
 {
     if ($this->isHttpException($e)) {
         switch ($e->getStatusCode()) {
             case '404':
                 \Log::error($e);
                 return \Response::view('errors.404');
                 break;
             case '500':
                 \Log::error($e);
                 return \Response::view('errors.500');
                 break;
             case '503':
                 \Log::error($e);
                 return \Response::view('errors.503');
                 break;
             default:
                 return $this->renderHttpException($e);
                 break;
         }
     } else {
         //return parent::render($request, $e);
         return \Response::view('errors.failure');
     }
 }
Ejemplo n.º 6
0
 /**
  * Creates a Laravel route, returning a closure which passes the raw input to AngularPHP and returns the response
  */
 protected function init()
 {
     $route = func_get_arg(0);
     $this->setErrorHandler(function (\Exception $e, Request $r) {
         \Log::error($e, $r->toArray());
     });
     $endpoint = $this;
     \Route::any($route, function () use($endpoint) {
         $path = '/' . \Request::path();
         $referrer = \Request::header('referer');
         $host = \Request::header('host');
         if (($origin = \Request::header('Origin')) && count($this->corsHosts)) {
             $this->setCorsOrigin($origin);
         }
         /**
          * If being called remotely, add the domain name to the URI
          */
         if (strlen($referrer) && parse_url($referrer, PHP_URL_HOST) != $host) {
             $uri = '//' . $host . $path;
         } else {
             $uri = $path;
         }
         $request = new Request(\Request::json()->all());
         $response = $endpoint->setUri($uri)->execute($request, \Request::getMethod());
         return \Response::make($response->content, $response->code, $response->headers)->header('Content-Type', $response->contentType);
     });
 }
Ejemplo n.º 7
0
 public function generateFeed()
 {
     $articles = $this->getArticles();
     $feed = Feed::make();
     // set your feed's title, description, link, pubdate and language
     $feed->title = 'cnBeta1';
     $feed->description = '一个干净、现代、开放的cnBeta';
     $feed->logo = 'http://cnbeta1.com/assets/img/cnbeta1.png';
     $feed->link = URL::to('feed');
     $feed->pubdate = $articles[0]['date'];
     $feed->lang = 'zh-cn';
     foreach ($articles as $article) {
         $articleModel = new Article($article['article_id']);
         try {
             $articleModel->load();
         } catch (Exception $ex) {
             Log::error('feed: fail to fetch article: ' . $article['article_id'] . ', error: ' . $ex->getMessage());
         }
         $content = $article['intro'];
         $content .= $articleModel->data['content'] ? $articleModel->data['content'] : '';
         // set item's title, author, url, pubdate, description and content
         $feed->add($article['title'], 'cnBeta1', URL::to($article['article_id']), $article['date'], $content, $content);
     }
     $this->data = $feed->render('atom', -1);
     $this->saveToCache();
 }
Ejemplo n.º 8
0
 public function action_term()
 {
     $id = (int) $this->request->param('id', 0);
     $term = ORM::factory('term', $id);
     if (!$term->loaded()) {
         throw HTTP_Exception::factory(404, 'Term ":term" Not Found', array(':term' => $id));
     }
     $this->title = __(':title', array(':title' => $term->name));
     $view = View::factory('taxonomy/term')->set('teaser', TRUE)->bind('pagination', $pagination)->bind('posts', $posts);
     $posts = $term->posts;
     if (!ACL::check('administer terms') and !ACL::check('administer content')) {
         $posts->where('status', '=', 'publish');
     }
     $total = $posts->reset(FALSE)->count_all();
     if ($total == 0) {
         Log::error('No posts found.');
         $this->response->body(View::factory('page/none'));
         return;
     }
     $pagination = Pagination::factory(array('current_page' => array('source' => 'cms', 'key' => 'page'), 'total_items' => $total, 'items_per_page' => 5, 'uri' => $term->url));
     $posts = $posts->order_by('created', 'DESC')->limit($pagination->items_per_page)->offset($pagination->offset)->find_all();
     $this->response->body($view);
     //Set the canonical and shortlink for search engines
     if ($this->auto_render === TRUE) {
         Meta::links(URL::canonical($term->url, $pagination), array('rel' => 'canonical'));
         Meta::links(Route::url('taxonomy', array('action' => 'term', 'id' => $term->id)), array('rel' => 'shortlink'));
     }
 }
Ejemplo n.º 9
0
 /**
  * storeMessageResource.
  *
  * @param int   $accountId 公众号id
  * @param array $message   消息
  *
  * @return int 消息资源id
  */
 private function storeMessageResource($accountId, $message)
 {
     $resourceModel = new $this->resourceModel();
     //$resourceModel->account_id =
     //
     \Log::error($message);
 }
 /**
  * Get the translation for the given key. Log a warning if we have to fall 
  * back to the fallback locale and log an error if the fallback doesn't 
  * exist either.
  *
  * @param  string  $key
  * @param  array   $replace
  * @param  string  $locale
  * @return string
  */
 public function get($key, array $replace = array(), $locale = null)
 {
     list($namespace, $group, $item) = $this->parseKey($key);
     // Don't log issues if looking for custom validation messages
     $ignore = strpos($key, 'validation.custom.') === 0;
     $locales = $this->parseLocale($locale);
     $tried = array();
     foreach ($locales as $locale) {
         $this->load($namespace, $group, $locale);
         $line = $this->getLine($namespace, $group, $locale, $item, $replace);
         if ($line !== null) {
             break;
         }
         $tried[] = $locale;
     }
     if ($line === null) {
         // Not found
         if (!$ignore) {
             \Log::error("No translation found in any locale for key '{$key}'; " . "rendering the key instead " . "(tried " . implode(", ", $tried) . ")");
         }
         return $key;
     }
     if (count($tried)) {
         if (!$ignore) {
             \Log::warning("Fell back to {$locale} locale for translation key '{$key}' " . "(tried " . implode(", ", $tried) . ")");
         }
     }
     return $line;
 }
Ejemplo n.º 11
0
 public function send_notification($devices, $message)
 {
     try {
         $errCounter = 0;
         $payload = json_encode(array('aps' => $message));
         $result = 0;
         $bodyError = '';
         foreach ($devices as $key => $value) {
             $msg = chr(0) . pack('n', 32) . pack('H*', str_replace(' ', '', $value)) . pack('n', strlen($payload)) . $payload;
             $result = fwrite($this->fp, $msg);
             $bodyError .= 'result: ' . $result . ', devicetoken: ' . $value;
             if (!$result) {
                 $errCounter = $errCounter + 1;
             }
         }
         //echo 'Result :- '.$result;
         if ($result) {
             Log::info('Delivered Message to APNS' . PHP_EOL);
             //echo 'Delivered Message to APNS' . PHP_EOL;
             $bool_result = true;
         } else {
             Log::info('Could not Deliver Message to APNS' . PHP_EOL);
             //echo 'Could not Deliver Message to APNS' . PHP_EOL;
             $bool_result = false;
         }
         fclose($this->fp);
         return $bool_result;
     } catch (Exception $e) {
         Log::error($e);
     }
 }
 public function store()
 {
     $rules = array('name' => 'required|max:200', 'email' => 'required|email|unique:users|max:200|', 'password' => 'required|min:8|max:200');
     $messages = array('email.unique' => "You have already registered with this email address. Sign in <a href=\"/login\">here</a>");
     $input = Input::all();
     $validator = Validator::make($input, $rules, $messages);
     if ($validator->fails()) {
         return Redirect::to('signup')->withInput()->withErrors($validator);
     } else {
         $password = Hash::make($input['password']);
         //Validation passed -- Make a new user in the DB
         $user = new User();
         $user->name = $input['name'];
         $user->password = $password;
         $user->email = $input['email'];
         $user->isActive = 1;
         $user->save();
         //Here we will send an email with the link to confirm .... https://github.com/Zizaco/confide
         //We'll send the user an email thanking them for registering
         $attempt = Auth::attempt(array('email' => $input['email'], 'password' => $input['password']));
         if ($attempt) {
             return Redirect::to('dashboard')->with('flash_message_good', 'Welcome to Open Source Collaborative Consumption Marketplace. You have been successfully signed up and logged in!');
         } else {
             Log::error('Trying to log user in straight after register failed. User redirected to login page');
             return Redirect::to('login')->with('flash_message_good', "Your signup has been successfull, go ahead and log in here!");
         }
     }
 }
 /**
  * Store a newly created session in storage.
  * POST /session
  *
  * @return Response
  */
 public function store()
 {
     // Attempt to login
     try {
         // Login credentials
         $credentials = array('email' => Input::get('email'), 'password' => Input::get('password'));
         // Authenticate the user
         if (Auth::attempt($credentials)) {
             // Store Session values for user
             Session::put('email', $credentials['email']);
             Session::put('user_id', User::getIdFromEmail($credentials['email']));
             // Redirect to dashboard with message
             Session::flash('alert_success', 'Logged in successfully.');
             return Redirect::intended('dashboard');
         } else {
             Session::flash('alert_warning', 'Unable to login. Please check your username and password, and try again.');
             return Redirect::to(secure_url('/login'))->withInput();
         }
     } catch (\RuntimeException $e) {
         // An unexpected error occurred.
         Log::error(date("Y-m-d H:i:s") . '- RuntimeException in app/contorllers/SessionController: ' . '\\$data = ' . print_r($data) . $e);
         Session::flash('alert_danger', 'An unexpected error occurred.');
         return Redirect::to(secure_url('/login'))->withInput();
     }
 }
Ejemplo n.º 14
0
 public function handle()
 {
     $eventId = $this->request->input('event_id');
     $organizationId = $this->request->input('attendee.organization_id');
     if (empty($eventId)) {
         throw new Exception("EventID empty.");
     }
     if (empty($organizationId)) {
         throw new Exception("OrganizationID empty.");
     }
     $attendeeData = array('event_id' => $eventId, 'organization_id' => $organizationId, 'firstname' => $this->request->input('attendee.firstname'), 'lastname' => $this->request->input('attendee.lastname'), 'email' => $this->request->input('attendee.email'), 'registration_date' => BaseDateTime::now());
     $attendeeApplicationFormData = array('student_phone' => $this->request->input('attendee_application_form.phone'), 'student_grade' => $this->request->input('attendee_application_form.grade'), 'language' => $this->request->input('attendee_application_form.language'), 'sweatshirt_size' => $this->request->input('attendee_application_form.sweatshirt_size'), 'address' => $this->request->input('attendee_application_form.address'), 'city' => $this->request->input('attendee_application_form.city'), 'state' => $this->request->input('attendee_application_form.state'), 'zipcode' => $this->request->input('attendee_application_form.zipcode'), 'country' => 'USA', 'birthdate' => Carbon::parse($this->request->input('attendee_application_form.birthdate')));
     $attendeeHealthReleaseFormData = array('gender' => $this->request->input('attendee_health_release_form.gender'), 'emg_contactname' => $this->request->input('attendee_health_release_form.emgcontactname'), 'emg_contactrel' => $this->request->input('attendee_health_release_form.emgcontactrel'), 'emg_contactnumber' => $this->request->input('attendee_health_release_form.emgcontactnumber'), 'healthproblems' => $this->request->input('attendee_health_release_form.healthproblems'), 'allergies' => $this->request->input('attendee_health_release_form.allergies'), 'lasttetanusshot' => Carbon::parse($this->request->input('attendee_health_release_form.lasttetanusshot')), 'lastphysicalexam' => Carbon::parse($this->request->input('attendee_health_release_form.lastphysicalexam')), 'insurancecarrier' => $this->request->input('attendee_health_release_form.insurancecarrier'), 'insurancepolicynum' => $this->request->input('attendee_health_release_form.insurancepolicynum'), 'guardian_name' => $this->request->input('attendee_health_release_form.guardianfullname'), 'guardian_contact' => $this->request->input('attendee_health_release_form.guardian_phone'), 'guardian_relation' => $this->request->input('attendee_health_release_form.relationship'), 'guardian_sign' => $this->request->input('parent_signature'));
     $appForm = new AttendeeApplicationForm($attendeeApplicationFormData);
     $healthReleaseForm = new AttendeeHealthReleaseForm($attendeeHealthReleaseFormData);
     $eventRepo = new EventRepository();
     $event = $eventRepo->findById($eventId);
     $organizationRepo = new OrganizationRepository();
     $organization = $organizationRepo->findById($organizationId);
     $newAttendee = new Attendee($attendeeData);
     // Save new attendee
     $newAttendee = $newAttendee->create($attendeeData);
     $newAttendee->application_form()->save($appForm);
     $newAttendee->health_release_form()->save($healthReleaseForm);
     $newAttendee->save();
     if (!empty($newAttendee->id)) {
         try {
             $this->dispatch(new SendRegistrationConfirmation($newAttendee, $event));
         } catch (Exception $e) {
             Log::error('Could not process SendRegistrationConfirmation job.');
         }
     }
 }
 /**
  * {@inheritdoc}
  */
 public function codes()
 {
     $codes = $this->getCache('phone_codes');
     if (!$codes) {
         try {
             $codes = array();
             $countries = $this->countries->all();
             if ($countries && !empty($countries)) {
                 $response = $this->http->client()->get($this->url);
                 $result = $this->http->result($response);
                 if ($result) {
                     $result = $response->json();
                     foreach ($result as $country) {
                         if (array_key_exists($country['alpha2Code'], $countries)) {
                             if (isset($country['callingCodes'][0]) && !empty($country['callingCodes'][0])) {
                                 $codes[$country['alpha2Code']] = '+' . $country['callingCodes'][0];
                             }
                         }
                     }
                 }
             }
             if (empty($codes)) {
                 $codes = false;
             }
         } catch (Exception $exception) {
             \Log::error($exception->getMessage());
         }
     }
     return $codes;
 }
Ejemplo n.º 16
0
 /**
  * mecab classifier
  * @param $document
  * @return array|void
  */
 public static function toWords($document)
 {
     if (!extension_loaded('mecab')) {
         Log::error('mecab extension not loaded');
         return;
     }
     $mecab = new \MeCab\Tagger();
     $nodes = $mecab->parseToNode($document);
     $words = [];
     foreach ($nodes as $n) {
         $word = $n->getSurface();
         if (static::isInvalidWord($word)) {
             continue;
         }
         if (strpos($n->getFeature(), '名詞') !== false) {
             $words[] = $word;
         }
         if (strpos($n->getFeature(), '動詞') !== false) {
             $words[] = $word;
         }
         if (strpos($n->getFeature(), '助動詞') !== false) {
             $words[] = $word;
         }
         if (strpos($n->getFeature(), '形容詞') !== false) {
             $words[] = $word;
         }
     }
     return $words;
 }
Ejemplo n.º 17
0
 /**
  * Internal building method builds all static services and some dynamic
  * services from file annotations, otherwise swagger info is loaded from
  * database or storage files for each service, if it exists.
  *
  * @throws \Exception
  */
 protected static function buildEventMaps()
 {
     \Log::info('Building event cache');
     //  Build event mapping from services in database
     //	Initialize the event map
     $processEventMap = [];
     $broadcastEventMap = [];
     //  Pull any custom swagger docs
     $result = ServiceModel::with(['serviceDocs' => function ($query) {
         $query->where('format', ApiDocFormatTypes::SWAGGER);
     }])->get();
     //	Spin through services and pull the events
     foreach ($result as $service) {
         $apiName = $service->name;
         try {
             if (empty($content = ServiceModel::getStoredContentForService($service))) {
                 throw new \Exception('  * No event content found for service.');
                 continue;
             }
             $serviceEvents = static::parseSwaggerEvents($apiName, $content);
             //	Parse the events while we get the chance...
             $processEventMap[$apiName] = ArrayUtils::get($serviceEvents, 'process', []);
             $broadcastEventMap[$apiName] = ArrayUtils::get($serviceEvents, 'broadcast', []);
             unset($content, $service, $serviceEvents);
         } catch (\Exception $ex) {
             \Log::error("  * System error building event map for service '{$apiName}'.\n{$ex->getMessage()}");
         }
     }
     static::$eventMap = ['process' => $processEventMap, 'broadcast' => $broadcastEventMap];
     //	Write event cache file
     \Cache::forever(static::EVENT_CACHE_KEY, static::$eventMap);
     \Log::info('Event cache build process complete');
 }
 /**
  * Bootstrap the application services.
  *
  * @return void
  */
 public function boot()
 {
     // Publish config
     $configPath = __DIR__ . '/../../config/config.php';
     $this->publishes([$configPath => config_path('liebigCron.php')], 'config');
     // Build in Cron run route
     \Route::get('cron.php', function () {
         // Get security key from config
         $cronkeyConfig = \Config::get('liebigCron.cronKey');
         // If no security key is set in the config, this route is disabled
         if (empty($cronkeyConfig)) {
             \Log::error('Cron route call with no configured security key');
             \App::abort(404);
         }
         // Get security key from request
         $cronkeyRequest = \Input::get('key');
         // Create validator for security key
         $validator = \Validator::make(array('cronkey' => $cronkeyRequest), array('cronkey' => 'required|alpha_num'));
         if ($validator->passes()) {
             if ($cronkeyConfig === $cronkeyRequest) {
                 \Artisan::call('cron:run', array());
             } else {
                 // Configured security key is not equals the sent security key
                 \Log::error('Cron route call with wrong security key');
                 \App::abort(404);
             }
         } else {
             // Validation not passed
             \Log::error('Cron route call with missing or no alphanumeric security key');
             \App::abort(404);
         }
     });
 }
Ejemplo n.º 19
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();
    }
}
Ejemplo n.º 20
0
 /**
  * Planet クロールする
  **/
 public static function __setup_crawl__()
 {
     $http_feed = new Feed();
     foreach (C(PlanetSubscription)->find_all() as $subscription) {
         Exceptions::clear();
         Log::debug(sprintf('[crawl] feed: %d (%s)', $subscription->id(), $subscription->title()));
         try {
             $feed = $http_feed->do_read($subscription->rss_url());
             $subscription->title($feed->title());
             if ($feed->is_link()) {
                 $subscription->link(self::_get_link_href($feed->link()));
             }
             $subscription->rss_url($http_feed->url());
             $subscription->save(true);
             foreach ($feed->entry() as $entry) {
                 Exceptions::clear();
                 try {
                     $planet_entry = new PlanetEntry();
                     $planet_entry->subscription_id($subscription->id());
                     $planet_entry->title(Tag::cdata($entry->title()));
                     $planet_entry->description(Text::htmldecode(Tag::cdata($entry->fm_content())));
                     $planet_entry->link($entry->first_href());
                     $planet_entry->updated($entry->published());
                     $planet_entry->save();
                 } catch (Exception $e) {
                     Log::warn($e->getMessage());
                 }
             }
         } catch (Exception $e) {
             Log::error($e);
         }
     }
 }
Ejemplo n.º 21
0
 /**
  * Set a configuration item's value.
  *
  * <code>
  *      // Set the "session" configuration array
  *      Config::set('session', $array);
  *
  *      // Set a configuration option that belongs by a bundle
  *      Config::set('admin::names.first', 'Taylor');
  *
  *      // Set the "timezone" option in the "application" configuration file
  *      Config::set('application.timezone', 'UTC');
  * </code>
  *
  * @param  string  $key
  * @param  mixed   $value
  * @return void
  */
 public static function set($key, $value, $persistence = true)
 {
     list($bundle, $file, $item) = static::parse($key);
     static::load($bundle, $file);
     // If the item is null, it means the developer wishes to set the entire
     // configuration array to a given value, so we will pass the entire
     // array for the bundle into the array_set method.
     if (is_null($item)) {
         // @TODO handle saving of
         // nested array configuration
         array_set(static::$items[$bundle], $file, $value);
     } else {
         if ($persistence) {
             $setting = Model\Setting::where_slug($item)->first();
             if (!empty($setting)) {
                 array_set(static::$items[$bundle][$file], $item, $value);
                 $setting->value = $value;
                 $setting->save();
             } else {
                 \Log::error('"' . __CLASS__ . '": Trying to persist a non existent setting "' . $item . '".');
                 return null;
             }
         } else {
             array_set(static::$items[$bundle][$file], $item, $value);
         }
     }
 }
Ejemplo n.º 22
0
 function exec()
 {
     if (!DB::isConnectionOpen()) {
         Log::error(__METHOD__, "La connessione al database non e' aperta prima della query con MysqlUpdate");
     }
     return mysql_query($this->sql());
 }
Ejemplo n.º 23
0
Archivo: DB.php Proyecto: ncube/edu
 public function query($sql, $data = array(), $fetch = FALSE)
 {
     if ($query = self::connect()->_conn->prepare($sql)) {
         $x = 1;
         if ($data === TRUE) {
             $fetch = TRUE;
         } else {
             if (count($data)) {
                 foreach ($data as $param) {
                     $query->bindValue($x, $param);
                     $x++;
                 }
             }
         }
         try {
             $execute = $query->execute();
         } catch (PDOException $error) {
             Log::error('db', $error);
             die('Sorry something went wrong please try again later.');
         }
         if ($execute) {
             if ($fetch) {
                 $results = $query->fetchAll(PDO::FETCH_OBJ);
                 $this->_results = $results;
             }
             $this->_count = $query->rowCount();
         } else {
             return FALSE;
         }
     }
     return $this;
 }
Ejemplo n.º 24
0
 public function action_send()
 {
     // CSRF対策
     if (!Security::check_token()) {
         throw new HttpInvalidInputException('ページ遷移が正しくありません');
     }
     $val = $this->forge_validation()->add_callable('MyValidationRules');
     if (!$val->run()) {
         $this->template->title = 'コンタクトフォーム: エラー';
         $this->template->content = View::forge('form/index');
         $this->template->content->set_safe('html_error', $val->show_errors());
         return;
     }
     $post = $val->validated();
     $data = $this->build_mail($post);
     // メールの送信
     try {
         $this->sendmail($data);
         $this->template->title = 'コンタクトフォーム: 送信完了';
         $this->template->content = View::forge('form/send');
         return;
     } catch (EmailValidationFailedException $e) {
         Log::error('メール検証エラー: ' . $e->getMessage(), __METHOD__);
         $html_error = '<p>メールアドレスに誤りがあります。</p>';
     } catch (EmailSendingFailedException $e) {
         Log::error('メール送信エラー: ' . $e->getMessage(), __METHOD__);
         $html_error = '<p>メールを送信できませんでした。</p>';
     }
     $this->template->title = 'コンタクトフォーム: 送信エラー';
     $this->template->content = View::forge('form/index');
     $this->template->content->set_safe('html_error', $html_error);
 }
Ejemplo n.º 25
0
 /**
  * Creates a new instance.
  *
  * @param $data New instance data.
  *
  * @return bool
  */
 public function create(array $data)
 {
     $customer_gateway_id = Service_Customer_Gateway::external_id($this->driver->customer, $this->driver->gateway);
     if (!$customer_gateway_id) {
         return false;
     }
     if (!($payment_method = Arr::get($data, 'payment_method'))) {
         return false;
     }
     if (!($amount = Arr::get($data, 'amount'))) {
         return false;
     }
     $request = new AuthorizeNetCIM();
     $transaction = new AuthorizeNetTransaction();
     $transaction->amount = $amount;
     $transaction->customerProfileId = $customer_gateway_id;
     $transaction->customerPaymentProfileId = $payment_method->external_id;
     // AuthOnly or AuthCapture
     $response = $request->createCustomerProfileTransaction('AuthCapture', $transaction);
     if (!$response->isOk()) {
         Log::error('Unable to create Authorize.net transaction.');
         return false;
     }
     $response = $response->getTransactionResponse();
     if (empty($response->transaction_id)) {
         return false;
     }
     return $response->transaction_id;
 }
Ejemplo n.º 26
0
 public function facebookCallback()
 {
     try {
         $facebook = Socialite::driver('facebook')->scopes(['email'])->user();
         // 確認使用者有提供 Email
         if (null === $facebook->getEmail()) {
             throw new OAuthException();
         }
         // 如果 Email 不存在,創見帳號,如 Email 已存在,則略過此步驟
         if (null === ($account = Account::where('email', '=', $facebook->getEmail())->first(['id']))) {
             $account = Account::create(['email' => $facebook->getEmail(), 'password' => str_random(32)]);
             if (!$account->exists) {
                 throw new ModelNotFoundException();
             }
             $account->load(['user'])->getRelation('user')->update(['nickname' => $facebook->getName() . '@facebook']);
         }
         \Auth::loginUsingId($account->getAttribute('id'), true);
         return redirect()->route('home');
     } catch (ClientException $e) {
         $data = ['您似乎並未允許本網站存取您的資料', false];
     } catch (InvalidStateException $e) {
         $data = ['似乎出了點狀況,請嘗試重新登入', false];
     } catch (ModelNotFoundException $e) {
         $data = ['網站似乎出了點狀況,請稍候再嘗試', false];
     } catch (OAuthException $e) {
         $data = ['您似乎並未允許本網站存取您的信箱', true];
     } catch (\Exception $e) {
         $data = ['網站似乎出了點狀況,請稍候再嘗試', false];
         \Log::error('Non-catch exception.', ['code' => $e->getCode(), 'message' => $e->getMessage()]);
     }
     return view('errors.oauthFailed', ['message' => $data[0], 'invalidEmail' => $data[1]]);
 }
Ejemplo n.º 27
0
 /**
  * Execute the console command.
  *
  *	@todo  DON'T UPDATE LOCATIONS IF THEY'RE ALREADY SET
  *
  * @return mixed
  */
 public function fire()
 {
     $Bodmin = Area::firstOrCreate(['name' => 'Bodmin']);
     // Ensure current locations are saved.
     foreach (array_unique(Interview::where('location_id', '=', '')->lists('location')) as $location) {
         if (strlen($location) === 0) {
             continue;
             // don't want to clobber real locations
         }
         $L = Location::firstOrNew(['name' => $location]);
         if ($L->exists) {
             continue;
         }
         $L->area()->associate($Bodmin);
         $L->save();
     }
     Interview::all()->each(function ($Interview) {
         $Location = Location::where('name', '=', $Interview->location);
         if ($Location->count() <= 0) {
             \Log::error("This location not found despite having just been confirmed a few lines above", $Interview->toArray());
             return;
         }
         $Interview->location_id = $Location->first()->id;
         $Interview->save();
     });
 }
Ejemplo n.º 28
0
 /**
  * Store a newly created resource in storage.
  *
  * @return Response
  */
 public function store()
 {
     //
     $rules = array('patient_number' => 'required|unique:patients,patient_number', 'name' => 'required', 'gender' => 'required', 'dob' => 'required');
     $validator = Validator::make(Input::all(), $rules);
     if ($validator->fails()) {
         return Redirect::back()->withErrors($validator)->withInput(Input::all());
     } else {
         // store
         $patient = new Patient();
         $patient->patient_number = Input::get('patient_number');
         $patient->name = Input::get('name');
         $patient->gender = Input::get('gender');
         $patient->dob = Input::get('dob');
         $patient->email = Input::get('email');
         $patient->address = Input::get('address');
         $patient->phone_number = Input::get('phone_number');
         $patient->created_by = Auth::user()->id;
         try {
             $patient->save();
             $url = Session::get('SOURCE_URL');
             return Redirect::to($url)->with('message', 'Successfully created patient!');
         } catch (QueryException $e) {
             Log::error($e);
         }
         // redirect
     }
 }
Ejemplo n.º 29
0
 public function getDislike(Request $r)
 {
     try {
         $uid = $r->get('id', false);
         $filterId = $r->get('filter_id', false);
         if ($uid) {
             $mid = $this->getUser()->id;
             if ($filterId) {
                 $filter = VKFilter::find($filterId);
             }
             $exits = DB::table('vk_like')->where('from_id', $mid)->where('to_id', $uid)->count();
             if ($exits) {
                 return response()->json(['id' => trans('main.already-like'), 'filter' => !empty($filter) ? $filter->getList($this->getUser()) : []], 422);
             } else {
                 DB::table('vk_like')->insert(['from_id' => $mid, 'to_id' => $uid, 'type' => 0]);
                 return response()->json(['ok' => 'ok', 'filter' => !empty($filter) ? $filter->getList($this->getUser()) : []]);
             }
         } else {
             return response()->json(['id' => trans('main.id-not-pass')]);
         }
     } catch (\Exception $e) {
         \Log::error($e->getMessage() . ' ' . $e->getFile() . ':' . $e->getLine());
         return $e->getMessage() . ' file ' . $e->getFile() . ':' . $e->getLine();
     }
 }
Ejemplo n.º 30
0
 protected function open()
 {
     $this->graph = new Graph();
     $rdfa_parser = new RdfaParser();
     $json_parser = new JsonLd();
     \EasyRdf\RdfNamespace::set('dcat', 'http://www.w3.org/ns/dcat#');
     \EasyRdf\RdfNamespace::set('lbld', 'http://decisions.data.vlaanderen.be/ns#');
     $data = file_get_contents($this->extractor->uri);
     // Assume we have an rdfa document to begin with
     $rdfa_parser->parse($this->graph, $data, 'rdfa', $this->extractor->base_uri);
     // Check if we have properties we need to include into the current graph
     $properties = explode(',', $this->extractor->follow_properties);
     foreach ($this->graph->resources() as $resource) {
         foreach ($properties as $property) {
             $resolve_resources = $resource->allResources($property);
             if (!empty($resolve_resources)) {
                 foreach ($resolve_resources as $resolve_resource) {
                     $data = file_get_contents($resolve_resource->getUri());
                     // Parse any rdfa data in the document into the existing graph
                     $this->graph->parse($data, 'rdfa', $resolve_resource->getUri());
                     $json = $this->parseJsonldSnippet($data);
                     if (!empty($json)) {
                         try {
                             $this->graph->parse($json, 'jsonld', $resolve_resource->getUri());
                         } catch (\Exception $ex) {
                             \Log::error("We could not parse json from the data, the data was:" . $json);
                         }
                     }
                 }
             }
         }
     }
     // We only return the graph once as a full datastructure
     $this->has_next = true;
 }