コード例 #1
0
ファイル: UserApi.php プロジェクト: dru-id/druid-php-sdk
 /**
  * Returns the user data stored trough the Genetsis ID personal identifier.
  * The identifiers could be: id (ckusid), screenName, email, dni
  * Sample: array('id'=>'XXXX','screenName'=>'xxxx');
  *
  * @param array The Genetsis IDs identifier to search, 'identifier' => 'value'
  * @return array A vector of {@link User} objects with user's
  *     personal data. The array could be empty.
  * @throws /Exception
  */
 public static function getUsers($identifiers)
 {
     $druid_user = array();
     if (is_array($identifiers)) {
         try {
             if (!($druid_user_data = FileCache::get('user-' . reset($identifiers)))) {
                 Identity::getLogger()->debug('Identifier: ' . reset($identifiers) . ' is Not in Cache System');
                 $client_token = Identity::getThings()->getClientToken();
                 if (is_null($client_token)) {
                     throw new Exception('The clientToken is empty');
                 }
                 /**
                  * Parameters:
                  * oauth_token: client token
                  * s (select): dynamic user data to be returned
                  * f (from): User
                  * w (where): param with OR w.param1&w.param2...
                  */
                 $params = array();
                 $params['oauth_token'] = $client_token->getValue();
                 $params['s'] = "*";
                 $params['f'] = "User";
                 foreach ($identifiers as $key => $val) {
                     $params['w.' . $key] = $val;
                 }
                 $base = OAuthConfig::getApiUrl('api.user', 'base_url');
                 $api = OAuthConfig::getApiUrl('api.user', 'user');
                 $response = Request::execute($base . $api, $params, Request::HTTP_POST);
                 if ($response['code'] != 200 || !isset($response['result']->data) || $response['result']->count == '0') {
                     throw new Exception('The data retrieved is empty');
                 }
                 $druid_user = $response['result']->data;
                 FileCache::set('user-' . reset($identifiers), $druid_user, self::USER_TTL);
             } else {
                 Identity::getLogger()->debug('Identifier: ' . reset($identifiers) . ' is in Cache System');
                 $druid_user = json_decode(json_encode($druid_user_data));
             }
         } catch (Exception $e) {
             Identity::getLogger()->error($e->getMessage());
         }
     }
     return $druid_user;
 }
コード例 #2
0
ファイル: index.php プロジェクト: dru-id/druid-php-skel
<a href="http://developers.dru-id.com/" style="max-height: 88px;" target="_blank">
    <img width="300" height="100" alt="DRUID Developers" src="/assets/img/Druid_logo_solo.png" style="max-height: 88px;">
</a>

<h1>Welcome to DRUID</h1>
<h2>Se how easy is integrate DRUID with your applications using the php SDK</h2>

