Topic-icon I Found a way to Parse the Address Field Accurately

Active Subscriptions:

None
10 years 9 months ago - 10 years 9 months ago #34987 by paulzmuda
So in my disappointment when I found that LinkedIn has 1 address field textbox while my JomSocial profiles separate Street Address, City, State, Zip, Country etc. I had to find a way to parse the address into the new fields.

I read a post about it here - www.sourcecoast.com/forums/jlinked/jlink...into-separate-fields


I figured it out by using Google's MAP API and reverse Geo-Coding.


Add the following to /components/com_jlinked/libraries/jlinkeddata.php
private function getAddress($element, $index)
    {
        $newValue = '';
$address = urlencode($element);
$request = file_get_contents("http://maps.google.com/maps/api/geocode/json?address=" . $address . "&sensor=false");
$json = json_decode($request, true);

 if ($index == 0) { $newValue = $json['results'][0]['address_components'][0]['short_name'] . ' ' . $json['results'][0]['address_components'][1]['short_name']; }
 elseif ($index == 1) { $newValue = $json['results'][0]['address_components'][3]['short_name']; }
 elseif ($index == 2) { $newValue = $json['results'][0]['address_components'][5]['short_name']; }
 elseif ($index == 3) { $newValue = $json['results'][0]['address_components'][7]['short_name']; }
 elseif ($index == 4) { $newValue = $json['results'][0]['address_components'][6]['long_name']; }

return $newValue;

    }


and also add the following in the same file (/components/com_jlinked/libraries/jlinkeddata.php) but higher up with the rest of the cases under public function get(...
case 'mainAddress':
            	return $this->getAddress($element, $index);


Then add the following to /components/com_jlinked/libraries/profile.php
Just below //Contact Info - r_contactinfo permission replace the main-address fields
        'main-address.0' => 'Contact Info - Address',
        'main-address.1' => 'Contact Info - City',
        'main-address.2' => 'Contact Info - State',
        'main-address.3' => 'Contact Info - Zip',
        'main-address.4' => 'Contact Info - Country',




Some Reading:
developers.google.com/maps/documentation/geocoding/
maps.google.com/maps/api/geocode/json?ad...2060606&sensor=false
www.ahowto.net/php/callingusing-google-m...se-geocoder-from-php
stackoverflow.com/questions/10735662/par...coding-json-with-php
Last edit: 10 years 9 months ago by paulzmuda.
The topic has been locked.
Support Specialist
10 years 9 months ago - 10 years 9 months ago #35019 by alzander
Both awesome and yeesh! :) The code above looks pretty clean and easy, though I haven't tested it. I hope you didn't bang your head too long learning JLinked in order to implement it.

I've taken a note in our feature tracker of this post. As I just mentioned in another thread about state/country importing, this is something along the lines of what we were planning, though we hadn't thought through exactly what was required.

We really appreciate you sharing what worked for you. There wasn't any specific questions above, but if you do have any issues, ideas for improvements to JLinked, or anything else you'd like to discuss, just let us know.

Thanks again, and best of luck,
Alex
Last edit: 10 years 9 months ago by alzander.
The topic has been locked.
Active Subscriptions:

None
10 years 9 months ago #35034 by paulzmuda
Nothing that a couple cups of coffee and good music couldn't help. Speaking of clean-code, your extension is so well notated that figuring out where to plug things in wasn't as stressful as I thought it'd be. I only followed your function scheme anyways :) So far my favorite part about JLinked is how future friendly the code is! It was the figuring out of how to pull apart Google's response that was the real pain. In that other thread you mentioned the Country needing to be how Jomsocial specifies (the long way instead of abbreviated) and this is exactly what I had in mind when picking out the proper response from Google - they provide you with both short and long versions of each component so it can be U.S. or United States (IL or Illinois)... even if the original profile had ILL, Chi-Town, or 'Murica. Aside from coming up with your own way to parse a person's sloppy address entry I'm very confident the Google API can do all the heavy lifting of figuring it out for us.
The topic has been locked.
Support Specialist
10 years 9 months ago #35037 by alzander
Awesome to know about the Google mapping stuff. Definitely something we'll have to look into. Also, glad to hear that you like the JLinked code. It's actually our 'older' codebase. JFBConnect is being upgraded to the new stuff we've been working on for months, which is similar, but much better organized and simpler in general. Tomorrow, we'll have an announcement blog post about the upcoming release of JFBConnect later this month, as well as a roadmap through the rest of the year.

