Exemplo n.º 1
0
 /**
  * Load license from database - throw exception if not found
  */
 public function loadFromStore()
 {
     $licenses = $this->context->dbDriver->get(RestoDatabaseDriver::LICENSES, array('licenseId' => $this->licenseId));
     if (!isset($licenses[$this->licenseId])) {
         RestoLogUtil::httpError(400, 'License ' . $this->licenseId . ' does not exist in database');
     }
     $this->description = $licenses[$this->licenseId];
 }
Exemplo n.º 2
0
 /**
  * Run module - this function should be called by Resto.php
  * 
  * @param array $segments : route segments
  * @param array $data : POST or PUT parameters
  * 
  * @return string : result from run process in the $context->outputFormat
  */
 public function run($segments, $data = array())
 {
     /*
      * Only GET method on 'search' route with json outputformat is accepted
      */
     if ($this->context->method !== 'GET' || count($segments) !== 0) {
         RestoLogUtil::httpError(404);
     }
     return $this->search($this->context->query);
 }
Exemplo n.º 3
0
 /**
  * Constructor 
  * 
  * @param RestoResto $context : Resto Context
  * @param RestoUser $user : Resto user
  * @param RestoCollection or array of RestoCollection $collections => First collection is the master collection !!
  */
 public function __construct($context, $user, $collections)
 {
     if (!isset($context) || !is_a($context, 'RestoContext')) {
         RestoLogUtil::httpError(500, 'Context is undefined or not valid');
     }
     $this->context = $context;
     $this->user = $user;
     if (isset($this->context->modules['QueryAnalyzer'])) {
         $this->queryAnalyzer = RestoUtil::instantiate($this->context->modules['QueryAnalyzer']['className'], array($this->context, $this->user));
     }
     $this->initialize($collections);
 }
Exemplo n.º 4
0
 /**
  * Stream WMS tiles for $feature in high resolution
  * or in low resolution if $lowResolution is set to true
  * 
  * @param type $feature
  * @param type $lowResolution
  */
 public function streamWMS($feature, $lowResolution = false)
 {
     /*
      * Easy case - no feature or no WMS
      */
     if (!isset($feature)) {
         RestoLogUtil::httpError(404);
     }
     $featureArray = $feature->toArray();
     if (!isset($featureArray['properties']['wmsInfos'])) {
         RestoLogUtil::httpError(404);
     }
     $this->stream($this->getWMSUrl($featureArray['properties']['wmsInfos'], $lowResolution));
 }
Exemplo n.º 5
0
 /**
  * Constructor
  * 
  * @param RestoUser $user
  * @param RestoContext $context
  */
 public function __construct($user, $context, $orderId)
 {
     /*
      * Context is mandatory
      */
     if (!isset($context) || !is_a($context, 'RestoContext')) {
         RestoLogUtil::httpError(500, 'Context must be defined');
     }
     /*
      * User is mandatory
      */
     if (!isset($user) || !is_a($user, 'RestoUser')) {
         RestoLogUtil::httpError(500, 'User must be defined');
     }
     $this->user = $user;
     $this->context = $context;
     $this->order = $this->context->dbDriver->get(RestoDatabaseDriver::ORDERS, array('email' => $this->user->profile['email'], 'orderId' => $orderId));
     /*
      * Is order id associated to a valid order
      */
     if (!isset($this->order['orderId'])) {
         RestoLogUtil::httpError(404, 'Order with id=' . $orderId . ' does not exist');
     }
 }
