Beispiel #1
0
 /**
  * push
  * @param mixed $registrations
  * @param mixed $data
  */
 public function push($registrations, $data)
 {
     $gcm_access_key = Config::get('push.gcm.access_key', false);
     if (!$gcm_access_key) {
         throw new \Exception("Please set 'push.gcm.access_key' value.");
     }
     $registration_ids = array();
     foreach ($registrations as $registration) {
         array_push($registration_ids, $registration['device_id']);
     }
     // Nobody registeted. Return 0 statuses
     if (empty($registration_ids)) {
         return array('success' => 0, 'failure' => 0);
     }
     // Payload data
     $payload = array('message' => $data['message'], 'vibrate' => 1, 'sound' => 1);
     // if (isset($data['ticker']) && strlen($data['ticker']) > 0) {
     // 	$payload['tickerText'] = $data['ticker'];
     // }
     // if (isset($data['sound']) && !$data['sound']) {
     // 	$payload['sound'] = 0;
     // }
     $client = new HttpClient();
     $response = $client->post('https://android.googleapis.com/gcm/send', array('Authorization' => 'key=' . $gcm_access_key, 'Content-Type' => 'application/json'), json_encode(array('registration_ids' => $registration_ids, 'data' => $payload)), array('exceptions' => false))->json();
     // Log results
     if (isset($response['results'])) {
         Logger::debug("PushNotification: GCM -> " . json_encode($response['results']));
     }
     return array('success' => $response['success'], 'failure' => $response['failure']);
 }
Beispiel #2
0
 public function testConfigDeploy()
 {
     $deployed = Config::deploy(array('something' => array('very' => array('deep' => array('here' => 'value'), 'nice' => 6)), 'another' => '10', 'hello' => array('there' => 'hey!')));
     $this->assertTrue($deployed);
     $this->assertEquals(Config::get('something.very.deep.here'), 'value');
     $this->assertEquals(Config::get('something.very.nice'), 6);
     $this->assertEquals(Config::get('another'), '10');
     $this->assertEquals(Config::get('hello.there'), 'hey!');
 }
Beispiel #3
0
 protected function getClient()
 {
     if (!$this->client) {
         $app_access_token = Config::get('storage.access_token');
         $client_identifier = "hook-server/0.2";
         $this->client = new dbx\Client($app_access_token, $client_identifier);
     }
     return $this->client;
 }
Beispiel #4
0
 protected function getClient()
 {
     if (!$this->client) {
         $bucket = Config::get('storage.bucket', 'default');
         $key = Config::get('storage.key');
         $secret = Config::get('storage.secret');
         $this->client = Aws::factory(array('bucket' => $bucket, 'key' => $key, 'secret' => $secret))->get('s3');
     }
     return $this->client;
 }
Beispiel #5
0
 public function __construct()
 {
     $config = Config::get('redis');
     if (!$config) {
         throw new ServiceUnavailableException("'redis' config key missing.");
     }
     $client = new Predis\Client($config, array('prefix' => 'sessions:'));
     // Set `gc_maxlifetime` to specify a time-to-live of 5 seconds for session keys.
     parent::__construct($client);
     // , array('gc_maxlifetime' => 5)
 }
Beispiel #6
0
 public function beforeCreate()
 {
     // cache Auth role for this token
     //
     // TODO: use auth() relationship.
     // Due the same problem at Auth::current(), it was needed to use
     // App::collection here
     //
     $this->role = App::collection('auth')->where('_id', $this->auth_id)->first()->role;
     $this->created_at = Carbon::now();
     $token_expiration = Config::get('auth.token_expiration', static::DEFAULT_TOKEN_EXPIRATION);
     $this->expire_at = Carbon::now()->addHours($token_expiration);
     $this->token = sha1(uniqid(rand(), true));
 }