Part of that roadmap is sucking LinkedIn/JLinked functionality into JFBConnect. By the end of this year, JFBConnect will have Google+, Twitter and LinkedIn authentication and integration... should be very excited.. and don't worry about having a JLinked subscription, you can keep using it, but will also be transitioned to a JFBConnect subscription when LinkedIn is pulled in.

The reason I mention all that is because the Google stuff you're doing is something we'll be looking into later this year to help standardize responses from all the social networks, as well as some hard-coded processing in the extension as well.. so it's great to hear what you're doing and get some early feedback on how that's worked for you.

Anyways, thanks again, and keep us posted if you need anything else,
Alex
The topic has been locked.
Active Subscriptions:

None
10 years 8 months ago - 10 years 8 months ago #35043 by paulzmuda
I'm very excited to see the merged product! I'll definitely be on the lookout for when it comes out and ill let my team know that it's in the pipeline.

Anyhow I've added a few other things that I figured i'd mention incase it would be of interest to you or anybody else. I've split up the response from LinkedIn to give the person's current Title and current Company as two separate fields. Our search needs to be very specific to Title and Company for our community.

I've also split up the phone numbers to differentiate between a LandLine and a Mobile Phone. I've pasted the complete code below as a reference point. I basically just added a listener for a third variable and just named it $third --- (no imagination on my part there lol)

/components/com_jlinked/libraries/jlinkeddata.php
<?php
/**
 * @package        JLinked
 * @copyright (C) 2009-2013 by Source Coast - All rights reserved
 * @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
 */
defined('_JEXEC') or die('Restricted access');

class JlinkedData extends JRegistry
{
    var $dataValid = false;
    var $error = false;
    var $errorRecoverable = false;
    private $rawData = null;

    private $fieldMap = null;

    function __construct($data = null)
    {
        parent::__construct();
        if ($data !== null)
        {
            $this->rawData = $data;
            $this->dataValid = $data['success'];
            if ($this->dataValid)
            {
                if (!is_array($data['linkedin']))
                {
                    $this->loadString($data['linkedin'], 'JSON');
                } else
                    $this->bindData($this->data, $data['linkedin']);
            } else
            {
                $this->error = true;
                if (!$this->checkForTimestampError())
                {
                    $jlinkedLibrary = JLinkedApiLibrary::getInstance();
                    $configModel = $jlinkedLibrary->getConfigModel();
                    if ($configModel->getSetting('linkedin_display_errors', false))
                    {
                        $app = JFactory::getApplication();
                        $app->enqueueMessage('JLinked API Error: ' . $this->rawData['error'] . ' (' . $this->rawData['linkedin']['oauth_problem'] . ')<br/>From:' . $this->rawData['info']['url'], 'error');
                    }
                }
            }
        }
    }

    public function getSuccess()
    {
        return $this->dataValid;
    }

    public function getLastError()
    {
        if ($this->error)
            $msg = $this->rawData['error'];
        else
            $msg = "";
        $response = new stdClass();
        $response->error = $this->error;
        $response->msg = $msg;
        $response->recoverable = $this->errorRecoverable;
        return $response;
    }

