Example #1
0
function Users_account_validate()
{
    Q_Valid::nonce(true);
    $birthday_year = $birthday_month = $birthday_day = null;
    extract($_REQUEST);
    $field_names = array('firstName' => 'First name', 'lastName' => 'Last name', 'username' => 'Username', 'gender' => 'Your gender', 'desired_gender' => 'Gender preference', 'orientation' => 'Orientation', 'relationship_status' => 'Status', 'zipcode' => 'Zipcode');
    foreach ($field_names as $name => $label) {
        if (isset($_POST[$name]) and !$_POST[$name]) {
            Q_Response::addError(new Q_Exception_RequiredField(array('field' => $label), $name));
        }
    }
    if (isset($birthday_year)) {
        if (!checkdate($birthday_month, $birthday_day, $birthday_year)) {
            $field = 'Birthday';
            $range = 'a valid date';
            Q_Response::addError(new Q_Exception_WrongValue(compact('field', 'range'), 'birthday'));
        }
    }
    global $Q_installing;
    if (isset($username) and isset($Q_installing)) {
        try {
            Q::event('Users/validate/username', compact('username'));
        } catch (Exception $e) {
            Q_Response::addError($e);
        }
    }
}
Example #2
0
/**
 * Standard tool for making payments.
 * @class Assets payment
 * @constructor
 * @param {array} $options Override various options for this tool
 *  @param {string} $options.payments can be "authnet" or "stripe"
 *  @param {string} $options.amount the amount to pay.
 *  @param {double} [$options.currency="usd"] the currency to pay in. (authnet supports only "usd")
 *  @param {string} [$options.payButton] Can override the title of the pay button
 *  @param {String} [$options.publisherId=Users::communityId()] The publisherId of the Assets/product or Assets/service stream
 *  @param {String} [$options.streamName] The name of the Assets/product or Assets/service stream
 *  @param {string} [$options.name=Users::communityName()] The name of the organization the user will be paying
 *  @param {string} [$options.image] The url pointing to a square image of your brand or product. The recommended minimum size is 128x128px.
 *  @param {string} [$options.description=null] A short name or description of the product or service being purchased.
 *  @param {string} [$options.panelLabel] The label of the payment button in the Stripe Checkout form (e.g. "Pay {{amount}}", etc.). If you include {{amount}}, it will be replaced by the provided amount. Otherwise, the amount will be appended to the end of your label.
 *  @param {string} [$options.zipCode] Specify whether Stripe Checkout should validate the billing ZIP code (true or false). The default is false.
 *  @param {boolean} [$options.billingAddress] Specify whether Stripe Checkout should collect the user's billing address (true or false). The default is false.
 *  @param {boolean} [$options.shippingAddress] Specify whether Checkout should collect the user's shipping address (true or false). The default is false.
 *  @param {string} [$options.email=Users::loggedInUser(true)->emailAddress] You can use this to override the email address, if any, provided to Stripe Checkout to be pre-filled.
 *  @param {boolean} [$options.allowRememberMe=true] Specify whether to include the option to "Remember Me" for future purchases (true or false).
 *  @param {boolean} [$options.bitcoin=false] Specify whether to accept Bitcoin (true or false). 
 *  @param {boolean} [$options.alipay=false] Specify whether to accept Alipay ('auto', true, or false). 
 *  @param {boolean} [$options.alipayReusable=false] Specify if you need reusable access to the customer's Alipay account (true or false).
 */
