Пример #1
0
 public function onLoad()
 {
     parent::onLoad();
     // friend request count
     $con = new Condition();
     $con->add('friendId', '=', $this->user->getId());
     $con->add('status', '=', Friend\Record::REQUEST);
     $requestCount = $this->getSql()->count($this->registry['table.user_friend'], $con);
     $this->template->assign('requestCount', $requestCount);
     // pending count
     $con = new Condition();
     $con->add('userId', '=', $this->user->getId());
     $con->add('status', '=', Friend\Record::REQUEST);
     $pendingCount = $this->getSql()->count($this->registry['table.user_friend'], $con);
     $this->template->assign('pendingCount', $pendingCount);
     // load groups
     $groupList = $this->getGroups();
     $this->template->assign('groupList', $groupList);
     // options
     $friends = new Option('friends', $this->registry, $this->user, $this->page);
     $friends->add('my_view', 'Friends', $this->page->getUrl() . '/friends');
     if ($requestCount > 0) {
         $friends->add('my_view', 'Request (' . $requestCount . ')', $this->page->getUrl() . '/friends/request');
     }
     if ($pendingCount > 0) {
         $friends->add('my_view', 'Pending (' . $pendingCount . ')', $this->page->getUrl() . '/friends/pending');
     }
     $friends->add('my_view', 'Groups', $this->page->getUrl() . '/friends/group');
     $friends->load(array($this->page));
     $this->template->assign('optionsFriends', $friends);
 }
Пример #2
0
 public function getTokensByApp($appId)
 {
     $now = new DateTime();
     $con = new Condition();
     $con->add('appId', '=', $appId);
     $con->add('status', '=', self::STATUS_ACTIVE);
     $con->add('expire', '>', $now->format('Y-m-d H:i:s'));
     return $this->getBy($con);
 }
Пример #3
0
 /**
  * Returns the GET response
  *
  * @param \PSX\Api\Version $version
  * @return array|\PSX\Data\RecordInterface
  */
 protected function doGet(Version $version)
 {
     $startIndex = $this->getParameter('startIndex', Validate::TYPE_INTEGER) ?: 0;
     $search = $this->getParameter('search', Validate::TYPE_STRING) ?: null;
     $condition = new Condition(['status', '=', 1]);
     $condition->add('path', 'NOT LIKE', '/backend%');
     $condition->add('path', 'NOT LIKE', '/doc%');
     $condition->add('path', 'NOT LIKE', '/authorization%');
     if (!empty($search)) {
         $condition->add('path', 'LIKE', '%' . $search . '%');
     }
     $table = $this->tableManager->getTable('Fusio\\Backend\\Table\\Routes');
     $table->setRestrictedFields(['config']);
     return array('totalItems' => $table->getCount($condition), 'startIndex' => $startIndex, 'entry' => $table->getAll($startIndex, null, 'id', Sql::SORT_DESC, $condition));
 }
Пример #4
0
 public function delete(RecordInterface $record)
 {
     if ($record->hasFields('id')) {
         // move all friends to uncategorized
         $con = new Condition();
         $con->add('userId', '=', $this->user->getId());
         $con->add('groupId', '=', $record->id);
         $this->sql->update($this->registry['table.user_friend'], array('groupId' => 0), $con);
         $con = new Condition(array('id', '=', $record->id));
         $this->table->delete($con);
         $this->notify(RecordAbstract::DELETE, $record);
         return $record;
     } else {
         throw new Exception('Missing field in record');
     }
 }
Пример #5
0
 /**
  * onLoad
  *
  * @param count integer
  */
 public function onLoad()
 {
     parent::onLoad();
     $count = $this->args->get('count', 8);
     $now = new DateTime('NOW', $this->registry['core.default_timezone']);
     $past = new DateTime('NOW', $this->registry['core.default_timezone']);
     $past->sub(new DateInterval('P' . $count . 'D'));
     $act = array();
     // condition
     $con = new Condition();
     $con->add('scope', '=', 0);
     $con->add('date', '>=', $past->format(DateTime::SQL));
     // get activities
     $handler = $this->hm->getHandler('AmunService\\User\\Activity');
     $result = $handler->getAll(array('id', 'scope', 'summary', 'date', 'authorId', 'authorName', 'authorThumbnailUrl'), 0, 64, 'date', Sql::SORT_ASC, $con);
     foreach ($result as $row) {
         $date = new DateTime($row['date'], $this->registry['core.default_timezone']);
         $interval = $date->diff($now);
         $key = $interval->format('%d');
         if (!isset($act[$key])) {
             $act[$key] = 1;
         } else {
             $act[$key]++;
         }
     }
     // build params
     $chd = array();
     $labels = array();
     $max = 0;
     $days = 0;
     for ($i = $count - 1; $i >= 0; $i--) {
         if (isset($act[$i])) {
             if ($act[$i] > $max) {
                 $max = $act[$i];
             }
             $chd[$i] = $act[$i];
         } else {
             $chd[$i] = 0;
         }
         $labels[] = date('d M', time() - $i * 3600 * 24);
         $days++;
     }
     $params = array('cht' => 'ls', 'chd' => 't:' . implode(',', $chd), 'chs' => '320x100', 'chco' => '0077CC', 'chds' => '0,' . $max, 'chxt' => 'x', 'chxl' => '0:|' . implode('|', $labels), 'chxr' => '0,1,' . $days . ',1');
     $this->display($params);
 }
