Exemple #1
0
 public function getHandler($conn)
 {
     Context::clear();
     $app = \Slim\Slim::getInstance();
     $credentials = $conn->WebSocket->request->getQuery()->toArray();
     //
     // Aparently, this doesn't work as expected.
     //
     // set x-auth-token
     if (isset($credentials['X-Auth-Token'])) {
         $app->request->headers->set('X-Auth-Token', $credentials['X-Auth-Token']);
         unset($credentials['X-Auth-Token']);
     }
     // remove "/" and possible "ws/" from resource path
     $resource = str_replace("ws/", "", substr($conn->WebSocket->request->getPath(), 1));
     $hash = md5($resource . join(",", array_values($credentials)));
     if (!isset($this->handlers[$hash])) {
         if ($key = Model\AppKey::where('app_id', $credentials['X-App-Id'])->where('key', $credentials['X-App-Key'])->first()) {
             Context::setKey($key);
             $channel = Model\Module::channel($resource);
             if ($channel) {
                 $this->handlers[$hash] = $channel->compile();
             }
         }
     }
     return isset($this->handlers[$hash]) ? $this->handlers[$hash] : null;
 }
Exemple #2
0
 public static function link_to($args, $attributes)
 {
     $text = isset($args[1]) ? $args[1] : $args[0];
     $app_key = \Hook\Application\Context::getKey();
     $public_url = public_url($args[0]) . '?X-App-Id=' . $app_key->app_id . '&X-App-Key=' . $app_key->key;
     return array('<a href="' . $public_url . '"' . html_attributes($attributes) . '>' . $text . '</a>', 'raw');
 }
Exemple #3
0
 public static function isAllowed($model, $action)
 {
     // commandline always have full-access
     if (Context::isTrusted() || $model instanceof Auth && $model->isTrustedAction()) {
         return true;
     }
     $is_allowed = false;
     $instance = static::getInstance();
     $collection_name = $instance->getCollectioName($model);
     $instance->token = AuthToken::current();
     $roles = $instance->getConfig($collection_name, $action);
     // Ensure array type for roles
     if (!is_array($roles)) {
         $roles = array($roles);
     }
     foreach ($roles as $role) {
         // At least one of the configured roles must match
         if ($is_allowed) {
             break;
         }
         if (in_array($role, $instance->builtInRoles)) {
             $is_allowed = call_user_func_array(array($instance, 'check' . ucfirst($role)), array($model));
         } else {
             $is_allowed = $instance->checkRole($role);
         }
     }
     return $is_allowed;
 }
Exemple #4
0
 public function testRegister()
 {
     $task = new ScheduledTask(array('task' => "something", 'schedule' => "daily"));
     preg_match("/X-App-Key: ([^']+)/", $task->getCommand(), $matches);
     $this->assertTrue(strlen($matches[1]) == 32, "should find a valid 32-char key.");
     $this->assertEquals($matches[1], Context::getAppKeys(AppKey::TYPE_SERVER)->first()->key, "tasks should use a valid server key");
 }
Exemple #5
0
 /**
  * url
  * @static
  * @param  string                       $segments segments
  * @param  array                        $options options
  * @return Database\CollectionDelegator
  */
 public static function url($segments, $options = array())
 {
     $request = Router::getInstance()->request;
     $options['X-App-Id'] = Context::getKey()->app_id;
     $options['X-App-Key'] = Context::getKey()->key;
     $segments .= '?' . http_build_query($options);
     return $request->getUrl() . $request->getScriptName() . '/' . $segments;
 }
Exemple #6
0
 public static function getInstance()
 {
     $app_key = Context::getKey();
     if (!static::$instance && $app_key) {
         static::$instance = new static($app_key->app->secret, $app_key->app_id);
     }
     return static::$instance;
 }
