/lib/Lampcms/Controllers/Loginlinkedin.php
PHP | 838 lines | 364 code | 141 blank | 333 comment | 55 complexity | 31d6a82761854f8025e1e1b6a8e940d0 MD5 | raw file
Possible License(s): LGPL-3.0
- <?php
- /**
- *
- * License, TERMS and CONDITIONS
- *
- * This software is licensed under the GNU LESSER GENERAL PUBLIC LICENSE (LGPL) version 3
- * Please read the license here : http://www.gnu.org/licenses/lgpl-3.0.txt
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * ATTRIBUTION REQUIRED
- * 4. All web pages generated by the use of this software, or at least
- * the page that lists the recent questions (usually home page) must include
- * a link to the http://www.lampcms.com and text of the link must indicate that
- * the website\'s Questions/Answers functionality is powered by lampcms.com
- * An example of acceptable link would be "Powered by <a href="http://www.lampcms.com">LampCMS</a>"
- * The location of the link is not important, it can be in the footer of the page
- * but it must not be hidden by style attributes
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- * IN NO EVENT SHALL THE FREEBSD PROJECT OR CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * This product includes GeoLite data created by MaxMind,
- * available from http://www.maxmind.com/
- *
- *
- * @author Dmitri Snytkine <cms@lampcms.com>
- * @copyright 2005-2012 (or current year) Dmitri Snytkine
- * @license http://www.gnu.org/licenses/lgpl-3.0.txt GNU LESSER GENERAL PUBLIC LICENSE (LGPL) version 3
- * @link http://www.lampcms.com Lampcms.com project
- * @version Release: @package_version@
- *
- *
- */
-
- namespace Lampcms\Controllers;
-
- use \Lampcms\WebPage;
- use \Lampcms\Responder;
- use \Lampcms\Request;
- use \Lampcms\Cookie;
- use \Lampcms\Mongo\Schema\User as Schema;
- use \Lampcms\Acl\Role;
-
- class Loginlinkedin extends WebPage
- {
-
- const REQUEST_TOKEN_URL = 'https://api.linkedin.com/uas/oauth/requestToken?scope=r_basicprofile+r_emailaddress+rw_nus';
-
- const ACCESS_TOKEN_URL = 'https://api.linkedin.com/uas/oauth/accessToken';
-
- const AUTHORIZE_URL = 'https://www.linkedin.com/uas/oauth/authenticate';
-
- //,location:(name) cannot be used together with location:(country:(code)) it generates duplicate field exception
- const PROFILE_URL = 'http://api.linkedin.com/v1/people/~:(id,first-name,last-name,picture-url,public-profile-url,location,summary,interests,date-of-birth,phone-numbers,skills,educations,certifications,languages)';
-
- //const PROFILE_URL = 'http://api.linkedin.com/v1/people/~';
-
- /**
- * URL TO GET email address of user
- */
- const EMAIL_URL = 'http://api.linkedin.com/v1/people/~/email-address';
-
- protected $callback = '{_WEB_ROOT_}/{_loginlinkedin_}';
-
- /**
- * Array of Tumblr's
- * oauth_token and oauth_token_secret
- *
- * @var array
- */
- protected $aAccessToken = array();
-
-
- /**
- * Object php OAuth
- *
- * @var object of type php OAuth
- * must have oauth extension for this
- */
- protected $oAuth;
-
-
- protected $bInitPageDoc = false;
-
-
- /**
- * Configuration of LinkedIn API
- * this is array of values LINKEDIN section
- * in !config.ini
- *
- * @var array
- */
- protected $aTM = array();
-
- /**
- * Flag indicates that this is the
- * request to connect Twitter account
- * with existing user account.
- *
- * @var bool
- */
- protected $bConnect = false;
-
- /**
- *
- * @var array of data from LinkedIn API,
- * created from the parsed XML response
- */
- protected $aData;
-
- /**
- * Email address from LinkedIn profile
- *
- * @var string
- */
- protected $email = '';
-
- /**
- * @var object object type User (may be LinkedinUser or just plain User)
- */
- protected $User;
-
-
- /**
- * The main purpose of this class is to
- * generate the oAuth token
- * and then redirect browser to twitter url with
- * this unique token
- *
- * No actual page generation will take place
- *
- * @see classes/WebPage#main()
- */
- protected function main()
- {
- $routerCallback = $this->Registry->Router->getCallback();
- $this->callback = $routerCallback($this->callback);
- d('$this->callback' . $this->callback);
-
- if (!extension_loaded('oauth')) {
- throw new \Exception('@@Unable to use LinkedIn API because OAuth extension is not available@@');
- }
-
- /**
- * If user is logged in then this is
- * a request to connect LinedIN Account
- * with existing account.
- */
- if ($this->isLoggedIn()) {
- $this->bConnect = true;
- }
-
- d('$this->bConnect: ' . $this->bConnect);
-
- $this->callback = $this->Registry->Ini->SITE_URL . $this->callback;
- d('$this->callback: ' . $this->callback);
-
- $this->aTm = $this->Registry->Ini['LINKEDIN'];
-
- try {
- $this->oAuth = new \OAuth($this->aTm['OAUTH_KEY'], $this->aTm['OAUTH_SECRET']);
- $this->oAuth->disableSSLChecks();
- $this->oAuth->enableDebug();
- } catch ( \OAuthException $e ) {
- e('OAuthException: ' . $e->getMessage());
- $aDebug = $this->oAuth->getLastResponseInfo();
- d('debug: ' . print_r($aDebug, 1));
- throw new \Exception('@@Something went wrong during authorization. Please try again later@@' . $e->getMessage());
- }
-
-
- /**
- * If this is start of dance then
- * generate token, secret and store them
- * in session and redirect to linkedin authorization page
- */
- if (empty($_SESSION['linkedin_oauth']) || empty($this->Request['oauth_token'])) {
- $this->step1();
- } else {
- $this->step2();
- }
- }
-
-
- /**
- * Generate oAuth request token
- * and redirect to Linkedin for authentication
- *
- * @throws \Exception in case something goes wrong during
- * this stage
- * @return object $this
- */
- protected function step1()
- {
- d('cp');
- try {
-
- $_SESSION['linkedin_oauth'] = $this->oAuth->getRequestToken(self::REQUEST_TOKEN_URL, $this->callback);
- $aDebug = $this->oAuth->getLastResponseInfo();
- d('debug: ' . print_r($aDebug, 1));
-
- d('$_SESSION[\'linkedin_oauth\']: ' . \print_r($_SESSION['linkedin_oauth'], 1));
- if (!empty($_SESSION['linkedin_oauth']) && !empty($_SESSION['linkedin_oauth']['oauth_token'])) {
- d('cp');
-
- Responder::redirectToPage(self::AUTHORIZE_URL . '?oauth_token=' . $_SESSION['linkedin_oauth']['oauth_token']);
- } else {
- /**
- * Here throw regular Exception, not Lampcms\Exception
- * so that it will be caught ONLY by the index.php and formatted
- * on a clean page, without any template
- */
- throw new \Exception("Failed fetching request token, response was: " . $this->oAuth->getLastResponse());
- }
- } catch ( \OAuthException $e ) {
- e('OAuthException: ' . $e->getMessage());
- $aDebug = $this->oAuth->getLastResponseInfo();
- d('debug: ' . print_r($aDebug, 1));
-
- throw new \Exception('Something went wrong during authorization. Please try again later' . $e->getMessage());
- }
-
- return $this;
- }
-
-
- /**
- * Step 2 in oAuth process
- * this is when linkedin redirected the user back
- * to our callback url, which calls this controller
- *
- * @throws \Exception in case something goes wrong with oAuth class
- * @return object $this
- */
- protected function step2()
- {
-
- try {
- /**
- * This is a callback (redirected back from linkedin page
- * after user authorized us)
- * In this case we must: create account or update account
- * in USER table
- * Re-create oViewer object
- * send cookie to remember user
- * and then send out HTML with js instruction to close the popup window
- */
- d('We are at step 2 of authentication. $_REQUEST: ' . print_r($_REQUEST, 1));
-
- $token = $this->Request['oauth_token'];
- d('$token: ' . $token);
-
- /**
- * @todo check first to make sure we do have oauth_token
- * on REQUEST, else close the window
- */
- $this->oAuth->setToken($token, $_SESSION['linkedin_oauth']['oauth_token_secret']);
-
- /**
- * Get 'oauth_verifier' request param which was sent from LinkedIn
- */
- $ver = $this->Registry->Request->get('oauth_verifier', 's', '');
- d('$ver: ' . $ver);
- if (empty($ver)) {
- $ver = null;
- }
-
- $url = self::ACCESS_TOKEN_URL;
- d('url: ' . $url);
-
- $this->aAccessToken = $this->oAuth->getAccessToken($url, null, $ver);
- d('$this->aAccessToken: ' . \print_r($this->aAccessToken, 1));
- $this->setTokenExpirationTime();
-
- unset($_SESSION['linkedin_oauth']);
-
- $this->oAuth->setToken($this->aAccessToken['oauth_token'], $this->aAccessToken['oauth_token_secret']);
-
- d('getting profile from PROFILE_URL');
- $this->oAuth->fetch(self::PROFILE_URL, null, OAUTH_HTTP_METHOD_GET, array('Connection'=> 'close'));
- $aDebug = $this->oAuth->getLastResponseInfo();
- d('debug: ' . \print_r($aDebug, 1));
-
- $resp = $this->oAuth->getLastResponse();
- $this->parseXML($resp);
- $this->getEmailAddress();
-
- $this->createOrUpdate();
-
- if (!$this->bConnect) {
- \Lampcms\Cookie::sendLoginCookie($this->Registry->Viewer->getUid(), $this->User->rs);
- } else {
- /**
- * The b_li flag in Viewer is necessary
- * for the social checkboxes to set
- * the checkbox to 'checked' state
- *
- */
- $this->Registry->Viewer['b_li'] = true;
- }
-
- $this->closeWindow();
-
- } catch ( \OAuthException $e ) {
- e('OAuthException: ' . $e->getMessage());
- $aDebug = $this->oAuth->getLastResponseInfo();
- d('debug: ' . print_r($aDebug, 1));
- $err = '@@Something went wrong during authorization. Please try again later@@ ' . $e->getMessage();
- throw new \Exception($err);
- }
-
- return $this;
- }
-
-
- /**
- * LinkedIn returns expiration times in the number of seconds from now format
- * Must convert these values into unix timestamp now.
- */
- protected function setTokenExpirationTime()
- {
- if (isset($this->aAccessToken['oauth_expires_in'])) {
- $this->aAccessToken['oauth_expires_in'] = time() + $this->aAccessToken['oauth_expires_in'];
- }
-
- if (isset($this->aAccessToken['oauth_authorization_expires_in'])) {
- $this->aAccessToken['oauth_authorization_expires_in'] = time() + $this->aAccessToken['oauth_authorization_expires_in'];
- }
- }
-
-
- /**
- * Parses the XML returned from LinkedIn API
- * and creates array of $this->aData from it
- *
- * @param $xml
- *
- * @throws \Lampcms\DevException
- * @throws \Lampcms\Exception if xml could not
- * be parsed for any reason
- * @internal param \Lampcms\Controllers\xml $string xml string received from LinkedIn API
- *
- * @return object $this
- */
- protected function parseXML($xml)
- {
- d('xml: ' . $xml);
-
- $oXML = new \Lampcms\Dom\Document();
- if (false === $oXML->loadXML($xml)) {
- $err = 'Unexpected Error parsing response XML';
-
- throw new \Lampcms\DevException($err);
- }
-
- $lid = $oXML->evaluate('string(/person/id[1])'); // it will be string!
- if (!$lid) {
- throw new \Lampcms\DevException('Unable to get LinkedIn ID from xml: ' . $xml);
- }
-
- $this->aData['linkedin_id'] = (string)$lid;
-
- if ('' !== $industry = $oXML->evaluate('string(/person/industry[1])')) {
- $this->aData['industry'] = $industry;
- }
-
- if ('' !== $summary = $oXML->evaluate('string(/person/summary[1])')) {
- $this->aData['description'] = $summary;
- }
-
- if ('' !== $city = $oXML->evaluate('string(/person/location/name[1])')) {
- $this->aData['city'] = $city;
- }
-
- if ('' !== $cc = $oXML->evaluate('string(/person/location/country/code[1])')) {
- $this->aData['cc'] = \strtoupper($cc);
- }
-
- if ('' !== $avtr = $oXML->evaluate('string(/person/picture-url[1])')) {
- $this->aData['avatar_external'] = $avtr;
- }
-
- if ('' !== $fn = $oXML->evaluate('string(/person/first-name[1])')) {
- $this->aData['fn'] = $fn;
- }
-
- if ('' !== $ln = $oXML->evaluate('string(/person/last-name[1])')) {
- $this->aData['ln'] = $ln;
- }
-
- $this->aData['linkedin'] = array(
- 'tokens' => $this->aAccessToken
- );
-
- if ('' !== $url = $oXML->evaluate('string(/person/public-profile-url[1])')) {
- d('profile url: ' . $url);
- $this->aData['linkedin']['url'] = $url;
- }
-
- d('$this->aData: ' . print_r($this->aData, 1));
-
- return $this;
- }
-
-
- /**
- * Get email address from LinkedIN API
- *
- */
- protected function getEmailAddress()
- {
- d('cp');
- try {
- $this->oAuth->fetch(self::EMAIL_URL, null, OAUTH_HTTP_METHOD_GET, array('Connection'=> 'close'));
- $resp = $this->oAuth->getLastResponse();
-
- /**
- * May return empty element
- *
- * $resp: <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
- * <email-address />
- *
- */
- d('EMAIL ADDRESS RESPONSE: ' . $resp);
- ;
-
- $oXML = new \Lampcms\Dom\Document();
- if (false === $oXML->loadXML($resp)) {
- $err = 'Unexpected Error parsing email address response XML';
- e($err);
-
- return;
- }
-
- $email = $oXML->evaluate('string(/email-address[1])');
- d('email: ' . $email);
-
- if (!empty($email)) {
- $this->email = \mb_strtolower($email);
- }
- } catch ( \OAuthException $e ) {
- e('Unable to fetch email address. OAuthException: ' . $e->getMessage());
- $aDebug = $this->oAuth->getLastResponseInfo();
- d('debug: ' . print_r($aDebug, 1));
- }
- }
-
-
- protected function createOrUpdate()
- {
- $aUser = $this->getUserByLinkedInId($this->aData['linkedin_id']);
-
- if (!empty($this->bConnect)) {
- d('this is connect action');
-
- $this->User = $this->Registry->Viewer;
- $this->updateUser();
-
- } elseif (!empty($aUser)) {
- /**
- * This means user previously joined with LInkedIn
- * and now logged back in with Linked in button again
- */
- $this->User = \Lampcms\UserLinkedin::userFactory($this->Registry, $aUser);
- $this->updateUser(); // only update token, secret, linkedin url
- } else {
-
-
- /**
- * Try to find user by email address from
- * LinkedIN profile
- */
- $User = $this->findUserByEmail();
- if (is_object($User) && ($User instanceof \Lampcms\User)) {
- /**
- * set $this->bConnect to true because this is a connection
- * of existing user with the new linkedin credentials
- */
- $this->bConnect = true;
- $this->User = $User;
- $this->updateUser();
- } else {
- d('User not found by email address');
- $this->isNewAccount = true;
- $this->createNewUser();
- }
- }
-
-
- try {
- $this->processLogin($this->User);
- } catch ( \Lampcms\LoginException $e ) {
- /**
- * re-throw as regular exception
- * so that it can be caught and show in popup window
- */
- e('Unable to process login: ' . $e->getMessage());
- throw new \Exception($e->getMessage());
- }
-
- $this->Registry->Dispatcher->post($this, 'onLinkedinLogin');
-
- return $this;
- }
-
-
- /**
- * Attempt to find existing user by email address
- * Search in EMAILS collection first, then if not found, in USERS collection
- * If record is found creates User object and returns it
- *
- * @return mixed null | User object
- */
- protected function findUserByEmail()
- {
- $User = null;
-
- /**
- * Search EMAILS collection
- * try to find user that has this email address
- */
- $res = $this->Registry->Mongo->EMAILS->findOne(array(Schema::EMAIL => $this->email), array('i_uid' => true));
- if (!empty($res) && !empty($res['i_uid'])) {
- d('found user id by email address. uid: ' . $res['i_uid']);
-
- $aUser = $this->Registry->Mongo->USERS->findOne(array(Schema::PRIMARY => $res['i_uid']));
- $User = \Lampcms\User::userFactory($this->Registry, $aUser);
- }
-
- /**
- * Was Not able to find user by search EMAILS collection
- * Search USERS collection by email address
- */
- if (null === $User) {
- $a = $this->Registry->Mongo->USERS->findOne(array(Schema::EMAIL => $this->email));
- if (!empty($a)) {
- d('found user id by email address. uid: ' . $a['_id']);
- $User = \Lampcms\User::userFactory($this->Registry, $a);
- }
- }
-
- d('User not found by email: ' . $this->email);
-
- return $User;
- }
-
-
- /**
- * Create new record in the USERS collection
- * also set the $this->User to the newly created
- * instance of UserLinkedin object
- *
- *
- */
- protected function createNewUser()
- {
- d('creating new user');
-
- /**
- * Need to call /people/~/email-address to get email address
- * and /people/~ to get data that includes avatar among other things
- */
-
- if (false !== $tzn = Cookie::get('tzn')) {
- $timezone = $tzn;
- } else {
- $timezone = $this->Registry->Ini->SERVER_TIMEZONE;
- }
-
- $ln = (!empty($this->aData['ln'])) ? $this->aData['ln'] : '';
-
- $oEA = \Lampcms\ExternalAuth::factory($this->Registry);
-
- $u = $this->aData['fn'] . ' ' . $ln;
- d('$u: ' . $u);
-
- $username = $oEA->makeUsername($u);
- $sid = \Lampcms\Cookie::getSidCookie();
- d('sid is: ' . $sid);
-
- $this->aData[Schema::USERNAME] = $username;
- $this->aData[Schema::USERNAME_LOWERCASE] = \mb_strtolower($username, 'utf-8');
- $this->aData[Schema::REGISTRATION_TIMESTAMP] = time();
- $this->aData[Schema::REGISTRATION_TIME] = date('r');
- $this->aData[Schema::ROLE] = Role::EXTERNAL_USER;
- $this->aData[Schema::SID] = (false !== $sid) ? $sid : \Lampcms\String::makeSid();
- $this->aData[Schema::REPUTATION] = 1;
- $this->aData[Schema::LANG] = $this->Registry->getCurrentLang();
- $this->aData[Schema::LOCALE] = $this->Registry->Locale->getLocale();
- $this->aData[Schema::TIMEZONE] = $timezone;
- if (!empty($this->email)) {
- $this->aData[Schema::EMAIL] = $this->email;
- }
-
- if (empty($this->aData['cc']) && empty($this->aData['city'])) {
- $this->aData = array_merge($this->Registry->Geo->Location->data, $this->aData);
- }
-
- $this->User = \Lampcms\UserLinkedin::userFactory($this->Registry, $this->aData);
-
- /**
- * This will mark this user object is new user
- * and will be persistent for the duration of this session ONLY
- * This way we can know it's a newly registered user
- * and ask the user to provide email address but only
- * during the same session
- */
- $this->User->setNewUser();
- d('isNewUser: ' . $this->User->isNewUser());
- $this->User->save();
-
- \Lampcms\PostRegistration::createReferrerRecord($this->Registry, $this->User);
-
- $this->Registry->Dispatcher->post($this->User, 'onNewUser');
-
- return $this;
- }
-
-
- /**
- *
- * Adds data from LinkedIn API, including
- * oauth token, secret to the
- * User object
- * avatar from LinkedIn, Country Code, City
- * and 'about' are added ONLY if they
- * don't already exist in User
- *
- * @post-condition: $this->User object is updated
- * with the valued from $this->aData AND $this->aAccessToken
- * and then saved using save()
- *
- * @return $this
- */
- protected function updateUser()
- {
-
- $avtr = $this->User['avatar_external'];
- /**
- * Special case:
- * if connecting user and another user
- * already exists with the same Linkedin_id
- * then we will still allow to add Linkedin key
- * to this Viewer's profile
- * but will NOT add the Linkedin_id to the Viewer object
- * This is because otherwise we will have 2 users
- * with the same value of Linkedin_id and then
- * when logging in with LinkedIN we will not know
- * which user to login. This is why we will enforce uniqueness
- * of Linkedin_id key here
- */
- if ($this->bConnect) {
- /**
- * Do we have another user with the same linkedin_id?
- */
- $a = $this->Registry->Mongo->USERS->findOne(array('linkedin_id' => $this->aData['linkedin_id']), array('_id' => 1));
-
- /**
- * If not then add linkedin_id to user being connected (which is current Viewer object)
- */
- if (empty($a)) {
- $this->User['linkedin_id'] = $this->aData['linkedin_id'];
- } else {
- /**
- * If found another user with the same linkedin_id
- * DO NOT add linkedin_id to user being connected!
- * This is because we cannot have 2 users with the same linkedin_id
- * The connected user will still get the ['linkedin'] element
- * added to user object and it will contain oath token and secret
- */
- }
-
- /**
- *
- * If user does not have email address or email
- * is not activated
- * then add value of $this->email
- * and switch unactivated status to activated!
- */
- $currentEmail = $this->User[Schema::EMAIL];
- $currentStatus = $this->User[Schema::ROLE];
- d('currentEmail: ' . $currentEmail . ' currentStatus: ' . $currentStatus);
-
- /**
- * If Linking in existing user and user does not have email address
- * for any reason then add email address from LinkedIN profile
- *
- * If User has email address but status in unactivated for any reason
- * then change status to Role::REGISTERED or Role::EXTERNAL_USER
- */
- if (empty($currentEmail)) {
- if (!empty($this->email)) {
- d('User did not have email address. Adding one from LinkedIn account');
- $this->User[Schema::EMAIL] = $this->email;
- }
- } elseif ($currentStatus === Role::UNACTIVATED && $currentEmail === $this->email) {
- d('User had unactivated email address. Setting status to REGISTERED');
- $this->User->setRoleId(Role::REGISTERED);
- } elseif ($currentStatus === Role::UNACTIVATED_EXTERNAL && $currentEmail === $this->email) {
- d('User had unactivated email address. Setting status to EXTERNAL_USER');
- $this->User->setRoleId(Role::EXTERNAL_USER);
- }
-
- } else {
- /**
- * This is not a connect situation - this is a new user
- * OR it may be a case of existing linkedIN user logging in
- * with LinkedIN login button in which case
- * this->User already has the same linkedin_id so setting it again
- * to the same value is not a problem
- */
- $this->User['linkedin_id'] = $this->aData['linkedin_id'];
- }
-
- /**
- * Update the following field ONLY
- * if they DON'T already exists in this user's record!
- *
- * This means that if record exists and is an empty
- * string - don't update this because it usually means
- * that user did have this field before and then removed
- * the value by editing profile.
- */
- if (empty($avtr) && !empty($this->aData['avatar_external'])) {
- $this->User[Schema::EXTERNAL_AVATAR] = $this->aData['avatar_external'];
- }
-
- if (null === $this->User[Schema::DESCRIPTION] && !empty($this->aData['description'])) {
- $this->User[Schema::DESCRIPTION] = $this->aData['description'];
- }
-
- if (null === $this->User[Schema::COUNTRY_CODE] && !empty($this->aData['cc'])) {
- $this->User[Schema::COUNTRY_CODE] = $this->aData['cc'];
- }
-
- if (null === $this->User[Schema::CITY] && !empty($this->aData['city'])) {
- $this->User[Schema::CITY] = $this->aData['city'];
- }
-
- /**
- * Always update the 'linkedin' element
- * of user record. It contains 2 keys: tokens
- * with is array holding oauth tokens
- * and optionally 'url' with Linkedin profile url
- *
- */
- $this->User['linkedin'] = $this->aData['linkedin'];
-
-
- $this->User->save();
-
- return $this;
- }
-
-
- /**
- * Find user data in USERS collection
- * using linkedin_id key
- *
- * @todo make linkedin_id a unique index
- * This will add extra protection against
- * allowing more than one user to have same
- * linked-in account
- *
- * @param string $lid LinkedIn id - from LinkedIn website
- * It is a string, not an integer!
- *
- * @return mixed null | array of user data
- *
- */
- protected function getUserByLinkedInId($lid)
- {
- $coll = $this->Registry->Mongo->USERS;
- $coll->ensureIndex(array('linkedin_id' => 1));
-
- $aUser = $coll->findOne(array('linkedin_id' => (string)$lid));
- d('aUser: ' . print_r($aUser, 1));
-
- return $aUser;
- }
-
-
- /**
- * Return html that contains JS window.close code and nothing else
- *
- * @param array $a
- *
- * @return void
- */
- protected function closeWindow(array $a = array())
- {
- d('cp a: ' . print_r($a, 1));
- $js = '';
-
- $tpl = '
- var myclose = function(){
- window.close();
- }
- if(window.opener){
- %s
- setTimeout(myclose, 100); // give opener window time to process login and cancell intervals
- }else{
- alert("This is not a popup window or opener window gone away");
- }';
- d('cp');
-
- $script = \sprintf($tpl, $js);
-
- $s = Responder::PAGE_OPEN . Responder::JS_OPEN .
- $script .
- Responder::JS_CLOSE .
- '<h2>You have successfully connected your LinkedIn account. You should close this window now</h2>' .
-
- Responder::PAGE_CLOSE;
- d('cp s: ' . $s);
- echo $s;
- fastcgi_finish_request();
- exit;
- }
-
- }