Ejemplo n.º 1
0
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;
    }
}
Ejemplo n.º 2
0
function Users_activate_validate()
{
    $uri = Q_Dispatcher::uri();
    $emailAddress = Q::ifset($_REQUEST, 'e', $uri->emailAddress);
    $mobileNumber = Q::ifset($_REQUEST, 'm', $uri->mobileNumber);
    if ($emailAddress && !Q_Valid::email($emailAddress, $e_normalized, array('no_ip' => 'false'))) {
        throw new Q_Exception_WrongValue(array('field' => 'email', 'range' => 'a valid email address'), 'emailAddress');
    }
    if ($mobileNumber && !Q_Valid::phone($mobileNumber, $m_normalized)) {
        throw new Q_Exception_WrongValue(array('field' => 'mobile phone', 'range' => 'a valid phone number'), 'mobileNumber');
    }
    if ($emailAddress or $mobileNumber) {
        if (empty($_REQUEST['code'])) {
            throw new Q_Exception("The activation code is missing");
        }
    } else {
        throw new Q_Exception("The contact information is missing");
    }
    if (!empty($e_normalized)) {
        Users::$cache['emailAddress'] = $e_normalized;
    }
    if (!empty($m_normalized)) {
        Users::$cache['mobileNumber'] = $m_normalized;
    }
}
Ejemplo n.º 3
0
function Overlay_before_Q_responseExtras()
{
    $app = Q_Config::expect('Q', 'app');
    Q_Response::addStylesheet('plugins/Q/css/Q.css');
    Q_Response::addStylesheet('css/Overlay.css', '@end');
    Q_Response::addStylesheet('http://fonts.googleapis.com/css?family=Open+Sans:400italic,400,300,700');
    if (Q_Config::get('Q', 'firebug', false)) {
        Q_Response::addScript("https://getfirebug.com/firebug-lite-debug.js");
    }
    Q_Response::addScript('js/Overlay.js');
    Q_Response::setMeta("title", "Customize My Pic!");
    Q_Response::setMeta("description", "Make a statement on Facebook by customizing your profile picture, even from your smartphone.");
    Q_Response::setMeta("image", Q_Html::themedUrl('img/icon/icon.png'));
    if (Q_Request::isIE()) {
        header("X-UA-Compatible", "IE=edge");
    }
    header('Vary: User-Agent');
    // running an event for loading action-specific extras (if there are any)
    $uri = Q_Dispatcher::uri();
    $module = $uri->module;
    $action = $uri->action;
    $event = "{$module}/{$action}/response/responseExtras";
    if (Q::canHandle($event)) {
        Q::event($event);
    }
}
Ejemplo n.º 4
0
/**
 * Override Q/noModule handler.
 * just goes on to render our app's response,
 * which will echo a 404 view.
 */
function Q_noModule($params)
{
    header("HTTP/1.0 404 Not Found");
    Q_Dispatcher::uri()->module = Q_Config::expect('Q', 'app');
    Q_Dispatcher::uri()->action = 'notFound';
    Q::event('Q/response', $params);
}
Ejemplo n.º 5
0
function Q_post($params)
{
    $uri = Q_Dispatcher::uri();
    $module = $uri->module;
    $action = $uri->action;
    if (!Q::canHandle("{$module}/{$action}/post")) {
        throw new Q_Exception_MethodNotSupported(array('method' => 'POST'));
    }
    if (isset($_SERVER['CONTENT_LENGTH'])) {
        $contentLength = (int) $_SERVER['CONTENT_LENGTH'];
        foreach (array('upload_max_filesize', 'post_max_size') as $name) {
            $value = ini_get($name);
            switch (substr($value, -1)) {
                case 'K':
                    $value *= 1024;
                    break;
                case 'M':
                    $value *= 1024 * 1024;
                    break;
                case 'B':
                    $value *= 1024 * 1024 * 1024;
                    break;
            }
            if ($contentLength > $value) {
                throw new Q_Exception_ContentLength(array('contentLength' => $contentLength, 'exceeds' => $name));
            }
        }
    }
    return Q::event("{$module}/{$action}/post", $params);
}
Ejemplo n.º 6
0
/**
 * Tool for admins to edit the url, title, keywords, description of the current page
 * @class Websites seo
 * @constructor
 * @param {Object} [$options] Options for the tool
 * @param {String} [$options.skipIfNotAuthorized=true] Whether to skip rendering the contents of the tool if the logged-in user is not authorized to edit the SEO information for this page.
 */
