protected static function email($template, $title, $data, $receivers, $sender, $bcc = null, $file = null)
 {
     $data['app_name'] = Config::get('app.name');
     $data['base'] = Config::get('app.url');
     $data['title'] = $title;
     $data['receivers'] = $receivers;
     $data['user_name'] = $sender['name'];
     $data['user_email'] = $sender['email'];
     $data['bcc'] = (array) $bcc;
     $data['file'] = $file;
     $success = false;
     try {
         Log::info('<!> Sending new email...');
         Mail::queue('emails.' . $template, $data, function ($message) use($data) {
             $message->from($data['user_email'], $data['user_name'])->subject($data['app_name'] . ' - ' . $data['title']);
             if (!empty($data['receivers'])) {
                 $message->to($data['receivers']);
             }
             if (!empty($data['bcc'])) {
                 $message->bcc($data['bcc']);
             }
             if (!empty($data['file'])) {
                 $message->attach($data['file']);
             }
         });
         Log::info('...DONE!');
         // Log::info( json_encode($data) );
         $success = true;
     } catch (Exception $e) {
         Log::warning('<!!!> ...FAILED! Exception while sending email: ' . $e->getMessage());
     }
     return $success;
 }
 public static function load($controlName = '', $funcName = 'index')
 {
     // $funcOfController = '';
     if (preg_match('/(\\w+)\\@(\\w+)/i', $controlName, $matchesName)) {
         $controlName = $matchesName[1];
         // $funcOfController = $matchesName[2];
         $funcName = $matchesName[2];
     }
     // $path = CONTROLLERS_PATH . $controlName . '.php';
     $path = self::getPath() . $controlName . '.php';
     if (!file_exists($path)) {
         Response::headerCode(404);
         Log::warning('Controller <b>' . $controlName . '</b> not exists.');
     }
     include $path;
     if (preg_match('/.*?\\/(\\w+)$/i', $controlName, $matches)) {
         $controlName = $matches[1];
     }
     $load = new $controlName();
     if (!isset($funcName[0])) {
         $funcName = 'index';
     }
     $funcName = $funcName == 'index' ? $funcName : 'get' . ucfirst($funcName);
     if (!method_exists($load, $funcName)) {
         Response::headerCode(404);
         Log::warning('Function <b>' . $funcName . '</b> not exists inside controller <b>' . $controlName . '</b> .');
     }
     $load->{$funcName}();
 }
Example #3
0
 /**
  * Returns a DaoIterator for a specific reference.
  * A DataSource can directly return the DataHash, so it doesn't have to be fetched.
  *
  * @param Record $record
  * @param string $attribute The attribute it's being accessed on
  * @return DaoIterator
  */
 public function getReferenced($record, $attribute)
 {
     if ($data = $record->getDirectly($attribute)) {
         if (is_array($data)) {
             if (count($data) === 0 || is_array(reset($data))) {
                 // The data hash is an array, either empty, or containing the hashes.
                 return new DaoHashListIterator($data, $this->getForeignDao());
             } elseif (is_int(reset($data)) && ($foreignKey = $this->getForeignKey())) {
                 // The data hash is an array containing the ids, and there is a
                 // foreign key to link them to.
                 return new DaoKeyListIterator($data, $this->getForeignDao(), $foreignKey);
             }
         }
         Log::warning(sprintf('The data hash for `%s` was set but incorrect.', $attribute));
         return new DaoHashListIterator(array(), $this->getForeignDao());
     } else {
         // Get the list of ids
         $localKey = $this->getLocalKey();
         $foreignKey = $this->getForeignKey();
         if ($localKey && $foreignKey) {
             $localValue = $record->get($localKey);
             return new DaoKeyListIterator($localValue ? $localValue : array(), $this->getForeignDao(), $foreignKey);
         }
         return new DaoKeyListIterator(array(), $this->getForeignDao(), $foreignKey);
     }
 }
Example #4
0
 public function authenticate($ticket, $service)
 {
     $r = Request::get($this->getValidateUrl($ticket, $service))->sendsXml()->timeoutIn($this->timeout)->send();
     $r->body = str_replace("\n", "", $r->body);
     try {
         $xml = new SimpleXMLElement($r->body);
     } catch (\Exception $e) {
         throw new \UnexpectedValueException("Return cannot be parsed : '{$r->body}'");
     }
     $namespaces = $xml->getNamespaces();
     $serviceResponse = $xml->children($namespaces['cas']);
     $user = $serviceResponse->authenticationSuccess->user;
     if ($user) {
         return (string) $user;
         // cast simplexmlelement to string
     } else {
         $authFailed = $serviceResponse->authenticationFailure;
         if ($authFailed) {
             $attributes = $authFailed->attributes();
             Log::warning("AuthenticationFailure : " . $attributes['code'] . " ({$ticket}, {$service})");
             throw new AuthenticationFailure((string) $attributes['code']);
         } else {
             Log::error("Cas return is weird : '{$r->body}'");
             throw new \UnexpectedValueException($r->body);
         }
     }
     // never reach there
 }