Пример #6
0
 public function onGet()
 {
     try {
         $token = $this->get->token('string', array(new Filter\Length(40, 40), new Filter\Xdigit()));
         if ($token !== false) {
             $handler = $this->getHandler('AmunService\\User\\Account');
             $account = $handler->getNotActivatedByToken($token);
             if ($account instanceof Account\Record) {
                 try {
                     $expire = 'PT24H';
                     // expire after 24 hours
                     $now = new DateTime('NOW', $this->registry['core.default_timezone']);
                     if ($now > $account->getDate()->add(new DateInterval($expire))) {
                         throw new Exception('Activation is expired');
                     }
                     if ($_SERVER['REMOTE_ADDR'] == $account->ip) {
                         $account->setStatus(Account\Record::NORMAL);
                         $handler->update($account);
                         $this->template->assign('success', true);
                     } else {
                         throw new Exception('Registration was requested from another IP');
                     }
                 } catch (\Exception $e) {
                     $con = new Condition();
                     $con->add('id', '=', $account->id);
                     $con->add('status', '=', Account\Record::NOT_ACTIVATED);
                     $this->sql->delete($this->registry['table.user_account'], $con);
                     throw $e;
                 }
             } else {
                 throw new Exception('Invalid token');
             }
         } else {
             throw new Exception('Token not set');
         }
     } catch (\Exception $e) {
         $this->template->assign('error', $e->getMessage());
     }
 }
Пример #7
0
 public function remove($opEndpoint, $assocHandle)
 {
     $con = new Condition();
     $con->add('opEndpoint', '=', $opEndpoint);
     $con->add('assocHandle', '=', $assocHandle);
     $this->sql->delete($con);
 }
Пример #8
0
 public function clear()
 {
     $con = new Condition();
     $con->add('ip', '=', $_SERVER['REMOTE_ADDR']);
     $this->sql->delete($this->registry['table.login_attempt'], $con);
 }
Пример #9
0
 private function getComments()
 {
     $con = new Condition();
     $con->add('pageId', '=', $this->page->getId());
     $con->add('refId', '=', $this->id);
     $url = new Url($this->base->getSelf());
     $count = $url->getParam('count') > 0 ? $url->getParam('count') : 8;
     $count = $count > 16 ? 16 : $count;
     $result = $this->getHandler('AmunService\\Comment')->getResultSet(array(), $url->getParam('startIndex'), $count, $url->getParam('sortBy'), $url->getParam('sortOrder'), $con, Sql::FETCH_OBJECT);
     $paging = new Paging($url, $result);
     $this->template->assign('pagingComments', $paging, 0);
     return $result;
 }
Пример #10
0
 public static function getCondition(FilterParameter $parameter, $dateColumn = 'date')
 {
     $condition = new Condition();
     if ($parameter->getFilterBy() && $parameter->getFilterValue()) {
         switch ($parameter->getFilterOp()) {
             case 'contains':
                 $condition->add($parameter->getFilterBy(), 'LIKE', '%' . $parameter->getFilterValue() . '%');
                 break;
             case 'equals':
                 $condition->add($parameter->getFilterBy(), '=', $parameter->getFilterValue());
                 break;
             case 'startsWith':
                 $condition->add($parameter->getFilterBy(), 'LIKE', $parameter->getFilterValue() . '%');
                 break;
             case 'present':
                 $condition->add($parameter->getFilterBy(), 'IS NOT', 'NULL', 'AND');
                 $condition->add($parameter->getFilterBy(), 'NOT LIKE', '');
                 break;
         }
     }
     if ($parameter->getUpdatedSince() instanceof \DateTime) {
         $condition->add($dateColumn, '>', $parameter->getUpdatedSince()->format(DateTime::SQL));
     }
     return $condition;
 }