function Assets_payment_tool($options)
{
    Q_Valid::requireFields(array('payments', 'amount'), $options, true);
    if (empty($options['name'])) {
        $options['name'] = Users::communityName();
    }
    if (!empty($options['image'])) {
        $options['image'] = Q_Html::themedUrl($options['image']);
    }
    $options['payments'] = strtolower($options['payments']);
    if (empty($options['email'])) {
        $options['email'] = Users::loggedInUser(true)->emailAddress;
    }
    $payments = ucfirst($options['payments']);
    $currency = strtolower(Q::ifset($options, 'currency', 'usd'));
    if ($payments === 'Authnet' and $currency !== 'usd') {
        throw new Q_Exception("Authnet doesn't support currencies other than USD", 'currency');
    }
    $className = "Assets_Payments_{$payments}";
    switch ($payments) {
        case 'Authnet':
            $adapter = new $className($options);
            $token = $options['token'] = $adapter->authToken();
            $testing = $options['testing'] = Q_Config::expect('Assets', 'payments', $lcpayments, 'testing');
            $action = $options['action'] = $testing ? "https://test.authorize.net/profile/manage" : "https://secure.authorize.net/profile/manage";
            break;
        case 'Stripe':
            $publishableKey = Q_Config::expect('Assets', 'payments', 'stripe', 'publishableKey');
            break;
    }
    $titles = array('Authnet' => 'Authorize.net', 'Stripe' => 'Stripe');
    Q_Response::setToolOptions($options);
    $payButton = Q::ifset($options, 'payButton', "Pay with " . $titles[$payments]);
    return Q::view("Assets/tool/payment/{$payments}.php", compact('token', 'publishableKey', 'action', 'payButton'));
}
Example #3
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;
    }
}
Example #4
0
function Streams_after_Q_image_save($params)
{
    $user = Users::loggedInUser(true);
    $path = $subpath = $data = $save = null;
    extract($params, EXTR_OVERWRITE);
    if (isset(Users::$cache['iconUrlWasChanged']) and Users::$cache['iconUrlWasChanged'] === false) {
        // the logged-in user's icon was changed without the url changing
        $stream = Streams::fetchOne($user->id, $user->id, "Streams/user/icon");
    } else {
        if (!empty(Streams::$cache['canWriteToStream'])) {
            // some stream's icon was being changed
            $stream = Streams::$cache['canWriteToStream'];
        }
    }
    if (empty($stream)) {
        return;
    }
    $url = $data[''];
    $stream->icon = Q_Valid::url($url) ? $url : Q_Request::baseUrl() . '/' . $url;
    $sizes = array();
    foreach ($save as $k => $v) {
        $sizes[] = "{$k}";
    }
    sort($sizes);
    $stream->setAttribute('sizes', $sizes);
    if (empty(Streams::$beingSavedQuery)) {
        $stream->changed($user->id);
    } else {
        $stream->save();
    }
}
Example #5
0
function Streams_interest_validate($params)
{
    // Protect against CSRF attacks:
    if (Q_Request::method() !== 'GET') {
        Q_Valid::nonce(true);
    }
}
Example #6
0
function Streams_after_Q_file_save($params)
{
    $user = Users::loggedInUser(true);
    $path = $subpath = $name = $writePath = $data = $tailUrl = null;
    extract($params, EXTR_OVERWRITE);
    if (!empty(Streams::$cache['canWriteToStream'])) {
        // some stream's associated file was being changed
        $stream = Streams::$cache['canWriteToStream'];
    }
    if (empty($stream)) {
        return;
    }
    $filesize = filesize($writePath . DS . $name);
    $url = $tailUrl;
    $url = Q_Valid::url($url) ? $url : Q_Request::baseUrl() . '/' . $url;
    $prevUrl = $stream->getAttribute('file.url');
    $stream->setAttribute('file.url', $url);
    $stream->setAttribute('file.size', $filesize);
    // set the title and icon every time a new file is uploaded
    $stream->title = $name;
    $parts = explode('.', $name);
    $urlPrefix = Q_Request::baseUrl() . '/plugins/Streams/img/icons/files';
    $dirname = STREAMS_PLUGIN_FILES_DIR . DS . 'Streams' . DS . 'icons' . DS . 'files';
    $extension = end($parts);
    $stream->icon = file_exists($dirname . DS . $extension) ? "{$urlPrefix}/{$extension}" : "{$urlPrefix}/_blank";
    if (empty(Streams::$beingSavedQuery)) {
        $stream->changed($user->id);
    } else {
        $stream->save();
    }
}
Example #7
0
function Users_user_validate()
{
    Q_Valid::nonce(true);
    $type = isset($_REQUEST['identifierType']) ? $_REQUEST['identifierType'] : Q_Config::get("Users", "login", "identifierType", "email,mobile");
    $parts = explode(',', $type);
    $accept_mobile = true;
    $expected = 'email address or mobile number';
    $fields = array('emailAddress', 'mobileNumber', 'identifier');
    if (count($parts) === 1) {
        if ($parts[0] === 'email') {
            $expected = 'email address';
            $fields = array('emailAddress', 'identifier');
            $accept_mobile = false;
        } else {
            if ($parts[0] === 'mobile') {
                $expected = 'mobile number';
                $fields = array('mobileNumber', 'identifier');
            }
        }
    }
    if (!isset($_REQUEST['identifier'])) {
        throw new Q_Exception("a valid {$expected} is required", $fields);
    }
    if (!Q_Valid::email($_REQUEST['identifier'])) {
        if (!$accept_mobile) {
            throw new Q_Exception("a valid {$expected} is required", $fields);
        }
        if (!Q_Valid::phone($_REQUEST['identifier'])) {
            throw new Q_Exception("a valid {$expected} is required", $fields);
        }
    }
}
Example #8
0
function Streams_invite_validate()
{
    if (Q_Request::method() === 'PUT') {
        return;
    }
    if (Q_Request::method() !== 'GET') {
        Q_Valid::nonce(true);
    }
    $fields = array('publisherId', 'streamName');
    if (Q_Request::method() === 'POST') {
        if (Q_Valid::requireFields($fields)) {
            return;
        }
        foreach ($fields as $f) {
            if (strlen(trim($_REQUEST[$f])) === 0) {
                Q_Response::addError(new Q_Exception("{$f} can't be empty", $f));
            }
        }
    }
    if (isset($_REQUEST['fullName'])) {
        $length_min = Q_Config::get('Streams', 'inputs', 'fullName', 'lengthMin', 5);
        $length_max = Q_Config::get('Streams', 'inputs', 'fullName', 'lengthMax', 30);
        if (strlen($_REQUEST['fullName']) < $length_min) {
            throw new Q_Exception("A user's full name can't be that short.", 'fullName');
        }
        if (strlen($_REQUEST['fullName']) > $length_max) {
            throw new Q_Exception("A user's full name can't be that long.", 'fullName');
        }
    }
}
Example #9
0
function Users_account_post()
{
    Q_Session::start();
    Q_Valid::nonce(true);
    extract($_REQUEST);
    // Implement the action
    $user = Users::loggedInUser(true);
}
Example #10
0
function Users_user_validate()
{
    if (isset($_REQUEST['userIds']) or isset($_REQUEST['batch'])) {
        return;
    }
    $type = isset($_REQUEST['identifierType']) ? $_REQUEST['identifierType'] : Q_Config::get("Users", "login", "identifierType", "email,mobile");
    $parts = explode(',', $type);
    $accept_mobile = true;
    $expected = 'email address or mobile number';
    $fields = array('emailAddress', 'mobileNumber', 'identifier');
    if (count($parts) === 1) {
        if ($parts[0] === 'email') {
            $expected = 'email address';
            $fields = array('emailAddress', 'identifier');
            $accept_mobile = false;
        } else {
            if ($parts[0] === 'mobile') {
                $expected = 'mobile number';
                $fields = array('mobileNumber', 'identifier');
            }
        }
    }
    if (!isset($_REQUEST['identifier'])) {
        throw new Q_Exception("a valid {$expected} is required", $fields);
    }
    if (!Q_Valid::email($_REQUEST['identifier'])) {
        if (!$accept_mobile) {
            throw new Q_Exception("a valid {$expected} is required", $fields);
        }
        if (!Q_Valid::phone($_REQUEST['identifier'])) {
            throw new Q_Exception("a valid {$expected} is required", $fields);
        }
    }
    $identifier = Users::requestedIdentifier($type);
    // check our db
    if ($user = Users::userFromContactInfo($type, $identifier)) {
        $verified = !!Users::identify($type, $identifier);
        return array('exists' => $user->id, 'verified' => $verified, 'username' => $user->username, 'icon' => $user->icon, 'passphrase_set' => !empty($user->passphraseHash), 'fb_uid' => $user->fb_uid ? $user->fb_uid : null);
    }
    if ($type === 'email') {
        $email = new Users_Email();
        Q_Valid::email($identifier, $normalized);
        $email->address = $normalized;
        $exists = $email->retrieve();
    } else {
        if ($type === 'mobile') {
            $mobile = new Users_Mobile();
            Q_Valid::phone($identifier, $normalized);
            $mobile->number = $normalized;
            $exists = $mobile->retrieve();
        }
    }
    if (empty($exists) and Q_Config::get('Users', 'login', 'noRegister', false)) {
        $nicetype = $type === 'email' ? 'email address' : 'mobile number';
        throw new Q_Exception("This {$nicetype} was not registered", array('identifier'));
    }
}
Example #11
0
function Streams_publisher_validate($params)
{
    // Protect against CSRF attacks:
    Q_Valid::nonce(true);
    $type = Streams::requestedType();
    if ($type && Q::canHandle("Streams/validate/{$type}")) {
        return Q::event("Streams/validate/{$type}", $params);
    }
}
Example #12
0
function Users_register_validate()
{
    Q_Valid::nonce(true);
    foreach (array('identifier', 'username', 'icon') as $field) {
        if (!isset($_REQUEST[$field])) {
            throw new Q_Exception("{$field} is missing", array($field));
        }
    }
}
Example #13
0
 /**
  * Adds a device to the system, after sending a test notification to it
  * @param {array} $device
  * @param {string} $device.userId
  * @param {string} $device.deviceId
  * @param {string} [$device.formFactor]
  * @param {string} [$device.platform]
  * @param {string} [$device.version]
  * @param {string} [$device.sessionId]
  * @param {boolean} [$device.sandbox]
  * @param {string} [$device.passphrase]
  * @param {boolean} [$skipNotification=false] if true, skips sending notification
  * @return {Users_Device}
  */
 static function add($device, $skipNotification = false)
 {
     Q_Valid::requireFields(array('userId', 'deviceId'), $device, true);
     $userId = $device['userId'];
     $deviceId = $device['deviceId'];
     if (!$skipNotification) {
         $app = Q::app();
         $sandbox = Q::ifset($device, 'sandbox', null);
         if (!isset($sandbox)) {
             $sandbox = Q_Config::get($app, "cordova", "ios", "sandbox", false);
         }
         $env = $sandbox ? ApnsPHP_Abstract::ENVIRONMENT_SANDBOX : ApnsPHP_Abstract::ENVIRONMENT_PRODUCTION;
         $s = $sandbox ? 'sandbox' : 'production';
         $cert = APP_LOCAL_DIR . DS . 'Users' . DS . 'certs' . DS . $app . DS . $s . DS . 'bundle.pem';
         $authority = USERS_PLUGIN_FILES_DIR . DS . 'Users' . DS . 'certs' . DS . 'EntrustRootCA.pem';
         $logger = new Users_ApnsPHP_Logger();
         $push = new ApnsPHP_Push($env, $cert);
         $push->setLogger($logger);
         $push->setRootCertificationAuthority($authority);
         if (isset($device['passphrase'])) {
             $push->setProviderCertificatePassphrase($device['passphrase']);
         }
         $push->connect();
         $message = new ApnsPHP_Message($deviceId);
         $message->setCustomIdentifier('Users_Device-adding');
         $message->setBadge(0);
         $message->setText(Q_Config::get($app, "cordova", "ios", "device", "text", "Notifications have been enabled"));
         $message->setCustomProperty('userId', $userId);
         $message->setExpiry(5);
         $push->add($message);
         $push->send();
         $push->disconnect();
         $errors = $push->getErrors();
         if (!empty($errors)) {
             $result = reset($errors);
             throw new Users_Exception_DeviceNotification($result['ERRORS'][0]);
         }
     }
     $sessionId = Q_Session::id();
     $user = Users::loggedInUser();
     $info = array_merge(Q_Request::userAgentInfo(), array('sessionId' => $sessionId, 'userId' => $user ? $user->id : null, 'deviceId' => null));
     $device2 = Q::take($device, $info);
     $d = new Users_Device($device2);
     $d->save(true);
     if ($sessionId) {
         $s = new Users_Session();
         $s->id = $sessionId;
         if (!$s->retrieve()) {
             $s->deviceId = $deviceId;
         }
     }
     $_SESSION['Users']['deviceId'] = $deviceId;
     $device2['Q/method'] = 'Users/device';
     Q_Utils::sendToNode($device2);
     return $d;
 }