Example #5
0
 /**
  * @param \User $user
  *
  * @return mixed
  */
 public function getNestData(\User $user)
 {
     // start, return is false:
     $data = false;
     $count = 0;
     while ($data === false && $count < 5) {
         \Log::debug('Attempt #' . ($count + 1));
         // try to get the data:
         $URL = 'https://developer-api.nest.com/?auth=' . $user->accessToken;
         $client = new Client();
         try {
             $response = $client->get($URL);
         } catch (RingException $e) {
             \Log::error('GuzzleHttp\\Ring\\Exception\\ConnectException for user ' . $user->id . '! ' . $e->getMessage());
             sleep(5);
             return false;
         } catch (ConnectException $e) {
             \Log::error('GuzzleHttp\\Exception\\ConnectException for user ' . $user->id . '!! ' . $e->getMessage());
             sleep(5);
             return false;
         } catch (\Exception $e) {
             \Log::error('General exception (' . get_class($e) . ') for user ' . $user->id . '! ' . $e->getMessage());
             if ($e->getCode() == 401) {
                 \Log::warning('This is unauthorized! Delete the user!');
                 $user->delete();
             }
             sleep(5);
             return false;
         }
         $body = $response->getBody()->getContents();
         $data = json_decode($body);
         $count++;
     }
     return $data;
 }
Example #6
0
 public static function render($template, $vars = array())
 {
     Log::debug(__CLASS__ . ': Attempting to render template "' . $template . '"');
     $template_file = 'tpl.' . $template . '.php';
     if (!self::$template_dir && !(self::$template_dir = Config::get('template_dir'))) {
         $included_dirs = ini_get('include_path');
         foreach (explode(':', $included_dirs) as $dir) {
             if (is_readable($dir . '/templates')) {
                 self::$template_dir = $dir . '/templates';
                 break;
             }
         }
     }
     if (is_readable(self::$template_dir . '/' . $template_file)) {
         ob_start();
         extract($vars);
         include self::$template_dir . '/' . $template_file;
         $output = ob_get_contents();
         ob_end_clean();
         return $output;
     } else {
         Log::warning(__CLASS__ . ': Could not render template ' . self::$template_dir . '/' . $template_file);
     }
     return '';
 }