Пример #11
0
 public function create(RecordInterface $record)
 {
     if ($record->hasFields('groupId', 'status', 'identity', 'name', 'pw')) {
         // check whether identity exists
         $con = new Condition();
         $con->add('identity', '=', $record->identity);
         if ($this->table->count($con) > 0) {
             throw new Exception('Identity already exists');
         }
         // check whether name and hostid exists
         $con = new Condition();
         $con->add('hostId', '=', !empty($record->hostId) ? $record->hostId : 0);
         $con->add('name', '=', $record->name);
         if ($this->table->count($con) > 0) {
             throw new Exception('Identity already exists');
         }
         // default values
         if (!isset($record->countryId)) {
             $record->setCountryId(1);
         }
         if (!isset($record->timezone)) {
             $record->setTimezone('UTC');
         }
         $date = new DateTime('NOW', $this->registry['core.default_timezone']);
         $record->token = Security::generateToken();
         $record->ip = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '127.0.0.1';
         $record->lastSeen = $date->format(DateTime::SQL);
         $record->updated = $date->format(DateTime::SQL);
         $record->date = $date->format(DateTime::SQL);
         // set host id if we have an remote host discover the profile url
         if (empty($record->hostId)) {
             $record->hostId = 0;
             $record->profileUrl = $this->config['psx_url'] . '/' . $this->config['psx_dispatch'] . 'profile/' . $record->name;
         } else {
             $record->status = Record::REMOTE;
             $record->profileUrl = $this->discoverProfileUrl($record->hostId, $record->name);
         }
         // set global id
         if (!isset($record->globalId)) {
             $profileUrl = new Url($record->profileUrl);
             $record->globalId = $this->base->getUUID('user:account:' . $profileUrl->getHost() . ':' . $record->name . ':' . uniqid());
         }
         // set thumbnail if email available and thumbnail not set
         if (!isset($record->thumbnailUrl)) {
             $default = $this->config['psx_url'] . '/img/avatar/no_image.png';
             if (!empty($record->email)) {
                 $record->thumbnailUrl = 'http://www.gravatar.com/avatar/' . md5(strtolower(trim($record->email))) . '?d=' . urlencode($default) . '&s=48';
             } else {
                 $record->thumbnailUrl = $default;
             }
         }
         $this->table->insert($record->getData());
         $record->id = $this->sql->getLastInsertId();
         // insert relation to self
         $this->sql->insert($this->registry['table.user_friend'], array('status' => Friend\Record::NORMAL, 'userId' => $record->id, 'friendId' => $record->id, 'date' => $date->format(DateTime::SQL)));
         $this->notify(RecordAbstract::INSERT, $record);
         return $record;
     } else {
         throw new Exception('Missing field in record');
     }
 }
Пример #12
0
    /**
     * If a user on an remote website accepts our friendship request the website
     * makes a call to the api/user/friend/relation inorder to inform us that
     * the relation was accepted. If the user exists we add a relation and set
     * the status
     *
     * @param RecordInterface $record
     * @return boolean
     */
    protected function handleAccept(RecordInterface $record)
    {
        $sql = <<<SQL
SELECT
\t`account`.`id`    AS `accountId`,
\t`host`.`id`       AS `hostId`,
\t`host`.`name`     AS `hostName`,
\t`host`.`template` AS `hostTemplate`
FROM 
\t{$this->registry['table.user_account']} `account`
INNER JOIN 
\t{$this->registry['table.core_host']} `host`
\tON `account`.`hostId` = `host`.`id`
WHERE 
\t`account`.`name` = ?
AND 
\t`host`.`name` = ?
AND 
\t`account`.`status` = ?
SQL;
        $row = $this->sql->getRow($sql, array($record->name, $record->host, Account\Record::REMOTE));
        if (!empty($row)) {
            // create relation
            $date = new DateTime('NOW', $this->registry['core.default_timezone']);
            $this->table->insert(array('status' => Record::NORMAL, 'userId' => $row['accountId'], 'friendId' => $this->user->getId(), 'date' => $date->format(DateTime::SQL)));
            // update status
            $con = new Condition();
            $con->add('userId', '=', $this->user->getId());
            $con->add('friendId', '=', $row['accountId']);
            $this->table->update(array('status' => Record::NORMAL, 'date' => $date->format(DateTime::SQL)), $con);
            return true;
        } else {
            throw new Exception('Account does not exist');
        }
    }