Example #14
0
function Users_importContacts_validate()
{
    Q_Valid::nonce(true);
    if (empty($_GET['provider'])) {
        throw new Q_Exception('No provider specified');
    }
    if (!Q::canHandle('Users/importContacts/providers/' . $_GET['provider'])) {
        throw new Q_Exception('Unsupported provider specified: ' . $_GET['provider']);
    }
}
Example #15
0
/**
 * Post one or more fields here to change the corresponding basic streams for the logged-in user. Fields can include:
 * "firstName": specify the first name directly
 * "lastName": specify the last name directly
 * "fullName": the user's full name, which if provided will be split into first and last name and override them
 * "gender": the user's gender
 * "birthday_year": the year the user was born
 * "birthday_month": the month the user was born
 * "birthday_day": the day the user was born
 */
function Streams_basic_post()
{
    Q_Valid::nonce(true);
    $user = Users::loggedInUser(true);
    $request = $_REQUEST;
    $fields = array();
    if (!empty($request['birthday_year']) && !empty($request['birthday_month']) && !empty($request['birthday_day'])) {
        $request['birthday'] = sprintf("%04d-%02d-%02d", $_REQUEST['birthday_year'], $_REQUEST['birthday_month'], $_REQUEST['birthday_day']);
    }
    //	$request['icon'] = $user->icon;
    if (isset($request['fullName'])) {
        $name = Streams::splitFullName($request['fullName']);
        $request['firstName'] = $name['first'];
        $request['lastName'] = $name['last'];
    }
    foreach (array('firstName', 'lastName', 'birthday', 'gender') as $field) {
        if (isset($request[$field])) {
            $fields[] = $field;
        }
    }
    $p = new Q_Tree();
    $p->load(STREAMS_PLUGIN_CONFIG_DIR . DS . 'streams.json');
    $p->load(APP_CONFIG_DIR . DS . 'streams.json');
    $names = array();
    foreach ($fields as $field) {
        $names[] = "Streams/user/{$field}";
    }
    $streams = Streams::fetch($user, $user->id, $names);
    foreach ($fields as $field) {
        $name = "Streams/user/{$field}";
        $type = $p->get($name, "type", null);
        if (!$type) {
            throw new Q_Exception("Missing {$name} type", $field);
        }
        $title = $p->get($name, "title", null);
        if (!$title) {
            throw new Q_Exception("Missing {$name} title", $field);
        }
        $stream = $streams[$name];
        if (isset($stream) and $stream->content === (string) $request[$field]) {
            continue;
        }
        if (!isset($stream)) {
            $stream = new Streams_Stream();
            $stream->publisherId = $user->id;
            $stream->name = $name;
        }
        $messageType = $stream->wasRetrieved() ? 'Streams/changed' : 'Streams/created';
        $stream->content = (string) $request[$field];
        $stream->type = $type;
        $stream->title = $title;
        $stream->changed($user->id, $messageType);
    }
}
Example #16
0
function Streams_stream_validate($params)
{
    // Protect against CSRF attacks:
    if (Q_Request::method() !== 'GET') {
        Q_Valid::nonce(true);
    }
    $type = Streams::requestedType();
    if ($type && Q::canHandle("Streams/validate/{$type}")) {
        return Q::event("Streams/validate/{$type}", $params);
    }
}
Example #17
0
function Users_user_response_data($params)
{
    $identifier = Users::requestedIdentifier($type);
    // check our db
    if ($user = Users::userFromContactInfo($type, $identifier)) {
        $verified = !!Users::identify($type, $identifier);
        return array('exists' => $user->id, 'verified' => $verified, 'username' => $user->username, 'icon' => $user->icon, 'passphrase_set' => !empty($user->passphraseHash), 'fb_uid' => $user->fb_uid ? $user->fb_uid : null);
    }
    if ($type === 'email') {
        $email = new Users_Email();
        Q_Valid::email($identifier, $normalized);
        $email->address = $normalized;
        $exists = $email->retrieve();
    } else {
        if ($type === 'mobile') {
            $mobile = new Users_Mobile();
            Q_Valid::phone($identifier, $normalized);
            $mobile->number = $normalized;
            $exists = $mobile->retrieve();
        }
    }
    if (empty($exists) and Q_Config::get('Users', 'login', 'noRegister', false)) {
        $nicetype = $type === 'email' ? 'email address' : 'mobile number';
        throw new Q_Exception("This {$nicetype} was not registered", array('identifier'));
    }
    // Get Gravatar info
    // WARNING: INTERNET_REQUEST
    $hash = md5(strtolower(trim($identifier)));
    $thumbnailUrl = Q_Request::baseUrl() . "/action.php/Users/thumbnail?hash={$hash}&size=80&type=" . Q_Config::get('Users', 'login', 'iconType', 'wavatar');
    $json = @file_get_contents("http://www.gravatar.com/{$hash}.json");
    $result = json_decode($json, true);
    if ($result) {
        if ($type === 'email') {
            $result['emailExists'] = !empty($exists);
        } else {
            if ($type === 'mobile') {
                $result['mobileExists'] = !empty($exists);
            }
        }
        return $result;
    }
    // otherwise, return default
    $email_parts = explode('@', $identifier, 2);
    $result = array("entry" => array(array("id" => "571", "hash" => "357a20e8c56e69d6f9734d23ef9517e8", "requestHash" => "357a20e8c56e69d6f9734d23ef9517e8", "profileUrl" => "http://gravatar.com/test", "preferredUsername" => ucfirst($email_parts[0]), "thumbnailUrl" => $thumbnailUrl, "photos" => array(), "displayName" => "", "urls" => array())));
    if ($type === 'email') {
        $result['emailExists'] = !empty($exists);
    } else {
        $result['mobileExists'] = !empty($exists);
    }
    if ($terms_label = Users::termsLabel('register')) {
        $result['termsLabel'] = $terms_label;
    }
    return $result;
}
Example #18
0
function Users_login_validate()
{
    if (Q_Request::method() === 'GET') {
        return;
    }
    Q_Valid::nonce(true);
    foreach (array('identifier', 'passphrase') as $field) {
        if (!isset($_REQUEST[$field])) {
            throw new Q_Exception("{$field} is missing", array($field));
        }
    }
}
Example #19
0
function Users_user_response_users($params = array())
{
    $req = array_merge($_REQUEST, $params);
    Q_Valid::requireFields(array('userIds'), $req, true);
    $userIds = $req['userIds'];
    if (is_string($userIds)) {
        $userIds = explode(",", $userIds);
    }
    $fields = Q_Config::expect('Users', 'avatarFields');
    $users = Users_User::select($fields)->where(array('id' => $userIds))->fetchDbRows(null, null, 'id');
    return Q_Response::setSlot('users', Db::exportArray($users, array('asAvatar' => true)));
}
Example #20
0
/**
 * Lets the user search for streams they can relate a given stream to, and relate it
 * @class Streams relate
 * @constructor
 * @param {array} [$options] Override various options for this tool
 * @param {string} $publisherId publisher id of the stream to relate
 * @param {string} $streamName name of stream to relate
 * @param {string} [$communityId=Users::communityId()] id of the user publishing the streams to relate to
 * @param {array} [$types=Q_Config::expect('Streams','relate','types')] the types of streams the user can select
 * @param {array} [$typeNames] pairs of array($type => $typeName) to override names of the types, which would otherwise be taken from the types
 * @param {Boolean} [options.multiple=true] whether the user can select multiple types for the lookup
 * @param {boolean} [$relateFrom=false] if true, will relate FROM the user-selected stream TO the streamName instead
 * @param {string} [$types=Q_Config::expect('Streams','relate','types')] the types of streams the user can select
 * @param {Q.Event} [$options.onRelate] This event handler occurs when a stream is successfully related
 */