    private function checkForTimestampError()
    {
        if ($this->rawData['linkedin']['oauth_problem'] == 'timestamp_refused')
        {
            $liTime = str_replace("+-300", "", $this->rawData['linkedin']['oauth_acceptable_timestamps']);
            $offset = time() - $liTime;
            $jlinkedLibrary = JLinkedApiLibrary::getInstance();
            $configModel = $jlinkedLibrary->getConfigModel();
            $configModel->update('linkedin_oauth_timestamp_offset', $offset);
            $jlinkedLibrary->setTimestampOffset($offset);
            if ($configModel->getSetting('linkedin_display_errors', false))
            {
                $app = JFactory::getApplication();
                $app->enqueueMessage('JLinked Notice: Server time not in sync with LinkedIn. Setting correction offset to: ' . $offset . 's', 'error');
            }
            $this->errorRecoverable = true;
            return true;
        } else
            return false;
    }

    private function makeJSONKey($key)
    {
        $parts = explode('-', $key);
        $parts = array_map('ucfirst', $parts);
        $string = implode('', $parts);
        $string[0] = strtolower($string[0]);

        return $string;
    }

    public function get($path, $default = "")
    {
        $value = $default;
        if (!$this->dataValid)
            return $value;

        $path = $this->makeJSONKey($path);

        if ($this->exists($path))
            $value = parent::get($path, $default);

        $valueParts = explode('.', $path);
        $element = parent::get($valueParts[0]);
        if (array_key_exists(1, $valueParts))
            $index = intval($valueParts[1]);
            
            if (array_key_exists(2, $valueParts))
            $third = intval($valueParts[2]);

        switch ($valueParts[0])
        {
           // case 'positions':
           //     return $this->getPosition($element, $index);
            case 'threeCurrentPositions':
                return $this->getPosition($element, $index, $third);
            case 'threePastPositions':
                return $this->getPosition($element, $index);
            case 'publications':
                return $this->getPublication($element, $index);
            case 'patents':
                return $this->getPatent($element, $index);
            case 'languages':
                return $this->getLanguage($element, $index);
            case 'skills':
                return parent::get('skills.values.' . $index . '.skill.name');
            case 'certifications':
                return $this->getCertification($element, $index);
            case 'educations':
                return $this->getEducation($element, $index);
            case 'courses':
                return $this->getCourse($element, $index);
            case 'volunteer':
                return $this->getVolunteer($element, $index);
            case 'recommendationsReceived':
                return $this->getRecommendation($element, $index);
            case 'phoneNumbers':
                return $this->getPhoneNumber($element, $index, $third);
            case 'imAccounts':
                return $this->getIMAccount($element, $index);
            case 'twitterAccounts':
                return parent::get($valueParts[0] . '.values.' . $index . '.providerAccountName');
            case 'primaryTwitterAccount':
                return parent::get($valueParts[0] . '.providerAccountName');
            case 'dateOfBirth':
                return $this->getDOB($value);
            case 'siteStandardProfileRequest':
                return parent::get('siteStandardProfileRequest.url', '');
            case 'mainAddress':
            	return $this->getAddress($element, $index);
        }

        return $value;
    }

    private function getDOB($element)
    {
        $newValue = '';
        $year = (string)($element->year);
        $month = (string)($element->month);
        $day = (string)($element->day);

        if ($month != '' && $day != '' && $year != '')
            $newValue = $month . '/' . $day . '/' . $year;

        return $newValue;
    }

    private function getPosition($element, $index, $third)
    {
    
    if(!isset($third)) {
    
        if (!property_exists($element->values, $index))
            return null;

      $position = $element->values->$index;
      $dateString = $this->getDateRange($position);

      $newValue = $position->title . ' at ' . $position->company->name . ': ';
       $newValue .= $dateString;

        return $newValue;
        
        }
        else {
        
     if ($third == 1) {
	$position = $element->values->$index;
	$newValue = $position->title;
	return $newValue;
	}
	elseif ($third == 2) {
	$position = $element->values->$index;
	$newValue = $position->company->name;
	return $newValue;
	}
       
        }
        
    }
    