Exemple #7
0
 public function testTrustedCanUpdateRole()
 {
     Context::setTrusted(true);
     $auth = Auth::where('email', "*****@*****.**")->first();
     $auth->role = "admin";
     $auth->setTrustedAction(true);
     $auth->save();
     $this->assertTrue($auth->role == "admin");
 }
 public function notify()
 {
     if (!(Context::getKey()->isServer() && Request::header('X-Scheduled-Task'))) {
         throw new ForbiddenException("Need a 'device' key to perform this action.");
     }
     $notifier = new PushNotification\Notifier();
     $messages = Model\App::collection('push_messages')->where('status', Model\PushMessage::STATUS_QUEUE);
     return $notifier->push_messages($messages);
 }
Exemple #9
0
 public function beforeSave()
 {
     if (!$this->getAttribute('_id')) {
         if (!Context::getKey()->isServer()) {
             throw new ForbiddenException("Need a 'server' key to perform this action.");
         }
         if (!$this->getAttribute('message')) {
             throw new InternalException("Can't create PushMessage: 'message' is required.");
         }
         $this->setAttribute('status', self::STATUS_QUEUE);
         $this->setAttribute('devices', 0);
         $this->setAttribute('failure', 0);
     }
     parent::beforeSave();
 }
Exemple #10
0
 public function getCommand()
 {
     $shortcuts = array('hourly' => '0 * * * *', 'daily' => '0 0 * * *', 'monthly' => '0 0 1 * *', 'weekly' => '0 0 * * 0');
     $schedule = preg_match('/[a-z]/', $this->schedule) ? $shortcuts[$this->schedule] : $this->schedule;
     $protocol = isset($_SERVER['HTTPS']) && !empty($_SERVER['HTTPS']) ? 'https' : 'http';
     // $public_url = $protocol . '://' . $_SERVER['SERVER_NAME'] . ':' . $_SERVER['SERVER_PORT'] . $_SERVER['SCRIPT_NAME'] . '/' . $this->task;
     $public_url = $protocol . '://' . $_SERVER['SERVER_NAME'] . $_SERVER['SCRIPT_NAME'] . '/' . $this->task;
     // retrieve server key to allow calls from crontab.
     $server_key = Context::getAppKeys(AppKey::TYPE_SERVER)->first();
     $curl_headers = "-H 'X-App-Id: {$server_key->app_id}' ";
     $curl_headers .= "-H 'X-App-Key: {$server_key->key}' ";
     $curl_headers .= "-H 'X-Scheduled-Task: yes' ";
     // Output the response to application log file
     $app = \Slim\Slim::getInstance();
     $output_file = $app->log->getWriter()->getFilePath();
     // Redirect stderr and stdout to file
     return $schedule . ' ' . "curl -XGET {$curl_headers} '{$public_url}' &> " . $output_file;
 }
Exemple #11
0
 public function call()
 {
     $app = $this->app;
     $app_key = Context::getKey();
     //
     // TODO: need a way to enable/disable logs for production use
     //
     // Log all queries
     $dispatcher = \Hook\Model\Collection::getEventDispatcher();
     $dispatcher->listen('illuminate.query', function ($query, $bindings, $time, $name) use(&$app) {
         $data = compact('bindings', 'time', 'name');
         // Format binding data for sql insertion
         foreach ($bindings as $i => $binding) {
             if ($binding instanceof \DateTime) {
                 $bindings[$i] = $binding->format('\'Y-m-d H:i:s\'');
             } else {
                 if (is_string($binding)) {
                     $bindings[$i] = "'{$binding}'";
                 }
             }
         }
         // Insert bindings into query
         $query = str_replace(array('%', '?'), array('%%', '%s'), $query);
         $query = vsprintf($query, $bindings);
         \Logger::debug($query);
     });
     if (!$app->request->isOptions() && $app_key) {
         // set application log writer for this app
         $log_file = storage_dir() . 'logs.txt';
         $app->log->setWriter(new LogWriter($log_file));
         // disable log if storage directory doesn't exists.
         // maybe we're on a readonly filesystem
         $app->log->setEnabled(is_writable($log_file));
         if (strpos($app->request->getPath(), "/apps/") === false) {
             $app->log->info($app->request->getIp() . ' - [' . date('d-m-Y H:i:s') . '] ' . $app->request->getMethod() . ' ' . $app->request->getResourceUri());
             $app->log->info('Params: ' . json_encode($app->request->params()));
         }
     }
     return $this->next->call();
 }