function Websites_seo_tool($options)
{
    $skipIfNotAuthorized = Q::ifset($options, 'skipIfNotAuthorized', true);
    if ($skipIfNotAuthorized) {
        $websitesUserId = Users::communityId();
        $sha1 = sha1(Q_Dispatcher::uri());
        $seoStreamName = "Websites/seo/{$sha1}";
        $stream = Streams::fetchOne(null, $websitesUserId, $seoStreamName);
        $user = Users::loggedInUser();
        if (!$user or $stream and !$stream->testWriteLevel('suggest')) {
            $options['skip'] = true;
        }
        if (!$stream and !Streams::isAuthorizedToCreate($user->id, $websitesUserId, 'Websites/seo')) {
            $options['skip'] = true;
        }
    }
    unset($options['skipIfNotAuthorized']);
    Q_Response::addStylesheet('plugins/Websites/css/Websites.css');
    Q_Response::addScript("plugins/Websites/js/Websites.js");
    Q_Response::setToolOptions($options);
    $user = Users::loggedInUser(false, false);
    $userId = $user ? $user->id : "";
    $communityId = Users::communityId();
    $sha1 = sha1(Q_Dispatcher::uri());
    $seoStreamName = "Websites/seo/{$sha1}";
    $streams = Streams::fetch($userId, $communityId, array("Websites/header", "Websites/title", "Websites/slogan", $seoStreamName));
    foreach ($streams as $name => $s) {
        if ($s) {
            $s->addPreloaded($userId);
        }
    }
}
Ejemplo n.º 7
0
function Q_validate($params)
{
    $uri = Q_Dispatcher::uri();
    $module = $uri->module;
    $action = $uri->action;
    if (!Q::canHandle("{$module}/{$action}/validate")) {
        return null;
    }
    return Q::event("{$module}/{$action}/validate", $params);
}
Ejemplo n.º 8
0
function Q_put($params)
{
    $uri = Q_Dispatcher::uri();
    $module = $uri->module;
    $action = $uri->action;
    if (!Q::canHandle("{$module}/{$action}/put")) {
        throw new Q_Exception_MethodNotSupported(array('method' => 'PUT'));
    }
    return Q::event("{$module}/{$action}/put", $params);
}
Ejemplo n.º 9
0
function Q_response_title()
{
    // The default title
    $title = Q_Config::get('Q', 'app', basename(APP_DIR));
    $action = Q_Dispatcher::uri()->action;
    if ($action) {
        $title .= ": {$action}";
    }
    return $title;
}
Ejemplo n.º 10
0
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, '&'));
}
Ejemplo n.º 11
0
function Q_delete($params)
{
    $uri = Q_Dispatcher::uri();
    $module = $uri->module;
    $action = $uri->action;
    if (!Q::canHandle("{$module}/{$action}/delete")) {
        throw new Q_Exception_MethodNotSupported(array('method' => 'DELETE'));
    }
    Q_Request::requireValidNonce();
    return Q::event("{$module}/{$action}/delete", $params);
}
Ejemplo n.º 12
0
/**
 * This is the default handler for the Q/responseExtras event.
 * It should not be invoked during AJAX requests, and especially
 * not during JSONP requests. It will output things like the nonce,
 * which prevents CSRF attacks, but is only supposed to be printed
 * on our webpages and not also given to anyone who does a JSONP request.
 */