Beispiel #7
0
 public function getConfig($collection_name, $action)
 {
     $role = null;
     $security = Config::get('security.collections.' . $collection_name, array());
     if (isset($security[$action])) {
         $role = $security[$action];
     } else {
         if (isset($security['crud'])) {
             $role = $security['crud'];
         } else {
             $role = $this->defaults[$action];
         }
     }
     return $role ?: "all";
 }
Beispiel #8
0
 protected function getBlobService()
 {
     if (!$this->service) {
         $endpoint = Config::get('storage.endpoint_protocol', 'https');
         $account = Config::get('storage.account');
         if (!$account) {
             throw new Exception(__CLASS__ . ": 'storage.account' config is required.");
         }
         $key = Config::get('storage.key');
         if (!$key) {
             throw new Exception(__CLASS__ . ": 'storage.key' config is required.");
         }
         $conection = array("DefaultEndpointsProtocol={$endpoint}", "AccountName={$account}", "AccountKey={$key}");
         $this->service = ServicesBuilder::getInstance()->createBlobService(join(";", $conection));
     }
     return $this->service;
 }
Beispiel #9
0
 /**
  * Trigger 'forgot password' email
  */
 public function forgotPassword()
 {
     $data = $this->getData();
     $auth = Auth::where('email', $data['email'])->first();
     if (!$auth) {
         throw new Exceptions\NotFoundException("invalid_user");
     }
     if (!isset($data['subject'])) {
         $data['subject'] = 'Forgot your password?';
     }
     $body_data = Context::unsafe(function () use(&$auth) {
         $array = $auth->generateForgotPasswordToken()->toArray();
         $array['token'] = $auth->getAttribute(Auth::FORGOT_PASSWORD_FIELD);
         return $array;
     });
     $template = isset($data['template']) ? $data['template'] : self::TEMPLATE_FORGOT_PASSWORD;
     return array('success' => Mail::send(array('subject' => $data['subject'], 'from' => Config::get('mail.from', '*****@*****.**'), 'to' => $auth->email, 'body' => Module::template($template)->compile($body_data))) === 1);
 }
Beispiel #10
0
 public function beforeCreate()
 {
     if ($this->file) {
         $provider = Config::get('storage.provider', 'filesystem');
         $contents = null;
         if ($base64 = static::base64($this->file)) {
             preg_match('/\\/([a-z\\.-]+)/', $base64[1], $ext);
             $extension = $ext[1];
             $this->name = sha1(uniqid(rand(), true)) . '.' . $extension;
             $this->mime = $base64[1];
             $contents = base64_decode($base64[3]);
         } else {
             $this->name = md5($this->file['name']) . uniqid() . "." . pathinfo($this->file['name'], PATHINFO_EXTENSION);
             $this->mime = $this->file['type'];
             $contents = file_get_contents($this->file['tmp_name']);
         }
         $this->path = Provider::get($provider)->store($this->name, $contents, array('mime' => $this->mime));
         unset($this->attributes['file']);
     }
 }
Beispiel #11
0
 public static function getTransport()
 {
     $params = array();
     $allowed_configs = array('driver', 'host', 'port', 'encryption', 'username', 'password');
     foreach (Config::get('mail', array()) as $name => $value) {
         if (in_array($name, $allowed_configs)) {
             $params[$name] = $value;
         }
     }
     // set 'mail' as default driver
     if (!isset($params['driver'])) {
         $params['driver'] = 'mail';
     } else {
         $preset_file = __DIR__ . '/presets/' . $params['driver'] . '.php';
         if (file_exists($preset_file)) {
             $preset_params = (require $preset_file);
             unset($params['driver']);
             // allow to overwrite default preset settings with custom configs
             $params = array_merge($preset_params, $params);
         }
     }
     $transport_klass = '\\Swift_' . ucfirst(strtolower($params['driver'])) . 'Transport';
     $transport = call_user_func(array($transport_klass, 'newInstance'));
     unset($params['driver']);
     // Set custom transport params
     foreach ($params as $param => $value) {
         call_user_func(array($transport, 'set' . ucfirst($param)), $value);
     }
     return $transport;
 }