Exemplo n.º 6
0
 /**
  * 
  * Return a featureArray array from an input rawFeatureArray.
  * A rawFeatureArray is the array format returned by a GET request
  * to the RestoDatabaseDriver::FEATURE_DESCRIPTION object
  * 
  * @param array $rawFeatureArray
  * 
  */
 public function toFeatureArray($rawFeatureArray)
 {
     /*
      * No result - throw Not Found exception
      */
     if (!isset($rawFeatureArray) || !is_array($rawFeatureArray)) {
         RestoLogUtil::httpError(404);
     }
     /*
      * Add collection
      */
     if (!isset($this->collections[$rawFeatureArray['collection']])) {
         $this->collections[$rawFeatureArray['collection']] = new RestoCollection($rawFeatureArray['collection'], $this->context, $this->user, array('autoload' => true));
     }
     /*
      * First correct types
      */
     $rawCorrectedArray = $this->correctTypes($rawFeatureArray);
     /*
      * Initialize featureArray
      */
     $featureArray = array('type' => 'Feature', 'id' => $rawFeatureArray['identifier'], 'geometry' => isset($rawCorrectedArray['geometry']) ? $rawCorrectedArray['geometry'] : null, 'properties' => $this->toProperties($rawCorrectedArray));
     return $featureArray;
 }
Exemplo n.º 7
0
 /**
  * Create a collection and store it within database
  * 
  * @param array $object : collection description as json file
  */
 public function create($object)
 {
     $name = isset($object['name']) ? $object['name'] : null;
     /*
      * Check that collection does not exist
      */
     if (isset($name) && isset($this->collections[$name])) {
         RestoLogUtil::httpError(2003);
     }
     /*
      * Load collection
      */
     $collection = new RestoCollection($name, $this->context, $this->user);
     $collection->loadFromJSON($object, true);
     /*
      * Store query
      */
     if ($this->context->storeQuery === true) {
         $this->user->storeQuery($this->context->method, 'create', $name, null, $this->context->query, $this->context->getUrl());
     }
     return true;
 }
Exemplo n.º 8
0
 /**
  * Return rights array for add/update/delete
  * 
  * @param array $rights
  * @param string $collectionName
  * @param string $featureIdentifier
  * 
  * @return string
  */
 private function getRightsArray($rights, $collectionName = null, $featureIdentifier = null)
 {
     /*
      * Default target is all collections
      */
     $target = '*';
     /*
      * Check that collection/feature exists
      */
     if (isset($collectionName)) {
         if (!$this->context->dbDriver->check(RestoDatabaseDriver::COLLECTION, array('collectionName' => $collectionName))) {
             RestoLogUtil::httpError(404, 'Collection does not exist');
         }
         $target = $collectionName;
     }
     if (isset($featureIdentifier)) {
         if (!$this->context->dbDriver->check(RestoDatabaseDriver::FEATURE, array('featureIdentifier' => $featureIdentifier))) {
             RestoLogUtil::httpError(404, 'Feature does not exist');
         }
         $target = $featureIdentifier;
     }
     return array('rights' => $rights, 'ownerType' => 'user', 'owner' => $this->profile['email'], 'targetType' => isset($featureIdentifier) ? 'feature' : 'collection', 'target' => $target);
 }
Exemplo n.º 9
0
 /**
  * Check if value is valid for a given filter regarding the model
  * 
  * @param string $filterKey
  * @param string $value
  */
 private function validateFilter($filterKey, $value)
 {
     /*
      * Check pattern for string
      */
     if (isset($this->searchFilters[$filterKey]['pattern'])) {
         if (preg_match('\'' . $this->searchFilters[$filterKey]['pattern'] . '\'', $value) !== 1) {
             RestoLogUtil::httpError(400, 'Value for "' . $this->searchFilters[$filterKey]['osKey'] . '" must follow the pattern ' . $this->searchFilters[$filterKey]['pattern']);
         }
     } else {
         if (isset($this->searchFilters[$filterKey]['minInclusive']) || isset($this->searchFilters[$filterKey]['maxInclusive'])) {
             if (!is_numeric($value)) {
                 RestoLogUtil::httpError(400, 'Value for "' . $this->searchFilters[$filterKey]['osKey'] . '" must be numeric');
             }
             if (isset($this->searchFilters[$filterKey]['minInclusive']) && $value < $this->searchFilters[$filterKey]['minInclusive']) {
                 RestoLogUtil::httpError(400, 'Value for "' . $this->searchFilters[$filterKey]['osKey'] . '" must be greater than ' . ($this->searchFilters[$filterKey]['minInclusive'] - 1));
             }
             if (isset($this->searchFilters[$filterKey]['maxInclusive']) && $value > $this->searchFilters[$filterKey]['maxInclusive']) {
                 RestoLogUtil::httpError(400, 'Value for "' . $this->searchFilters[$filterKey]['osKey'] . '" must be lower than ' . ($this->searchFilters[$filterKey]['maxInclusive'] + 1));
             }
         }
     }
     return true;
 }