function Q_before_Q_responseExtras()
{
    $app = Q_Config::expect('Q', 'app');
    $uri = Q_Dispatcher::uri();
    $url = Q_Request::url(true);
    $base_url = Q_Request::baseUrl();
    $ajax = Q_Request::isAjax();
    if (!$uri) {
        return;
    }
    $info = array('url' => $url, 'uriString' => (string) $uri);
    if ($uri) {
        $info['uri'] = $uri->toArray();
    }
    if (!$ajax) {
        $info = array_merge(array('app' => Q_Config::expect('Q', 'app')), $info, array('proxies' => Q_Config::get('Q', 'proxies', array()), 'baseUrl' => $base_url, 'proxyBaseUrl' => Q_Uri::url($base_url), 'proxyUrl' => Q_Uri::url($url), 'sessionName' => Q_Session::name(), 'nodeUrl' => Q_Utils::nodeUrl(), 'slotNames' => Q_Config::get("Q", "response", "slotNames", array('content', 'dashboard', 'title', 'notices'))));
    }
    foreach ($info as $k => $v) {
        Q_Response::setScriptData("Q.info.{$k}", $v);
    }
    if (!$ajax) {
        $uris = Q_Config::get('Q', 'javascript', 'uris', array());
        $urls = array();
        foreach ($uris as $u) {
            $urls["{$u}"] = Q_Uri::url("{$u}");
        }
        Q_Response::setScriptData('Q.urls', $urls);
    }
    // Export more variables to inline js
    $nonce = isset($_SESSION['Q']['nonce']) ? $_SESSION['Q']['nonce'] : null;
    if ($nonce) {
        Q_Response::setScriptData('Q.nonce', $nonce);
    }
    // Attach stylesheets and scripts
    foreach (Q_Config::get('Q', 'javascript', 'responseExtras', array()) as $src => $b) {
        if (!$b) {
            continue;
        }
        Q_Response::addScript($src);
    }
    foreach (Q_Config::get('Q', 'stylesheets', 'responseExtras', array()) as $src => $media) {
        if (!$media) {
            continue;
        }
        if ($media === true) {
            $media = 'screen,print';
        }
        Q_Response::addStylesheet($src, null, $media);
    }
}
Ejemplo n.º 13
0
function Q_response_content()
{
    $app = Q_Config::expect('Q', 'app');
    $url = Q_Request::url();
    $module = Q_Dispatcher::uri()->module;
    if (empty($module)) {
        return Q::event("{$app}/notFound/response/content");
    }
    $action = Q_Dispatcher::uri()->action;
    $event = "{$module}/{$action}/response/content";
    if (!Q::canHandle($event)) {
        return Q::event("{$app}/notFound/response/content");
    }
    // Go ahead and fire the event, returning the result.
    return Q::event($event);
}
Ejemplo n.º 14
0
function Q_response_content()
{
    $app = Q_Config::expect('Q', 'app');
    $url = Q_Request::url();
    $module = Q_Dispatcher::uri()->module;
    if (empty($module)) {
        return Q::event("{$app}/notFound/response/content");
    }
    $action = Q_Dispatcher::uri()->action;
    $event = "{$module}/{$action}/response/content";
    if (!Q::canHandle($event)) {
        return Q::event("{$app}/notFound/response/content");
    }
    Q_Response::setMeta('format-detection', 'telephone=no,date=no,address=no,email=no,url=no');
    // Go ahead and fire the event, returning the result.
    return Q::event($event);
}
Ejemplo n.º 15
0
function Users_activate_objects()
{
    $uri = Q_Dispatcher::uri();
    $email = null;
    $mobile = null;
    $user = null;
    $emailAddress = Q::ifset(Users::$cache, 'emailAddress', null);
    $mobileNumber = Q::ifset(Users::$cache, 'mobileNumber', null);
    if ($emailAddress) {
        $user = Users_activate_objects_email(Users::$cache['emailAddress'], $email);
        $type = 'email address';
    }
    if ($mobileNumber) {
        $user = Users_activate_objects_mobile($mobileNumber, $mobile);
        $type = 'mobile number';
    }
    Users::$cache = compact('user', 'email', 'mobile', 'type', 'emailAddress', 'mobileNumber');
}
Ejemplo n.º 16
0
function Websites_before_Q_responseExtras()
{
    $user = Users::loggedInUser(false, false);
    $userId = $user ? $user->id : "";
    $websitesUserId = Users::communityId();
    $sha1 = sha1(Q_Dispatcher::uri());
    $seoStreamName = "Websites/seo/{$sha1}";
    $stream = Streams::fetchOne($userId, $websitesUserId, $seoStreamName);
    if ($stream) {
        $fields = Q::take($stream->getAllAttributes(), array('keywords', 'description'));
        foreach ($fields as $k => $v) {
            Q_Response::setMeta($k, $v);
        }
        Q_Response::setSlot('title', $stream->getAttribute('title'));
    }
    Q_Response::setScriptData('Q.plugins.Websites.seoStreamName', $seoStreamName);
    Q_Response::setScriptData('Q.plugins.Websites.userId', Users::communityId());
    Q_Response::setScriptData('Q.plugins.Websites.seoReload', Q_Config::expect('Websites', 'seoReload'));
}
Ejemplo n.º 17
0
/**
 * Tool for admins to edit the url, title, keywords, description of the current page
 * @class Websites seo
 * @constructor
 * @param {Object} [$options] Options for the tool
 * @param {String} [$options.skipIfNotAuthorized=true] Whether to skip rendering the contents of the tool if the logged-in user is not authorized to edit the SEO information for this page.
 */
