Example #1
0
/**
 * Provide player content to view the members of category listing
 * Uses Streams/$type/category.php view (Streams/$streamType/category/get.php can be used for viewing the category
 * stream itself if type of category is $streamType/category)
 * and Streams::related to retrieve streams data
 *
 **/
function Streams_category_response_player()
{
    $user = Users::loggedInUser();
    $userId = $user ? $user->id : 0;
    // These are PK of the category!
    $publisherId = Streams::requestedPublisherId(true);
    $name = Streams::requestedName(true);
    // need to know publisher and type of the streams to list
    $streamType = Streams::requestedType();
    if ($streamType) {
        $prefix = "{$streamType}/";
    }
    $stream_publisherId = Q::expect('Streams', $streamType, 'publisher');
    if (substr($name, -1) === '/') {
        throw new Q_Exception("Player cannot show listing for multiple categories", compact('publisherId', 'name'));
    }
    /*
     * Get shall return only streams which user is authorized to see.
     */
    $categories = Streams::fetch($userId, $publisherId, $name);
    if (empty($categories)) {
        throw new Q_Exception_MissingRow(array('table' => 'stream', 'criteria' => compact('publisherId', 'name')));
    }
    $category = reset($categories);
    // Are you authorized to see category content?
    if (!$category->testReadLevel('content')) {
        throw new Users_Exception_NotAuthorized();
    }
    // get all the streams which are members of this category
    // as Streams::get verifies access rights, it's safe to show all streams' content
    list($relations, $streams) = Streams::related($userId, $publisherId, $name, true, array('prefix' => $prefix, 'skipAccess' => true));
    Q::view("Stream/{$type}/category.php", compact('relations', 'streams', 'userId'));
}
Example #2
0
 /**
  * @constructor
  * @param {array} $options=array() Any initial options
  * @param {string} $options.secret
  * @param {string} $options.publishableKey
  * @param {string} $options.token If provided, allows us to create a customer and charge them
  * @param {Users_User} [$options.user=Users::loggedInUser()] Allows us to set the user to charge
  */
 function __construct($options = array())
 {
     if (!isset($options['user'])) {
         $options['user'] = Users::loggedInUser(true);
     }
     $this->options = array_merge(array('secret' => Q_Config::expect('Assets', 'payments', 'stripe', 'secret'), 'publishableKey' => Q_Config::expect('Assets', 'payments', 'stripe', 'publishableKey')), $options);
 }
Example #3
0
function Q_response_dashboard()
{
    $app = Q_Config::expect('Q', 'app');
    $slogan = "Powered by Q.";
    $user = Users::loggedInUser();
    return Q::view("{$app}/dashboard.php", compact('slogan', 'user'));
}
Example #4
0
 /**
  * Retrieve avatars for one or more publishers as displayed to a particular user.
  * 
  * @method fetch
  * @static
  * @param $toUserId {User_User|string} The id of the user to which this would be displayed
  * @param $publisherIds {string|array} Array of various users whose avatars are being fetched
  * @param $indexField {string} Optional name of the field by which to index the resulting array
  * @return {Streams_Avatar|array}
  */
 static function fetch($toUserId, $publisherId, $indexField = null)
 {
     if (!isset($toUserIs)) {
         $toUserId = Users::loggedInUser();
         if (!$toUserId) {
             $toUserId = "";
         }
     }
     if ($toUserId instanceof Users_User) {
         $toUserId = $toUserId->id;
     }
     if ($publisherId instanceof Users_User) {
         $publisherId = $publisherId->id;
     }
     $return_one = false;
     if (!is_array($publisherId)) {
         $publisherId = array($publisherId);
         $return_one = true;
     }
     $rows = Streams_Avatar::select('*')->where(array('toUserId' => array($toUserId, ''), 'publisherId' => $publisherId))->fetchDbRows(null, '', $indexField);
     $avatars = array();
     foreach ($rows as $r) {
         if (!isset($avatars[$r->publisherId]) or $r->toUserId !== '') {
             $avatars[$r->publisherId] = $r;
         }
     }
     return $return_one ? $avatars ? reset($avatars) : null : $avatars;
 }