Exemplo n.º 10
0
 /**
  * Stream file from external url
  * 
  * @return type
  */
 private function streamExternalUrl()
 {
     $handle = fopen($this->featureArray['properties']['services']['download']['url'], "rb");
     if ($handle === false) {
         RestoLogUtil::httpError(500, 'Resource cannot be downloaded');
     }
     header('HTTP/1.1 200 OK');
     header('Content-Disposition: attachment; filename="' . basename($this->featureArray['properties']['services']['download']['url']) . '"');
     header('Content-Type: ' . isset($this->featureArray['properties']['services']['download']['mimeType']) ? $this->featureArray['properties']['services']['download']['mimeType'] : 'application/unknown');
     while (!feof($handle) && connection_status() === CONNECTION_NORMAL) {
         echo fread($handle, 10 * 1024 * 1024);
         flush();
     }
     return fclose($handle);
 }
Exemplo n.º 11
0
 /**
  * Add feature to collection 
  * 
  * @param RestoCollection $collection
  * @param array $data
  * 
  */
 private function addFeatureToCollection($collection, $data)
 {
     $feature = $collection->addFeature($data);
     /*
      * Store query
      */
     if ($this->context->storeQuery === true) {
         $this->user->storeQuery($this->context->method, 'insert', $collection->name, $feature->identifier, $this->context->query, $this->context->getUrl());
     }
     return RestoLogUtil::success('Feature ' . $feature->identifier . ' inserted within ' . $collection->name, array('featureIdentifier' => $feature->identifier));
 }
Exemplo n.º 12
0
 /**
  * Return filter PostGIS filter on bounding box
  * 
  * Input coordinates are in longitude/latitude (WGS84) ordered as follow
  * 
  *  array(lonMin, latMin, lonMax, latMax)
  * 
  * 
  * @param array $coords
  */
 private function getBBOXFilter($coords)
 {
     /*
      * Invalid coordinates
      */
     if (!is_array($coords) || count($coords) !== 4) {
         RestoLogUtil::httpError(400, 'Invalid bbox');
     }
     /*
      * Non numeric coordinates
      */
     for ($i = 4; $i--;) {
         if (!is_numeric($coords[$i])) {
             RestoLogUtil::httpError(400, 'Invalid bbox');
         }
     }
     return 'ST_intersects(geom, ST_GeomFromText(\'' . pg_escape_string('POLYGON((' . $coords[0] . ' ' . $coords[1] . ',' . $coords[0] . ' ' . $coords[3] . ',' . $coords[2] . ' ' . $coords[3] . ',' . $coords[2] . ' ' . $coords[1] . ',' . $coords[0] . ' ' . $coords[1] . '))') . '\', 4326))';
 }
Exemplo n.º 13
0
 /**
  * Return suffix from input url
  * @return string
  */
 private function getPathSuffix()
 {
     $splitted = explode('.', $this->path);
     $size = count($splitted);
     if ($size > 1) {
         if (array_key_exists($splitted[$size - 1], RestoUtil::$contentTypes)) {
             $suffix = $splitted[$size - 1];
             array_pop($splitted);
             $this->path = join('.', $splitted);
             return $suffix;
         } else {
             RestoLogUtil::httpError(404);
         }
     }
     return null;
 }