    private function getPublication($element, $index)
    {
        $newValue = '';
        if (isset($element->publication[$index]))
        {
            $publication = $element->publication[$index];
            $dateString = $this->getDateString($publication->date, ', ', '.');

            $newValue = $publication->author->name . '. ' . $publication->title . '. ' . $publication->publisher->name;
            $newValue .= $dateString;
        }
        return $newValue;
    }

    private function getPatent($element, $index)
    {
        $newValue = '';
        if (isset($element->patent[$index]))
        {
            $patent = $element->patent[$index];
            $dateString = $this->getDateString($patent->date, ', ', '.');

            $newValue = $patent->inventor->name . '. "' . $patent->title . '." ' . $patent->office->name . ' ' . $patent->number;
            $newValue .= $dateString;
        }
        return $newValue;
    }

    private function getLanguage($element, $index)
    {
        $newValue = '';
        if (isset($element->language[$index]))
        {
            $language = $element->language[$index];
            $newValue = $language->name;
        }
        return $newValue;
    }

    private function getCertification($element, $index)
    {
        $newValue = '';
        if (isset($element->certification[$index]))
        {
            $certification = $element->certification[$index];
            $newValue = $certification->name;
            if ($certification->number)
                $newValue .= ' ' . $certification->number;
        }
        return $newValue;
    }

    private function getEducation($element, $index)
    {
        $newValue = '';
        if (isset($element->values->$index))
        {
            $education = $element->values->$index;
            $dateString = $this->getDateRange($education);

            $schoolNameString = 'schoolName';
            $fieldOfStudyString = 'fieldOfStudy';

            $newValue = $education->$schoolNameString . ': ' .
                    $education->$fieldOfStudyString . ', ' .
                    $dateString;
        }
        return $newValue;
    }

    private function getCourse($element, $index)
    {
        $newValue = '';
        if (isset($element->course[$index]))
        {
            $course = $element->course[$index];
            $newValue = $course->number . ": " . $course->name;
        }
        return $newValue;
    }

    private function getVolunteer($element, $index)
    {
        $newValue = '';
        $volunteerString = 'volunteerExperience';
        if (isset($element->$volunteerString[$index]))
        {
            $volunteer = $element->$volunteerString[$index];
            $newValue = $volunteer->role . " at " .
                    $volunteer->organization->name . ', ' .
                    $volunteer->cause->name;
        }
        return $newValue;
    }

    private function getRecommendation($element, $index)
    {
        $newValue = '';
        if (isset($element->recommendation[$index]))
        {
            $recommendation = $element->recommendation[$index];
            $recommendationTypeString = 'recommendationType';
            $newValue = $recommendation->recommender . ' - ' . $recommendation->$recommendationTypeString;
        }
        return $newValue;
    }

    private function getPhoneNumber($element, $index, $third)
    {
    
    if (!isset($third)) {
        $newValue = '';
        $phoneNumberString = 'phoneNumber';
        $phoneTypeString = 'phoneType';

        if (isset($element->values->$index->$phoneNumberString))
        {
            $newValue = $element->values->$index->$phoneNumberString . ' ' .
                    $element->values->$index->$phoneTypeString;
        }
        return $newValue;
        }
      
     elseif ($third == 1) {
     $newValue = '';
        $phoneNumberString = 'phoneNumber';
        $phoneTypeString = 'phoneType';

        if (isset($element->values->$index->$phoneNumberString))
        {
            $newValue = $element->values->$index->$phoneNumberString;
        }
        if ($element->values->$index->$phoneTypeString == 'home') { return $newValue; } elseif ($element->values->$index->$phoneTypeString == 'work') { return $newValue; }
     }
     elseif ($third == 2) {
    	$newValue = '';
        $phoneNumberString = 'phoneNumber';
        $phoneTypeString = 'phoneType';

        if (isset($element->values->$index->$phoneNumberString))
        {
            $newValue = $element->values->$index->$phoneNumberString;
        }
        if ($element->values->$index->$phoneTypeString == 'mobile') { return $newValue; }
     }
       
    }