Beispiel #12
0
 /**
  * push
  * @param mixed $registrations
  * @param mixed $data
  */
 public function push($registrations, $data)
 {
     $apns_environment = Config::get('push.apns.environment', 'sandbox');
     $apns_certificate_file = Config::get('push.apns.cert.file', false);
     $apns_certificate_pass = Config::get('push.apns.cert.pass', false);
     if (!$apns_certificate_file) {
         throw new \Exception("APNS config error: 'push.apns.cert.file' not set.");
     }
     $total_failure = 0;
     // Instantiate a new ApnsPHP_Push object
     $push = new \ApnsPHP_Push($apns_environment == 'sandbox' ? \ApnsPHP_Abstract::ENVIRONMENT_SANDBOX : \ApnsPHP_Abstract::ENVIRONMENT_PRODUCTION, $this->getCertificateFile($apns_certificate_file));
     // set custom logger
     $push->setLogger(new APNSLogger());
     // Set the Provider Certificate passphrase
     if ($apns_certificate_pass) {
         $push->setProviderCertificatePassphrase($apns_certificate_pass);
     }
     // Set the Root Certificate Autority to verify the Apple remote peer
     $push->setRootCertificationAuthority($this->getRootCertificationAuthority());
     // Connect to the Apple Push Notification Service
     $push->connect();
     $message = new \ApnsPHP_Message();
     // Add all registrations as message recipient
     foreach ($registrations as $registration) {
         try {
             $message->addRecipient($registration->device_id);
         } catch (\ApnsPHP_Message_Exception $e) {
             Logger::error($e->getMessage());
             $total_failure += 1;
         }
     }
     Logger::debug("Recipients => " . json_encode($message->getRecipients()));
     // Set a custom identifier. To get back this identifier use the getCustomIdentifier() method
     // over a ApnsPHP_Message object retrieved with the getErrors() message.
     if (isset($data['custom_identifier'])) {
         $message->setCustomIdentifier($data['custom_identifier']);
     }
     // Set badge icon to "3"
     if (isset($data['badge']) && is_int($data['badge'])) {
         $message->setBadge((int) $data['badge']);
     }
     // Set text
     $message->setText($data['message']);
     // Play the default sound
     if (!isset($data['sound']) || empty($data['sound'])) {
         $data['sound'] = 'default';
     }
     $message->setSound($data['sound']);
     // Set the expiry value to 30 seconds
     if (isset($data['expiry']) && $data['expiry'] > 0) {
         $message->setExpiry($data['expiry']);
     }
     // Set custom properties
     $invalid_properties = array('_id', 'app_id', 'created_at', 'updated_at', 'sound', 'text', 'badge', 'expiry', 'custom_identifier');
     $custom_properties = array_diff_key($data, array_flip($invalid_properties));
     foreach ($custom_properties as $property => $value) {
         $message->setCustomProperty($property, $value);
     }
     // Add the message to the message queue
     $push->add($message);
     // Send all messages in the message queue
     $stats = $push->send();
     // Disconnect from the Apple Push Notification Service
     $push->disconnect();
     // Examine the error message container
     $error_list = $push->getErrors();
     // Log delivery status
     $errors = $push->getErrors();
     $total_failure += count($errors);
     if ($total_failure > 0) {
         foreach ($errors as $error) {
             Logger::error($error);
         }
     }
     return array('success' => $registrations->count() - $total_failure, 'failure' => $total_failure);
 }