Example #5
0
function MyApp_home_response_content($params)
{
    // Implement a home page for the user
    $user = Users::loggedInUser();
    // For now we will just internally forward to the welcome page
    Q_Dispatcher::forward("MyApp/welcome");
}
Example #6
0
function users_contact_post()
{
    Pie_Session::start();
    Pie_Valid::nonce(true);
    extract($_REQUEST);
    $user = Users::loggedInUser();
    if (!$user) {
        throw new Users_Exception_NotLoggedIn();
    }
    $app = Pie_Config::expect('pie', 'app');
    $subject = "Welcome! Activate your email.";
    $view = "{$app}/email/setEmail.php";
    $fields = array();
    $p = array();
    $p['subject'] =& $subject;
    $p['view'] =& $view;
    $p['fields'] =& $fields;
    Pie::event('users/setEmail', $p, 'before');
    // may change the fields
    if (isset($first_name)) {
        $user->first_name = $first_name;
    }
    if (isset($last_name)) {
        $user->last_name = $last_name;
    }
    $user->addEmail($_REQUEST['email_address'], $subject, $view, true, $fields);
    // If no exceptions were throw, save this user row
    if (isset($first_name) or isset($last_name)) {
        $user->save();
    }
}
Example #7
0
/**
 * Adds a label to the system. Fills the "label" (and possibly "icon") slot.
 * @param {array} $_REQUEST
 * @param {string} $_REQUEST.title The title of the label
 * @param {string} [$_REQUEST.label] You can override the label to use
 * @param {string} [$_REQUEST.icon] Optional path to an icon
 * @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_label_post($params = array())
{
    $req = array_merge($_REQUEST, $params);
    Q_Request::requireFields(array('title'), $req, true);
    $loggedInUserId = Users::loggedInUser(true)->id;
    $userId = Q::ifset($req, 'userId', $loggedInUserId);
    $icon = Q::ifset($req, 'icon', null);
    $title = $req['title'];
    $l = Q::ifset($req, 'label', 'Users/' . Q_Utils::normalize($title));
    Users::canManageLabels($loggedInUserId, $userId, $l, true);
    $label = new Users_Label();
    $label->userId = $userId;
    $label->label = $l;
    if ($label->retrieve()) {
        throw new Users_Exception_LabelExists();
    }
    $label->title = $title;
    if (is_array($icon)) {
        // Process any icon that was posted
        $icon['path'] = 'uploads/Users';
        $icon['subpath'] = "{$userId}/label/{$label}/icon";
        $data = Q::event("Q/image/post", $icon);
        Q_Response::setSlot('icon', $data);
        $label->icon = Q_Request::baseUrl() . '/' . $data[''];
    } else {
        $label->icon = 'default';
    }
    $label->save();
    Q_Response::setSlot('label', $label->exportArray());
}
Example #8
0
function Shipping_shipment_response_content($params)
{
    $user = Users::loggedInUser(true);
    // copy from shipment
    $useTemplate = Q_Request::uri()->template ? "Shipping/shipment/" . Q_Request::uri()->template : false;
    // Check if stream "Shipping/shipments" exists for current user. If no -> create one.
    Shipping::shipments();
    // Check if stream "Shipping/templates" exists for current user. If no -> create one.
    Shipping::createTemplatesStream();
    // Collect streams for shipments. Relations: "describing", "scheduled", "confirmed", "shipping", "canceled", "returned"
    $shipment = Shipping::shipment();
    //$shipment->addPreloaded($userId);
    // test for UPS pickup
    //$stream = Streams::fetchOne("Shipping", "Shipping", "Shipping/shipment/Qdqpcspny");
    //$carrier = new Shipping_Carrier_UPS();
    //$carrier->pickupCreate($stream);
    //-------------------------------
    // add main style
    Q_Response::addStylesheet('css/Shipment.css');
    // set communityId
    Q_Response::setScriptData("Q.info.communityId", Users::communityId());
    Q_Response::setScriptData("Q.info.useTemplate", $useTemplate);
    Q_Response::addScript('js/shipment.js');
    Q_Response::addScript('js/date.js');
    // add jquery UI
    //Q_Response::addStylesheet('//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css');
    //Q_Response::addScript('//code.jquery.com/ui/1.11.4/jquery-ui.js');
    // add pickadate as date picker
    Q_Response::addStylesheet('js/pickadate/compressed/themes/default.css');
    Q_Response::addStylesheet('js/pickadate/compressed/themes/default.date.css');
    Q_Response::addScript('js/pickadate/compressed/picker.js');
    Q_Response::addScript('js/pickadate/compressed/picker.date.js');
    return Q::view('Shipping/content/shipment.php', compact('user', 'shipment', 'useTemplate'));
}
Example #9
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;
    }
}
function Websites_before_Streams_Stream_save_Websites_article($params)
{
    $stream = $params['stream'];
    $modifiedFields = $params['modifiedFields'];
    if ($stream->wasRetrieved()) {
        return;
    }
    $user = new Users_User();
    if (empty($stream->userId) and empty($modifiedFields['userId'])) {
        if ($liu = Users::loggedInUser()) {
            $stream->userId = $liu->id;
        } else {
            throw new Q_Exception_RequiredField(array('field' => 'userId'));
        }
    }
    $user->id = $stream->userId;
    if (!$user->retrieve()) {
        throw new Users_Exception_NoSuchUser();
    }
    $title = Streams::displayName($user, array('fullAccess' => true));
    if (isset($title)) {
        $stream->title = $title;
    }
    $stream->icon = $user->iconUrl();
    $s = Streams::fetchOne($user->id, $user->id, "Streams/user/icon");
    if (!$s or !($sizes = $s->getAttribute('sizes', null))) {
        $sizes = Q_Config::expect('Users', 'icon', 'sizes');
        sort($sizes);
    }
    $stream->setAttribute('sizes', $sizes);
}
Example #11
0
function Streams_after_Q_objects()
{
    $user = Users::loggedInUser();
    if (!$user) {
        return;
    }
    $invite = Streams::$followedInvite;
    if (!$invite) {
        return;
    }
    $displayName = $user->displayName();
    if ($displayName) {
        return;
    }
    $stream = new Streams_Stream();
    $stream->publisherId = $invite->publisherId;
    $stream->name = $invite->streamName;
    if (!$stream->retrieve()) {
        throw new Q_Exception_MissingRow(array('table' => 'stream', 'criteria' => 'with that name'), 'streamName');
    }
    // Prepare the complete invite dialog
    $invitingUser = Users_User::fetch($invite->invitingUserId);
    list($relations, $related) = Streams::related($user->id, $stream->publisherId, $stream->name, false);
    $params = array('displayName' => null, 'action' => 'Streams/basic', 'icon' => $user->iconUrl(), 'token' => $invite->token, 'user' => array('icon' => $invitingUser->iconUrl(), 'displayName' => $invitingUser->displayName(array('fullAccess' => true))), 'stream' => $stream->exportArray(), 'relations' => Db::exportArray($relations), 'related' => Db::exportArray($related));
    $config = Streams_Stream::getConfigField($stream->type, 'invite', array());
    $defaults = Q::ifset($config, 'dialog', array());
    $tree = new Q_Tree($defaults);
    if ($tree->merge($params)) {
        $dialogData = $tree->getAll();
        if ($dialogData) {
            Q_Response::setScriptData('Q.plugins.Streams.invite.dialog', $dialogData);
            Q_Response::addTemplate('Streams/invite/complete');
        }
    }
}
Example #12
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 #13
0
function Streams_participant_response_participant()
{
    if (isset(Streams::$cache['participant'])) {
        return Streams::$cache['participant'];
    }
    $publisherId = Streams::requestedPublisherId(true);
    $streamName = Streams::requestedName(true);
    if (empty($_REQUEST['userId'])) {
        throw new Q_Exception_RequiredField(array('field' => 'userId'));
    }
    $user = Users::loggedInUser();
    $userId = $user ? $user->id : "";
    $stream = Streams::fetch($userId, $publisherId, $streamName);
    if (empty($stream)) {
        throw new Q_Exception_MissingRow(array('table' => 'Stream', 'criteria' => "{publisherId: '{$publisherId}', name: '{$streamName}'}"));
    }
    $stream = reset($stream);
    if (!$stream->testReadLevel('participants')) {
        throw new Users_Exception_NotAuthorized();
    }
    $p = new Streams_Participant();
    $p->publisherId = $publisherId;
    $p->streamName = $streamName;
    $p->userId = $_REQUEST['userId'];
    if ($p->retrieve()) {
        return $p->exportArray();
    }
    return null;
}
Example #14
0
function Streams_stream_response_Q_inplace()
{
    $user = Users::loggedInUser();
    $stream = isset(Streams::$cache['stream']) ? Streams::$cache['stream'] : null;
    if (!$stream) {
        throw new Exception("No stream");
    }
    if (isset($_REQUEST['title'])) {
        $result = $stream->title;
    } else {
        if (isset($_REQUEST['attributes'])) {
            if (is_array($_REQUEST['attributes'])) {
                reset($_REQUEST['attributes']);
                $result = $stream->getAttribute(key($_REQUEST['attributes']));
            } else {
                $result = $stream->attributes;
            }
        } else {
            $fieldNames = array_diff(Streams::getExtendFieldNames($stream->type), array('insertedTime', 'updatedTime'));
            $field = 'content';
            foreach ($fieldNames as $f) {
                if (isset($_REQUEST[$f])) {
                    $field = $f;
                    break;
                }
            }
            $result = $stream->{$field};
        }
    }
    $convert = Q::ifset($_REQUEST, 'convert', '["\\n"]');
    return Q_Html::text($result, json_decode($convert, true));
}
Example #15
0
function Websites_seo_post()
{
    if (empty($_REQUEST['streamName'])) {
        throw new Q_Exception_RequiredField(array('field' => 'streamName'));
    }
    $prefix = "Websites/seo/";
    if (substr($_REQUEST['streamName'], 0, strlen($prefix)) !== $prefix) {
        throw new Q_Exception_WrongValue(array('field' => 'streamName', 'range' => "string beginning with {$prefix}"));
    }
    $user = Users::loggedInUser(true);
    $publisherId = Users::communityId();
    $type = "Websites/seo";
    if (!Streams::isAuthorizedToCreate($user->id, $publisherId, $type)) {
        throw new Users_Exception_NotAuthorized();
    }
    $stream = new Streams_Stream($publisherId);
    $stream->publisherId = $publisherId;
    $stream->name = $_REQUEST['streamName'];
    $stream->type = $type;
    if (isset($_REQUEST['uri'])) {
        $stream->setAttribute('uri', $_REQUEST['uri']);
    }
    $stream->save();
    $stream->post($user->id, array('type' => 'Streams/created', 'content' => '', 'instructions' => Q::json_encode($stream->toArray())), true);
    $stream->subscribe();
    // autosubscribe to streams you yourself create, using templates
    Q_Response::setSlot('stream', $stream->exportArray());
}
Example #16
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 #17
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'));
}
function Streams_before_Q_responseExtras()
{
    Q_Response::addScript('plugins/Streams/js/Streams.js');
    $host = Q_Config::get('Streams', 'node', 'host', Q_Config::get('Q', 'node', 'host', null));
    $port = Q_Config::get('Streams', 'node', 'port', Q_Config::get('Q', 'node', 'port', null));
    $user = Users::loggedInUser();
    if ($user) {
        Q_Response::setScriptData('Q.plugins.Users.loggedInUser.displayName', Streams::displayName($user));
    }
    if (!Q_Request::isAjax()) {
        $invite_url = Q_Config::get('Streams', 'invite', 'url', "http://invites.to");
        Q_Response::setScriptData('Q.plugins.Streams.invite.url', $invite_url);
        if (isset($host) && isset($port)) {
            Q_Response::setScriptData('Q.plugins.Streams.node', array("http://{$host}:{$port}"));
        }
        if ($sizes = Q_Config::expect('Streams', 'types', 'Streams/image', 'sizes')) {
            sort($sizes);
            Q_Response::setScriptData('Q.plugins.Streams.image.sizes', $sizes);
        }
        $defaults = array('readLevel' => Streams::$READ_LEVEL['messages'], 'writeLevel' => Streams::$WRITE_LEVEL['join'], 'adminLevel' => Streams::$ADMIN_LEVEL['invite']);
        Q_Response::setScriptData('Q.plugins.Streams.defaults', $defaults);
        if ($froalaKey = Q_Config::get('Streams', 'froala', 'key', null)) {
            Q_Response::setScriptData('Q.plugins.Streams.froala.key', $froalaKey);
        }
    }
    Q_Response::addStylesheet("plugins/Streams/css/Streams.css");
}
Example #19
0
/**
 * Used to create a new stream
 *
 * @param {array} $_REQUEST 
 * @param {String} [$_REQUEST.title] Required. The title of the interest.
 * @param {String} [$_REQUEST.publisherId] Optional. Defaults to the app name.
 * @return {void}
 */