Example #7
0
 /**
  * Search objects of specified type for certain criteria.
  *
  * @param string $type     object type (e.g. changeset)
  * @param array  $criteria array of criterion objects.
  *
  * @return Services_OpenStreetMap_Objects
  */
 public function searchObjects($type, array $criteria)
 {
     $query = array();
     foreach ($criteria as $criterion) {
         $query[] = $criterion->query();
     }
     $config = $this->getConfig();
     $url = $config->getValue('server') . 'api/' . $config->getValue('api_version') . '/' . $type . 's?' . implode('&', $query);
     try {
         $response = $this->getResponse($url);
     } catch (Services_OpenStreetMap_Exception $ex) {
         $this->log->warning((string) $ex);
         switch ($ex->getCode()) {
             case self::NOT_FOUND:
             case self::UNAUTHORISED:
             case self::GONE:
                 return false;
             default:
                 throw $ex;
         }
     }
     $class = 'Services_OpenStreetMap_' . ucfirst(strtolower($type)) . 's';
     $obj = new $class();
     $sxe = @simplexml_load_string($response->getBody());
     if ($sxe === false) {
         $obj->setVal(trim($response->getBody()));
     } else {
         $obj->setXml($sxe);
     }
     return $obj;
 }
 /**
  * @param null $page
  */
 public static function getInfobox($page = null)
 {
     self::$parameters['titles'] = $page;
     $url = self::buildApiURL(self::$protocol, self::$locale, self::$endpoint, self::$parameters);
     $response = self::doRequest($url);
     if (self::isSuccessful($response->getStatusCode()) && self::isJson($response->getHeader('content-type'), self::$expectedReponseHeader)) {
         if (!empty($response->json()['query']) && !empty($response->json()['query']['pages'])) {
             $revision = array_pop($response->json()['query']['pages']);
             $infobox = self::parseInfobox($revision['revisions'][0]['*']);
             if (count($infobox) === 1) {
                 $lines = explode("\n", $infobox[0]);
                 $returnArray = self::convertInfoBoxToKeyValuePairs($lines);
                 echo json_encode($returnArray);
             } else {
                 if (count($infobox) > 1) {
                     \Log::warning('more than one infobox found');
                 } else {
                     \Log::warning('Infobox not found');
                 }
             }
         }
     } else {
         \Log::warning('request not in json format');
     }
 }
 /**
  * Run the database seeds.
  *
  * @return void
  */
 public function run()
 {
     Eloquent::unguard();
     if (!Config::get('gosmart.integrated_patient_database')) {
         \Log::warning("Can only seed simulations if a patient database is available");
         return;
     }
     $this->clean();
     //$this->deepClean();
     $organs = ['liver', 'kidney'];
     foreach ($organs as $organ) {
         $referenceSimulation[$organ] = [];
         $sim = Simulation::join('ItemSet_Patient AS IS_P', 'IS_P.Id', '=', 'Simulation.Patient_Id')->join('ItemSet AS IS', 'IS.Id', '=', 'IS_P.Id')->join('Simulation_Needle AS SN', 'SN.Simulation_Id', '=', 'Simulation.Id')->where('IS_P.OrganType', '=', ContextEnum::value($organ))->where('IS.IsDeleted', '=', 'FALSE')->select('Simulation.*')->first();
         if ($sim) {
             $referenceSimulation[$organ]["patient"] = DB::table('ItemSet_Patient')->whereId($sim->Patient_Id)->first();
             $referenceNeedle = $sim->SimulationNeedles->first();
             $referenceSimulation[$organ]["target"] = $referenceNeedle->Target;
             $referenceSimulation[$organ]["entry"] = $referenceNeedle->Entry;
         } else {
             $referenceSimulation[$organ]["patient"] = NULL;
             $referenceSimulation[$organ]["target"] = PointSet::fromArray([0, 0, 0]);
             $referenceSimulation[$organ]["entry"] = PointSet::fromArray([1, 1, 1]);
         }
     }
     foreach (['5cm', '4cm', '3cm', '2cm'] as $length) {
         $this->makeSimulation("{$length} RITA RFA", $referenceSimulation["liver"]["patient"], 'liver', 'NUMA RFA Basic SIF', "RITA Starburst {$length} Protocol", [], ['organ' => ["organ.vtp"], 'vessels' => ["vessels1.vtp"], 'tumour' => ["tumour.vtp"]], [["Manufacturer" => "RITA", "Name" => "Starburst MRI", "Parameters" => ['NEEDLE_TIP_LOCATION' => $referenceSimulation["liver"]["target"]->asString, 'NEEDLE_ENTRY_LOCATION' => $referenceSimulation["liver"]["entry"]->asString]]]);
     }
     $this->makeSimulation('Cryoablation', $referenceSimulation["kidney"]["patient"], 'kidney', 'NUMA Cryoablation Basic SIF', 'Empty', ['SETTING_FINAL_TIMESTEP' => '300'], ['organ' => ["organ.vtp"], 'vessels' => ["vessels1.vtp"], 'tumour' => ["tumour.vtp"]], [["Manufacturer" => "Galil Medical", "Name" => "IceROD", "Parameters" => ['NEEDLE_TIP_LOCATION' => $referenceSimulation["kidney"]["target"]->asString, 'NEEDLE_ENTRY_LOCATION' => $referenceSimulation["kidney"]["entry"]->asString]]]);
     $needleDeltas = [[10, 8, -5], [10, 8, 5], [10, -8, -5], [10, -8, 5], [10, 5, 0], [10, -5, 0]];
     $ireTipCentre = $referenceSimulation["liver"]["target"]->asArray;
     $ireEntryCentre = $referenceSimulation["liver"]["entry"]->asArray;
     $parallel = array_map(function ($c) use($ireTipCentre, $ireEntryCentre) {
         return $ireTipCentre[$c] - $ireEntryCentre[$c];
     }, [0, 1, 2]);
     $norm = sqrt($parallel[0] * $parallel[0] + $parallel[1] * $parallel[1] + $parallel[2] * $parallel[2]);
     $parallel = array_map(function ($c) use($norm) {
         return $c / $norm;
     }, $parallel);
     $randVec = [0, 1.2384717624, 3.42878E-6];
     $perp1 = crossProduct($parallel, $randVec);
     $perp2 = crossProduct($parallel, $perp1);
     //$parallel = [1, 0, 0];
     //$perp1 = [0, 1, 0];
     //$perp2 = [0, 0, 1];
     $ireNeedles = [];
     foreach ($needleDeltas as $needleDelta) {
         $needleOffset = array_map(function ($c) use($needleDelta, $parallel, $perp1, $perp2) {
             return $needleDelta[0] * $parallel[$c] + $needleDelta[1] * $perp1[$c] + $needleDelta[2] * $perp2[$c];
         }, [0, 1, 2]);
         $needleTip = array_map(function ($p) {
             return $p[0] + $p[1];
         }, array_map(null, $ireTipCentre, $needleOffset));
         $ireNeedle = ["Manufacturer" => "Angiodynamics", "Name" => "Basic", "Parameters" => ['NEEDLE_TIP_LOCATION' => json_encode($needleTip), 'NEEDLE_ENTRY_LOCATION' => json_encode(array_map(function ($p) {
             return $p[0] + $p[1];
         }, array_map(null, $ireEntryCentre, $needleOffset)))]];
         $ireNeedles[] = $ireNeedle;
     }
     $this->makeSimulation('IRE', $referenceSimulation["liver"]["patient"], 'liver', 'NUMA IRE 3D SIF', 'Empty', ['CONSTANT_IRE_POTENTIAL_DIFFERENCES' => "[1300, 1500, 1300, 1900, 1300, 1300, 1300, 1900, 1300]"], ['organ' => ["organ.vtp"], 'vessels' => ["vessels1.vtp"], 'tumour' => ["tumour.vtp"]], $ireNeedles);
     $this->makeSimulation('Amica MWA', $referenceSimulation["kidney"]["patient"], 'kidney', 'NUMA MWA Nonlinear SIF', 'Generic modifiable power', [], ['organ' => ["organ.vtp"], 'vessels' => ["vessels1.vtp"], 'tumour' => ["tumour.vtp"]], [["Manufacturer" => "HS", "Name" => "APK11150T19V5", "Parameters" => ['NEEDLE_TIP_LOCATION' => $referenceSimulation["kidney"]["target"]->asString, 'NEEDLE_ENTRY_LOCATION' => $referenceSimulation["kidney"]["entry"]->asString]]]);
 }
 public static function sanitize($str)
 {
     $tag = "DatabaseSanitizer::sanitize()";
     //Log::debug("$tag: $str");
     $db_host = BPConfig::$db_host;
     $db_database = BPConfig::$db_database;
     $db_user = BPConfig::$db_user_read_only;
     $db_passwd = BPConfig::$db_passwd_read_only;
     // connect to mysql database
     $connection = new mysqli($db_host, $db_user, $db_passwd, $db_database);
     // verify connection
     if (mysqli_connect_error()) {
         // connection failed
         throw new Exception("Connection Failed");
     }
     // For backward compatibility
     // Strip slashes automatically added when magic_quotes_gpc is On
     // Note: magic_quotes_gpc deprecated in PHP 5.3 and removed in PHP 5.4
     if (get_magic_quotes_gpc()) {
         Log::warning("{$tag}: magic_quotes_gpc = On");
         $str = stripslashes($str);
     }
     // Escape string
     $str = mysqli_real_escape_string($connection, $str);
     return $str;
 }