function Websites_seo_tool($options)
{
    $skipIfNotAuthorized = Q::ifset($options, 'skipIfNotAuthorized', true);
    if ($skipIfNotAuthorized) {
        $websitesUserId = Q_Config::expect("Websites", "user", "id");
        $sha1 = sha1(Q_Dispatcher::uri());
        $seoStreamName = "Websites/seo/{$sha1}";
        $stream = Streams::fetchOne(null, $websitesUserId, $seoStreamName);
        $user = Users::loggedInUser();
        if (!$user or $stream and !$stream->testWriteLevel('suggest')) {
            $options['skip'] = true;
        }
        if (!$stream and !Streams::isAuthorizedToCreate($user->id, $websitesUserId, 'Websites/seo')) {
            $options['skip'] = true;
        }
    }
    unset($options['skipIfNotAuthorized']);
    Q_Response::addStylesheet('plugins/Websites/css/Websites.css');
    Q_Response::addScript("plugins/Websites/js/Websites.js");
    Q_Response::setToolOptions($options);
}
Ejemplo n.º 18
0
function Trump_before_Q_responseExtras()
{
    $app = Q_Config::expect('Q', 'app');
    Q_Response::addStylesheet('plugins/Q/css/Q.css');
    Q_Response::addStylesheet('css/html.css', '@end');
    if (Q_Config::get('Q', 'firebug', false)) {
        Q_Response::addScript("https://getfirebug.com/firebug-lite-debug.js");
    }
    Q_Response::addScript('js/Trump.js');
    if (Q_Request::isIE()) {
        header("X-UA-Compatible: IE=edge");
    }
    header('Vary: User-Agent');
    // running an event for loading action-specific extras (if there are any)
    $uri = Q_Dispatcher::uri();
    $module = $uri->module;
    $action = $uri->action;
    $event = "{$module}/{$action}/response/responseExtras";
    if (Q::canHandle($event)) {
        Q::event($event);
    }
}
Ejemplo n.º 19
0
function Q_response_default($params)
{
    if (!isset($params['slotName'])) {
        throw new Q_Exception_RequiredField(array('field' => '$slotName'));
    }
    $slotName = $params['slotName'];
    $uri = Q_Dispatcher::uri();
    $module = $uri->module;
    $action = $uri->action;
    if (!$module or !$action) {
        return "{$module}/{$action} is not a valid URI";
    }
    $event = "{$module}/{$action}/response/{$slotName}";
    $function_name = $module . '_' . $action . '_response_' . $slotName;
    if (function_exists($function_name)) {
        $result = Q::event($event);
        $result = isset($result) ? $result : "Don't return null from {$function_name}";
    }
    if (Q::canHandle($event)) {
        return Q::event($event);
    }
    throw new Q_Exception_MissingSlot(compact('event'));
}
Ejemplo n.º 20
0
function Users_before_Q_objects()
{
    $app = Q_Config::expect('Q', 'app');
    $fb_info = Q_Config::get('Users', 'facebookApps', $app, null);
    // We sometimes pass this in the request, for browsers like Safari
    // that don't allow setting of cookies using javascript inside 3rd party iframes
    if (!empty($fb_info['appId']) and !empty($_REQUEST['Users']['facebook_authResponse'])) {
        $appId = $fb_info['appId'];
        $auth_response = $_REQUEST['Users']['facebook_authResponse'];
        if (is_array($auth_response)) {
            if ($auth_response) {
                $cookie = $auth_response['signedRequest'];
                $expires = 0;
            } else {
                $cookie = "";
                $expires = 1;
            }
            try {
                $facebook = new Facebook(array('appId' => $fb_info['appId'], 'secret' => $fb_info['secret'], 'fileUpload' => true));
                $cookie_name = 'fbsr_' . $facebook->getAppId();
                if (!empty($_SERVER['HTTP_HOST'])) {
                    Q_Response::setCookie($cookie_name, $cookie, $expires);
                }
            } catch (Exception $e) {
                // do nothing
            }
        }
    }
    $uri = Q_Dispatcher::uri();
    $actions = array('activate' => true);
    if ($uri->module === 'Users' and isset($actions[$uri->action])) {
        Q::event("Users/{$uri->action}/objects");
    }
    // Fire an event for hooking into, if necessary
    Q::event('Users/objects', array(), 'after');
}
Ejemplo n.º 21
0
function Websites_before_Q_responseExtras()
{
    $user = Users::loggedInUser(false, false);
    $userId = $user ? $user->id : "";
    $websitesUserId = Q_Config::expect("Websites", "user", "id");
    $sha1 = sha1(Q_Dispatcher::uri());
    $seoStreamName = "Websites/seo/{$sha1}";
    $streams = Streams::fetch($userId, $websitesUserId, array("Websites/header", "Websites/title", "Websites/slogan", $seoStreamName));
    if (!empty($streams[$seoStreamName])) {
        $fields = Q::take($streams[$seoStreamName]->getAllAttributes(), array('keywords', 'description'));
        foreach ($fields as $k => $v) {
            Q_Response::setMeta($k, $v);
        }
        Q_Response::setSlot('title', $streams[$seoStreamName]->getAttribute('title'));
    }
    foreach ($streams as $name => $s) {
        if ($s) {
            $s->addPreloaded($userId);
        }
    }
    Q_Response::setScriptData('Q.plugins.Websites.seoStreamName', $seoStreamName);
    Q_Response::setScriptData('Q.plugins.Websites.userId', Q_Config::expect('Websites', 'user', 'id'));
    Q_Response::setScriptData('Q.plugins.Websites.seoReload', Q_Config::expect('Websites', 'seoReload'));
}
Ejemplo n.º 22
0
 protected static function handleForwardException($e)
 {
     $slotNames = Q_Request::slotNames(true);
     foreach ($slotNames as $slotName) {
         Q_Response::clearSlot($slotName);
     }
     // Go again, this time with a different URI.
     Q::$toolWasRendered = array();
     self::$uri = Q_Uri::from($e->uri);
     if (is_array($e->skip)) {
         self::$skip = $e->skip;
     } else {
         // Don't process any non-GET methods this time around,
         // Do not collect any analytics
         // And also ignore any accumulated errors
         self::$skip = array('Q/method' => true, 'Q/analytics' => true, 'Q/errors' => true);
     }
     // We'll be handling errors anew
     self::$handling_errors = false;
 }