function Streams_interest_delete()
{
    $user = Users::loggedInUser(true);
    $title = Q::ifset($_REQUEST, 'title', null);
    if (!isset($title)) {
        throw new Q_Exception_RequiredField(array('field' => 'title'));
    }
    $app = Q_Config::expect('Q', 'app');
    $publisherId = Q::ifset($_REQUEST, 'publisherId', $app);
    $name = 'Streams/interest/' . Q_Utils::normalize($title);
    $stream = Streams::fetchOne(null, $publisherId, $name);
    if (!$stream) {
        throw new Q_Exception_MissingRow(array('table' => 'stream', 'criteria' => Q::json_encode(compact('publisherId', 'name'))));
    }
    $miPublisherId = $user->id;
    $miName = 'Streams/user/interests';
    $myInterests = Streams::fetchOne($user->id, $miPublisherId, $miName);
    if (!$myInterests) {
        throw new Q_Exception_MissingRow(array('table' => 'stream', 'criteria' => Q::json_encode(array('publisherId' => $miPublisherId, 'name' => $miName))));
    }
    $stream->leave();
    Streams::unrelate($user->id, $user->id, 'Streams/user/interests', 'Streams/interest', $publisherId, $name, array('adjustWeights' => true));
    Q_Response::setSlot('publisherId', $publisherId);
    Q_Response::setSlot('streamName', $name);
    /**
     * Occurs when the logged-in user has successfully removed an interest via HTTP
     * @event Streams/interest/delete {after}
     * @param {string} publisherId The publisher of the interest stream
     * @param {string} title The title of the interest
     * @param {Users_User} user The logged-in user
     * @param {Streams_Stream} stream The interest stream
     * @param {Streams_Stream} myInterests The user's "Streams/user/interests" stream
     */
    Q::event("Streams/interest/remove", compact('publisherId', 'title', 'subscribe', 'user', 'stream', 'myInterests'), 'after');
}
Example #20
0
/**
 * Used to post messages to EXISTING stream
 * $_REQUEST shall contain the content of the message. Also may include 'streamNames' 
 * field which is an array of additional names of the streams to post message to.
 *
 * @param string $params 
 *   publisher id and stream name of existing stream shall be supplied
 * @return {void}
 */