Exemplo n.º 14
0
 /**
  * 
  * Process HTTP PUT request on users
  *
  *    user
  *    user/cart/{itemid}                            |  Modify item in user cart
  * 
  * @param array $segments
  * @param array $data
  */
 private function PUT_user($segments, $data)
 {
     /*
      * user
      */
     if (!isset($segments[1])) {
         /*
          * For normal user (i.e. non admin), some properties cannot be modified after validation
          */
         if (!$this->user->isAdmin()) {
             /*
              * Already validated => avoid updating administrative properties
              */
             if (isset($this->user->profile['validatedby'])) {
                 unset($data['activated'], $data['validatedby'], $data['validationdate'], $data['country'], $data['organization'], $data['organizationcountry'], $data['flags']);
             }
             /*
              * These properties can only be changed by admin
              */
             unset($data['groups']);
         }
         /*
          * Ensure that user can only update its profile
          */
         $data['email'] = $this->user->profile['email'];
         $this->context->dbDriver->update(RestoDatabaseDriver::USER_PROFILE, array('profile' => $data));
         return RestoLogUtil::success('Update profile for user ' . $this->user->profile['email']);
     } else {
         if ($segments[1] === 'cart' && isset($segments[2])) {
             if ($this->user->getCart()->update($segments[2], $data, true)) {
                 return RestoLogUtil::success('Item ' . $segments[2] . ' updated', array('itemId' => $segments[2], 'item' => $data));
             } else {
                 return RestoLogUtil::error('Cannot update item ' . $segments[2]);
             }
         } else {
             RestoLogUtil::httpError(404);
         }
     }
 }
 /**
  * Return PostgreSQL database handler
  * 
  * @param array $options
  * @throws Exception
  */
 private function getHandler($options = array())
 {
     $dbh = null;
     /*
      * Store db username
      */
     if (isset($options) && isset($options['user'])) {
         $this->dbUsername = $options['user'];
     }
     if (isset($options) && isset($options['dbname'])) {
         try {
             $dbInfo = array('dbname=' . $options['dbname'], 'user='******'user'], 'password='******'password']);
             /*
              * If host is specified, then TCP/IP connection is used
              * Otherwise socket connection is used
              */
             if (isset($options['host'])) {
                 $dbInfo[] = 'host=' . $options['host'];
                 $dbInfo[] = 'port=' . (isset($options['port']) ? $options['port'] : '5432');
             }
             $dbh = @pg_connect(join(' ', $dbInfo));
             if (!$dbh) {
                 throw new Exception();
             }
         } catch (Exception $e) {
             RestoLogUtil::httpError(500, 'Database connection error');
         }
     }
     return $dbh;
 }
Exemplo n.º 16
0
 /**
  * Store or remove groups for user $userid
  * 
  * @param string $storeOrRemove
  * @param integer $userid
  * @param string $groups
  * @return null
  * @throws Exception
  */
 private function storeOrRemoveUserGroups($storeOrRemove, $userid, $groups)
 {
     if (!isset($userid)) {
         RestoLogUtil::httpError(500, 'Cannot ' . $storeOrRemove . ' groups - invalid user identifier : ' . $userid);
     }
     if (empty($groups)) {
         RestoLogUtil::httpError(500, 'Cannot ' . $storeOrRemove . ' groups - empty input groups');
     }
     $profile = $this->getUserProfile($userid);
     if (!isset($profile)) {
         RestoLogUtil::httpError(500, 'Cannot ' . $storeOrRemove . ' groups - user profile not found for : ' . $userid);
     }
     /*
      * Explode existing groups into an associative array
      */
     $userGroups = !empty($profile['groups']) ? array_flip(explode(',', $profile['groups'])) : array();
     /*
      * Explode input groups
      */
     $newGroups = array();
     $rawNewGroups = explode(',', $groups);
     for ($i = 0, $ii = count($rawNewGroups); $i < $ii; $i++) {
         if ($rawNewGroups[$i] !== '') {
             $newGroups[$rawNewGroups[$i]] = 1;
         }
     }
     /*
      * Store - merge new groups with user groups
      */
     if ($storeOrRemove === 'store') {
         $newGroups = array_keys(array_merge($newGroups, $userGroups));
     } else {
         foreach (array_keys($newGroups) as $key) {
             if ($key !== 'default') {
                 unset($userGroups[$key]);
             }
         }
         $newGroups = array_keys($userGroups);
     }
     /*
      * Update user profile
      */
     $results = count($newGroups) > 0 ? implode(',', $newGroups) : null;
     $this->dbDriver->fetch($this->dbDriver->query('UPDATE usermanagement.users SET groups=' . (isset($results) ? '\'{' . pg_escape_string($results) . '}\'' : 'NULL') . ' WHERE userid=\'' . $userid . '\''));
     return $results;
 }