function Streams_relate_tool($options)
{
    Q_Valid::requireFields(array('publisherId', 'streamName'), $options, true);
    if (!isset($options['communityId'])) {
        $options['communityId'] = Users::communityId();
    }
    if (!isset($options['types'])) {
        $options['types'] = Q_Config::get('Streams', 'relate', 'types', array());
    }
    Q_Response::setToolOptions($options);
    return '';
}
Example #21
0
/**
 * Used by HTTP clients to start a subscription
 * @class HTTP Assets subscription
 * @method post
 * @param {array} $_REQUEST
 * @param {string} $_REQUEST.payments Required. Should be either "authnet" or "stripe"
 *  @param {String} $_REQUEST.planStreamName the name of the subscription plan's stream
 *  @param {String} [$_REQUEST.planPublisherId=Users::communityId()] the publisher of the subscription plan's stream
 *  @param {String} [$_REQUEST.token=null] if using stripe, pass the token here
 */
function Assets_subscription_post($params = array())
{
    $req = array_merge($_REQUEST, $params);
    Q_Valid::requireFields(array('payments'), $req, true);
    // to be safe, we only start subscriptions from existing plans
    $planPublisherId = Q::ifset($req, 'planPublisherId', Users::communityId());
    $plan = Streams::fetchOne($planPublisherId, $planPublisherId, $req['planStreamName'], true);
    // the currency will always be assumed to be "USD" for now
    // and the amount will always be assumed to be in dollars, for now
    $token = Q::ifset($req, 'token', null);
    $subscription = Assets::startSubscription($plan, $req['payments'], compact('token'));
    Q_Response::setSlot('subscription', $subscription);
}
Example #22
0
/**
 * Adds contacts to the system. Fills the "contacts" slot.
 * @param {array} $_REQUEST
 * @param {string} $_REQUEST.label The label of the contact
 * @param {string} $_REQUEST.contactUserId The contactUserId of the contact
 * @param {string} [$_REQUEST.nickname] The nickname of the contact
 * @param {string} [$_REQUEST.userId=Users::loggedInUser(true)->id] You can override the user id, if another plugin adds a hook that allows you to do this
 */
