From aa336a3bd69d385e86427e6846293959d2de89fa Mon Sep 17 00:00:00 2001
From: Francisco Luz <franciscoferreiraluz@yahoo.com.au>
Date: Mon, 15 Aug 2011 19:17:48 -0400
Subject: [PATCH] Issue #1245548: Local account is created and associated to the remote one

---
 friendconnect.inc    |   82 +++++++++++++++++++++++++++++----
 friendconnect.info   |    8 +++
 friendconnect.module |  124 ++++++++++++++++++++++++++++++++++++++++++++------
 3 files changed, 190 insertions(+), 24 deletions(-)

diff --git a/friendconnect.inc b/friendconnect.inc
index 6844ff9..42d6241 100644
--- a/friendconnect.inc
+++ b/friendconnect.inc
@@ -101,10 +101,22 @@ function friendconnect_add_newsletter() {
  * Local account login, create account if it does not exist.
  */
 function friendconnect_join() {
+  $message = t('Id') .': @fcid <br/>' . 
+    t('Name:') . ': @fcname <br/>' .
+    t('Image') . ': @fcimage <br/>' . 
+    t('To') . ': @fcto <br/>';
+
+  $vars = array(
+    '@fcid' => $_GET['fcid'],
+    '@fcname' => $_GET['fcname'],
+    '@fcimage' => $_GET['fcimage'],
+    '@fcto' => $_GET['fcto']
+  );
+  watchdog('friendconnect', $message, $vars, WATCHDOG_DEBUG);
   global $user;
 
   // if already logged in, sorry we cannot proceed!
-  if ($user->uid) {
+  if ($user->uid > 0) {
     drupal_set_message(t('You are already logged in to this site! We currently support only auto-creation of new accounts. Linking existing accounts to Google Friend Connect is not supported at this time.'), 'error');
     return MENU_ACCESS_DENIED;
   }
@@ -115,6 +127,49 @@ function friendconnect_join() {
     return MENU_ACCESS_DENIED;
   }
 
+  $site_id = variable_get('friendconnect_siteid', '');
+  $fcauth_token = $_COOKIE["fcauth" . $site_id];
+  
+  if(!$fcauth_token) {
+    drupal_set_message(t('An error occurred. Please ping the site administrator for help!'), 'error');
+    return MENU_ACCESS_DENIED;
+  }
+  
+  if (!@file_exists(drupal_realpath(libraries_get_path('osapi')))) {
+    drupal_set_message(t('An error occurred. Please ping the site administrator for help!'), 'error');
+    return MENU_ACCESS_DENIED;
+  }
+
+  include_once(drupal_realpath(libraries_get_path('osapi')) . '/osapi.php');
+
+  //include_once realpath(dirname(__FILE__). '/osapi/osapi.php');
+  $provider = new osapiFriendConnectProvider();
+  $auth = new osapiFCAuth($fcauth_token);
+  $osapi = new osapi($provider,$auth);
+  $osapi->setStrictMode(true);
+  $batch = $osapi->newBatch();
+
+  $profile_fields = array('id' , 'name', 'thumbnailUrl', 'profileUrl');
+  
+  $self_request_params = array(
+    'userId' => '@viewer',            // Person we are fetching.
+    'groupId' => '@self',             // @self for one person.
+    'fields' => $profile_fields // Which profile fields to request.
+  );
+  $batch->add($osapi->people->get($self_request_params), 'viewer');
+  try {
+    $a = $batch->execute();
+    $viewer = $a['viewer'];
+   
+    if(!$viewer instanceof osapiPerson || $viewer->id != $_GET['fcid']) {
+      drupal_set_message(t('Invalid FC user. Please ping the site administrator for help!'), 'error');
+      return MENU_ACCESS_DENIED;
+    }
+    
+  } catch ( Exception $e ){
+    drupal_set_message(t($e->getMessage() . 'Please ping the site administrator for help!'), 'error');
+    return MENU_ACCESS_DENIED;
+  }
   // default return to home page
   $_GET += array(
     'fcto' => url(),
@@ -123,15 +178,16 @@ function friendconnect_join() {
   watchdog('friendconnect', 'ID: @id<br />Name: @name<br />@Image: @image<br />To: @to', array('@id' => $_GET['fcid'], '@name' => $_GET['fcname'], '@image' => $_GET['fcimage'], '@to' => $_GET['fcto']), WATCHDOG_DEBUG);
 
   // login the old/new visitor into the local site
-  $uname = friendconnect_local_user($_GET['fcid'], $_GET['fcname']);
-  $status = friendconnect_register_user($_GET['fcid'], $uname, $_GET['fcimage']);
+  $uname = friendconnect_local_user($viewer->id, $viewer->displayName);
+  $status = friendconnect_register_user($viewer->id, $uname, $viewer->thumbnailUrl);
   if ($status != 0) return $status;
 
   // update visitor profile image
-  //friendconnect_local_image($user->uid, $_GET['fcimage']);
+  friendconnect_local_image($user->uid, $viewer->thumbnailUrl);
 
   // take the user back to the original page
   drupal_goto($_GET['fcto']);
+  
 }
 
 /**
@@ -187,8 +243,12 @@ function friendconnect_register_user($fcid, $uname, $picture = '') {
 /**
  * Update the profile image for the user.
  */
-/*function friendconnect_local_image($uid, $image) {
-  $result = drupal_http_request($image);
+function friendconnect_local_image($uid, $image) {
+  //global $user;
+  
+  //TODO: Update user local pic with their remote one
+  //
+/*
   if ($result->code == 200 && $result->headers['Content-Type'] == 'image/png') {
     $dst = file_directory_path();
     if (variable_get('user_pictures_path', ''))
@@ -199,8 +259,10 @@ function friendconnect_register_user($fcid, $uname, $picture = '') {
 
     // ignore if image fetch/save fails, we can try again during next login
     if ($status != '0') {
-      $query = 'UPDATE {users} SET picture="%s" WHERE uid=%d';
-      $queryResult = db_query($query, $status, $uid);
+      db_update('users')
+        ->fields(array('picture' => $status,))
+        ->condition('uid', $uid)
+        ->execute();
     }
-  }
-}*/
+  }*/
+}
diff --git a/friendconnect.info b/friendconnect.info
index 5d85083..ef7cd7d 100644
--- a/friendconnect.info
+++ b/friendconnect.info
@@ -1,8 +1,16 @@
 name = Google Friend Connect
 description = "Allow visitors to access your site using Google Friend Connect."
 core = 7.x
+dependencies[] = libraries
 files[] = friendconnect.module
 files[] = friendconnect.admin.inc
 files[] = friendconnect.inc
 files[] = friendconnect.install
 configure = admin/config/services/friendconnect
+
+; Information added by drupal.org packaging script on 2011-02-25
+version = "7.x-1.x-dev"
+core = "7.x"
+project = "friendconnect"
+datestamp = "1298619308"
+
diff --git a/friendconnect.module b/friendconnect.module
index 4482de8..e98558a 100644
--- a/friendconnect.module
+++ b/friendconnect.module
@@ -1,17 +1,42 @@
 <?php
+define('FRIENDCONNECT',
+  'http://www.google.com/friendconnect/script/friendconnect.js');
+
+define('GOOGLE', 'http://www.google.com/friendconnect/');
+define('PROJECT_NAME', 'Google Friend Connect Plugins');
+define('PROJECT_URL', 
+  'http://code.google.com/p/google-friend-connect-plugins');
+
+define('FRIEND_CONNECT_MEMBERS',0);
+define('FRIEND_CONNECT_RECOMMENDATIONS',1);
+define('FRIEND_CONNECT_GLOBAL_COMMENTS',2);
+define('FRIEND_CONNECT_POLLS',3);
+define('FRIEND_CONNECT_NEWSLETTER',4);
+define('FRIEND_CONNECT_FEATURED_CONTENT',5);
+define('FRIEND_CONNECT_ADENSE',6);
+define('FRIEND_CONNECT_ACTIVITIES',7);
 
 /**
- * Implements hook_help().
+ * Implementation of hook_help().
  */
 function friendconnect_help($path, $arg) {
-  switch ($path) {
+  $output = '';
+  switch($path) {
     case 'admin/help#friendconnect':
-      $output = '<p>' . t("The Google Friend Connect module allows your users to easily connect and contribute to your site's contents.") . '</p>';
-      $output .= '<p>' . t('Register your site once at <a href="@gfc">@gfc</a> and drive more traffic to your site!', array('@gfc' => 'http://www.google.com/friendconnect/')) . '</p>';
-      $output .= '<p>' . t('Visit the official <a href="@code">Google Friend Connect Plugins</a> site for more details.', array('@code' => 'http://code.google.com/p/google-friend-connect-plugins')) . '</p>';
-      return $output;
+      $output = '<p>' . t('The Google Friend Connect module allows your users'
+      . ' to easily connect and contribute to your site\'s contents.')
+      . '</p>';
+      $output .= '<p>' . t('Register your site once at <a href="@gfc">'
+      . GOOGLE . '</a> and drive more traffic to your site!',
+      array('@gfc' => GOOGLE)) . '</p>';
+      $output .= '<p>' . t('Visit the official <a href="@code">'
+      . PROJECT_NAME . '</a> site for more details.',
+      array('@code' => PROJECT_URL)) . '</p>';
+      break;
   }
-}
+  return $output;
+};
+
 
 /**
  * Impelements hook_permission().
@@ -49,6 +74,84 @@ function friendconnect_menu() {
 }
 
 /**
+ * Helper for setting javascript attributes.
+ */
+function friendconnect_js_helper($arg, $value) {
+  drupal_add_js('Drupal.settings.friendconnect["' . $arg . '"] = "'
+  . $value . '";', array('type' => 'inline', 'scope' => 'footer', ));
+};
+
+/**
+ * Implements hook_init().
+ */
+function friendconnect_init() {
+  friendconnect_add_gadget('socialbar');
+ 
+  $module_path = drupal_get_path('module', 'friendconnect') . '/';
+  $parent_url = base_path() . $module_path;
+  $site_id = variable_get('friendconnect_siteid', '');
+  $join_url = url('friendconnect/join');
+  $logout_url = url('logout');
+  $destination = drupal_get_destination();
+  $current_url = $destination['destination'];  // change from 'x=y*' to 'y*' format
+  
+  // get friendconnect id of logged in user
+  global $user;
+  $current_fcid = '0';
+  if ($user->uid != 0) {
+    $query = db_query("SELECT fcid FROM {friendconnect} WHERE uid = :uid LIMIT 1", array(':uid' => $user->uid));
+    foreach($query as $row){
+      $current_fcid = $row->fcid;
+    }
+  }
+
+
+  // load remote js file
+  drupal_add_js('http://www.google.com/jsapi', array('type' => 'external', 'scope' => 'header', 'weight' => -50));
+  
+  /*drupal_set_html_head('<script type="text/javascript" '
+  . 'src="http://www.google.com/jsapi"></script>');*/
+  
+  drupal_add_js('google.load("friendconnect", "0.8");', array('type' => 'inline', 'scope' => 'header'));
+
+  // load local js file
+  drupal_add_js($module_path . 'friendconnect.js', array('type' => 'inline', 'scope' => 'footer'));
+
+  // populate interesting parameters
+  drupal_add_js('Drupal.settings.friendconnect = [];', array('type' => 'inline', 'scope' => 'footer'));
+  friendconnect_js_helper('site_id', $site_id);
+  friendconnect_js_helper('parent_url', $parent_url);
+  friendconnect_js_helper('join_url', $join_url);
+  friendconnect_js_helper('logout_url', $logout_url);
+  friendconnect_js_helper('clean_url', variable_get('clean_url', 0));
+  friendconnect_js_helper('current_url', $current_url);
+  friendconnect_js_helper('current_uid', $user->uid);
+  friendconnect_js_helper('current_fcid', $current_fcid);
+
+  // invoke friendconnect api
+  drupal_add_js('FC_LoadFriendConnect();', array('type' => 'inline', 'scope' => 'footer'));
+  
+}
+
+
+/**
+ * Implementation of hook_form_alter().
+ */
+function friendconnect_form_alter(&$form, $form_state, $form_id) {
+  if ($form_id == 'user_login_block'
+    || $form_id == 'user_login') {
+    $form['friendconnect_displayset']['friendconnect_display'] = array(
+      '#type' => 'markup',
+      '#prefix' => '<p>'.t('Google Friend Connect').'</p>' 
+        . '<div id="friendconnect_display">',
+      '#value' => t('loading...'),
+      '#suffix' => '</div>',
+    );
+  }
+
+}
+
+/**
  * Implements hook_user_load().
  */
 function friendconnect_user_load(array $accounts) {
@@ -117,13 +220,6 @@ function friendconnect_form_comment_form_alter(&$form, $form_state) {
   }
 }
 
-/**
- * Implements hook_init().
- */
-function friendconnect_init() {
-  friendconnect_add_gadget('socialbar');
-}
-
 function friendconnect_is_gadget_enabled($gadget) {
   $settings = friendconnect_var($gadget);
   return !empty($settings['enabled']);
-- 
1.7.4.1