Example #11
0
 public function page($slug = '')
 {
     // allow admin to view unpublished posts
     if (Users::authed() === false) {
         $params['status'] = 'published';
     }
     // if no slug is set we will use our default page
     if (empty($slug)) {
         $params['id'] = Config::get('metadata.home_page');
     } else {
         $params['slug'] = $slug;
     }
     // if we cant find either it looks like we're barney rubble (in trouble)
     if (($page = Pages::find($params)) === false) {
         Log::warning('Page connot be found: ' . $slug);
         return Response::error(404);
     }
     // store our page for template functions
     IoC::instance('page', $page, true);
     // does the current page host our posts?
     if ($page->id == Config::get('metadata.posts_page')) {
         // render our posts template
         return Template::render('posts');
     }
     // render our page template
     Template::render('page');
 }
Example #12
0
 private function updateFromServer()
 {
     try {
         $fetcher = new CnbetaArticleFetcher($this->id);
         $newArticle = $fetcher->article;
         Log::info('updating data for article: ' . $this->id);
         if ($newArticle['hotlist']) {
             $this->data = $newArticle;
         } else {
             if (isset($newArticle['view_num']) && isset($newArticle['comment_num'])) {
                 $this->data['view_num'] = $newArticle['view_num'];
                 $this->data['comment_num'] = $newArticle['comment_num'];
             } else {
                 throw new Exception('nothing to save');
             }
         }
         $this->saveToCache();
         $article_entry = ArticleEntry::where('article_id', $this->id)->first();
         $article_entry->view_num = $newArticle['view_num'];
         $article_entry->comment_num = $newArticle['comment_num'];
         $article_entry->save();
         Log::info('updated article: ' . $this->id);
         $this->markUpToDate();
     } catch (Exception $ex) {
         Log::warning('fetching article failed: ' . $ex->getMessage());
     }
 }
Example #13
0
 /**
  * Attempts to change the default database logging functionality
  * into a file stream.
  */
 public function testOverridingDefaultLogFunctionalityWithFileHandler()
 {
     if (file_exists(dirname(__FILE__) . '/test.log')) {
         unlink(dirname(__FILE__) . '/test.log');
     }
     Log::info('This should be in the database.');
     // now we will add a stream handler that can handle all the different
     // types of debug messages, but it should keep things OUT of the database
     $r = new stdClass();
     $r->test = 'test';
     $sh = new \Monolog\Handler\StreamHandler(dirname(__FILE__) . '/test.log', Logger::DEBUG, false);
     Log::pushHandler($sh);
     Log::warning('This is a warning!');
     Log::info('This is an interesting object', array($r));
     $db = Database::get();
     $r = $db->GetAll('select * from Logs');
     // there should only be one item in the logs table because the first info
     // should be in there but the rest should not be.
     $this->assertTrue($r[0]['logID'] == 1);
     $this->assertTrue($r[0]['channel'] == Logger::CHANNEL_APPLICATION);
     $this->assertTrue($r[0]['message'] == 'This should be in the database.');
     $this->assertTrue($r[0]['level'] == Log::getLevelCode('info'));
     $this->assertEquals(count($r), 1);
     $contents = trim(file_get_contents(dirname(__FILE__) . '/test.log'));
     $entries = explode("\n", $contents);
     $this->assertEquals(count($entries), 2);
     if (file_exists(dirname(__FILE__) . '/test.log')) {
         unlink(dirname(__FILE__) . '/test.log');
     }
 }