Exemplo n.º 17
0
 /**
  * Run module - this function should be called by Resto.php
  * 
  * @param array $segments : route segments
  * @param array $data : POST or PUT parameters
  * 
  * @return string : result from run process in the $context->outputFormat
  */
 public function run($segments, $data = array())
 {
     /*
      * Only GET method on 'search' route with json outputformat is accepted
      */
     if ($this->context->method !== 'GET' || count($segments) !== 0) {
         RestoLogUtil::httpError(404);
     }
     $query = isset($this->context->query['searchTerms']) ? $this->context->query['searchTerms'] : (isset($this->context->query['q']) ? $this->context->query['q'] : null);
     return $this->analyze($query);
 }
Exemplo n.º 18
0
 /**
  * Check that input json description is valid
  * 
  * @param array $object
  */
 private function checkJSONValidity($object)
 {
     /*
      * Input $object should be JSON
      */
     if (!isset($object) || !is_array($object)) {
         RestoLogUtil::httpError(500, 'Invalid input JSON');
     }
     /*
      * Check that input file is for the current collection
      */
     if (!isset($object['name']) || $this->name !== $object['name']) {
         RestoLogUtil::httpError(500, 'Property "name" and collection name differ');
     }
     /*
      * Model name must be set in JSON file
      */
     if (!isset($object['model'])) {
         RestoLogUtil::httpError(500, 'Property "model" is mandatory');
     }
     /*
      * At least an english OpenSearch Description object is mandatory
      */
     if (!isset($object['osDescription']) || !is_array($object['osDescription']) || !isset($object['osDescription']['en']) || !is_array($object['osDescription']['en'])) {
         RestoLogUtil::httpError(500, 'English OpenSearch description is mandatory');
     }
 }
Exemplo n.º 19
0
 /**
  * Return formated rights
  * 
  * @param RestoUser $user
  * @param string $collectionName
  * @param string $featureIdentifier
  */
 private function getRights($user, $collectionName, $featureIdentifier)
 {
     return RestoLogUtil::success('Rights for ' . $user->profile['email'], array('email' => $user->profile['email'], 'userid' => $user->profile['userid'], 'groups' => $user->profile['groups'], 'rights' => $user->getRights($collectionName, $featureIdentifier)));
 }
Exemplo n.º 20
0
 /**
  * Place order for user from cart - empty cart afterward
  * 
  * @param string $identifier
  * @param array $items
  * 
  * @return array
  * @throws exception
  */
 private function storeOrder($identifier, $items)
 {
     /*
      * Do not create empty orders
      */
     if (!isset($items) || count($items) === 0) {
         return -1;
     }
     try {
         $orderId = RestoUtil::encrypt($identifier . microtime());
         $values = array('\'' . pg_escape_string($orderId) . '\'', '\'' . pg_escape_string($identifier) . '\'', '\'' . pg_escape_string(json_encode($items)) . '\'', 'now()');
         $this->dbDriver->query('INSERT INTO usermanagement.orders (orderid, email, items, querytime) VALUES (' . join(',', $values) . ')');
     } catch (Exception $e) {
         RestoLogUtil::httpError($e->getCode(), $e->getMessage());
     }
     return $orderId;
 }
Exemplo n.º 21
0
 /**
  * Return error execution status as an array
  *  
  * @param string $message
  * @param array $additional
  */
 public static function error($message, $additional = array())
 {
     return RestoLogUtil::message('error', $message, $additional);
 }