    private function getIMAccount($element, $index)
    {
        $newValue = '';
        $imAccountType = 'imAccountType';
        $imAccountName = 'imAccountName';

        if (isset($element->values->$index->$imAccountName))
        {
            $newValue = $element->values->$index->$imAccountName . ' ' .
                    $element->values->$index->$imAccountType;
        }

        return $newValue;
    }
    
    
     private function getAddress($element, $index)
    {
        $newValue = '';
        
$address = urlencode($element);
$request = file_get_contents("http://maps.google.com/maps/api/geocode/json?address=" . $address . "&sensor=false");
$json = json_decode($request, true);

 if ($index == 0) { $newValue = $json['results'][0]['address_components'][0]['short_name'] . ' ' . $json['results'][0]['address_components'][1]['short_name']; }

 elseif ($index == 1) { $newValue = $json['results'][0]['address_components'][3]['short_name']; }

 elseif ($index == 2) { $newValue = $json['results'][0]['address_components'][5]['short_name']; }
 
 elseif ($index == 3) { $newValue = $json['results'][0]['address_components'][7]['short_name']; }
 
 elseif ($index == 4) { $newValue = $json['results'][0]['address_components'][6]['long_name']; }

// else { $newValue = 'fail'; }

// if ($index == 0) { $newValue = 'address'; }  
// elseif ($index == 1) { $newValue = 'city'; } 
// elseif ($index == 2) { $newValue = 'state'; }  
// elseif ($index == 3) { $newValue = 'zip'; }  
// else {$newValue = 'fail';}

return $newValue;

    }
    
    
    
    
    

    private function getDateRange($element)
    {
        $dateRange = "";
        $startDateString = 'startDate';
        $endDateString = 'endDate';
        $start = '';
        $end = '';
        if (property_exists($element, $startDateString))
            $start = $this->getDateString($element->$startDateString, null, null);
        if (property_exists($element, $endDateString))
            $end = $this->getDateString($element->$endDateString, null, null);

        if ($start)
            $dateRange = $start . ' to ';

        if ($end)
            $dateRange .= $end;
        else
            $dateRange .= 'Present';
        return $dateRange;
    }

    private function getDateString($date, $prefix, $suffix)
    {
        $dateValue = '';
        if (is_object($date))
        {
            if (property_exists($date, 'month'))
                $dateValue = $date->month . '-' . $date->year;
            else if (property_exists($date, 'year'))
                $dateValue = $date->year;

            if ($dateValue != '')
            {
                if ($prefix)
                    $dateValue = $prefix . $dateValue;
                if ($suffix)
                    $dateValue = $dateValue . $suffix;
            }
        }
        return $dateValue;
    }


    function getFieldWithUserState($field)
    {
        $val = JRequest::getVar($field, '', 'POST');
        // Check if there's a session variable from a previous POST, and use that
        if (empty($val))
        {
            $app = JFactory::getApplication();
            $prevPost = $app->getUserState('com_jlinked.registration.data', array());
            if (array_key_exists($field, $prevPost))
                $val = $prevPost[$field];
        }

        if (empty($val))
            $val = $this->getFieldFromMapping($field);

        return $val;
    }

    function getFieldFromMapping($field)
    {
        if (!property_exists($this->fieldMap, $field))
            return "";

        $fieldName = $this->fieldMap->$field;
        return $this->get($fieldName, "");
    }

    function setFieldMap($fieldMap)
    {
        $this->fieldMap = $fieldMap;
    }

    /* bindData
    * Overridden function due to Joomla's checking of each variable to see if it's an associative array or not
    * We don't care, we want all arrays to be translated to a class
    */
    protected function bindData($parent, $data)
    {
        // Ensure the input data is an array.
        if (is_object($data))
        {
            $data = get_object_vars($data);
        } else
        {
            $data = (array)$data;
        }

        foreach ($data as $k => $v)
        {
            if (is_array($v) || is_object($v))
            {
                $parent->$k = new stdClass;
                $this->bindData($parent->$k, $v);
            } else
            {
                $parent->$k = $v;
            }
        }
    }
}