Пример #13
0
 private function insertEntry(Entry $entry)
 {
     // get global id
     $urn = new Urn($entry->id);
     $globalId = $urn->getNss();
     // get author of the entry
     $author = current($entry->author);
     if (!empty($author)) {
         $urn = new Urn($author['uri']);
         $con = new Condition();
         $con->add('globalId', '=', $urn->getNss());
         $con->add('name', '=', $author['name']);
         $userId = $this->sql->select($this->registry['table.user_account'], array('id'), $con, Sql::SELECT_FIELD);
         $user = new User($userId, $this->registry);
         $handler = new Handler($user);
     } else {
         throw new Exception('No author set');
     }
     // get threading extension
     $thread = $entry->getElement()->getElementsByTagNameNS('http://purl.org/syndication/thread/1.0', 'in-reply-to');
     $refId = 0;
     if ($thread->length > 0) {
         // search for referenced activity globalId
         $ref = $thread->item(0)->getAttribute('ref');
         $urn = new Urn($ref);
         $con = new Condition(array('globalId', '=', $urn->getNss()));
         $refId = $this->hm->getTable('AmunService\\User\\Activity')->getField('id', $con);
         if (empty($refId)) {
             throw new Exception('Invalid referenced id');
         }
     }
     $activity = $this->hm->getTable('AmunService\\User\\Activity')->getRecord();
     $activity->globalId = $globalId;
     $activity->parentId = $refId;
     $activity->table = 'amun_user_activity';
     $activity->verb = 'add';
     $activity->summary = $entry->content;
     $activity->date = $entry->updated->format(DateTime::SQL);
     $handler->create($activity);
 }
Пример #14
0
 public function testGetAllConditionOrConjunction()
 {
     $table = $this->getTable();
     if (!$table instanceof TableQueryInterface) {
         $this->markTestSkipped('Table not an query interface');
     }
     $con = new Condition();
     $con->add('userId', '=', 1, 'OR');
     $con->add('userId', '=', 3);
     $result = $table->getAll(0, 16, 'id', Sql::SORT_DESC, $con);
     $this->assertEquals(true, is_array($result));
     $this->assertEquals(3, count($result));
     $expect = array(new Record('comment', array('id' => 4, 'userId' => 3, 'title' => 'blub', 'date' => new \DateTime('2013-04-29 16:56:32'))), new Record('comment', array('id' => 2, 'userId' => 1, 'title' => 'bar', 'date' => new \DateTime('2013-04-29 16:56:32'))), new Record('comment', array('id' => 1, 'userId' => 1, 'title' => 'foo', 'date' => new \DateTime('2013-04-29 16:56:32'))));
     $this->assertEquals($expect, $result);
 }
Пример #15
0
 protected function getRequestCondition()
 {
     $con = new Condition();
     $filterBy = isset($_GET['filterBy']) ? $_GET['filterBy'] : null;
     $filterOp = isset($_GET['filterOp']) ? $_GET['filterOp'] : null;
     $filterValue = isset($_GET['filterValue']) ? $_GET['filterValue'] : null;
     $updatedSince = isset($_GET['updatedSince']) ? $_GET['updatedSince'] : null;
     switch ($filterOp) {
         case 'contains':
             $con->add($filterBy, 'LIKE', '%' . $filterValue . '%');
             break;
         case 'equals':
             $con->add($filterBy, '=', $filterValue);
             break;
         case 'startsWith':
             $con->add($filterBy, 'LIKE', $filterValue . '%');
             break;
         case 'present':
             $con->add($filterBy, 'IS NOT', 'NULL', 'AND');
             $con->add($filterBy, 'NOT LIKE', '');
             break;
     }
     if ($updatedSince !== null) {
         $datetime = new DateTime($updatedSince);
         $con->add('date', '>', $datetime->format(DateTime::SQL));
     }
     return $con;
 }