Ejemplo n.º 23
0
 /**
  * Get the stream field from the request, if it can't be deduced throws error
  * @method requestedField
  * @static
  * @param {string} $field
  *	The fiels name
  * @param {boolean} $throwIfMissing=false
  *  Optional. If true, throws an exception if the stream field cannot be deduced
  * @param {mixed} $default=null
  *	Is returned if field is not set
  * @return {string}
  *  The value of the field
  * @throws {Q_Exception_RequiredField}
  *  If the field value can't be deduced, this is thrown
  */
 static function requestedField($field, $throwIfMissing = false, $default = null)
 {
     $uri = Q_Dispatcher::uri();
     if (isset($_REQUEST[$field])) {
         return $_REQUEST[$field];
     } else {
         if (isset($uri->{$field})) {
             if (is_array($uri->{$field})) {
                 return implode('/', $uri->{$field});
             }
             return $uri->{$field};
         } else {
             if ($field = Q_Request::special("Streams.{$field}", $default)) {
                 return $field;
             }
         }
     }
     if ($throwIfMissing) {
         throw new Q_Exception_RequiredField(array('field' => "stream {$field}"), $field);
     }
     return $default;
 }
Ejemplo n.º 24
0
 static function htmlAttributes()
 {
     $touchscreen = Q_Request::isTouchscreen() ? 'Q_touchscreen' : 'Q_notTouchscreen';
     $mobile = Q_Request::isMobile() ? 'Q_mobile' : 'Q_notMobile';
     $cordova = Q_Request::isCordova() ? 'Q_cordova' : 'Q_notCordova';
     $platform = 'Q_' . Q_Request::platform();
     $ie = Q_Request::isIE() ? 'Q_ie' : 'Q_notIE';
     $ie8 = Q_Request::isIE(0, 8) ? 'Q_ie8OrBelow' : 'Q_notIE8OrBelow';
     $uri = Q_Dispatcher::uri();
     $classes = "{$uri->module} {$uri->module}_{$uri->action}";
     $result = 'lang="en" prefix="og: http://ogp.me/ns# object: http://ogp.me/ns/object#" ' . "class='{$touchscreen} {$mobile} {$cordova} {$platform} {$ie} {$ie8} {$classes}'";
     return $result;
 }