/components/com_jlinked/libraries/profile.php
<?php
/**
 * @package        JLinked
 * @copyright (C) 2009-2013 by Source Coast - All rights reserved
 * @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
 */
// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die('Restricted access');

jimport('joomla.plugin.plugin');
jimport('joomla.application.component.controller');
jimport('joomla.filesystem.file');
jimport('sourcecoast.profile');

include_once(JPATH_SITE . '/components/com_jlinked/libraries/jlinkeddata.php');

class JLinkedProfileLibrary
{
    # Profile fields available from
    # https://developer.linkedin.com/documents/profile-fields
    static $profileFields = array(
        //Basic Profile Fields - r_basicprofile permission
        '0' => 'None',
        'first-name' => 'Basic Info - First Name',
        'last-name' => 'Basic Info - Last Name',
        'maiden-name' => 'Basic Info - Maiden Name',
        'formatted-name' => 'Basic Info - Formatted Name',
        'phonetic-first-name' => 'Basic Info - Phonetic First Name',
        'phonetic-last-name' => 'Basic Info - Phonetic Last Name',
        'formatted-phonetic-name' => 'Basic Info - Formatted Phonetic Name',
        'headline' => 'Basic Info - Headline',
        'location.name' => 'Basic Info - Current Location',
        'location.country.code' => 'Basic Info - Current Country Code',
        'industry' => 'Basic Info - Industry',
        'current-share.comment' => 'Basic Info - Current Status/Last Share',
        'num-connections' => 'Basic Info - Number of Connections',
//        'num-connections-capped' => 'Basic Info - Number of Connections (Capped)',
        'summary' => 'Basic Info - Summary',
        'specialties' => 'Basic Info - Specialties',
        'picture-url' => 'Basic Info - Profile Picture URL',
        'site-standard-profile-request' => 'Basic Info - Authenticated Profile URL',
        'public-profile-url' => 'Basic Info - Public Profile URL',
        //Email Fields - r_emailaddress permission
        'email-address' => 'Email Fields - Primary Email Address',
        //Full Profile Fields - f_fullprofile permission
        'proposal-comments' => 'Full Info - Proposal Approach',
        'associations' => 'Full Info - Associations',
        'honors' => 'Full Info - Honors',
        'interests' => 'Full Info - Interests',
        'num-recommenders' => 'Full Info - Number of Recommendations',
        'date-of-birth' => 'Full Info - Date of Birth',
        /* Collections */
//        'positions.0' => 'Current Position - 0 - ??',
        'three-current-positions.0.1' => 'Current Position - Title',
        'three-current-positions.0.2' => 'Current Position - Company',
        'three-current-positions.2' => 'Current Position - 2 - Summary',
        'three-past-positions.0' => 'Past Position - 0 - Summary',
        'three-past-positions.1' => 'Past Position - 1 - Summary',
        'three-past-positions.2' => 'Past Position - 2 - Summary',
        'publications.0' => 'Publication - 0 - Summary',
        'publications.1' => 'Publication - 1 - Summary',
        'publications.2' => 'Publication - 2 - Summary',
        'patents.0' => 'Patents - 0 - Summary',
        'patents.1' => 'Patents - 1 - Summary',
        'patents.2' => 'Patents - 2 - Summary',
        'languages.0' => 'Language - 0 - Summary',
        'languages.1' => 'Language - 1 - Summary',
        'languages.2' => 'Language - 2 - Summary',
        'skills.0' => 'Skills - 0 - Summary',
        'skills.1' => 'Skills - 1 - Summary',
        'skills.2' => 'Skills - 2 - Summary',
        'certifications.0' => 'Certifications - 0 - Summary',
        'certifications.1' => 'Certifications - 1 - Summary',
        'certifications.2' => 'Certifications - 2 - Summary',
        'educations.0' => 'Educations - 0 - Summary',
        'educations.1' => 'Educations - 1 - Summary',
        'educations.2' => 'Educations - 2 - Summary',
        'courses.0' => 'Courses - 0 - Summary',
        'courses.1' => 'Courses - 1 - Summary',
        'courses.2' => 'Courses - 2 - Summary',
        'volunteer.0' => 'Volunteer Experience - 0 - Summary',
        'volunteer.1' => 'Volunteer Experience - 1 - Summary',
        'volunteer.2' => 'Volunteer Experience - 2 - Summary',
        'recommendations-received.0' => 'Recommendations - 0 - Summary',
        'recommendations-received.1' => 'Recommendations - 1 - Summary',
        'recommendations-received.2' => 'Recommendations - 2 - Summary',
        //Contact Info - r_contactinfo permission
        'main-address.0' => 'Contact Info - Address',
        'main-address.1' => 'Contact Info - City',
        'main-address.2' => 'Contact Info - State',
        'main-address.3' => 'Contact Info - Zip',
        'main-address.4' => 'Contact Info - Country',
        'phone-numbers.0.1' => 'Phone Number - LandLine',
        'phone-numbers.0.2' => 'Phone Number - Mobile',
        'phone-numbers.2' => 'Phone Number - 2 - Summary',
        'im-accounts.0' => 'IM Accounts - 0 - Summary',
        'im-accounts.1' => 'IM Accounts - 1 - Summary',
        'im-accounts.2' => 'IM Accounts - 2 - Summary',
        'twitter-accounts.0' => 'Twitter Accounts - 0 - Summary',
        'twitter-accounts.1' => 'Twitter Accounts - 1 - Summary',
        'twitter-accounts.2' => 'Twitter Accounts - 2 - Summary',
        'primary-twitter-account' => 'Twitter Accounts - Primary'
    );