function Users_contact_post($params = array())
{
    if (Q_Request::slotName('batch') or Q_Request::slotName('contacts')) {
        return;
    }
    $req = array_merge($_REQUEST, $params);
    Q_Valid::requireFields(array('label', 'contactUserId'), $req, true);
    $loggedInUserId = Users::loggedInUser(true)->id;
    $userId = Q::ifset($req, 'userId', $loggedInUserId);
    $contactUserId = $req['contactUserId'];
    $nickname = Q::ifset($req, 'nickname', null);
    $contacts = Users_Contact::addContact($userId, $req['label'], $contactUserId, $nickname);
    Q_Response::setSlot('contacts', Db::exportArray($contacts));
}
Example #23
0
function Streams_access_put($params)
{
    $user = Users::loggedInUser(true);
    Q_Valid::nonce(true);
    $publisherId = Streams::requestedPublisherId(true);
    $streamName = Streams::requestedName(true);
    $stream = Streams::fetchOne($user->id, $publisherId, $streamName);
    if (!$stream) {
        throw new Q_Exception_MissingRow(array('table' => 'stream', 'criteria' => 'with that name'));
    }
    if (!$stream->testAdminLevel('own')) {
        throw new Users_Exception_NotAuthorized();
    }
    $p = array_merge($_REQUEST, $params);
    $access = new Streams_Access();
    $access->publisherId = $stream->publisherId;
    $access->streamName = $stream->name;
    $access->ofUserId = Q::ifset($_REQUEST, 'ofUserId', '');
    $access->ofContactLabel = Q::ifset($_REQUEST, 'ofContactLabel', '');
    if (empty($access->ofUserId) and empty($access->ofContactLabel)) {
        $fields = array('grantedByUserId', 'filter', 'readLevel', 'writeLevel', 'adminLevel', 'permissions');
        foreach ($fields as $field) {
            if (isset($p[$field])) {
                $stream->{$field} = $p[$field];
            }
        }
        $stream->save();
        return;
    }
    $access->retrieve();
    $fields = array('grantedByUserId', 'filter', 'readLevel', 'writeLevel', 'adminLevel', 'permissions');
    foreach ($fields as $field) {
        if (isset($p[$field])) {
            $access->{$field} = $p[$field];
        }
    }
    $defaults = array('grantedByUserId' => $user->id, 'readLevel' => -1, 'writeLevel' => -1, 'adminLevel' => -1);
    foreach ($defaults as $k => $v) {
        if (!isset($access->{$k})) {
            $access->{$k} = $v;
        }
    }
    $access->save();
    Streams::$cache['access'] = $access;
}
Example #24
0
function Users_user_response_batch($params = array())
{
    $req = array_merge($_REQUEST, $params);
    Q_Valid::requireFields(array('batch'), $req, true);
    $batch = $req['batch'];
    $batch = json_decode($batch, true);
    if (!isset($batch)) {
        throw new Q_Exception_WrongValue(array('field' => 'batch', 'range' => '{userIds: [userId1, userId2, ...]}'));
    }
    Q_Valid::requireFields(array('userIds'), $batch, true);
    $userIds = $batch['userIds'];
    $users = Q::event('Users/user/response/users', compact('userIds'));
    $result = array();
    foreach ($userIds as $userId) {
        $result[] = array('slots' => array('user' => isset($users[$userId]) ? $users[$userId] : null));
    }
    Q_Response::setSlot('batch', $result);
}
Example #25
0
function Streams_register_validate()
{
    Q_Valid::nonce(true);
    $fields = Users::loggedInUser() ? array('fullName') : array('identifier', 'fullName', 'icon');
    foreach ($fields as $field) {
        if (!isset($_REQUEST[$field])) {
            throw new Q_Exception("{$field} is missing", array($field));
        }
    }
    $length_min = Q_Config::get('Streams', 'inputs', 'fullName', 'lengthMin', 5);
    $length_max = Q_Config::get('Streams', 'inputs', 'fullName', 'lengthMax', 30);
    if (strlen($_REQUEST['fullName']) < $length_min) {
        throw new Q_Exception("Your full name can't be that short.", 'fullName');
    }
    if (strlen($_REQUEST['fullName']) > $length_max) {
        throw new Q_Exception("Your full name can't be that long.", 'fullName');
    }
}
Example #26
0
function Users_activate_post()
{
    Q_Valid::nonce(true);
    $email = $mobile = $type = $user = null;
    extract(Users::$cache, EXTR_IF_EXISTS);
    if (isset($_REQUEST['passphrase'])) {
        if (empty($_REQUEST['passphrase'])) {
            throw new Q_Exception("You can't set a blank passphrase.", 'passphrase');
        }
        $isHashed = !empty($_REQUEST['isHashed']);
        if ($isHashed and $isHashed !== 'true' and intval($_REQUEST['isHashed']) > 1) {
            // this will let us introduce other values for isHashed in the future
            throw new Q_Exception("Please set isHashed to 0 or 1", 'isHashed');
        }
        // Save the pass phrase even if there may be a problem adding an email later.
        // At least the user will be able to log in.
        $user->passphraseHash = $user->computePassphraseHash($_REQUEST['passphrase'], $isHashed);
        Q_Response::setNotice("Users/activate/passphrase", "Your pass phrase has been saved.", true);
        // Log the user in, since they were able to set the passphrase
        Users::setLoggedInUser($user);
        // This also saves the user.
        if (empty($user->passphraseHash)) {
            throw new Q_Exception("Please set a pass phrase on your account", 'passphrase', true);
        }
    }
    if ($type) {
        if ($type == 'email address') {
            $user->setEmailAddress($email->address);
            // may throw exception
        } else {
            if ($type == 'mobile number') {
                $user->setMobileNumber($mobile->number);
                // may throw exception
            }
        }
        // Log the user in, since they have just added an email to their account
        Users::setLoggedInUser($user);
        // This also saves the user.
        Q_Response::removeNotice('Users/activate/objects');
        Q_Response::setNotice("Users/activate/activated", "Your {$type} has been activated.", true);
    }
    Users::$cache['passphrase_set'] = true;
    Users::$cache['success'] = true;
}
Example #27
0
function Streams_basic_validate()
{
    Q_Valid::nonce(true);
    if (Q_Request::method() !== 'POST') {
        return;
    }
    $fields = array('firstName' => 'First name', 'lastName' => 'Last name', 'gender' => 'Gender', 'birthday_month' => 'Month', 'birthday_day' => 'Day', 'birthday_year' => 'Year');
    if (isset($_REQUEST['fullName'])) {
        $length_min = Q_Config::get('Streams', 'inputs', 'fullName', 'lengthMin', 5);
        $length_max = Q_Config::get('Streams', 'inputs', 'fullName', 'lengthMax', 30);
        if (strlen($_REQUEST['fullName']) < $length_min) {
            Q_Response::addError(new Q_Exception("Your full name can't be that short.", 'fullName'));
        }
        if (strlen($_REQUEST['fullName']) > $length_max) {
            Q_Response::addError(new Q_Exception("Your full name can't be that long.", 'fullName'));
        }
    }
    if (Q_Response::getErrors()) {
        return;
    }
    if (!empty($_REQUEST['birthday_month']) or !empty($_REQUEST['birthday_day']) or !empty($_REQUEST['birthday_year'])) {
        foreach (array('birthday_month', 'birthday_day', 'birthday_year') as $field) {
            if (empty($_REQUEST[$field]) or !trim($_REQUEST[$field])) {
                throw new Q_Exception_RequiredField(compact('field'), $field);
            }
        }
        if (!checkdate($_REQUEST['birthday_month'], $_REQUEST['birthday_day'], $_REQUEST['birthday_year'])) {
            Q_Response::addError(new Q_Exception("Not a valid date", "birthday_day"));
        }
        if ($_REQUEST['birthday_year'] > date('Y') - 13) {
            // compliance with COPPA
            Q_Response::addError(new Q_Exception("You're still a kid.", "birthday_year"));
        }
        if ($_REQUEST['birthday_year'] < date('Y') - 100) {
            Q_Response::addError(new Q_Exception("A world record? Really?", "birthday_year"));
        }
    }
    if (!empty($_REQUEST['gender'])) {
        if (!in_array($_REQUEST['gender'], array('male', 'female'))) {
            Q_Response::addError(new Q_Exception("Please enter male or female", "gender"));
        }
    }
}
Example #28
0
function Streams_after_Q_file_save($params)
{
    $path = $subpath = $name = $writePath = $data = $tailUrl = $size = $audio = null;
    extract($params, EXTR_OVERWRITE);
    if (!empty(Streams::$cache['canWriteToStream'])) {
        // some stream's associated file was being changed
        $stream = Streams::$cache['canWriteToStream'];
    }
    if (empty($stream)) {
        return;
    }
    $url = Q_Valid::url($tailUrl) ? $tailUrl : '{{baseUrl}}/' . $tailUrl;
    $stream->setAttribute('Q.file.url', $url);
    $stream->setAttribute('Q.file.size', $size);
    if ($audio) {
        include_once Q_CLASSES_DIR . DS . 'Audio' . DS . 'getid3' . DS . 'getid3.php';
        $getID3 = new getID3();
        $meta = $getID3->analyze($writePath . $name);
        $bitrate = $meta['audio']['bitrate'];
        $bits = $size * 8;
        $duration = $bits / $bitrate;
        $stream->setAttribute('Q.audio.bitrate', $bitrate);
        $stream->setAttribute('Q.audio.duration', $duration);
    }
    if (Streams_Stream::getConfigField($stream->type, 'updateTitle', false)) {
        // set the title every time a new file is uploaded
        $stream->title = $name;
    }
    if (Streams_Stream::getConfigField($stream->type, 'updateIcon', false)) {
        // set the icon every time a new file is uploaded
        $parts = explode('.', $name);
        $urlPrefix = Q_Request::baseUrl() . '/plugins/Streams/img/icons/files';
        $dirname = STREAMS_PLUGIN_FILES_DIR . DS . 'Streams' . DS . 'icons' . DS . 'files';
        $extension = end($parts);
        $stream->icon = file_exists($dirname . DS . $extension) ? "{$urlPrefix}/{$extension}" : "{$urlPrefix}/_blank";
    }
    if (empty(Streams::$beingSavedQuery)) {
        $stream->changed();
    } else {
        $stream->save();
    }
}
Example #29
0
function Users_oAuth_post()
{
    // Validate the inputs
    $fields = array('response_type', 'token_type', 'access_token', 'expires_in', 'scope', 'state', 'Q_Users_oAuth');
    Q_Request::requireFields($fields, true);
    $params = Q::take($_REQUEST, $fields);
    $params['Q.Users.oAuth'] = $params['Q_Users_oAuth'];
    unset($params['Q_Users_oAuth']);
    Q_Valid::signature(true, $params, array('Q.Users.oAuth'));
    // Set the session id to the access_token
    Q_Session::id($params['access_token']);
    // Add a device, if any
    if ($deviceId = Q::ifset($_REQUEST, 'deviceId', null)) {
        $fields2 = array('deviceId', 'platform', 'version', 'formFactor');
        Q_Request::requireFields($fields2);
        $device = Q::take($_REQUEST, $fields2);
        $device['userId'] = Users::loggedInUser(true)->id;
        Users_Device::add($device);
    }
}
Example #30
0
function Users_contact_response_batch($params = array())
{
    $req = array_merge($_REQUEST, $params);
    Q_Valid::requireFields(array('batch'), $req, true);
    $batch = $req['batch'];
    $batch = json_decode($batch, true);
    if (!isset($batch)) {
        throw new Q_Exception_WrongValue(array('field' => 'batch', 'range' => '{userIds: [...], labels: [...], contactUserIds: [...]}'));
    }
    Q_Valid::requireFields(array('userIds', 'labels', 'contactUserIds'), $batch, true);
    $userIds = $batch['userIds'];
    $labels = $batch['labels'];
    $contactUserIds = $batch['contactUserIds'];
    $contacts = Q::event('Users/contact/response/contacts', compact('userIds', 'labels', 'contactUserIds'));
    $result = array();
    foreach ($contacts as $contact) {
        $result[] = array('slots' => array('contact' => $contact));
    }
    Q_Response::setSlot('batch', $result);
}