Example #14
0
 /**
  * Attach theme paths to a local Url. The Url must be a resource located on the asset path
  * of the current theme or it's parents.
  *
  * @param  string $url
  * @return string
  */
 public function url($url)
 {
     // return external URLs unmodified
     if (preg_match('/^((http(s?):)?\\/\\/)/i', $url)) {
         return $url;
     }
     // Is it on AWS? Dont lookup parent themes...
     if (preg_match('/^((http(s?):)?\\/\\/)/i', $this->assetPath)) {
         return $this->assetPath . '/' . ltrim($url, '/');
     }
     // Lookup asset in current's theme asset path
     $fullUrl = (empty($this->assetPath) ? '' : '/') . $this->assetPath . '/' . ltrim($url, '/');
     if (file_exists($fullPath = public_path($fullUrl))) {
         return $fullUrl;
     }
     // If not found then lookup in parent's theme asset path
     if ($this->getParent()) {
         return $this->getParent()->url($url);
     }
     // Asset not found at all. Error handling
     $action = \Config::get('themes.asset_not_found', 'LOG_ERROR');
     if ($action == 'THROW_EXCEPTION') {
         throw new themeException("Asset not found [{$url}]");
     } elseif ($action == 'LOG_ERROR') {
         \Log::warning("Asset not found [{$url}] in Theme [" . \Theme::get() . "]");
     } elseif ($action === 'ASSUME_EXISTS') {
         $assetPath = \Theme::find(\Theme::get())->assetPath;
         return (empty($assetPath) ? '' : '/') . $assetPath . '/' . ltrim($url, '/');
     }
 }
 /**
  * GIF/JPEG/PNG のみ対象
  * @param String $filepath
  * @return bool
  */
 function isValidImageFile($filepath)
 {
     try {
         // WARNING, NOTICE が発生する可能性有り
         $img_info = getimagesize($filepath);
         switch ($img_info[2]) {
             case IMAGETYPE_GIF:
             case IMAGETYPE_JPEG:
             case IMAGETYPE_PNG:
                 // getimagesize関数はマジックバイトを見ているだけ
                 // イメージリソースが生成できるかどうかでファイルの中身を判定する。
                 // データに問題がある場合、WARNING が発生する可能性有り
                 if (imagecreatefromstring(file_get_contents($filepath)) !== false) {
                     return true;
                 }
         }
     } catch (\ErrorException $e) {
         $err_msg = sprintf("%s(%d): %s (%d) filepath = %s", __METHOD__, $e->getLine(), $e->getMessage(), $e->getCode(), $filepath);
         switch ($e->getSeverity()) {
             case E_WARNING:
                 \Log::warning($err_msg);
                 break;
             case E_NOTICE:
                 \Log::notice($err_msg);
                 break;
             default:
                 \Log::error($err_msg);
         }
     }
     return false;
 }
Example #16
0
 public function editRegisteredClient($id)
 {
     $user = $this->auth_service->getCurrentUser();
     $client = $this->client_service->getClientByIdentifier($id);
     if (is_null($client)) {
         Log::warning(sprintf("invalid oauth2 client id %s", $id));
         return View::make("404");
     }
     $allowed_uris = $client->getClientRegisteredUris();
     $allowed_origins = $client->getClientAllowedOrigins();
     $selected_scopes = $client->getClientScopes();
     $aux_scopes = array();
     foreach ($selected_scopes as $scope) {
         array_push($aux_scopes, $scope->id);
     }
     $scopes = $this->scope_service->getAvailableScopes($user->canUseSystemScopes());
     $access_tokens = $this->token_service->getAccessTokenByClient($client->client_id);
     foreach ($access_tokens as $token) {
         $friendly_scopes = $this->scope_service->getFriendlyScopesByName(explode(' ', $token->scope));
         $token->setFriendlyScopes(implode(',', $friendly_scopes));
     }
     $refresh_tokens = $this->token_service->getRefreshTokenByClient($client->client_id);
     foreach ($refresh_tokens as $token) {
         $friendly_scopes = $this->scope_service->getFriendlyScopesByName(explode(' ', $token->scope));
         $token->setFriendlyScopes(implode(',', $friendly_scopes));
     }
     return View::make("oauth2.profile.edit-client", array('client' => $client, 'allowed_uris' => $allowed_uris, 'allowed_origins' => $allowed_origins, 'selected_scopes' => $aux_scopes, 'scopes' => $scopes, 'access_tokens' => $access_tokens, "is_oauth2_admin" => $user->isOAuth2ServerAdmin(), "is_openstackid_admin" => $user->isOpenstackIdAdmin(), "use_system_scopes" => $user->canUseSystemScopes(), 'refresh_tokens' => $refresh_tokens));
 }