    static $instance;

    static public function getInstance()
    {
        if (!self::$instance)
            self::$instance = new JLinkedProfileLibrary();

        return self::$instance;
    }

    public function getPermissionsForFields($fields)
    {
        $scope = array();
        if (!$fields)
            return $scope;

        foreach ($fields as $field)
        {
            if ($field == 'proposal-comments' ||
                    $field == 'associations' ||
                    $field == 'honors' ||
                    $field == 'interests' ||
                    $field == 'num-recommenders' ||
                    $field == 'date-of-birth' ||
                    strpos($field, 'three-current-positions') !== false ||
                    strpos($field, 'three-past-positions') !== false ||
                    strpos($field, 'publications') !== false ||
                    strpos($field, 'patents') !== false ||
                    strpos($field, 'languages') !== false ||
                    strpos($field, 'skills') !== false ||
                    strpos($field, 'certifications') !== false ||
                    strpos($field, 'educations') !== false ||
                    strpos($field, 'courses') !== false ||
                    strpos($field, 'volunteer') !== false ||
                    strpos($field, 'recommendations-received') !== false
            )
            {
                $scope[] = 'r_fullprofile';
            } else if ($field == 'main-address' ||
                    $field == 'primary-twitter-account' ||
                    strpos($field, 'phone-numbers') !== false ||
                    strpos($field, 'im-accounts') !== false ||
                    strpos($field, 'twitter-accounts') !== false
            )
            {
                $scope[] = 'r_contactinfo';
            }
        }
        return $scope;
    }