Beispiel #13
0
 public function call()
 {
     // The Slim application
     $app = $this->app;
     self::decode_query_string();
     $origin = $app->request->headers->get('ORIGIN', '*');
     // Always keep connection open
     $app->response->headers->set('Connection', 'Keep-Alive');
     // Allow Cross-Origin Resource Sharing
     $app->response->headers->set('Access-Control-Allow-Credentials', 'true');
     $app->response->headers->set('Access-Control-Allow-Methods', 'GET, PUT, POST, DELETE');
     $app->response->headers->set('Access-Control-Allow-Headers', 'x-app-id, x-app-key, x-auth-token, x-http-method-override, content-type, user-agent, accept');
     if ($app->request->isOptions()) {
         // Always allow OPTIONS requests.
         $app->response->headers->set('Access-Control-Allow-Origin', $origin);
     } else {
         // Get application key
         $app_key = Context::validateKey($app->request->headers->get('X-App-Id') ?: $app->request->get('X-App-Id'), $app->request->headers->get('X-App-Key') ?: $app->request->get('X-App-Key'));
         if ($app_key) {
             // Check the application key allowed origins, and block if necessary.
             if ($app_key->isBrowser()) {
                 $app->response->headers->set('Access-Control-Allow-Origin', $origin);
                 $request_origin = preg_replace("/https?:\\/\\//", "", $origin);
                 $allowed_origins = Config::get('security.allowed_origins', array($request_origin));
                 $is_origin_allowed = array_filter($allowed_origins, function ($allowed_origin) use(&$request_origin) {
                     return fnmatch($allowed_origin, $request_origin);
                 });
                 if (count($is_origin_allowed) == 0) {
                     // throw new NotAllowedException("origin_not_allowed");
                     $app->response->setStatus(403);
                     // forbidden
                     $app->response->headers->set('Content-type', 'application/json');
                     $app->response->setBody(json_encode(array('error' => "origin_not_allowed")));
                     return;
                 }
             }
             // Require custom app packages
             Package\Manager::autoload();
             // // Register session handler
             // Session\Handler::register(Config::get('session.handler', 'database'));
             // Query and compile route module if found
             $route_module_name = strtolower($app->request->getMethod()) . '_' . substr($app->request->getPathInfo(), 1) . '.php';
             $alternate_route_module_name = 'any_' . substr($app->request->getPathInfo(), 1) . '.php';
             $custom_route = Module::where('type', Module::TYPE_ROUTE)->where('name', $route_module_name)->orWhere('name', $alternate_route_module_name)->first();
             if ($custom_route) {
                 // Flag request as "trusted".
                 Context::setTrusted(true);
                 // "Compile" the route to be available for the router
                 $custom_route->compile();
             }
         } else {
             if (!\Hook\Controllers\ApplicationController::isRootOperation()) {
                 $app->response->setStatus(403);
                 $app->response->setBody(json_encode(array('error' => "Your IP Address is not allowed to perform this operation.")));
                 return;
             }
         }
         //
         // Parse incoming JSON data
         if ($app->request->isPost() || $app->request->isPut() || $app->request->isDelete()) {
             $input_data = $app->environment->offsetGet('slim.input');
             $app->environment->offsetSet('slim.request.form_hash', json_decode($input_data, true));
         }
         return $this->next->call();
     }
 }
Beispiel #14
0
 /**
  * Generate sha1 hash of a password, using 'salt' and 'pepper' (Config)
  *
  * @static
  *
  * @param string $password
  * @param string $salt
  *
  * @return string
  */
 public static function password_hash($password, $salt)
 {
     $app_auth_pepper = Config::get('security.auth_pepper', '');
     return sha1($password . $salt . $app_auth_pepper);
 }
Beispiel #15
0
 public static function config($args)
 {
     return \Hook\Application\Config::get($args[0]);
 }