<h3>(you have more examples available at <a href="http://developers.dru-id.com/sdks/php-sdk/sdk-code-examples/">http://developers.dru-id.com/sdks/php-sdk/sdk-code-examples/</a>)</h3>

<h4>This page demostrates how to create login and registration links for not connected users, and show logout link and retrieve user email when user is connected:</h4>


<p style="background-color:#e5ffff; border: thin solid #99ffff; padding: 20px">
<?php 
try {
    if (!Identity::isConnected()) {
        echo "<a href=" . URLBuilder::getUrlLogin() . ">Login</a> ";
        echo "<a href=" . URLBuilder::getUrlRegister() . ">Register</a>";
    } else {
        $info = UserApi::getUserLogged();
        $picture = UserApi::getUserLoggedAvatarUrl();
        echo "<img src='{$picture}' onerror='this.src=/assets/img/placeholder.png' width='32'/>";
        echo " Welcome " . $info->user->user_ids->email->value;
        echo "<br/><br/>";
        echo "<a href=\"opi.php\">Fill Opi</a>";
        echo "<br/><br/>";
        echo "<a href=\"/actions/logout\">Logout</a>";
    }
} catch (Exception $e) {
    echo $e->getMessage() . "\n" . $e->getTraceAsString();
}
コード例 #3
0
ファイル: Request.php プロジェクト: dru-id/druid-php-sdk
 /**
  * @param string $url Endpoint where the request is sent. Without params.
  * @param array $parameters mixed Associative vector with request params. Use key as param name, and value as value. The values shouldn't be prepared.
  * @param string $http_method string HTTP method. One of them:
  *        - {@link self::HTTP_GET}
  *        - {@link self::HTTP_POST}
  *        - {@link self::HTTP_METHOD_HEAD}
  *        - {@link self::HTTP_METHOD_PUT}
  *        - {@link self::HTTP_METHOD_DELETE}
  * @param bool $credentials If true, client_id and client_secret are included in params
  * @param array $http_headers A vector of strings with HTTP headers or FALSE if no additional headers to sent.
  * @param array $cookies A vector of strings with cookie data or FALSE if no cookies to sent. One line per cookie ("key=value"), without trailing semicolon.
  * @return array An associative array with that items:
  *     - result: An string or array on success, or FALSE if there is no result.
  *     - code: HTTP code.
  *     - content-type: Content-type related to result
  * @throws \Exception If there is an error.
  */
 public static function execute($url, $parameters = array(), $http_method = self::HTTP_GET, $credentials = self::NOT_SECURED, $http_headers = array(), $cookies = array())
 {
     if (!extension_loaded('curl')) {
         throw new Exception('The PHP extension curl must be installed to use this library.');
     }
     if (($url = trim($url)) == '') {
         return array('result' => false, 'code' => 0, 'content_type' => '');
     }
     $is_ssl = preg_match('#^https#Usi', $url) ? true : false;
     $curl_options = array(CURLOPT_RETURNTRANSFER => true, CURLOPT_CUSTOMREQUEST => $http_method, CURLOPT_USERAGENT => $_SERVER['HTTP_USER_AGENT']);
     if ($is_ssl) {
         $curl_options[CURLOPT_SSL_VERIFYPEER] = false;
         $curl_options[CURLOPT_SSL_VERIFYHOST] = 0;
     } else {
         $curl_options[CURLOPT_SSL_VERIFYPEER] = true;
     }
     if ($credentials) {
         $parameters['client_id'] = OAuthConfig::getClientId();
         $parameters['client_secret'] = OAuthConfig::getClientSecret();
     }
     switch ($http_method) {
         case self::HTTP_POST:
             $curl_options[CURLOPT_POST] = true;
             // Check if parameters must to be in json format
             if (isset($http_headers['Content-Type']) && $http_headers['Content-Type'] == 'application/json' && !empty($parameters) && is_array($parameters)) {
                 //echo (json_encode($parameters));
                 $curl_options[CURLOPT_POSTFIELDS] = json_encode($parameters);
             } else {
                 $curl_options[CURLOPT_POSTFIELDS] = http_build_query($parameters);
             }
             break;
         case self::HTTP_PUT:
             $curl_options[CURLOPT_POSTFIELDS] = http_build_query($parameters);
             break;
         case self::HTTP_HEAD:
             $curl_options[CURLOPT_NOBODY] = true;
             /* No break */
         /* No break */
         case self::HTTP_DELETE:
             // Check if parameters are in json
             if (isset($http_headers['Content-Type']) && $http_headers['Content-Type'] == 'application/json' && !empty($parameters) && is_array($parameters)) {
                 $curl_options[CURLOPT_POSTFIELDS] = json_encode($parameters);
             } else {
                 $url .= '?' . http_build_query($parameters, null, '&');
             }
             break;
         case self::HTTP_GET:
             if (!empty($parameters)) {
                 $url .= '?' . http_build_query($parameters, null, '&');
             }
             break;
         default:
             break;
     }
     $curl_options[CURLOPT_URL] = $url;
     // Cookies.
     if (is_array($cookies) && !empty($cookies)) {
         // Removes trailing semicolons, if exists.
         foreach ($cookies as $key => $value) {
             $cookies[$key] = rtrim($value, ';');
         }
         $curl_options[CURLOPT_COOKIE] = implode('; ', $cookies);
     }
     // Prepare headers.
     if (is_array($http_headers) && !empty($http_headers)) {
         $header = array();
         foreach ($http_headers as $key => $parsed_urlvalue) {
             $header[] = "{$key}: {$parsed_urlvalue}";
         }
         $curl_options[CURLOPT_HTTPHEADER] = $header;
     }
     // Send request.
     $ch = curl_init();
     curl_setopt_array($ch, $curl_options);
     $result = curl_exec($ch);
     $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
     $content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
     $total_time = curl_getinfo($ch, CURLINFO_TOTAL_TIME);
     curl_close($ch);
     Identity::getLogger()->debug('### BEGIN REQUEST ###');
     Identity::getLogger()->debug(sprintf('URL -> [%s][%s] %s', $http_method, $is_ssl ? 'ssl' : 'no ssl', var_export($url, true)));
     Identity::getLogger()->debug('Params -> ' . var_export($parameters, true));
     Identity::getLogger()->debug('Headers -> ' . var_export($http_headers, true));
     Identity::getLogger()->debug(sprintf("Response -> [%s][%s]\n%s", $content_type, $http_code, var_export($result, true)));
     Identity::getLogger()->debug('Total Time -> ' . var_export($total_time, true));
     Identity::getLogger()->debug('### END REQUEST ###');
     return array('result' => $content_type === 'application/json' ? null === json_decode($result) ? $result : json_decode($result) : $result, 'code' => $http_code, 'content_type' => $content_type);
 }
コード例 #4
0
ファイル: URLBuilder.php プロジェクト: dru-id/druid-php-sdk
 /**
  * Builds the URL to fill up data for a specific section.
  *
  * @param string The endpoint. Normally the 'edit_account_endpoint' of
  *     OAuth server.
  * @param string Where the user will be redirected when finished
  *     fill up data.
  * @param string Where the user will be redirected if the process is
  *     cancelled.
  * @param string Section-key identifier of the web client. The
  *     section-key is located in "oauthconf.xml" file.
  * @return string The URL generated.
  * @throws \Exception If there is an error.
  */
 private static function buildCompleteAccountUrl($endpoint_url, $next_url, $cancel_url, $scope)
 {
     try {
         if (self::checkParam($endpoint_url)) {
             throw new Exception('Endpoint URL is empty');
         }
         if (self::checkParam($next_url)) {
             throw new Exception('Next URL is empty');
         }
         if (self::checkParam($cancel_url)) {
             throw new Exception('Cancel URL is empty');
         }
         $access_token = Identity::getThings()->getAccessToken();
         if (is_null($access_token)) {
             throw new Exception('Access token is empty');
         }
         if (self::checkParam($scope)) {
             throw new Exception('Scope section is empty');
         }
         $endpoint_url = rtrim($endpoint_url, '?');
         $params = array();
         $params['next'] = $next_url;
         $params['cancel_url'] = $cancel_url;
         $params['oauth_token'] = $access_token->getValue();
         unset($access_token);
         $params['scope'] = $scope;
         return $endpoint_url . '?' . http_build_query($params, null, '&');
     } catch (Exception $e) {
         Identity::getLogger()->debug('Error [' . __FUNCTION__ . '] - ' . $e->getMessage());
     }
 }
コード例 #5
0
ファイル: OAuth.php プロジェクト: dru-id/druid-php-sdk
 /**
  * Checks if the user has accepted terms and conditions for the specified section (scope).
  *
  * @param string $endpoint_url The endpoint where the request will be sent.
  * @param string $scope Section-key identifier of the web client. The section-key is located in "oauthconf.xml" file.
  * @return boolean TRUE if the user need to accept the terms and conditions (not accepted yet) or
  *      FALSE if it has already accepted them (no action required).
  * @throws \Exception If there is an error.
  */
 public static function doCheckUserNeedAcceptTerms($endpoint_url, $scope)
 {
     try {
         if (($endpoint_url = trim((string) $endpoint_url)) == '') {
             throw new Exception('Endpoint URL is empty');
         }
         if (($scope = trim((string) $scope)) == '') {
             throw new Exception('Scope is empty');
         }
         if (!($access_token = Identity::getThings()->getAccessToken()) instanceof AccessToken || $access_token->getValue() == '') {
             throw new Exception('Access token is empty');
         }
         // Send request.
         $params = array();
         $params['oauth_token'] = $access_token->getValue();
         $params['s'] = "needsToCompleteData";
         $params['f'] = "UserMeta";
         $params['w.section'] = $scope;
         $response = Request::execute($endpoint_url, $params, Request::HTTP_POST);
         self::checkErrors($response);
         if (isset($response['code']) && $response['code'] == 200) {
             return call_user_func(function ($result) {
                 if (isset($result->data) && is_array($result->data)) {
                     foreach ($result->data as $data) {
                         if (isset($data->meta->name) && $data->meta->name === 'needsToAcceptTerms') {
                             return isset($data->meta->value) && $data->meta->value === 'true';
                         }
                     }
                 }
                 return false;
             }, $response['result']);
         } else {
             return false;
         }
     } catch (Exception $e) {
         throw new Exception('Error [' . __FUNCTION__ . '] - ' . $e->getMessage());
     }
 }
コード例 #6
0
ファイル: logout.php プロジェクト: dru-id/druid-php-skel
<?php

use Genetsis\URLBuilder;
use Genetsis\Identity;
require __DIR__ . "/../../lib/vendor/autoload.php";
try {
    Identity::init();
    if (Identity::isConnected()) {
        Identity::logoutUser();
        header('Location: /');
    } else {
        echo 'We cant log out a user that is not logged, please <a href="' . URLBuilder::getUrlLogin() . '">Log in</a>';
    }
} catch (Exception $e) {
    echo $e->getMessage() . "\n" . $e->getTraceAsString();
}
コード例 #7
0
ファイル: callback.php プロジェクト: dru-id/druid-php-skel
 */
require __DIR__ . "/../../lib/vendor/autoload.php";
use Genetsis\Identity;
try {
    Identity::init();
} catch (Exception $e) {
    echo $e->getMessage() . "\n" . $e->getTraceAsString();
    die;
}
$error = $_GET['error'];
$uid = $_GET['uid'];
$gohome = true;
if (!$error) {
    $code = $_GET['code'];
    if (!Identity::isConnected() && (isset($code) || trim($code) != '')) {
        Identity::authorizeUser($code);
    }
} else {
    if ('user_cancel' != $error) {
        $error_description = $_GET['error_description'];
        echo $error . " -> " . $error_description;
        $gohome = false;
    }
}
if (file_exists($_SERVER['DOCUMENT_ROOT'] . '/myactions/callback.php')) {
    include $_SERVER['DOCUMENT_ROOT'] . '/myactions/callback.php';
}
if ($gohome) {
    // redirect to home as example
    header("Location: /");
}