    public function fetchProfileFromFieldMap($fieldMap, $permissionGranted = true)
    {
        $fields = array();
        if (is_object($fieldMap))
        {
            foreach ($fieldMap as $field)
            {
                $fieldArray = explode('.', $field);
                if (!empty($fieldArray[0]))
                    $fields[] = $fieldArray[0]; // Get the root field to grab from FB
            }
        }
        $jlinkedLibrary = JLinkedApiLibrary::getInstance();
        $liMemberId = $jlinkedLibrary->getLinkedInMemberId();

        $fields = array_unique($fields);
        if ($permissionGranted)
            $profile = $this->fetchProfile($liMemberId, $fields);
        else
            $profile = new JlinkedData();
        $profile->setFieldMap($fieldMap);
        return $profile;

    }

    /* Fetch a user's profile based on the passed in array of fields
    * @return JRegistry with profile field values
    */
    public function fetchProfile($liMemberId, $fields)
    {
        if (!empty($fields))
        {
            $colFields = implode(",", $fields);
            $jlinkedLibrary = JLinkedApiLibrary::getInstance();
            $profile = $jlinkedLibrary->api('profile', $liMemberId . ':(' . $colFields . ')');
        } else
            $profile = new JlinkedData();

        return $profile;
    }

    /* Fetch a user's profile based on the passed in array of fields
    * @return JRegistry with profile field values
    */
    public function fetchStatus()
    {
        $jlinkedLibrary = JLinkedApiLibrary::getInstance();
        $response = $jlinkedLibrary->api('profile', '~:(current-share)');
        $status = $response->get('currentShare.comment');
        return $status;
    }

    /**
     *  Get all permissions that are required by Linked for email, status, and/or profile, regardless
     *    of whether they're set to required in LinkedIn
     * @return string Comma separated list of LinkedIn permissions that are required
     */
    static private $requiredScope;

    static function getRequiredScope()
    {
        if (self::$requiredScope)
            return self::$requiredScope;

        self::$requiredScope = array();
        self::$requiredScope[] = "r_emailaddress";

        JPluginHelper::importPlugin('socialprofiles');
        $app = JFactory::getApplication();
        $args = array('linkedin');
        $perms = $app->triggerEvent('socialProfilesGetRequiredScope', $args);
        if ($perms)
        {
            foreach ($perms as $permArray)
                self::$requiredScope = array_merge(self::$requiredScope, $permArray);
        }

        $configModel = JLinkedModelConfig::getSingleton();
        $customPermsSetting = $configModel->getSetting('linkedin_perm_custom');
        if ($customPermsSetting != '')
        {
            //Separate into an array to be able to merge and then take out duplicates
            $customPerms = explode(',', $customPermsSetting);
            foreach ($customPerms as $customPerm)
                self::$requiredScope[] = trim($customPerm);
        }

        self::$requiredScope = array_unique(self::$requiredScope);
        self::$requiredScope = implode(",", self::$requiredScope);

        return self::$requiredScope;
    }

    // nullForDefault - If the avatar is the default image for the social network, return null instead
    // Prevents the default avatars from being imported
    function getAvatarURL($liMemberId, $nullForDefault = true)
    {
        $jlinkedLibrary = JLinkedApiLibrary::getInstance();
       // $data = $jlinkedLibrary->api('profile', $liMemberId . ':(picture-url)');
       $data = $jlinkedLibrary->api('profile', $liMemberId . ':(picture-urls::(original))');
        
        $avatarUrl = $data->get('picture-urls.values.0');
        if (!$avatarUrl)
            return null;

        return $avatarUrl;
    }

    /*
    //TODO - update in 2.2
    function getProfilePermissionChoice()
    {
        return JRequest::getBool('jlinkedProfilePermission', false);
    }
    */

    function getFetchedProfile()
    {
        include_once(JPATH_SITE . '/components/com_jlinked/libraries/jlinkeddata.php');

        $session = JFactory::getSession();
        $socialProfileData = $session->get($this->profilePrefix . $this->profileName . '.fetchedData', null);
        $session->clear($this->profilePrefix . $this->profileName . '.fetchedData');
        $socialProfile = new JlinkedData($socialProfileData);
        return $socialProfile;
    }
}
Last edit: 10 years 8 months ago by paulzmuda.
The topic has been locked.