Ejemplo n.º 25
0
 /**
  * Renders Q-specific information for a form
  * @method formInfo
  * @static
  * @param {string} $onSuccess The URI or URL to redirect to in case of success
  *  If you put "true" here, it uses Q_Request::special('onSuccess', $uri),
  *  or if it's not there, then `Q_Dispatcher::uri()`
  * @param {string} [$onErrors=null] The URI or URL to redirect to in case of errors
  *  If you put "true" here, it uses Q_Request::special('onErrors', $uri),
  *  or if it's not there, then `Q_Dispatcher::uri()`
  * @param {string} [$sessionNonceField=null] The name of the nonce field to use in the session.
  *  If the config parameter "Q"/"session"/"nonceField" is set, uses that.
  * @return {string} The generated markup
  */
 static function formInfo($onSuccess, $onErrors = null, $sessionNonceField = null)
 {
     $uri = Q_Dispatcher::uri();
     if ($onSuccess === true) {
         $onSuccess = Q_Request::special('onSuccess', $uri);
     }
     if ($onErrors === true) {
         $onErrors = Q_Request::special('onErrors', $uri);
     }
     $hiddenFields = array();
     if (isset($onSuccess)) {
         $hiddenFields['Q.onSuccess'] = Q_Uri::url($onSuccess);
     }
     if (isset($onErrors)) {
         $hiddenFields['Q.onErrors'] = Q_Uri::url($onErrors);
     }
     if (!isset($sessionNonceField)) {
         $sessionNonceField = Q_Config::get('Q', 'session', 'nonceField', 'nonce');
     }
     if (isset($sessionNonceField)) {
         if (!isset($_SESSION['Q'][$sessionNonceField])) {
             $_SESSION['Q'][$sessionNonceField] = uniqid();
         }
         $hiddenFields['Q.nonce'] = $_SESSION['Q'][$sessionNonceField];
     }
     return self::hidden($hiddenFields);
 }
Ejemplo n.º 26
0
/**
 * This tool renders tabs which behave appropriately in many different environments
 * @class Q tabs
 * @constructor
 * @param {array} [$options] options to pass to the tool
 *  @param {array} [$options.tabs] An associative array of name: title pairs.
 *  @param {array} [$options.urls] An associative array of name: url pairs to override the default urls.
 *  @param {string} [$options.field='tab'] Uses this field when urls doesn't contain the tab name.
 *  @param {boolean} [options.checkQueryString=false] Whether the default getCurrentTab should check the querystring when determining the current tab
 *  @param {boolean} [$options.vertical=false] Stack the tabs vertically instead of horizontally
 *  @param {boolean} [$options.compact=false] Display the tabs interface in a compact space with a contextual menu
 *  @param {Object} [$options.overflow]
 *  @param {String} [$options.overflow.content] The html that is displayed when the tabs overflow. You can interpolate {{count}}, {{text}} or {{html}} in the string. 
 *  @param {String} [$options.overflow.glyph] Override the glyph that appears next to the overflow text. You can interpolate {{count}} here
 *  @param {String} [$options.overflow.defaultText] The text to interpolate {{text}} in the content when no tab is selected
 *  @param {String} [$options.overflow.defaultHtml] The text to interpolate {{text}} in the content when no tab is selected
 *  @param {string} [$options.defaultTabName] Here you can specify the name of the tab to show by default
 *  @param {string} [$options.selectors] Array of (slotName => selector) pairs, where the values are CSS style selectors indicating the element to update with javascript, and can be a parent of the tabs. Set to null to reload the page.
 *  @param {string} [$options.slot] The name of the slot to request when changing tabs with javascript.
 *  @param {string} [$options.classes] An associative array of the form name => classes, for adding classes to tabs
 *  @param {string} [$options.titleClasses]  An associative array for adding classes to tab titles
 *  @param {string} [$options.after] Name of an event that will return HTML to place after the generated HTML in the tabs tool element
 *  @param {string} [$options.loader] Name of a function which takes url, slot, callback. It should call the callback and pass it an object with the response info. Can be used to implement caching, etc. instead of the default HTTP request. This function shall be Q.batcher getter
 *  @param {string} [$options.onClick] Event when a tab was clicked, with arguments (name, element). Returning false cancels the tab switching.
 *  @param {string} [$options.beforeSwitch] Event when tab switching begins. Returning false cancels the switching.
 *  @param {string} [$options.beforeScripts] Name of the function to execute after tab is loaded but before its javascript is executed.
 *  @param {string} [$options.onCurrent] Name of the function to execute after a tab is shown to be selected.
 *  @param {string} [$options.onActivate] Name of the function to execute after a tab is activated.
 */