function Streams_message_post()
{
    $user = Users::loggedInUser(true);
    $publisherId = Streams::requestedPublisherId(true);
    $streamName = Streams::requestedName(true);
    // check if type is allowed
    $streams = Streams::fetch($user->id, $publisherId, $streamName);
    if (empty($streams)) {
        throw new Streams_Exception_NoSuchStream();
    }
    $stream = reset($streams);
    if (empty($_REQUEST['type'])) {
        throw new Q_Exception_RequiredField(array('field' => 'type'), 'type');
    }
    $type = $_REQUEST['type'];
    if (!Q_Config::get("Streams", "types", $stream->type, "messages", $type, 'post', false)) {
        throw new Q_Exception("This app doesn't support directly posting messages of type '{$type}' for streams of type '{$stream->type}'");
    }
    $result = Streams_Message::post($user->id, $publisherId, $streamName, $_REQUEST);
    if (is_array($result)) {
        Streams::$cache['messages'] = $result;
    } else {
        Streams::$cache['message'] = $result;
    }
}
Example #21
0
function Broadcast_control_response_content($params)
{
    $user = Users::loggedInUser(true);
    $organizations = Broadcast_Agreement::select('a.userId, a.publisherId, u.organization_title, u.organization_domain', 'a')->join(Broadcast_User::table() . ' u', array('a.publisherId' => 'u.userId'))->where(array('a.userId' => $user->id))->fetchAll(PDO::FETCH_ASSOC);
    foreach ($organizations as $k => $org) {
        $messages = Streams_Message::select('content')->where(array('publisherId' => $org['publisherId'], 'streamName' => 'Broadcast/main'))->orderBy('sentTime')->fetchAll(PDO::FETCH_ASSOC);
        $organizations[$k]['messages'] = array();
        foreach ($messages as $msg) {
            $content = json_decode($msg['content'], true);
            if (isset($content['link'])) {
                $ch = curl_init();
                $timeout = 5;
                curl_setopt($ch, CURLOPT_URL, $content['link']);
                curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
                curl_setopt($ch, CURLOPT_HEADER, 0);
                curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (X11; U; Linux i686; cs-CZ; rv:1.7.12) Gecko/20050929");
                $page_contents = curl_exec($ch);
                curl_close($ch);
                preg_match('/<title>([^<]+)<\\/title>/', $page_contents, $matches);
                if (isset($matches[1])) {
                    $content['link_title'] = $matches[1];
                }
            }
            $organizations[$k]['messages'][] = $content;
        }
    }
    Q_Config::set('Q', 'response', 'Broadcast', 'layout_html', 'Broadcast/layout/canvas.php');
    Q_Response::addStylesheet('css/canvas.css');
    Q_Response::addScript('http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js');
    Q_Response::addScript('js/canvas.js');
    return Q::view('Broadcast/content/control.php', compact('organizations'));
}
Example #22
0
/**
 * Displays an HTML document that can be printed, ideally with line breaks.
 * Uses a particular view for the layout.
 * @param {array} $_REQUEST
 * @param {string} $_REQUEST.invitingUserId Required. The id of the user that generated the invitations with a call to Streams::invite.
 * @param {string} $_REQUEST.batch Required. The name of the batch under which invitations were saved during a call to Streams::invite.
 * @param {string} [$_REQUEST.limit=100] The maximum number of invitations to show on the page
 * @param {string} [$_REQUEST.offset=0] Used for paging
 * @param {string} [$_REQUEST.title='Invitations'] Override the title of the document
 * @param {string} [$_REQUEST.layout='default'] The name of the layout to use for the HTML document
 * @see Users::addLink()
 */