Exemplo n.º 22
0
 /**
  * Launch module run() function if exist otherwise returns 404 Not Found
  * 
  * @param array $segments - path (i.e. a/b/c/d) exploded as an array (i.e. array('a', 'b', 'c', 'd')
  * @param array $data - data (POST or PUT)
  */
 protected function processModuleRoute($segments, $data = array())
 {
     $module = null;
     foreach (array_keys($this->context->modules) as $moduleName) {
         if (isset($this->context->modules[$moduleName]['route'])) {
             $moduleSegments = explode('/', $this->context->modules[$moduleName]['route']);
             $routeIsTheSame = true;
             $count = 0;
             for ($i = 0, $l = count($moduleSegments); $i < $l; $i++) {
                 $count++;
                 if (!isset($segments[$i]) || $moduleSegments[$i] !== $segments[$i]) {
                     $routeIsTheSame = false;
                     break;
                 }
             }
             if ($routeIsTheSame) {
                 $module = RestoUtil::instantiate($moduleName, array($this->context, $this->user));
                 for ($i = $count; $i--;) {
                     array_shift($segments);
                 }
                 return $module->run($segments, $data);
             }
         }
     }
     if (!isset($module)) {
         RestoLogUtil::httpError(404);
     }
 }
Exemplo n.º 23
0
 /**
  * Store Collection description 
  * 
  * @param RestoCollection $collection
  * 
  */
 private function storeCollectionDescription($collection)
 {
     $licenseId = 'NULL';
     if (isset($collection->license)) {
         $licenseDescription = $collection->license->toArray();
         $licenseId = '\'' . pg_escape_string($licenseDescription['licenseId']) . '\'';
     }
     /*
      * Create collection
      */
     if (!$this->collectionExists($collection->name)) {
         $toBeSet = array('collection' => '\'' . pg_escape_string($collection->name) . '\'', 'creationdate' => 'now()', 'model' => '\'' . pg_escape_string($collection->model->name) . '\'', 'licenseid' => $licenseId, 'mapping' => '\'' . pg_escape_string(json_encode($collection->propertiesMapping)) . '\'', 'status' => '\'' . pg_escape_string($collection->status) . '\'', 'owner' => '\'' . pg_escape_string($collection->owner) . '\'');
         $this->dbDriver->query('INSERT INTO resto.collections (' . join(',', array_keys($toBeSet)) . ') VALUES(' . join(',', array_values($toBeSet)) . ')');
     } else {
         $this->dbDriver->query('UPDATE resto.collections SET status = \'' . pg_escape_string($collection->status) . '\', mapping = \'' . pg_escape_string(json_encode($collection->propertiesMapping)) . '\', licenseid=' . $licenseId . ' WHERE collection = \'' . pg_escape_string($collection->name) . '\'');
     }
     /*
      * Insert OpenSearch descriptions within osdescriptions table
      * (one description per lang)
      * 
      * CREATE TABLE resto.osdescriptions (
      *  collection          TEXT,
      *  lang                TEXT,
      *  shortname           VARCHAR(16),
      *  longname            VARCHAR(48),
      *  description         VARCHAR(1024),
      *  tags                VARCHAR(256),
      *  developer           VARCHAR(64),
      *  contact             TEXT,
      *  query               TEXT,
      *  attribution         VARCHAR(256),
      * );
      */
     $this->dbDriver->query('DELETE FROM resto.osdescriptions WHERE collection=\'' . pg_escape_string($collection->name) . '\'');
     foreach ($collection->osDescription as $lang => $description) {
         $osFields = array('collection', 'lang');
         $osValues = array('\'' . pg_escape_string($collection->name) . '\'', '\'' . pg_escape_string($lang) . '\'');
         /*
          * OpenSearch 1.1 draft 5 constraints
          * (http://www.opensearch.org/Specifications/OpenSearch/1.1)
          */
         $validProperties = array('ShortName' => 16, 'LongName' => 48, 'Description' => 1024, 'Tags' => 256, 'Developer' => 64, 'Contact' => -1, 'Query' => -1, 'Attribution' => 256);
         foreach (array_keys($description) as $key) {
             /*
              * Throw exception if property is invalid
              */
             if (isset($validProperties[$key])) {
                 if ($validProperties[$key] !== -1 && strlen($description[$key]) > $validProperties[$key]) {
                     RestoLogUtil::httpError(400, 'OpenSearch property ' . $key . ' length is greater than ' . $validProperties[$key] . ' characters');
                 }
                 $osFields[] = strtolower($key);
                 $osValues[] = '\'' . pg_escape_string($description[$key]) . '\'';
             }
         }
         $this->dbDriver->query('INSERT INTO resto.osdescriptions (' . join(',', $osFields) . ') VALUES(' . join(',', $osValues) . ')');
     }
     return true;
 }