function Q_tabs_tool($options)
{
    $field = 'tab';
    $slot = 'content,title';
    $selectors = array('content' => '#content_slot');
    $urls = array();
    extract($options);
    if (!isset($tabs)) {
        return '';
    }
    if (isset($overflow) and is_string($overflow)) {
        $overflow = array('content' => $overflow);
    }
    /**
     * @var array $tabs
     * @var boolean $vertical
     * @var boolean $compact
     */
    $sel = isset($_REQUEST[$field]) ? $_REQUEST[$field] : null;
    $result = '';
    $i = 0;
    $selectedName = null;
    $uri_string = (string) Q_Dispatcher::uri();
    foreach ($tabs as $name => $title) {
        if ($name === $sel or $name === $uri_string or $urls[$name] === $uri_string or $urls[$name] === Q_Request::url()) {
            $selectedName = $name;
            break;
        }
    }
    foreach ($tabs as $name => $title) {
        if (isset($urls[$name])) {
            $urls[$name] = Q_Uri::url($urls[$name]);
        } else {
            $urls[$name] = Q_Uri::url(Q_Request::url(array($field => $name, "/Q\\.(.*)/" => null)));
        }
        $selected_class = $name === $selectedName ? ' Q_current' : '';
        $classes_string = " Q_tab_" . Q_Utils::normalize($name);
        if (isset($classes[$name])) {
            if (is_string($classes[$name])) {
                $classes_string .= ' ' . $classes[$name];
            } else {
                if (is_array($classes[$name])) {
                    $classes_string .= ' ' . implode(' ', $classes[$name]);
                }
            }
        }
        $titleClasses_string = '';
        if (isset($titleClasses[$name])) {
            if (is_string($titleClasses[$name])) {
                $titleClasses_string = $titleClasses[$name];
            } else {
                if (is_array($titleClasses[$name])) {
                    $titleClasses_string = implode(' ', $titleClasses[$name]);
                }
            }
        }
        $title_container = Q_Html::div(null, "Q_tabs_title {$titleClasses_string}", isset($title) ? $title : $name);
        $result .= Q_Html::tag('li', array('id' => 'tab_' . ++$i, 'class' => "Q_tabs_tab {$classes_string}{$selected_class}", 'data-name' => $name), Q_Html::a($urls[$name], $title_container));
    }
    Q_Response::setToolOptions(compact('selectors', 'slot', 'urls', 'defaultTabName', 'vertical', 'compact', 'overflow', 'field', 'loader', 'beforeSwitch', 'beforeScripts', 'onActivate'));
    Q_Response::addScript('plugins/Q/js/tools/tabs.js');
    Q_Response::addStylesheet('plugins/Q/css/tabs.css');
    $classes = empty($vertical) ? ' Q_tabs_horizontal' : ' Q_tabs_vertical';
    if (!empty($compact)) {
        $classes .= " Q_tabs_compact";
    }
    $after = isset($options['after']) ? Q::event($options['after'], $options) : '';
    return "<ul class='Q_tabs_tabs Q_clearfix{$classes}'>{$result}{$after}</ul>";
}
Ejemplo n.º 27
0
/**
 * 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);
}
Ejemplo n.º 28
0
/**
 * The default implementation.
 */