function Streams_invitations_response()
{
    Q_Request::requireFields(array('batch', 'invitingUserId'), true);
    $invitingUserId = $_REQUEST['invitingUserId'];
    $batch = $_REQUEST['batch'];
    $user = Users::loggedInUser(true);
    $stream = Streams::fetchOne(null, $invitingUserId, 'Streams/invitations', true);
    if (!$stream->testReadLevel('content')) {
        throw new Users_Exception_NotAuthorized();
    }
    $title = Q::ifset($_REQUEST, 'layout', 'title');
    $layoutKey = Q::ifset($_REQUEST, 'layout', 'default');
    $limit = min(1000, Q::ifset($_REQUEST, 'limit', 100));
    $offset = Q::ifset($_REQUEST, 'offset', 0);
    $layout = Q_Config::expect('Streams', 'invites', 'layout', $layoutKey);
    $pattern = Streams::invitationsPath($invitingUserId) . DS . $batch . DS . "*.html";
    $filenames = glob($pattern);
    $parts = array();
    foreach ($filenames as $f) {
        if (--$offset > 0) {
            continue;
        }
        $parts[] = file_get_contents($f);
        if (--$limit == 0) {
            break;
        }
    }
    $content = implode("\n\n<div class='Q_pagebreak Streams_invitations_separator'></div>\n\n", $parts);
    echo Q::view($layout, compact('title', 'content', 'parts'));
    return false;
}
Example #23
0
/**
 * Renders chat tool.
 * @class Streams chat
 * @constructor
 * @param {array} $options Options for the tool
 * @param {string} $options.publisherId Publisher id of the stream to get messsages from.
 * @param {string} $options.streamName Required. Name of the stream to get messsages from.
 * @param {string} [$options.loadMore] May have one these values: 'scroll', 'click' or 'pull' which indicates what kind of algorithm will be used for loading new messages. 'scroll' means that new messages will be loaded when scrollbar of the chat cointainer reaches the top (for desktop) or whole document scrollbar reaches the top (for android). 'click' will show label with 'Click to see earlier messages' and when user clicks it, new messages will be loaded. Finally, 'pull' implements 'pull-to-refresh' behavior used in many modern applications today when new messages loaded by rubber-scrolling the container by more amount than it actually begins. Defaults to 'scroll' for desktop and Android devices and 'pull' for iOS devices.
*/
function Streams_chat_tool($options)
{
    $user = Users::loggedInUser();
    $userId = $user ? $user->id : '';
    /*
    $defaults = array(
    	'loadMore'         => (Q_Request::isTouchscreen() && Q_Request::platform() != 'android') ? 'click' : 'scroll',
    	'messagesToLoad'   => 5,
    	'messageMaxHeight' => 200
    );
    $options = array_merge($defaults, $options);
    */
    extract($options);
    if (!isset($publisherId)) {
        $publisherId = Streams::requestedPublisherId(true);
    }
    if (!isset($streamName)) {
        $streamName = Streams::requestedName();
    }
    $stream = Streams::fetchOne($userId, $publisherId, $streamName);
    if (!$stream) {
        throw new Q_Exception_MissingRow(array('table' => 'stream', 'criteria' => compact('publisherId', 'streamName')));
    }
    $options['userId'] = $userId;
    if (!isset($options['notLoggedIn'])) {
        $options['notLoggedIn'] = 'You are not logged in';
    }
    if (!isset($options['notAuthorized'])) {
        $options['notAuthorized'] = 'You are not authorized';
    }
    Q_Response::setToolOptions($options);
}
Example #24
0
function Shipping_scheduled_response_content($params)
{
    // redirect to home page if not logged in
    if (!Users::loggedInUser()) {
        header("Location: " . Q_Request::baseUrl());
        exit;
    }
    // get "Shipping/shipments" stream
    $publisherId = Users::communityId();
    $streamName = 'Shipping/shipment/' . Q_Request::uri()->shipmentStreamName;
    $stream = Streams::fetchOne($publisherId, $publisherId, $streamName);
    //$xml = simplexml_load_file(APP_DIR.'/classes/dhl/response.xml');
    //$xml = simplexml_load_string(str_replace('req:', '', file_get_contents(APP_DIR.'/classes/dhl/response.xml')));
    //print_r($xml); exit;
    // test pickup
    //$carrier = new Shipping_Carrier_DHL();
    //$carrier->createAWBBarCode($stream, 'iVBORw0KGgoAAAANSUhEUgAAAYwAAABeAQMAAAAKdrGZAAAABlBMVEX///8AAABVwtN+AAAAaklEQVR42mNkYGBIyL8wZcutG2wTzVMZfG99eep7y1tp5oIokaMMOtabG6PuTflrnnHqVfI013vzlRYwMDAxkAxGtYxqGdUyqmVUy6iWUS2jWka1jGoZ1TKqZVTLqJZRLaNaRrWMaiEVAABqDRe8DYfcJgAAAABJRU5ErkJggg==', "AWBBarCode");
    // -----------
    //echo Shipping::getShipmentRelation($stream, true);
    //unlink("/tmp/dhl-api-autoload.php");
    if (!$stream || !$stream->testReadLevel('see')) {
        throw new Users_Exception_NotAuthorized();
    }
    return Q::view('Shipping/content/scheduled.php', compact('streamName'));
}
Example #25
0
function Streams_invite_response_data()
{
    if (isset(Streams::$cache['invited'])) {
        return Streams::$cache['invited'];
    }
    $user = Users::loggedInUser(true);
    $publisherId = Streams::requestedPublisherId();
    $streamType = Streams::requestedType();
    $invitingUserId = Streams::requestedField('invitingUserId');
    $limit = Q::ifset($_REQUEST, 'limit', Q_Config::get('Streams', 'invites', 'limit', 100));
    $invited = Streams_Invited::select('*')->where(array('userId' => $user->id, 'state' => 'pending', 'expireTime <' => new Db_Expression('CURRENT_TIMESTAMP')))->limit($limit)->fetchDbRows(null, null, 'token');
    $query = Streams_Invite::select('*')->where(array('token' => array_keys($invited)));
    if (isset($publisherId)) {
        $query = $query->where(array('publisherId' => $publisherId));
    }
    if (isset($streamType)) {
        $query = $query->where(array('streamName' => new Db_Range($streamType . '/', true, false, true)));
    }
    if (isset($invitingUserId)) {
        $query = $query->where(array('invitingUserId' => $invitingUserId));
    }
    $invites = $query->fetchDbRows();
    $streams = array();
    foreach ($invites as $invite) {
        $stream = new Streams_Stream();
        $stream->publisherId = $invite->publisherId;
        $stream->name = $invite->streamName;
        if ($stream->retrieve()) {
            $streams[$invite->token] = $stream->exportArray();
            $streams[$invite->token]['displayName'] = $invite->displayName;
        }
    }
    return compact('streams', 'invites');
}
Example #26
0
function Users_identifier_post()
{
    $userId = Q::ifset($_REQUEST, 'userId', null);
    if (isset($userId)) {
        $user = Users_User::fetch($userId, true);
        if ($user->emailAddress or $user->mobileNumber) {
            throw new Q_Exception("This user is already able to log in and set their own email and mobile number.");
        }
    } else {
        $user = Users::loggedInUser(true);
    }
    $app = Q_Config::expect('Q', 'app');
    $fields = array();
    $identifier = Users::requestedIdentifier($type);
    if (!$type) {
        throw new Q_Exception("a valid email address or mobile number is required", array('identifier', 'mobileNumber', 'emailAddress'));
    }
    if ($type === 'email') {
        $subject = Q_Config::get('Users', 'transactional', 'identifier', 'subject', "Welcome! Verify your email address.");
        $view = Q_Config::get('Users', 'transactional', 'identifier', 'body', 'Users/email/addEmail.php');
        $user->addEmail($identifier, $subject, $view, array(), array('html' => true));
    } else {
        if ($type === 'mobile') {
            $view = Q_Config::get('Users', 'transactional', 'identifier', 'sms', 'Users/sms/addMobile.php');
            $user->addMobile($identifier, $view);
        }
    }
}
Example #27
0
/**
 * This tool renders all user sessions opened.
 *
 * @param {array} $options An associative array of parameters, containing:
 * @param {string} [$options.userId]
 *   The user's id. Defaults to id of the logged-in user, if any.
 * @param {bool} [$options.editable=true]
 *   Whether user can delete sessions
 * @param {bool} [$options.devices=true]
 *   Whether to show devices info
 */