Beispiel #16
0
 public function auth($strategy = null, $callback = null)
 {
     $query_params = $this->getQueryParams();
     if (isset($_POST['opauth'])) {
         $opauth = unserialize(base64_decode($_POST['opauth']));
         if (isset($opauth['error'])) {
             // throw new UnauthorizedException($opauth['error']['code']);
             return $this->relay_frame_close();
         }
         $opauth_data = $opauth['auth'];
         $identity = AuthIdentity::firstOrNew(array('provider' => strtolower($opauth_data['provider']), 'uid' => $opauth_data['uid']));
         if (!$identity->auth_id || $identity->auth == NULL) {
             // cleanup nested infos before registering it
             foreach ($opauth_data['info'] as $key => $value) {
                 if (is_array($value)) {
                     unset($opauth_data['info'][$key]);
                 }
             }
             // register new auth
             if (isset($opauth_data['info']['email'])) {
                 $auth = Auth::current() ?: Auth::firstOrNew(array('email' => $opauth_data['info']['email']));
             } else {
                 // creating auth entry without email
                 $auth = Auth::current() ?: new Auth();
             }
             // If is a new user, fill and save with auth data
             if (!$auth->_id) {
                 $auth->fill($opauth_data['info']);
             }
             // set visible provider_id on auth row.
             // such as 'facebook_id', 'google_id', etc.
             $auth->setTrustedAction(true);
             $auth->setAttribute($identity->provider . '_id', $identity->uid);
             $auth->save();
             $identity->auth_id = $auth->_id;
             $identity->save();
         } else {
             $auth = $identity->auth;
         }
         $data = $auth->dataWithToken();
         // output oauth credentials on authentication request
         if (isset($opauth_data['credentials'])) {
             $data['credentials'] = $opauth_data['credentials'];
         }
         if (Context::getKey()->isBrowser()) {
             $js_origin = "window.opener.location.protocol + '//' + window.opener.location.hostname + (window.opener.location.port ? ':' + window.opener.location.port: '')";
             // Use mozilla/winchan to allow trusted cross-browser postMessages
             $winchanjs = 'WinChan=function(){var RELAY_FRAME_NAME="__winchan_relay_frame";var CLOSE_CMD="die";function addListener(w,event,cb){if(w.attachEvent)w.attachEvent("on"+event,cb);else if(w.addEventListener)w.addEventListener(event,cb,false)}function removeListener(w,event,cb){if(w.detachEvent)w.detachEvent("on"+event,cb);else if(w.removeEventListener)w.removeEventListener(event,cb,false)}function isInternetExplorer(){var rv=-1;var ua=navigator.userAgent;if(navigator.appName==="Microsoft Internet Explorer"){var re=new RegExp("MSIE ([0-9]{1,}[.0-9]{0,})");if(re.exec(ua)!=null)rv=parseFloat(RegExp.$1)}else if(ua.indexOf("Trident")>-1){var re=new RegExp("rv:([0-9]{2,2}[.0-9]{0,})");if(re.exec(ua)!==null){rv=parseFloat(RegExp.$1)}}return rv>=8}function isFennec(){try{var userAgent=navigator.userAgent;return userAgent.indexOf("Fennec/")!=-1||userAgent.indexOf("Firefox/")!=-1&&userAgent.indexOf("Android")!=-1}catch(e){}return false}function isSupported(){return window.JSON&&window.JSON.stringify&&window.JSON.parse&&window.postMessage}function extractOrigin(url){if(!/^https?:\\/\\//.test(url))url=window.location.href;var a=document.createElement("a");a.href=url;return a.protocol+"//"+a.host}function findRelay(){var loc=window.location;var frames=window.opener.frames;for(var i=frames.length-1;i>=0;i--){try{if(frames[i].location.protocol===window.location.protocol&&frames[i].location.host===window.location.host&&frames[i].name===RELAY_FRAME_NAME){return frames[i]}}catch(e){}}return}var isIE=isInternetExplorer();if(isSupported()){return{open:function(opts,cb){if(!cb)throw"missing required callback argument";var err;if(!opts.url)err="missing required \'url\' parameter";if(!opts.relay_url)err="missing required \'relay_url\' parameter";if(err)setTimeout(function(){cb(err)},0);if(!opts.window_name)opts.window_name=null;if(!opts.window_features||isFennec())opts.window_features=undefined;var iframe;var origin=extractOrigin(opts.url);if(origin!==extractOrigin(opts.relay_url)){return setTimeout(function(){cb("invalid arguments: origin of url and relay_url must match")},0)}var messageTarget;if(isIE){iframe=document.createElement("iframe");iframe.setAttribute("src",opts.relay_url);iframe.style.display="none";iframe.setAttribute("name",RELAY_FRAME_NAME);document.body.appendChild(iframe);messageTarget=iframe.contentWindow}var w=window.open(opts.url,opts.window_name,opts.window_features);if(!messageTarget)messageTarget=w;var closeInterval=setInterval(function(){if(w&&w.closed){cleanup();if(cb){cb("unknown closed window");cb=null}}},500);var req=JSON.stringify({a:"request",d:opts.params});function cleanup(){if(iframe)document.body.removeChild(iframe);iframe=undefined;if(closeInterval)closeInterval=clearInterval(closeInterval);removeListener(window,"message",onMessage);removeListener(window,"unload",cleanup);if(w){try{w.close()}catch(securityViolation){messageTarget.postMessage(CLOSE_CMD,origin)}}w=messageTarget=undefined}addListener(window,"unload",cleanup);function onMessage(e){if(e.origin!==origin){return}try{var d=JSON.parse(e.data);if(d.a==="ready")messageTarget.postMessage(req,origin);else if(d.a==="error"){cleanup();if(cb){cb(d.d);cb=null}}else if(d.a==="response"){cleanup();if(cb){cb(null,d.d);cb=null}}}catch(err){}}addListener(window,"message",onMessage);return{close:cleanup,focus:function(){if(w){try{w.focus()}catch(e){}}}}},onOpen:function(cb){var o="*";var msgTarget=isIE?findRelay():window.opener;if(!msgTarget)throw"cant find relay frame";function doPost(msg){msg=JSON.stringify(msg);if(isIE)msgTarget.doPost(msg,o);else msgTarget.postMessage(msg,o)}function onMessage(e){var d;try{d=JSON.parse(e.data)}catch(err){}if(!d||d.a!=="request")return;removeListener(window,"message",onMessage);o=e.origin;if(cb){setTimeout(function(){cb(o,d.d,function(r){cb=undefined;doPost({a:"response",d:r})})},0)}}function onDie(e){if(e.data===CLOSE_CMD){try{window.close()}catch(o_O){}}}addListener(isIE?msgTarget:window,"message",onMessage);addListener(isIE?msgTarget:window,"message",onDie);try{doPost({a:"ready"})}catch(e){addListener(msgTarget,"load",function(e){doPost({a:"ready"})})}var onUnload=function(){try{removeListener(isIE?msgTarget:window,"message",onDie)}catch(ohWell){}if(cb)doPost({a:"error",d:"client closed window"});cb=undefined;try{window.close()}catch(e){}};addListener(window,"unload",onUnload);return{detach:function(){removeListener(window,"unload",onUnload)}}}}}else{return{open:function(url,winopts,arg,cb){setTimeout(function(){cb("unsupported browser")},0)},onOpen:function(cb){setTimeout(function(){cb("unsupported browser")},0)}}}}();';
             return "<!DOCTYPE html>\n                    <html>\n                        <head>\n                            <meta http-equiv='X-UA-Compatible' content='chrome=1' />\n                        </head>\n                        <body>\n                        <script type='text/javascript'>\n                          {$winchanjs}\n                          WinChan.onOpen(function(origin, args, cb) {\n                            cb(" . to_json($data) . ");\n                          });\n                        </script>\n                        </body>\n                    </html>";
         } else {
             return $data;
         }
     }
     ob_start();
     $opauth = new Opauth(array('path' => substr($_SERVER['REQUEST_URI'], 0, strpos($_SERVER['REQUEST_URI'], 'oauth/') + 6), 'callback_url' => '{path}callback' . $query_params, 'callback_transport' => 'post', 'Strategy' => Config::get('oauth'), 'security_salt' => Context::getKey()->app->secret), false);
     $this->fixOauthStrategiesCallback($opauth, $query_params);
     $opauth->run();
     $response = ob_get_contents();
     ob_end_clean();
     return $response;
 }