function Q_errors($params)
{
    extract($params);
    /**
     * @var Exception $exception
     * @var boolean $startedResponse
     */
    if (!empty($exception)) {
        Q_Response::addError($exception);
    }
    $errors = Q_Response::getErrors();
    $errors_array = Q_Exception::toArray($errors);
    // Simply return the errors, if this was an AJAX request
    if ($is_ajax = Q_Request::isAjax()) {
        try {
            $errors_json = @Q::json_encode($errors_array);
        } catch (Exception $e) {
            $errors_array = array_slice($errors_array, 0, 1);
            unset($errors_array[0]['trace']);
            $errors_json = @Q::json_encode($errors_array);
        }
        $json = "{\"errors\": {$errors_json}}";
        $callback = Q_Request::callback();
        switch (strtolower($is_ajax)) {
            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:
                header("Content-type: " . ($callback ? "application/javascript" : "application/json"));
                echo $callback ? "{$callback}({$json})" : $json;
        }
        return;
    }
    // Forward internally, if it was requested
    if ($onErrors = Q_Request::special('onErrors', null)) {
        $uri1 = Q_Dispatcher::uri();
        $uri2 = Q_Uri::from($onErrors);
        $url2 = $uri2->toUrl();
        if (!isset($uri2)) {
            throw new Q_Exception_WrongValue(array('field' => 'onErrors', 'range' => 'an internal URI reachable from a URL'));
        }
        if ($uri1->toUrl() !== $url2) {
            Q_Dispatcher::forward($uri2);
            return;
            // we don't really need this, but it's here anyway
        }
    }
    $params2 = compact('errors', 'exception', 'errors_array', 'exception_array');
    if (Q::eventStack('Q/response')) {
        // Errors happened while rendering response. Just render errors view.
        return Q::view('Q/errors.php', $params2);
    }
    if (!$startedResponse) {
        try {
            // Try rendering the response, expecting it to
            // display the errors along with the rest.
            $ob = new Q_OutputBuffer();
            Q::event('Q/response', $params2);
            $ob->endFlush();
            return;
        } catch (Exception $e) {
            if (get_class($e) === 'Q_Exception_DispatcherForward') {
                throw $e;
                // if forwarding was requested, do it
                // for all other errors, continue trying other things
            }
            $output = $ob->getClean();
        }
    }
    if ($errors) {
        // Try rendering the app's errors response, if any.
        $app = Q::app();
        if (Q::canHandle("{$app}/errors/response/content")) {
            Q_Dispatcher::forward("{$app}/errors");
        } else {
            echo Q::view("Q/errors.php", compact('errors'));
        }
    }
    if (!empty($e)) {
        return Q::event('Q/exception', array('exception' => $e));
    }
}
Ejemplo n.º 29
0
 /**
  * Returns the string containing all the html attributes
  * @method htmlAttributes
  * @static
  * @return {string}
  */
 static function htmlAttributes()
 {
     $touchscreen = Q_Request::isTouchscreen() ? 'Q_touchscreen' : 'Q_notTouchscreen';
     $mobile = Q_Request::isMobile() ? 'Q_mobile' : 'Q_notMobile';
     $cordova = Q_Request::isCordova() ? 'Q_cordova' : 'Q_notCordova';
     $platform = 'Q_' . Q_Request::platform();
     $ie = Q_Request::isIE() ? 'Q_ie' : 'Q_notIE';
     $ie8 = Q_Request::isIE(0, 8) ? 'Q_ie8OrBelow' : 'Q_notIE8OrBelow';
     $uri = Q_Dispatcher::uri();
     $classes = "{$uri->module} {$uri->module}_{$uri->action}";
     foreach (self::$htmlCssClasses as $k => $v) {
         $classes .= Q_Html::text(" {$k}");
     }
     $language = self::language();
     return 'lang="' . $language . '" ' . 'prefix="og: http://ogp.me/ns# object: http://ogp.me/ns/object#" ' . "class='{$touchscreen} {$mobile} {$cordova} {$platform} {$ie} {$ie8} {$classes}'";
 }
Ejemplo n.º 30
0
        if (empty($_REQUEST['p'])) {
            ?>
						Choose a <strong>pass phrase</strong> to log in with.<br>
						A simple phrase consisting of a few words that
						you will easily remember.
					<?php 
        } else {
            ?>
						Choose a good <strong>pass phrase</strong> to protect your account.
						See the suggestions for some ideas.
					<?php 
        }
        ?>
					</p>
					<?php 
        echo Q_Html::form(Q_Dispatcher::uri(), 'post', array('id' => 'Q_activation_form'));
        ?>
						<?php 
        echo Q_Html::formInfo(null);
        ?>
						<input type="password" id='activate_passphrase' name="passphrase" class='password' autofocus placeholder="Enter a passphrase" autocomplete="new-password" /><br>
						<button type="submit" class="Q_button" style="width: 250px;">Activate My Account</button>
						<input type="hidden" id="activate_identifier" name="<?php 
        echo $t;
        ?>
"
							value="<?php 
        echo Q_Html::text($identifier);
        ?>
">
						<input type="hidden" name="code" value="<?php