function Users_sessions_tool($options)
{
    $options = array_merge(array('editable' => true, 'devices' => true), $options);
    if (empty($options['userId'])) {
        $options['userId'] = Users::loggedInUser(true)->id;
    }
    Q_Response::addStylesheet('plugins/Users/css/tools/sessions.css');
    Q_Response::setToolOptions($options);
    $sessions = Users_Session::select("us.*, ud.deviceId, ud.platform, ud.version, ud.formFactor", "us")->join(Users_Device::table() . ' ud', array('us.userId' => 'ud.userId', 'us.id' => 'ud.sessionId'), "LEFT")->where(array('us.userId' => $options['userId']))->fetchDbRows();
    $noDevicesClass = $options['devices'] ? '' : "Users_sessions_noDevices";
    $html = "<table class='Users_sessions_container {$noDevicesClass}'><tr><th>Session Id</th><th class='Users_sessions_devicesData'>Platform</th><th class='Users_sessions_devicesData'>Version</th><th>Last Updated</th>";
    if ($options["editable"]) {
        $html .= '<th class="Users_sessions_actions"></th>';
    }
    $html .= '</tr>';
    foreach ($sessions as $session) {
        $updatedTime = date("M j, Y g:i A", strtotime($session->updatedTime));
        $html .= "<tr><td class='Users_sessions_sessionId'>{$session->id}</td>" . "<td class='Users_sessions_devicesData'>{$session->platform}</td>" . "<td class='Users_sessions_devicesData'>{$session->version}</td>" . "<td>{$updatedTime}</td>";
        if ($options["editable"]) {
            $html .= "<td class='Users_sessions_actions'><button name='delete'>Delete</button></td>";
        }
        $html .= '</tr>';
    }
    $html .= "</table>";
    return $html;
}
Example #28
0
 /**
  * Fetch an array of labels. By default, returns all the labels.
  * @method fetch
  * @param {string} [$userId=null] The id of the user whose contact labels should be fetched
  * @param {string|Db_Expression} [$filter=''] Pass a string prefix such as "Users/", or some db expression, to get only a particular subset of labels.
  * @param {boolean} [$checkContacts=false] Whether to also look in the Users_Contact table and only return labels that have at least one contact.
  * @return {array} An array of array(label => title) pairs
  */
 static function fetch($userId = null, $filter = '', $checkContacts = false)
 {
     if (!isset($userId)) {
         $user = Users::loggedInUser(true);
         $userId = $user->id;
     }
     $criteria = array('userId' => $userId);
     if ($filter) {
         $criteria['label'] = is_string($filter) ? new Db_Range($filter, true, false, null) : $filter;
     }
     if ($checkContacts) {
         $contact_array = Users_Contact::select('*')->where($criteria)->groupBy('userId, label')->fetchDbRows();
     }
     $labels = Users_Label::select('*')->where($criteria)->fetchDbRows(null, null, 'label');
     $icons = array();
     if (!$checkContacts) {
         return $labels;
     }
     $contacts = array();
     foreach ($contact_array as $contact) {
         $contacts[$contact->label] = $contact->label;
     }
     foreach ($labels as $label) {
         if (!isset($contacts[$label->label])) {
             unset($labels[$label->label]);
         }
     }
     return $labels;
 }
