function Users_after_Q_reroute($params, &$stop_dispatch) { $uri = Q_Dispatcher::uri(); $app = Q_Config::expect('Q', 'app'); $ma = $uri->module . '/' . $uri->action; $requireLogin = Q_Config::get('Users', 'requireLogin', array()); if (!isset($requireLogin[$ma])) { return; // We don't have to require login here } $user = Users::loggedInUser(); if ($requireLogin[$ma] === true and !$user) { // require login } else { if ($requireLogin[$ma] === 'facebook' and !Users::facebook($app)) { // require facebook } else { return; // We don't have to require login here } } $redirect_action = Q_Config::get('Users', 'uris', "{$app}/login", "{$app}/welcome"); if ($redirect and $ma != $redirect_action) { Q_Response::redirect($redirect_action); $stop_dispatch = true; return; } }
/** * We are going to implement a subset of the OAuth 1.0a functionality for now, * and later we can expand it to match the full OAuth specification. */ function Users_authorize_response() { if (Q_Response::getErrors()) { Q_Dispatcher::showErrors(); } $response_type = 'token'; $token_type = 'bearer'; $client_id = $_REQUEST['client_id']; $state = $_REQUEST['state']; $skip = Q::ifset($_REQUEST, 'skip', false); $scope = Users_OAuth::requestedScope(true, $scopes); $client = Users_User::fetch($client_id, true); if (!$client) { throw new Q_Exception_MissingRow(array('table' => 'client user', 'criteria' => "id = '{$client_id}'"), 'client_id'); } if (empty($client->url)) { throw new Q_Exception("Client app needs to register url", 'client_id'); } $redirect_uri = Q::ifset($_REQUEST, 'redirect_uri', $client->url); $user = Users::loggedInUser(); $oa = null; if (isset(Users::$cache['oAuth'])) { $oa = Users::$cache['oAuth']; } else { if ($user) { $oa = new Users_OAuth(); $oa->client_id = $client_id; $oa->userId = $user->id; $oa->state = $state; $oa = $oa->retrieve(); } } $remaining = $scope; if ($oa and $oa->wasRetrieved()) { // User is logged in and already has a token for this client_id and state $paths = Q_Config::get('Users', 'authorize', 'clients', Q::app(), 'redirectPaths', false); $path = substr($redirect_uri, strlen($client->url) + 1); $p = array('response_type' => $response_type, 'token_type' => $token_type, 'access_token' => $oa->access_token, 'expires_in' => $oa->token_expires_seconds, 'scope' => implode(' ', $scope), 'state' => $oa->state); $p = Q_Utils::sign($p, 'Q.Users.oAuth'); // the redirect uri could be a native app url scheme $s = strpos($redirect_uri, '#') === false ? '#' : '&'; $redirect_uri = Q_Uri::from($redirect_uri . $s . http_build_query($p), false)->toUrl(); if (!Q::startsWith($redirect_uri, $client->url) or is_array($paths) and !in_array($path, $paths)) { throw new Users_Exception_Redirect(array('uri' => $redirect_uri)); } Q_Response::redirect($redirect_uri); return false; } $terms_label = Users::termsLabel('authorize'); Q_Response::setScriptData('Q.Users.authorize', compact('client_id', 'redirect_uri', 'scope', 'scopes', 'remaining', 'state', 'response_type', 'skip')); $content = Q::view('Users/content/authorize.php', compact('client', 'user', 'redirect_uri', 'scope', 'scopes', 'remaining', 'state', 'terms_label', 'response_type', 'skip')); Q_Response::setSlot('content', $content); Q_Response::setSlot('column0', $content); return true; }
function Shipping_welcome_response_content($params) { // Do controller stuff here. Prepare variables $tabs = array("foo" => "bar"); $description = "this is a description"; if ($user = Users::loggedInUser()) { Q_Response::redirect('Shipping/shipment'); return ''; } return Q::view('Shipping/content/welcome.php', compact('tabs', 'description')); }
function Streams_invited_response() { if (!($token = Q_Dispatcher::uri()->token)) { throw new Q_Exception_RequiredField(array('field' => 'token'), 'token'); } if (!($invite = Streams_Invite::fromToken($token))) { throw new Q_Exception_MissingRow(array('table' => 'invite', 'criteria' => "token: {$token}"), 'token'); } Users_User::fetch($invite->userId, true)->setVerified(); Q_Response::redirect($invite->appUrl . "?" . http_build_query(array('Q.Streams.token' => $token), null, '&')); }
function Broadcast_main_response_content() { Q_Response::addScript('plugins/Broadcast/js/Broadcast.js'); $user = Users::loggedInUser(true); $stream = new Streams_Stream(); $stream->publisherId = $user->id; $stream->name = 'Broadcast/main'; if (!$stream->retrieve()) { $stream->type = 'Broadcast'; $stream->title = "Main broadcast stream"; $stream->content = "Whatever you post to this stream will be syndicated by everyone who has opted in."; $stream->save(); } Q_Response::redirect('Broadcast/stream publisherId=' . $stream->publisherId . ' name=Broadcast/main'); }
function Users_activate_response_content() { $email = $mobile = $type = $user = $emailAddress = $mobileNumber = null; extract(Users::$cache, EXTR_IF_EXISTS); $complete = false; if ($user and !empty($user->passphraseHash)) { if ($emailAddress and $user->emailAddress == $emailAddress) { $complete = true; } else { if ($mobileNumber and $user->mobileNumber = $mobileNumber) { $complete = true; } } } if (!empty(Users::$cache['success'])) { $app = Q_Config::expect('Q', 'app'); $successUrl = Q_Config::get('Users', 'uris', "{$app}/successUrl", "{$app}/home"); if (Q_Request::method() === 'POST') { if ($qs = $_SERVER['QUERY_STRING']) { $qs = "&{$qs}"; } Q_Response::redirect(Q_Config::get('Users', 'uris', "{$app}/afterActivate", $successUrl) . '?Q.fromSuccess=Users/activate' . $qs); return true; } } $view = Q_Config::get('Users', 'activateView', 'Users/content/activate.php'); $t = $email ? 'e' : 'm'; $identifier = $email ? $emailAddress : $mobileNumber; // Generate 10 passphrase suggestions $suggestions = array(); $arr = (include USERS_PLUGIN_FILES_DIR . DS . 'Users' . DS . 'passphrases.php'); for ($i = 0; $i < 10; ++$i) { $pre1 = $arr['pre'][mt_rand(0, count($arr['pre']) - 1)]; $noun1 = $arr['nouns'][mt_rand(0, count($arr['nouns']) - 1)]; $verb = $arr['verbs'][mt_rand(0, count($arr['verbs']) - 1)]; $pre2 = $arr['pre'][mt_rand(0, count($arr['pre']) - 1)]; $adj = $arr['adjectives'][mt_rand(0, count($arr['adjectives']) - 1)]; $noun2 = $arr['nouns'][mt_rand(0, count($arr['nouns']) - 1)]; //$suggestions[] = strtolower("$pre1 $noun1 $verb $pre2 $adj $noun2"); $suggestions[] = strtolower("{$pre1} {$noun1} {$verb} {$pre2} {$noun2}"); } $verb_ue = urlencode($arr['verbs'][mt_rand() % count($arr['verbs'])]); $noun_ue = urlencode($arr['nouns'][mt_rand() % count($arr['nouns'])]); $code = Q::ifset($_REQUEST['code']); Q_Response::addScriptLine("Q.onReady.set(function () {\n\t\tif (Q.Notice) {\n\t\t\tQ.Notice.hide('Users/email');\n\t\t\tQ.Notice.hide('Users/mobile');\n\t\t}\n\t});"); // shh! not while I'm activating! lol return Q::view($view, compact('identifier', 'type', 'user', 'code', 'suggestions', 'verb_ue', 'noun_ue', 't', 'app', 'home', 'complete')); }
/** * We are going to implement a subset of the OAuth 1.0a functionality for now, * and later we can expand it to match the full OAuth specification. */ function Users_authorize_response() { if (Q_Response::getErrors()) { Q_Dispatcher::showErrors(); } $client_id = $_REQUEST['client_id']; $redirect_url = $_REQUEST['redirect_uri']; $state = $_REQUEST['state']; $client = Users_User::fetch($client_id); if (!$client) { throw new Q_Exception_MissingRow(array('table' => 'user', 'criteria' => "id = '{$client_id}'"), 'client_id'); } if (empty($client->url)) { throw new Q_Exception("Client app needs to register url", 'client_id'); } if (substr($redirect_url, 0, strlen($client->url)) !== $client->url) { throw new Q_Exception_WrongValue(array('field' => 'redirect_uri', 'range' => "a url prefixed by client user's url")); } $user = Users::loggedInUser(); $oa = null; if (isset(Users::$cache['oAuth'])) { $oa = Users::$cache['oAuth']; } else { if ($user) { $oa = new Users_OAuth(); $oa->client_id = $client_id; $oa->userId = $user->id; $oa->state = $state; $oa->retrieve(); } } if ($oa and $oa->wasRetrieved()) { // User is logged in and already has a token for this client_id and state $separator = strpos($redirect_url, '?') === false ? '?' : '&'; $url = $redirect_url . $separator . http_build_query(array('access_token' => $oa->access_token, 'token_type' => 'bearer', 'expires_in' => $oa->token_expires_seconds, 'scope' => 'user', 'state' => $oa->state)); Q_Response::redirect(Q_Uri::from($url, false)); return false; } $terms_label = Users::termsLabel('authorize'); $content = Q::view('Users/content/authorize.php', compact('client', 'redirect_url', 'user', 'state', 'terms_label')); Q_Response::setSlot('content', $content); Q_Response::setSlot('column0', $content); return true; }
/** * Renders an import tool * @param $options * An associative array of parameters, which can include: * "provider" => Required. The provider from which we are importing. * @return {string} */ function Users_importContacts_tool($options) { $provider = $options['provider']; ob_start(); try { if (!($client = Users::oAuth($provider))) { throw new Users_Exception_NotAuthorized(); } Q::event('Users/importContacts/providers/' . $provider, array('client' => $client)); } catch (Users_Exception_OAuthTokenInvalid $ex) { #TODO: Log something to error log? Users::oAuthClear($provider); Q_Response::redirect(Q_Uri::url(Q_Request::url(true))); return false; } catch (Zend_Oauth_Exception $ex) { #TODO: Show a nicely-formatted message and close the pop-up echo 'Could not import contacts: ' . $ex->getMessage(); } $out = ob_get_contents(); ob_clean(); Q_Response::output($out, true); return true; }
/** * Default Q/response handler. * 1. Gets some slots, depending on what was requested. * 2. Renders them in a layout * The layout expects "title", "dashboard" and "contents" slots to be filled. */ function Q_response($params) { extract($params); /** * @var Exception $exception * @var array $errors */ if (empty($errors)) { $errors = Q_Response::getErrors(); } if (!empty($_GET['Q_ct'])) { Q_Response::setCookie('Q_ct', $_GET['Q_ct']); } // If output is set, use that $output = Q_Response::output(); if (isset($output)) { if ($output === true) { return; } if (is_string($output)) { echo $output; } return; } // Redirect to success page, if requested. $isAjax = Q_Request::isAjax(); if (empty($errors) and empty($exception)) { if (!$isAjax and null !== Q_Request::special('onSuccess', null)) { $onSuccess = Q_Request::special('onSuccess', null); if (Q_Config::get('Q', 'response', 'onSuccessShowFrom', true)) { $onSuccess = Q_Uri::url($onSuccess . '?Q.fromSuccess=' . Q_Dispatcher::uri()); } Q_Response::redirect($onSuccess); return; } } // Get the requested module $uri = Q_Dispatcher::uri(); if (!isset($module)) { $module = $uri->module; if (!isset($module)) { $module = 'Q'; Q_Dispatcher::uri()->module = 'Q'; } } if (!$isAjax || Q_Request::isLoadExtras()) { Q::event('Q/responseExtras', array(), 'before'); } // Get the main module (the app) $app = Q_Config::expect('Q', 'app'); $action = $uri->action; if (Q::canHandle("{$module}/{$action}/response")) { if (false === Q::event("{$module}/{$action}/response") and !$isAjax) { return; } } $slotNames = Q_Request::slotNames(true); $idPrefixes = array(); if ($temp = Q_Request::special('idPrefixes', null)) { foreach (explode(',', $temp) as $i => $prefix) { if (!isset($slotNames[$i])) { throw new Q_Exception("More id prefixes than slot names", "Q.idPrefixes"); } $idPrefixes[$slotNames[$i]] = $prefix; } } // What to do if this is an AJAX request if ($isAjax) { $to_encode = array(); if (Q_Response::$redirected) { // We already called Q_Response::redirect $to_encode['redirect']['url'] = Q_Uri::url(Q_Response::$redirected); try { $to_encode['redirect']['uri'] = Q_Uri::from(Q_Response::$redirected)->toArray(); } catch (Exception $e) { // couldn't get internal URI } } else { if (is_array($slotNames)) { foreach ($slotNames as $slotName) { Q_Response::fillSlot($slotName, 'default', Q::ifset($idPrefixes, $slotName, null)); } // Go through the slots again, because other handlers may have overwritten // their contents using Q_Response::setSlot() foreach ($slotNames as $sn) { Q_Response::fillSlot($sn, 'default', Q::ifset($idPrefixes, $slotName, null)); } if (Q_Response::$redirected) { // While rendering the slots we called Q_Redirect $to_encode['redirect']['url'] = Q_Uri::url(Q_Response::$redirected); try { $to_encode['redirect']['uri'] = Q_Uri::from(Q_Response::$redirected)->toArray(); } catch (Exception $e) { // couldn't get internal URI } } else { if (Q_Request::isLoadExtras()) { $to_encode['slots'] = Q_Response::slots(true); // add stylesheets, stylesinline, scripts, scriptlines, scriptdata, templates foreach (array_merge(array(''), $slotNames) as $slotName) { $temp = Q_Response::stylesheetsArray($slotName); if ($temp) { $to_encode['stylesheets'][$slotName] = $temp; } $temp = Q_Response::stylesInline($slotName); if ($temp) { $to_encode['stylesInline'][$slotName] = $temp; } $temp = Q_Response::scriptsArray($slotName); if ($temp) { $to_encode['scripts'][$slotName] = $temp; } $temp = Q_Response::scriptLines($slotName, true, "\n", false); if ($temp) { $to_encode['scriptLines'][$slotName] = $temp; } $temp = Q_Response::scriptData($slotName); if ($temp) { $to_encode['scriptData'][$slotName] = $temp; } $temp = Q_Response::templateData($slotName); if ($temp) { $to_encode['templates'][$slotName] = $temp; } } } else { $to_encode['slots'] = Q_Response::slots(true); // add stylesinline, scriptlines, scriptdata, templates foreach (array_merge(array(''), $slotNames) as $slotName) { $temp = Q_Response::stylesInline($slotName); if ($temp) { $to_encode['stylesInline'][$slotName] = $temp; } $temp = Q_Response::scriptData($slotName); if ($temp) { $to_encode['scriptData'][$slotName] = $temp; } $temp = Q_Response::scriptLines($slotName, true, "\n", false); if ($temp) { $to_encode['scriptLines'][$slotName] = $temp; } } } } } } $to_encode['timestamp'] = microtime(true); $echo = Q_Request::contentToEcho(); if (isset($echo)) { $to_encode['echo'] = $echo; } $json = Q::json_encode(Q::cutoff($to_encode)); $callback = Q_Request::callback(); switch (strtolower($isAjax)) { case 'iframe': if (!Q_Response::$batch) { header("Content-type: text/html"); } echo <<<EOT <!doctype html><html lang=en> <head><meta charset=utf-8><title>Q Result</title></head> <body> <script type="text/javascript"> window.result = function () { return {$json} }; </script> </body> </html> EOT; break; case 'json': default: if (!Q_Response::$batch) { header("Content-type: " . ($callback ? "application/javascript" : "application/json")); } echo $callback ? "{$callback}({$json})" : $json; } return; } // If this is a request for a regular webpage, // fill the usual slots and render a layout. if (Q_Response::$redirected) { return; // If already set a redirect header, simply return -- no reason to output all this HTML } static $added_Q_init = false; if (!$added_Q_init) { Q_Response::addScriptLine("\n// Now, initialize Q\nQ.init();\n", null, 'Q'); $added_Q_init = true; } // Get all the usual slots for a webpage $slots = array(); foreach ($slotNames as $sn) { Q_Response::fillSlot($sn, 'default', Q::ifset($idPrefixes, $sn, null)); } // Go through the slots again, because other handlers may have overwritten // their contents using Q_Response::setSlot() foreach ($slotNames as $sn) { Q_Response::fillSlot($sn, 'default', Q::ifset($idPrefixes, $sn, null)); } $output = Q_Response::output(); if (isset($output)) { if ($output === true) { return; } if (is_string($output)) { echo $output; } return; } if (!$isAjax or Q_Request::isLoadExtras()) { Q::event('Q/responseExtras', array(), 'after'); } $slots = Q_Response::slots(false); // Render a full HTML layout $layout_view = Q_Response::layoutView(); echo Q::view($layout_view, $slots); }