Exemplo n.º 24
0
 /**
  * Sign license identified by $licenseId
  * If license was already signed, add 1 to the signatures counter
  * 
  * @param string $identifier : user identifier 
  * @param string $licenseId
  * @param integer $signatureQuota
  * @return boolean
  * @throws Exception
  */
 public function signLicense($identifier, $licenseId, $signatureQuota = -1)
 {
     /*
      * Get previous signature
      */
     $results = $this->dbDriver->fetch($this->dbDriver->query('SELECT email, counter FROM usermanagement.signatures WHERE email=\'' . pg_escape_string($identifier) . '\' AND licenseid=\'' . pg_escape_string($licenseId) . '\''));
     /*
      * Sign license
      */
     if (count($results) === 0) {
         $this->dbDriver->query('INSERT INTO usermanagement.signatures (email, licenseid, signdate, counter) VALUES (\'' . pg_escape_string($identifier) . '\',\'' . pg_escape_string($licenseId) . '\',now(), 1)');
     } else {
         if ($signatureQuota !== -1) {
             if ((int) $results[0]['counter'] >= $signatureQuota) {
                 RestoLogUtil::httpError(403, 'Maximum signature quota exceed for this license');
             }
         }
         $this->dbDriver->query('UPDATE usermanagement.signatures SET signdate=now(),counter=counter+1 WHERE email=\'' . pg_escape_string($identifier) . '\' AND licenseid=\'' . pg_escape_string($licenseId) . '\'');
     }
     return true;
 }
Exemplo n.º 25
0
 /**
  * Return profile token if profile exist - throw exception otherwise
  * 
  * @param string $key
  * @return json
  */
 private function token($key)
 {
     $user = new RestoUser($this->context->dbDriver->get(RestoDatabaseDriver::USER_PROFILE, array('email' => strtolower($key))), $this->context);
     if ($user->profile['userid'] == -1) {
         RestoLogUtil::httpError(401, 'Unauthorized');
     }
     return $this->context->createJWT($user->profile['userid'], $user->profile);
 }
Exemplo n.º 26
0
 /**
  * Constructor
  */
 public function __construct()
 {
     parent::__construct();
     $this->searchFilters = array_merge($this->searchFilters, $this->extendedSearchFilters);
     /**
      * Read config.php file
      */
     $configFile = realpath(dirname(__FILE__)) . '/../../config.php';
     if (!file_exists($configFile)) {
         RestoLogUtil::httpError(4000, 'Missing mandatory configuration file');
     }
     $this->config = (include $configFile);
 }
Exemplo n.º 27
0
 /**
  * Check $action rights returning user
  * 
  * @param string $action
  * @param RestoUser $user
  * @param string $token
  * @param RestoCollection $collection
  * @param RestoFeature $feature
  * 
  */
 private function checkRights($action, $user, $token, $collection, $feature)
 {
     /*
      * Get token inititiator - bypass user rights
      */
     if (!empty($token)) {
         $initiatorEmail = $this->context->dbDriver->check(RestoDatabaseDriver::SHARED_LINK, array('resourceUrl' => $this->context->baseUrl . '/' . $this->context->path, 'token' => $token));
         /*
          * Non existing Token => exit
          */
         if (!$initiatorEmail) {
             RestoLogUtil::httpError(403);
         }
         if ($user->profile['email'] !== $initiatorEmail) {
             $user = new RestoUser($this->context->dbDriver->get(RestoDatabaseDriver::USER_PROFILE, array('email' => strtolower($initiatorEmail))), $this->context);
         }
     } else {
         if ($action === 'download' && !$user->hasRightsTo(RestoUser::DOWNLOAD, array('collectionName' => $collection->name, 'featureIdentifier' => $feature->identifier))) {
             RestoLogUtil::httpError(403);
         }
         if ($action === 'visualize' && !$user->hasRightsTo(RestoUser::VISUALIZE, array('collectionName' => $collection->name, 'featureIdentifier' => $feature->identifier))) {
             RestoLogUtil::httpError(403);
         }
     }
     return $user;
 }