Example #17
0
 /**
  * Returns a Record for a specific reference.
  * A DataSource can directly return the DataHash, so it doesn't have to be fetched.
  *
  * @param Record $record
  * @param string $attributeName The attribute it's being accessed on
  * @return Record
  */
 public function getReferenced($record, $attributeName)
 {
     if ($data = $record->getDirectly($attributeName)) {
         if (is_array($data)) {
             // If the data hash exists already, just return the Record with it.
             return $this->cacheAndReturn($record, $attributeName, $this->getForeignDao()->getRecordFromData($data));
         } elseif (is_int($data)) {
             // If data is an integer, it must be the id. So just get the record set with the data.
             return $this->cacheAndReturn($record, $attributeName, $this->getForeignDao()->getRecordFromData(array('id' => (int) $data), true, false, false));
         } elseif ($data instanceof Record) {
             // The record is cached. Just return it.
             return $data;
         } else {
             Log::warning(sprintf('The data hash for `%s` was set but incorrect.', $attributeName));
             return null;
         }
     } else {
         // Otherwise: get the data hash and return the Record.
         $localKey = $this->getLocalKey();
         $foreignKey = $this->getForeignKey();
         if ($localKey && $foreignKey) {
             $localValue = $record->get($localKey);
             if ($localValue === null) {
                 return null;
             }
             return $this->cacheAndReturn($record, $attributeName, $this->getForeignDao()->get(array($foreignKey => $localValue)));
         } else {
             return null;
         }
     }
 }
Example #18
0
 protected function request($type, $endPoint, $params)
 {
     // \Log::debug($endPoint, $params);
     $this->log->addDebug($endPoint, $params);
     $attempts = 0;
     do {
         $result = $this->connection->{$type}($endPoint, $params);
         if (isset($result->errors)) {
             if ($result->errors[0]->code == '88') {
                 \Log::warning('retry...${attempts}');
                 $attempts++;
                 sleep(60);
                 continue;
             }
         }
         break;
     } while ($attempts < self::NUM_OF_ATTEMPTS);
     if ($attempts == self::NUM_OF_ATTEMPTS) {
         throw new \Exception('API制限でリトライを諦めました');
     }
     if (isset($result->errors)) {
         throw new \Exception($endPoint . ":" . $result->errors[0]->code . ":" . $result->errors[0]->message, 1);
     }
     // 鍵つき
     if (isset($result->error)) {
         throw new \Exception($result->error);
     }
     return $result;
 }