Example #29
0
/**
 * This tool renders a user avatar
 *
 * @param {array} $options An associative array of parameters, containing:
 * @param {boolean} [$options.userId]
 *   "userId" => The user's id. Defaults to id of the logged-in user, if any.
 * @param {boolean} [$options.icon]
 *   "icon" => Optional. Render icon before the username.
 * @param {boolean} [$options.iconAttributes]
 *   "iconAttributes" => Optional. Array of attributes to render for the icon.
 * @param {boolean} [$options.editable]
 *   "editable" => Optional. Whether to provide an interface for editing the user's info. Can be array containing "icon", "name".
 * @param {array} [$options.inplaces] Additional fields to pass to the child Streams/inplace tools, if any
 * @param {boolean} [$options.renderOnClient]
 *    If true, only the html container is rendered, so the client will do the rest.
 */
function Users_avatar_tool($options)
{
    $defaults = array('icon' => false, 'editable' => false);
    $options = array_merge($defaults, $options);
    if (empty($options['userId'])) {
        $user = Users::loggedInUser();
        $options['userId'] = $user->id;
    } else {
        $user = Users_User::fetch($options['userId']);
    }
    Q_Response::addStylesheet('plugins/Q/css/Q.css');
    Q_Response::setToolOptions($options);
    if (!empty($options['renderOnClient'])) {
        return '';
    }
    if (!$user) {
        return '';
    }
    $user->addPreloaded();
    $p = $options;
    $p['userId'] = $user->id;
    Q_Response::setToolOptions($p);
    $result = '';
    $icon = $options['icon'];
    if ($icon) {
        if ($icon === true) {
            $icon = Q_Config::get('Users', 'icon', 'defaultSize', 40);
        }
        $attributes = isset($options['iconAttributes']) ? $options['iconAttributes'] : array();
        $attributes['class'] = isset($attributes['class']) ? $attributes['class'] . ' Users_avatar_icon' : 'Users_avatar_icon';
        $result .= Q_Html::img($user->iconUrl($icon), 'user icon', $attributes);
    }
    $result .= '<span class="Users_avatar_name">' . $user->username . '</span>';
    return $result;
}
Example #30
0
/**
 * Edits a label in the system. Fills the "label" (and possibly "icon") slot.
 * @param {array} $_REQUEST
 * @param {string} $_REQUEST.label The label
 * @param {string} [$_REQUEST.title] The title of the label
 * @param {string} [$_REQUEST.icon] Optional path to an icon
 * @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_label_put($params = array())
{
    $req = array_merge($_REQUEST, $params);
    Q_Request::requireFields(array('label'), $req, true);
    $loggedInUserId = Users::loggedInUser(true)->id;
    $userId = Q::ifset($req, 'userId', $loggedInUserId);
    $l = $req['label'];
    $icon = Q::ifset($req, 'icon', null);
    $title = Q::ifset($req, 'title', null);
    Users::canManageLabels($loggedInUserId, $userId, $l, true);
    $label = new Users_Label();
    $label->userId = $userId;
    $label->label = $l;
    if (!$label->retrieve()) {
        throw new Q_Exception_MissingRow(array('table' => 'Label', 'criteria' => json_encode($label->fields)));
    }
    if (isset($title)) {
        $label->title = $title;
    }
    if (is_array($icon)) {
        // Process any icon data
        $icon['path'] = 'uploads/Users';
        $icon['subpath'] = "{$userId}/label/{$label}/icon";
        $data = Q::event("Q/image/post", $icon);
        Q_Response::setSlot('icon', $data);
        $label->icon = Q_Request::baseUrl() . '/' . $data[''];
    }
    $label->save();
    Q_Response::setSlot('label', $label->exportArray());
}