Exemple #12
0
 public static function form()
 {
     $args = func_get_args();
     $options = array_pop($args);
     // use empty string as default action
     if (!isset($options['hash']['action'])) {
         $options['hash']['action'] = "";
     }
     // use GET method as default
     if (!isset($options['hash']['method'])) {
         $options['hash']['method'] = 'get';
     }
     // evaluate action url
     $app_key = \Hook\Application\Context::getKey();
     $action_url = parse_url($options['hash']['action']);
     if (!isset($action_url['query'])) {
         $action_url['query'] = 'X-App-Id=' . $app_key->app_id . '&X-App-Key=' . $app_key->key;
     }
     $options['hash']['action'] = unparse_url($action_url);
     $html = '<form' . html_attributes($options['hash']) . '>' . "\n" . $options['fn']() . '</form>';
     return $html;
 }
Exemple #13
0
 public static function isAllowedIP()
 {
     $allowed = false;
     $allowed_ip_addresses = Context::config('allowed_ip_addresses');
     if ($allowed_ip_addresses && !empty($allowed_ip_addresses)) {
         $allowed = in_array("*", $allowed_ip_addresses) || in_array(Request::ip(), $allowed_ip_addresses);
     }
     return $allowed;
 }
Exemple #14
0
 public function delete($name, $_id = null)
 {
     $collection = Model\App::collection($name);
     $success = false;
     // trusted context:
     // run a real truncate statement if performing a delete
     if (Context::isTrusted() && $_id == null && count(Input::get('q')) == 0) {
         $success = $collection->truncate();
     } else {
         // untrusted context:
         // remove a single row, or the items from a filter in
         $query = $_id ? $collection->find($_id) : $collection->filter(Input::get('q'));
         $success = $query->delete();
     }
     return array('success' => $success);
 }