Example #19
0
 public static function make($viewName = '', $viewData = array())
 {
     if (preg_match('/\\./i', $viewName)) {
         $viewName = str_replace('.', '/', $viewName);
     }
     // $path = VIEWS_PATH . $viewName . '.php';
     $path = self::getPath() . $viewName . '.php';
     if (!file_exists($path)) {
         Log::warning("View {$viewName} not exists!");
     }
     if (!($loadCache = self::loadCache($path))) {
         $total_data = count($viewData);
         if ($total_data > 0) {
             extract($viewData);
         }
         extract(System::$listVar['global']);
         if (isset(System::$listVar[$viewName])) {
             extract(System::$listVar[$viewName]);
         }
         include $path;
         self::saveCache($path);
     } else {
         echo $loadCache;
     }
 }
 public function save($data, $vendor = null)
 {
     $publicId = isset($data['public_id']) ? $data['public_id'] : false;
     if ($vendor) {
         // do nothing
     } elseif (!$publicId || $publicId == '-1') {
         $vendor = Vendor::createNew();
     } else {
         $vendor = Vendor::scope($publicId)->with('vendor_contacts')->firstOrFail();
         if (Utils::isNinjaDev()) {
             \Log::warning('Entity not set in vendor repo save');
         }
     }
     if ($vendor->is_deleted) {
         return $vendor;
     }
     $vendor->fill($data);
     $vendor->save();
     $first = true;
     $vendorcontacts = isset($data['vendor_contact']) ? [$data['vendor_contact']] : $data['vendor_contacts'];
     $vendorcontactIds = [];
     foreach ($vendorcontacts as $vendorcontact) {
         $vendorcontact = $vendor->addVendorContact($vendorcontact, $first);
         $vendorcontactIds[] = $vendorcontact->public_id;
         $first = false;
     }
     if (!$vendor->wasRecentlyCreated) {
         foreach ($vendor->vendor_contacts as $contact) {
             if (!in_array($contact->public_id, $vendorcontactIds)) {
                 $contact->delete();
             }
         }
     }
     return $vendor;
 }
 /**
  * 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;
 }
Example #22
0
 public static function addToQueue($queue, $ownerID, $vCode, $api, $scope)
 {
     // Prepare the auth array
     if ($vCode != null) {
         $auth = array('keyID' => $ownerID, 'vCode' => $vCode);
     } else {
         $auth = array();
     }
     // Check the databse if there are jobs outstanding ie. they have the status
     // Queued or Working. If not, we will queue a new job, else just capture the
     // jobID and return that
     $jobID = \SeatQueueInformation::where('ownerID', '=', $ownerID)->where('api', '=', $api)->whereIn('status', array('Queued', 'Working'))->first();
     // Check if the $jobID was found, else, queue a new job
     if (!$jobID) {
         $jobID = \Queue::push($queue, $auth);
         \SeatQueueInformation::create(array('jobID' => $jobID, 'ownerID' => $ownerID, 'api' => $api, 'scope' => $scope, 'status' => 'Queued'));
     } else {
         // To aid in potential capacity debugging, lets write a warning log entry so that a user
         // is able to see that a new job was not submitted
         \Log::warning('A new job was not submitted due a similar one still being outstanding. Details: ' . $jobID, array('src' => __CLASS__));
         // Set the jobID to the ID from the database
         $jobID = $jobID->jobID;
     }
     return $jobID;
 }
 public function save($input, $expense = null)
 {
     $publicId = isset($input['public_id']) ? $input['public_id'] : false;
     if ($expense) {
         // do nothing
     } elseif ($publicId) {
         $expense = Expense::scope($publicId)->firstOrFail();
         if (Utils::isNinjaDev()) {
             \Log::warning('Entity not set in expense repo save');
         }
     } else {
         $expense = Expense::createNew();
     }
     if ($expense->is_deleted) {
         return $expense;
     }
     // First auto fill
     $expense->fill($input);
     if (isset($input['expense_date'])) {
         $expense->expense_date = Utils::toSqlDate($input['expense_date']);
     }
     $expense->should_be_invoiced = isset($input['should_be_invoiced']) && floatval($input['should_be_invoiced']) || $expense->client_id ? true : false;
     if (!$expense->expense_currency_id) {
         $expense->expense_currency_id = \Auth::user()->account->getCurrencyId();
     }
     if (!$expense->invoice_currency_id) {
         $expense->invoice_currency_id = \Auth::user()->account->getCurrencyId();
     }
     $rate = isset($input['exchange_rate']) ? Utils::parseFloat($input['exchange_rate']) : 1;
     $expense->exchange_rate = round($rate, 4);
     if (isset($input['amount'])) {
         $expense->amount = round(Utils::parseFloat($input['amount']), 2);
     }
     $expense->save();
     // Documents
     $document_ids = !empty($input['document_ids']) ? array_map('intval', $input['document_ids']) : [];
     foreach ($document_ids as $document_id) {
         // check document completed upload before user submitted form
         if ($document_id) {
             $document = Document::scope($document_id)->first();
             if ($document && Auth::user()->can('edit', $document)) {
                 $document->invoice_id = null;
                 $document->expense_id = $expense->id;
                 $document->save();
             }
         }
     }
     // prevent loading all of the documents if we don't have to
     if (!$expense->wasRecentlyCreated) {
         foreach ($expense->documents as $document) {
             if (!in_array($document->public_id, $document_ids)) {
                 // Not checking permissions; deleting a document is just editing the invoice
                 $document->delete();
             }
         }
     }
     return $expense;
 }
Example #24
0
 public static function get($keyName, $addOns = array())
 {
     if (!isset($keyName[1])) {
         return false;
     }
     $dirName = App::get('locale');
     $fileName = '';
     $fieldName = '';
     $childName = '';
     $langPath = self::getPath() . $dirName . '/';
     $loadData = self::parseName($keyName);
     $fileName = $loadData['fileName'];
     $fieldName = $loadData['fieldName'];
     if (isset($loadData['childName'])) {
         $childName = $loadData['childName'];
     }
     if (!isset(self::$data[$fileName])) {
         $langPath = $langPath . $fileName . '.php';
         if (!file_exists($langPath)) {
             Log::warning('Language ' . ucfirst($fileName) . ' not exists in system.');
             return false;
         }
         if ((int) self::$totalRow == 0) {
             include $langPath;
             // return self::$lang;
         }
         if (!isset($lang)) {
             // Alert::make('The language '.ucfirst($lang).' not exists inside system.');
             Log::warning('The language ' . ucfirst($lang) . ' not exists inside system.');
             return false;
         }
         if (isset($fieldName[1]) && !isset($lang[$fieldName])) {
             // Alert::make('The field '.ucfirst($fieldName).' not exists inside language '.ucfirst($fileName));
             Log::warning('The field ' . ucfirst($fieldName) . ' not exists inside language ' . ucfirst($fileName));
             return false;
         }
         self::$data[$fileName] = $lang;
     } else {
         $lang = self::$data[$fileName];
     }
     self::$totalRow = count($lang);
     if ($fieldName == '') {
         return $lang;
     }
     $totalAddons = count($addOns);
     if ($totalAddons > 0 && !is_array($lang[$fieldName])) {
         $keyNames = array_keys($addOns);
         for ($i = 0; $i < $totalAddons; $i++) {
             // $keyName=$keyNames[$i];
             $keyNames[$i] = ':' . $keyNames[$i];
             // $lang[$keyName]=$addOns[$keyName];
         }
         $lang[$fieldName] = str_replace(array_keys($addOns), array_values($addOns), $lang[$fieldName]);
     }
     $theText = isset($childName[1]) ? $lang[$fieldName][$childName] : $lang[$fieldName];
     return $theText;
 }
Example #25
0
 protected function truncate_file($file, $contents, $max_file_size, $actual_file_size)
 {
     // should we really warn about this?
     $actual_file_size_up = intval(($actual_file_size + 1000 * 10 - 1) / (1000 * 10)) * (1000 * 10);
     // round up to get a nicer number
     Log::warning("The reference implementation produced a file that is too large\n{$file} has size {$actual_file_size}, while max is {$max_file_size}\nTo suppress this warning, add  'filesize limit: {$actual_file_size_up}' to the into file", $this->entity->path());
     return $contents;
     // don't actually truncate
 }
Example #26
0
 /**
  * Store a newly created resource in storage.
  *
  * @param  \Illuminate\Http\Request  $request
  * @return \Illuminate\Http\Response
  */
 public function payHooks(Request $request)
 {
     $content = "finshed";
     $status = 200;
     $value = "text/html";
     $hookType = $request->input('type');
     \Log::warning($hookType);
     return response($content, $status)->header('Content-Type', $value);
 }
 /**
  * Main Controller Method for Shopify Authorization
  */
 public function installOrAuthenticate()
 {
     if (Input::get('code')) {
         // New install
         Log::info('New Install: ' . Input::get('shop'));
         $sh = App::make('ShopifyAPI', ['API_KEY' => Config::get('shopify.APP_API_KEY'), 'API_SECRET' => Config::get('shopify.APP_API_SECRET'), 'SHOP_DOMAIN' => Input::get('shop')]);
         // Get Access Token
         try {
             $accessToken = $sh->getAccessToken(Input::get('code'));
         } catch (Exception $e) {
             Log::error($e->getMessage());
             die('<pre>Error: ' . $e->getMessage() . '</pre>');
         }
         $shop = Shop::where('domain', Input::get('shop'))->first();
         if (!$shop) {
             //Log::info(__LINE__ . ': New Shop');
             $shop = new Shop();
         }
         $shop->setDomain(Input::get('shop'));
         $shop->setAccessToken($accessToken);
         $shop->save();
         $this->updateShopInfo($shop);
         /**
          * Create the shop's first api key automatically, on install
          */
         $apiKey = new ApiKey();
         $apiKey->shop_id = $shop->id;
         $apiKey->public_key = Hash::make($shop->id . 'REMEDY');
         $apiKey->access_level_id = AccessLevel::where('title', 'Free Plus')->first()->id;
         $apiKey->save();
         /**
          * Create webhook for uninstall
          */
         $hookData = array('webhook' => array('topic' => 'app/uninstalled', 'address' => 'https://' . $_ENV['HOST'] . '/uninstall-hook', 'format' => 'json'));
         try {
             $sh->setup(['ACCESS_TOKEN' => $shop->getAccessToken()]);
             $sh->call(['URL' => 'webhooks.json', 'METHOD' => 'POST', 'DATA' => $hookData]);
         } catch (Exception $e) {
             Log::error('Issue creating uninstall webhook - ' . $shop->domain . ' : ' . $e->getMessage());
         }
         Session::put('shop', $shop->domain);
         return Redirect::to('/');
     } else {
         // Accessing app from apps screen
         $shop = Shop::where('domain', Input::get('shop'))->first();
         if ($shop) {
             Log::info('Shop found after Auth: ' . Input::get('shop'));
             $this->updateShopInfo($shop);
             Session::put('shop', Input::get('shop'));
             return Redirect::to('/');
         } else {
             Log::warning('Shop redirecting to install: ' . Input::get('shop'));
             $sh = App::make('ShopifyAPI', ['API_KEY' => Config::get('shopify.APP_API_KEY'), 'SHOP_DOMAIN' => Input::get('shop')]);
             return Redirect::to($sh->installURL(['permissions' => Config::get('shopify.APP_API_SCOPE'), 'redirect' => 'https://' . $_ENV['HOST'] . '/auth']));
         }
     }
 }
Example #28
0
 public static function load($modelName = '')
 {
     // $path = MODELS_PATH . $modelName . '.php';
     $path = self::getPath() . $modelName . '.php';
     if (!file_exists($path)) {
         Log::warning('Model <b>' . $modelName . '</b> not exists.');
     }
     include $path;
 }
Example #29
0
 public function index()
 {
     if (Auth::User()->admin == '1') {
         return view('admin.index');
     } else {
         \Log::warning('Notice,User guest try to visit admins:' . Auth::User()->username);
         return Redirect::to('/');
     }
 }
 protected function isValidSalesAgent($sales_agent)
 {
     if (in_array($sales_agent, $this->valid_sales_agents)) {
         return true;
     }
     if (!empty($sales_agent)) {
         \Log::warning('Sales agent ' . $sales_agent . ' is not valid per configuration.');
     }
     return false;
 }