Пример #16
0
 protected function isOpenidProvider($identity)
 {
     // add http prefix if its not an email
     if (strpos($identity, '@') === false && substr($identity, 0, 7) != 'http://' && substr($identity, 0, 8) != 'https://') {
         $identity = 'http://' . $identity;
     }
     // build callback
     $callback = $this->pageUrl . '/callback/remote';
     // create an openid object
     $openid = new \PSX\OpenId($this->http, $this->config['psx_url'], $this->store);
     // check whether identity is an url if not it is an email
     $filter = new Filter\Url();
     if ($filter->apply($identity) === false) {
         $pos = strpos($identity, '@');
         $provider = substr($identity, $pos + 1);
         // check whether the provider belongs to an connected website. If
         // yes we also try to get an token and tokenSecret for the user
         $host = $this->hm->getTable('AmunService\\Core\\Host')->select(array('id', 'consumerKey', 'url', 'template'))->where('name', '=', $provider)->where('status', '=', Host\Record::NORMAL)->getRow();
         if (!empty($host)) {
             // make webfinger request
             $webfinger = new Webfinger($this->http);
             $acct = 'acct:' . $identity;
             $xrd = $webfinger->getLrdd($acct, $host['template']);
             // check subject
             if (strcmp($xrd->getSubject(), $acct) !== 0) {
                 throw new Exception('Invalid subject');
             }
             // get profile url
             $profileUrl = $xrd->getLinkHref('profile');
             if (empty($profileUrl)) {
                 throw new Exception('Could not find profile');
             }
             // get global id
             $globalId = $xrd->getPropertyValue('http://ns.amun-project.org/2011/meta/id');
             // initalize openid
             $openid->initialize($profileUrl, $callback);
             // if the provider is connected with the website and supports
             // the oauth extension request an token
             $identity = sha1($this->config['amun_salt'] . OpenId::normalizeIdentifier($profileUrl));
             $con = new Condition(array('identity', '=', $identity));
             $userId = $this->hm->getTable('AmunService\\User\\Account')->getField('id', $con);
             $oauth = false;
             if (!empty($userId)) {
                 $con = new Condition();
                 $con->add('hostId', '=', $host['id']);
                 $con->add('userId', '=', $userId);
                 $requestId = $this->hm->getTable('AmunService\\Core\\Host\\Request')->getField('id', $con);
                 if (empty($requestId)) {
                     $oauth = true;
                 }
             } else {
                 $oauth = true;
             }
             if ($oauth) {
                 $oauth = new Extension\Oauth($host['consumerKey']);
                 if ($openid->hasExtension($oauth->getNs())) {
                     $this->session->set('openid_register_user_host_id', $host['id']);
                     $this->session->set('openid_register_user_global_id', $globalId);
                     $openid->add($oauth);
                 }
             }
             return $openid;
         }
     }
     return false;
 }
Пример #17
0
 public function hasFriend(Account\Record $account)
 {
     $con = new Condition();
     $con->add('userId', '=', $this->id);
     $con->add('friendId', '=', $account->id);
     $con->add('status', '=', Friend\Record::NORMAL);
     $count = $this->sql->count($this->registry['table.user_friend'], $con);
     return $count > 0;
 }
Пример #18
0
 protected function getResponse(Provider\Consumer $consumer, Provider\Request $request)
 {
     // we check how often this ip has requested an token ... because
     // of security reasons each consumer can have max 5 request tokens
     $maxCount = 5;
     $ip = $_SERVER['REMOTE_ADDR'];
     $con = new Condition(array('ip', '=', $ip), array('status', '=', Oauth\Record::TEMPORARY));
     $count = $this->sql->count($this->registry['table.oauth_request'], $con);
     if ($count >= $maxCount) {
         $conDelete = new Condition();
         $result = $this->sql->select($this->registry['table.oauth_request'], array('id', 'expire', 'date'), $con, Sql::SELECT_ALL);
         foreach ($result as $row) {
             $now = new DateTime('NOW', $this->registry['core.default_timezone']);
             $date = new DateTime($row['date'], $this->registry['core.default_timezone']);
             $date->add(new DateInterval($row['expire']));
             if ($now > $date) {
                 $conDelete->add('id', '=', $row['id'], 'OR');
             }
         }
         if ($conDelete->hasCondition()) {
             $this->sql->delete($this->registry['table.oauth_request'], $conDelete);
         }
         throw new Exception('You can only have max. ' . $maxCount . ' active request tokens');
     }
     // get nonce
     $nonce = $request->getNonce();
     // assign callback
     $callback = $request->getCallback();
     // generate tokens
     $token = Security::generateToken();
     $tokenSecret = Security::generateToken();
     // we save the timestamp in the request but because it comes from
     // the user we doesnt use them to check the expire date
     $timestamp = $request->getTimestamp();
     // you have 30 minutes to authorize the request token and to exchange
     // them for an access token
     $expire = 'PT30M';
     $date = new DateTime('NOW', $this->registry['core.default_timezone']);
     $this->sql->insert($this->registry['table.oauth_request'], array('apiId' => $this->apiId, 'status' => Oauth\Record::TEMPORARY, 'ip' => $ip, 'nonce' => $nonce, 'callback' => $callback, 'token' => $token, 'tokenSecret' => $tokenSecret, 'timestamp' => $timestamp, 'expire' => $expire, 'date' => $date->format(DateTime::SQL)));
     $response = new Provider\Response();
     $response->setToken($token);
     $response->setTokenSecret($tokenSecret);
     return $response;
 }