Exemple #15
0
 /**
  * migrate
  *
  * @param Hook\Model\Collection $model
  * @param array $collection_config
  *
  * @return bool
  */
 public function migrate($model, $collection_config, $is_dynamic = false)
 {
     $that = $this;
     $result = false;
     $connection = $model->getConnectionResolver()->connection();
     // Ignore NoSQL databases.
     if (!$connection->getPdo()) {
         return;
     }
     // Get modified Schema\Grammar for hook features.
     $connection->setSchemaGrammar($this->getSchemaGrammar($connection));
     // Set custom blueprint resolver
     $builder = $connection->getSchemaBuilder();
     $builder->blueprintResolver(function ($table, $callback) {
         return new \Hook\Database\Schema\Blueprint($table, $callback);
     });
     $table = $model->getTable();
     $table_schema = Cache::get($table);
     $table_prefix = Context::getPrefix();
     $collection_config = $this->sanitizeConfigs($table, $collection_config, $is_dynamic);
     $is_creating = !$builder->hasTable($table);
     if (!empty($collection_config['attributes']) || !empty($collection_config['relationships'])) {
         $migrate = function ($t) use($that, &$table, &$table_prefix, &$builder, &$is_creating, &$table_schema, $collection_config, &$result) {
             $table_columns = array('created_at', 'updated_at', 'deleted_at');
             if ($is_creating) {
                 $that->createCollection($t);
             } else {
                 $table_columns = array_merge($table_columns, $builder->getColumnListing($table));
             }
             foreach ($collection_config['attributes'] as $attribute) {
                 if (!isset($attribute['name'])) {
                     throw new MethodFailureException('invalid_schema');
                 }
                 $field_name = strtolower(array_remove($attribute, 'name'));
                 $type = camel_case(array_remove($attribute, 'type') ?: 'string');
                 $default = array_remove($attribute, 'default');
                 $index = array_remove($attribute, 'index');
                 $unique = array_remove($attribute, 'unique') || $index == 'unique';
                 $required = array_remove($attribute, 'required');
                 // Skip if column already exists
                 // TODO: deprecate strtolower
                 if (in_array($field_name, array_map('strtolower', $table_columns))) {
                     continue;
                 }
                 // include field_name to list of collection columns
                 array_push($table_columns, $field_name);
                 if (count($attribute) > 0) {
                     // the remaining attributes on field definition are
                     // the data-type related collection_config, such as 'length',
                     // 'allowed', 'total', 'places', etc.
                     $column = $t->newColumn($type, $field_name, $attribute);
                 } else {
                     $column = $t->{$type}($field_name);
                 }
                 // apply default value
                 if ($default !== NULL) {
                     $required = true;
                     $column->default($default);
                 }
                 // spatial indexes are NOT NULL by default
                 $nullable = !$required && $type !== 'point';
                 // columns are nullable unless specified as 'required'
                 if ($nullable) {
                     $column->nullable();
                 }
                 if ($index == 'spatial') {
                     // apply geospatial index, only MyISAM
                     $t->spatialIndex($field_name);
                 } else {
                     if ($index && !$unique) {
                         // apply index if specified
                         $column->index();
                     }
                 }
                 if ($unique) {
                     // apply unique index if specified
                     $unique_fields = !is_array($unique) ? $field_name : array_unique(array_merge(array($field_name), $unique));
                     $t->unique($unique_fields);
                 }
             }
             // onDelete / onUpdate actions
             $actions = array('restrict' => "RESTRICT", 'cascade' => "CASCADE", 'none' => "NO ACTION", 'null' => "SET NULL", 'default' => "SET DEFAULT");
             if (!isset($collection_config['relationships'])) {
                 $collection_config['relationships'] = array();
             }
             foreach ($collection_config['relationships'] as $relation => $fields) {
                 // only create field on belongs_to relationships
                 if ($relation == "belongs_to") {
                     foreach ($fields as $field => $config) {
                         // create 'foreign_key' column on collection.
                         if (!in_array($config['foreign_key'], array_map('strtolower', $table_columns))) {
                             $column = $t->unsignedInteger($config['foreign_key']);
                             $column->nullable();
                         }
                         // create collection if it doesn't exists
                         if (!$builder->hasTable($config['collection'])) {
                             $builder->create($table_prefix . $config['collection'], function ($t) use($that) {
                                 $that->createCollection($t);
                             });
                         }
                         // //
                         // // create foreign key on database
                         // //
                         // // TODO: list foreign keys already defined before
                         // // trying to create it.
                         // //
                         // $t->foreign($config['foreign_key'])
                         //     ->references($config['primary_key'])
                         //     ->on($table_prefix . $config['collection'])
                         //     ->onDelete($actions[$config['on_delete']])
                         //     ->onUpdate($actions[$config['on_update']]);
                     }
                 }
             }
             // return true when any modification is present
             if (count($t->getColumns()) > 0 || count($t->getCommands()) > 0) {
                 $result = true;
             }
         };
         if ($is_creating) {
             // CREATE TABLE statement
             $builder->create($table_prefix . $table, $migrate);
         } else {
             // ALTER TABLE statement.
             $builder->table($table_prefix . $table, $migrate);
         }
     }
     // merge previous schema with new one.
     $table_schema = $this->mergeSchema($table_schema, $collection_config, $is_dynamic);
     // Cache table schema for further reference
     Cache::forever($table, $table_schema);
     $app_collections = Cache::get('app_collections');
     Cache::forever('app_collections', array_unique(array_merge($app_collections, array($table))));
     return $result;
 }
Exemple #16
0
 protected function isUpdateAllowed()
 {
     //
     // Allow updates only when:
     // - Is using 'server' context.
     // - Is using 'commandline' context.
     // - Authenticated user is updating it's own data
     //
     return Context::isTrusted() || Role::isAllowed($this, 'update') || $this->isAuthenticated();
 }
Exemple #17
0
 public static function setKey($app_key)
 {
     static::$app_key = $app_key;
     Context::setPrefix($app_key->app->_id);
     return static::$app_key;
 }