Exemplo n.º 28
0
 /**
  * Store new group - check if group exists before
  * 
  * @param string $groupid
  * @throws Exception
  */
 public function storeGroup($groupid)
 {
     $groups = $this->getGroups($groupid);
     if (empty($groups)) {
         try {
             $result = pg_query($this->dbDriver->dbh, 'INSERT INTO usermanagement.groups (groupid) VALUES (\'' . pg_escape_string($groupid) . '\')');
             if (!$result) {
                 throw new Exception();
             }
             return $this->getGroups();
         } catch (Exception $e) {
             RestoLogUtil::httpError(500, 'Cannot store group');
         }
     } else {
         RestoLogUtil::httpError(500, 'Cannot store group - groupid is missing');
     }
 }
Exemplo n.º 29
0
 /**
  * Encode input $array to JSON
  * 
  * @param array $object
  * @throws Exception
  */
 private function formatObject($object)
 {
     $methodName = 'to' . strtoupper($this->context->outputFormat);
     if (method_exists(get_class($object), $methodName)) {
         /*
          * JSON-P case
          */
         if ($this->context->outputFormat === 'json') {
             $pretty = isset($this->context->query['_pretty']) ? filter_var($this->context->query['_pretty'], FILTER_VALIDATE_BOOLEAN) : false;
             if (isset($this->context->query['callback'])) {
                 return $this->context->query['callback'] . '(' . $object->{$methodName}($pretty) . ')';
             }
             return $object->{$methodName}($pretty);
         } else {
             return $object->{$methodName}();
         }
     } else {
         RestoLogUtil::httpError(404);
     }
 }
Exemplo n.º 30
0
 /**
  * 
  * Process user
  * 
  *    user/cart                                     |  Remove all cart items
  *    user/cart/{itemid}                            |  Remove {itemid} from user cart
  * 
  *  @SWG\Delete(
  *      tags={"user"},
  *      path="/user/cart/{itemId}",
  *      summary="Delete cart item(s)",
  *      description="Delete cart item {itemId}. Delete all items if no {itemId} is specified",
  *      operationId="deleteCartItem",
  *      produces={"application/json"},
  *      @SWG\Parameter(
  *          name="itemId",
  *          in="path",
  *          description="Cart item identifier",
  *          required=false,
  *          type="string",
  *          @SWG\Items(type="string")
  *      ),
  *      @SWG\Response(
  *          response="200",
  *          description="Acknowledgment on successful cart item(s) deletion"
  *      ),
  *      @SWG\Response(
  *          response="404",
  *          description="ItemId not found"
  *      ),
  *      @SWG\Response(
  *          response="403",
  *          description="Forbidden"
  *      )
  *  )
  * 
  * @param array $segments
  */
 private function DELETE_user($segments)
 {
     if (isset($segments[1]) && $segments[1] === 'cart') {
         /*
          * Clear all cart items
          */
         if (!isset($segments[2])) {
             return $this->user->getCart()->clear(true) ? RestoLogUtil::success('Cart cleared') : RestoLogUtil::error('Cannot clear cart');
         } else {
             return $this->user->getCart()->remove($segments[2], true) ? RestoLogUtil::success('Item removed from cart', array('itemid' => $segments[2])) : RestoLogUtil::error('Item cannot be removed', array('itemid' => $segments[2]));
         }
     } else {
         RestoLogUtil::httpError(404);
     }
 }