Exemple #18
0
 /**
  * Reset auth password
  */
 public function resetPassword()
 {
     $data = $this->getData();
     if (!isset($data['token']) === 0) {
         throw new Exceptions\BadRequestException("you must provide a 'token'.");
     }
     if (!isset($data['password']) || strlen($data['password']) === 0) {
         throw new Exceptions\BadRequestException("you must provide a valid 'password'.");
     }
     // Set trusted context to update auths row
     Context::setTrusted(true);
     $auth = Auth::where(Auth::FORGOT_PASSWORD_FIELD, $data['token'])->first();
     if ($auth && $auth->resetPassword($data['password'])) {
         return array('success' => true);
     } else {
         throw new Exceptions\UnauthorizedException("invalid_token");
     }
 }
Exemple #19
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();
     }
 }
Exemple #20
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;
 }
Exemple #21
0
 public static function current()
 {
     return Context::getKey();
 }
Exemple #22
0
 /**
  * compile
  * Compile module code
  * @param array options
  * @return mixed
  */
 public function compile($options = array())
 {
     $app = Slim\Slim::getInstance();
     $extension = '.' . pathinfo($this->name, PATHINFO_EXTENSION);
     $name = basename($this->name, $extension);
     if ($this->type == static::TYPE_OBSERVER || $this->type == static::TYPE_CHANNEL || $this->type == static::TYPE_ROUTE) {
         //
         // Expose handy aliases for modules
         //
         $aliases = '';
         $aliases .= 'use Hook\\Application\\Context;';
         $aliases .= 'use Hook\\Model\\Module;';
         $aliases .= 'use Hook\\Model\\File;';
         $aliases .= 'use Hook\\Model\\Auth;';
         $aliases .= 'use Hook\\Model\\AuthToken;';
         $aliases .= 'use Hook\\Model\\Collection;';
         $aliases .= 'use Hook\\Cache\\Cache;';
         $aliases .= 'use Hook\\Logger\\Logger;';
         if ($this->type == self::TYPE_OBSERVER || $this->type == self::TYPE_CHANNEL) {
             // Prevent name conflict by using unique class names for custom modules
             $klass = 'CustomModule' . uniqid();
             eval($aliases . preg_replace('/class ([^\\ {]+)/', 'class ' . $klass, $this->code, 1));
             if (class_exists($klass)) {
                 // Return module instance for registering on model.
                 return new $klass();
             } else {
                 throw new Exceptions\MethodFailureException("Module '{$name}.php' must define a class.");
             }
         } elseif ($this->type == self::TYPE_ROUTE) {
             try {
                 eval($aliases . $this->code);
             } catch (\Exception $e) {
                 $message = $this->name . ': ' . $e->getMessage();
                 $app->log->info($message);
                 $app->response->headers->set('X-Error-' . uniqid(), $message);
                 file_put_contents('php://stderr', $message);
             }
         }
     } elseif ($this->type == static::TYPE_TEMPLATE) {
         $app->view->setTemplateString($this->code);
         // Expose app_key to compiled templates.
         // Mainly used to generate server-side routes when
         // `Hook\View\Helper::link_to` isn't capable to handle it
         //
         // TODO: remove this after implementing issue #131
         // (https://github.com/doubleleft/hook/issues/131)
         $options['app_key'] = \Hook\Application\Context::getKey();
         return $app->view->render($this->name, $options);
     }
 }
Exemple #23
0
 /**
  * Create a new Collection instance. No database operations here.
  *
  * @param  array             $attributes attributes
  * @return \Model\Collection
  */
 public function create_new(array $attributes = array())
 {
     $instance = null;
     if (!$this->is_collection) {
         $instance = new self::$custom_collections[$this->name]();
     } else {
         $instance = new Collection(array('table_name' => $this->name));
     }
     $instance->fill($attributes);
     // Fill '_id' if it's provided and in a trusted context
     if (isset($attributes['_id']) && Context::isTrusted()) {
         $instance->_id = $attributes['_id'];
     }
     return $instance;
 }