<?vsp
--   search_ajax.vsp
--
--   $Id$
--
--   AJAX Handler for the google map control
--
--  This file is part of the OpenLink Software Virtuoso Open-Source (VOS)
--  project.
--
--  Copyright (C) 1998-2018 OpenLink Software
--
--  This project is free software; you can redistribute it and/or modify it
--  under the terms of the GNU General Public License as published by the
--  Free Software Foundation; only version 2 of the License, dated June 1991.
--
--  This program is distributed in the hope that it will be useful, but
--  WITHOUT ANY WARRANTY; without even the implied warranty of
--  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
--  General Public License for more details.
--
--  You should have received a copy of the GNU General Public License along
--  with this program; if not, write to the Free Software Foundation, Inc.,
--  51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--
--
   declare sid,realm,fb_session,_err_msg,_xml,helpertact varchar;
   declare curr_user_id,addressbook_instid,addressbook_domain_id,addressbook_cid,fb_userid,facebook_cid,_err_code,usemapping,usevalidation integer;
   declare fb_dba_options,mappingarr,validationarr,mapping_keywords,validation_keywords any;

   declare _fb DB.DBA.Facebook;

   sid := get_keyword('sid',params,'');
   realm := get_keyword('realm',params,'wa');
   _xml:='';
--   dbg_obj_print(get_keyword('mapping',params,'') );

--   dbg_obj_print('###',split_and_decode(get_keyword('mapping',params,''),0,'\0\0|'));


   mappingarr := coalesce(split_and_decode(get_keyword('mapping',params,''),0,'\0\0;'),vector());
   validationarr := coalesce(split_and_decode(get_keyword('validation',params,''),0,'\0\0;'),vector());

   addressbook_instid := cast(get_keyword('instid',params,-1) as integer);
   addressbook_cid := cast(get_keyword('ods_cid',params,-1) as integer);
   facebook_cid := cast(get_keyword('fb_cid',params,-1) as integer);
   usemapping :=  cast(get_keyword('usemapping',params,null) as integer);
   usevalidation :=  cast(get_keyword('usevalidation',params,null) as integer);

   fb_session := get_keyword('fb_session',params,'');
   fb_userid := cast(get_keyword('fb_userid',params,-1) as integer);
   helpertact := get_keyword('helpertact',params,'');


   _err_code :=0; --0 - successful update; 1 - error
   _err_msg  :='';

--   dbg_obj_print(mappingarr);



   if(usemapping and length(mappingarr)>0)
   {
      mapping_keywords:=vector();

      declare i,l integer;

      i := 0;
      l := length (mappingarr);
      while (i < l)
      {
        declare __key, __val varchar;
        declare _tmparr varchar;
        _tmparr:=split_and_decode(mappingarr[i],0,'\0\0,');
        __key := _tmparr[0];
        __val := _tmparr[1];
        mapping_keywords:=vector_concat(mapping_keywords,vector(__key,__val));
        i := i + 1;
      }


   }

   if(usevalidation and length(validationarr)>0)
   {
      validation_keywords:=vector();

      declare i,l integer;

      i := 0;
      l := length (validationarr);
      while (i < l)
      {
        declare __key, __val varchar;
        declare _tmparr varchar;
        _tmparr:=split_and_decode(validationarr[i],0,'\0\0,');
        __key := _tmparr[0];
        __val := _tmparr[1];
        validation_keywords:=vector_concat(validation_keywords,vector(__key,__val));
        i := i + 1;
      }


   }



   if(_get_ods_fb_settings(fb_dba_options)) --fb_dba_options is array of type (facebook_api_key,facebook_api_secret)
   {
       _fb:= new Facebook(fb_dba_options[0], fb_dba_options[1], params,lines);


   }
   else
   {
     _err_code :=1;
     _err_msg  :='Facebook integration not complete.';
     goto _end;
   }

   if(length(fb_session)=0 or fb_userid<1)
   {
     _err_code :=1;
     _err_msg  :='Facebook authentication invalid.';
     goto _end;
   }


   curr_user_id:=-1;

   declare exit handler for not found {curr_user_id:=-1;
                                       _err_code :=1;
                                       _err_msg  :='Authentication invalid.';
                                       goto _end;
                                      };
   select U.U_ID
     into curr_user_id
     from DB.DBA.VSPX_SESSION S,WS.WS.SYS_DAV_USER U
    where S.VS_REALM = realm
      and S.VS_SID   = sid
      and S.VS_UID   = U.U_NAME;


   if(curr_user_id>0)
   {
      _fb.set_user(fb_userid,fb_session,now());

      if(helpertact='deref') goto _deref;

--      if(facebook_cid<1 or addressbook_cid<1)
      if(facebook_cid<1)
      {
        _err_code :=1;
        _err_msg  :='Incorrect synchronize contact pair.';
        goto _end;
      }

      declare exit handler for not found {
                                          addressbook_domain_id:=-1;
                                          _err_code :=1;
                                          _err_msg  :='Addressbook instance invalid.';
                                          goto _end;
                                         };
      select top 1 B.WAI_ID into addressbook_domain_id from WA_MEMBER A, WA_INSTANCE B where A.WAM_MEMBER_TYPE = 1 and A.WAM_INST = B.WAI_NAME and A.WAM_APP_TYPE='AddressBook' and A.WAM_USER=curr_user_id and B.WAI_ID=addressbook_instid;

      if(addressbook_domain_id>0)
      {
        declare addressbook_cid_arr any;
        addressbook_cid_arr:=vector(addressbook_cid);

        if(usevalidation and length(validationarr)>0)
        {
          declare _res any;
          _res:=_fb.api_client.users_getInfo(facebook_cid,'name,first_name,last_name,sex,birthday,current_location,work_history,hometown_location,timezone');
          _res:=xpath_eval('/users_getInfo_response/user',_res,0);
          if(_res is not null and length(_res)>0)
          {
--             dbg_obj_print(validationarr);

             addressbook_cid_arr:=valid_abid_by_fbid(curr_user_id,_res[0],addressbook_domain_id,validation_keywords);
             if(addressbook_cid_arr is null)
                addressbook_cid:=-1;
             if(addressbook_cid_arr is not null and length(addressbook_cid_arr)>1) -- when one or multiple addressbook contacts match one facebook contact
             {
                addressbook_cid:=addressbook_cid_arr[0];
             };

          }else
          {
               _err_code :=1;
               _err_msg  :='No such facebook contact.';
               goto _end;
          }

        }



       declare _res any;
       _res:=_fb.api_client.users_getInfo(facebook_cid,'name,first_name,last_name,sex,birthday,current_location,work_history,hometown_location,timezone');
       if(_res is not null)
       {
         _res:=xpath_eval('/users_getInfo_response/user',_res);
         if(_res is not null)
         {
            declare full_name,first_name,last_name varchar;
            full_name  := trim(xpath_eval('string(name)',_res));
            first_name := trim(xpath_eval('string(first_name)',_res));
            last_name  := trim(xpath_eval('string(last_name)',_res));


            declare _col, _val any;
            declare _tmpval,_tmpcustomcol varchar;

            _col    :=vector();
            _val    :=vector();
            _tmpval :='';
            _tmpcustomcol:='';

            _tmpcustomcol:=get_keyword('name',mapping_keywords,'P_FULL_NAME');
            _tmpval:=trim(xpath_eval('string(name)',_res));
            if(_tmpval<>'')
            {
               if(usemapping)
               {
                 if(_tmpcustomcol<>'skip')
                 {
                    _col:=vector_concat(_col,vector(_tmpcustomcol));
                    _val:=vector_concat(_val,vector(_tmpval));
                 }
               }else
               {
                    _col:=vector_concat(_col,vector('P_FULL_NAME'));
                    _val:=vector_concat(_val,vector(_tmpval));
               }

            }


            _tmpcustomcol:=get_keyword('first_name',mapping_keywords,'P_FIRST_NAME');
            _tmpval:=trim(xpath_eval('string(first_name)',_res));
            if(_tmpval<>'')
            {
               if(usemapping)
               {
                 if(_tmpcustomcol<>'skip')
                 {
                    _col:=vector_concat(_col,vector(_tmpcustomcol));
                    _val:=vector_concat(_val,vector(_tmpval));
                 }
               }else
               {
                    _col:=vector_concat(_col,vector('P_FIRST_NAME'));
                    _val:=vector_concat(_val,vector(_tmpval));
               }
            }


            _tmpcustomcol:=get_keyword('last_name',mapping_keywords,'P_LAST_NAME');
            _tmpval:=trim(xpath_eval('string(last_name)',_res));
            if(_tmpval<>'')
            {
               if(usemapping)
               {
                 if(_tmpcustomcol<>'skip')
                 {
                    _col:=vector_concat(_col,vector(_tmpcustomcol));
                    _val:=vector_concat(_val,vector(_tmpval));
                 }
               }else
               {
                    _col:=vector_concat(_col,vector('P_LAST_NAME'));
                    _val:=vector_concat(_val,vector(_tmpval));
               }

            }


            _tmpcustomcol:=get_keyword('sex',mapping_keywords,'P_GENDER');
            _tmpval:=trim(xpath_eval('string(sex)',_res));
            if(_tmpval<>'')
            {
               if(usemapping)
               {
                 if(_tmpcustomcol<>'skip')
                 {
                    _col:=vector_concat(_col,vector(_tmpcustomcol));
                    _val:=vector_concat(_val,vector(_tmpval));
                 }
               }else
               {
                    _col:=vector_concat(_col,vector('P_GENDER'));
                    _val:=vector_concat(_val,vector(_tmpval));
               }

            }

            _tmpcustomcol:=get_keyword('birthday',mapping_keywords,'P_BIRTHDAY');
            _tmpval:=trim(xpath_eval('string(birthday)',_res));
            if(_tmpval<>'')
            {
               declare _date date;
               declare _arr any;

               _arr:=split_and_decode(cast(_tmpval as varchar),0,'\0\0,');
               if(_arr is not null and length(_arr)>0)
                  _arr[0]:=split_and_decode(_arr[0],0,'\0\0 ');
               if(length(_arr)=1)
                  _date:=stringdate('1970-'||cast(_get_monhtbyname(trim(_arr[0][0])) as varchar)||'-'||trim(_arr[0][1]));
               else
                  _date:=stringdate(trim(_arr[1])||'-'||cast(_get_monhtbyname(trim(_arr[0][0])) as varchar)||'-'||trim(_arr[0][1]));

               if(usemapping)
               {
                 if(_tmpcustomcol<>'skip')
                 {
                    _col:=vector_concat(_col,vector(_tmpcustomcol));
                    if(_col='P_BIRTHDAY')
                       _val:=vector_concat(_val,vector(_date));
                    else
                       _val:=vector_concat(_val,vector(left(datestring(_date),10)));

                 }
               }else
               {
                    _col:=vector_concat(_col,vector('P_BIRTHDAY'));
                    _val:=vector_concat(_val,vector(_date));
               }

            }

            _tmpcustomcol:=get_keyword('hometown_location/city',mapping_keywords,'P_H_CITY');
            _tmpval:=trim(xpath_eval('string(hometown_location/city)',_res));
            if(_tmpval<>'')
            {
               if(usemapping)
               {
                 if(_tmpcustomcol<>'skip')
                 {
                    _col:=vector_concat(_col,vector(_tmpcustomcol));
                    _val:=vector_concat(_val,vector(_tmpval));
                 }
               }else
               {
                    _col:=vector_concat(_col,vector('P_H_CITY'));
                    _val:=vector_concat(_val,vector(_tmpval));
               }

            }


            _tmpcustomcol:=get_keyword('hometown_location/state',mapping_keywords,'P_H_STATE');
            _tmpval:=trim(xpath_eval('string(hometown_location/state)',_res));
            if(_tmpval<>'')
            {
               if(usemapping)
               {
                 if(_tmpcustomcol<>'skip')
                 {
                    _col:=vector_concat(_col,vector(_tmpcustomcol));
                    _val:=vector_concat(_val,vector(_tmpval));
                 }
               }else
               {
                    _col:=vector_concat(_col,vector('P_H_STATE'));
                    _val:=vector_concat(_val,vector(_tmpval));
               }
            }

            _tmpcustomcol:=get_keyword('hometown_location/country',mapping_keywords,'P_H_COUNTRY');
            _tmpval:=trim(xpath_eval('string(hometown_location/country)',_res));
            if(_tmpval<>'')
            {
               if(usemapping)
               {
                 if(_tmpcustomcol<>'skip')
                 {
                    _col:=vector_concat(_col,vector(_tmpcustomcol));
                    _val:=vector_concat(_val,vector(_tmpval));
                 }
               }else
               {
                    _col:=vector_concat(_col,vector('P_H_COUNTRY'));
                    _val:=vector_concat(_val,vector(_tmpval));
               }
            }

            _tmpcustomcol:=get_keyword('hometown_location/zip',mapping_keywords,'P_H_CODE');
            _tmpval:=trim(xpath_eval('string(hometown_location/zip)',_res));
            if(_tmpval<>'')
            {
               if(usemapping)
               {
                 if(_tmpcustomcol<>'skip')
                 {
                    _col:=vector_concat(_col,vector(_tmpcustomcol));
                    _val:=vector_concat(_val,vector(_tmpval));
                 }
               }else
               {
                    _col:=vector_concat(_col,vector('P_H_CODE'));
                    _val:=vector_concat(_val,vector(_tmpval));
               }
            }


            _tmpcustomcol:=get_keyword('work_info/location/city',mapping_keywords,'P_B_CITY');
            _tmpval:=trim(xpath_eval('string(work_history/work_info[1]/location/city)',_res));
            if(_tmpval<>'')
            {
               if(usemapping)
               {
                 if(_tmpcustomcol<>'skip')
                 {
                    _col:=vector_concat(_col,vector(_tmpcustomcol));
                    _val:=vector_concat(_val,vector(_tmpval));
                 }
               }else
               {
                    _col:=vector_concat(_col,vector('P_B_CITY'));
                    _val:=vector_concat(_val,vector(_tmpval));
               }
            }

            _tmpcustomcol:=get_keyword('work_info/location/state',mapping_keywords,'P_B_STATE');
            _tmpval:=trim(xpath_eval('string(work_history/work_info[1]/location/state)',_res));
            if(_tmpval<>'')
            {
               if(usemapping)
               {
                 if(_tmpcustomcol<>'skip')
                 {
                    _col:=vector_concat(_col,vector(_tmpcustomcol));
                    _val:=vector_concat(_val,vector(_tmpval));
                 }
               }else
               {
                    _col:=vector_concat(_col,vector('P_B_STATE'));
                    _val:=vector_concat(_val,vector(_tmpval));
               }
            }

            _tmpcustomcol:=get_keyword('work_info/location/country',mapping_keywords,'P_B_COUNTRY');
            _tmpval:=trim(xpath_eval('string(work_history/work_info[1]/location/country)',_res));
            if(_tmpval<>'')
            {
               if(usemapping)
               {
                 if(_tmpcustomcol<>'skip')
                 {
                    _col:=vector_concat(_col,vector(_tmpcustomcol));
                    _val:=vector_concat(_val,vector(_tmpval));
                 }
               }else
               {
                    _col:=vector_concat(_col,vector('P_B_COUNTRY'));
                    _val:=vector_concat(_val,vector(_tmpval));
               }
            }

            _tmpcustomcol:=get_keyword('work_info/company_name',mapping_keywords,'P_B_ORGANIZATION');
            _tmpval:=trim(xpath_eval('string(work_history/work_info[1]/company_name)',_res));
            if(_tmpval<>'')
            {
               if(usemapping)
               {
                 if(_tmpcustomcol<>'skip')
                 {
                    _col:=vector_concat(_col,vector(_tmpcustomcol));
                    _val:=vector_concat(_val,vector(_tmpval));
                 }
               }else
               {
                    _col:=vector_concat(_col,vector('P_B_ORGANIZATION'));
                    _val:=vector_concat(_val,vector(_tmpval));
               }
            }


            _tmpcustomcol:=get_keyword('work_info/position',mapping_keywords,'P_B_JOB');
            _tmpval:=trim(xpath_eval('string(work_history/work_info[1]/position)',_res));
            if(_tmpval<>'')
            {
               if(usemapping)
               {
                 if(_tmpcustomcol<>'skip')
                 {
                    _col:=vector_concat(_col,vector(_tmpcustomcol));
                    _val:=vector_concat(_val,vector(_tmpval));
                 }
               }else
               {
                    _col:=vector_concat(_col,vector('P_B_JOB'));
                    _val:=vector_concat(_val,vector(_tmpval));
               }
            }


            _tmpcustomcol:=get_keyword('current_location/city',mapping_keywords);
            _tmpval:=trim(xpath_eval('string(current_location/city)',_res));
            if(_tmpval<>'')
            {
               if(usemapping)
               {
                 if(_tmpcustomcol<>'' and _tmpcustomcol<>'skip')
                 {
                    _col:=vector_concat(_col,vector(_tmpcustomcol));
                    _val:=vector_concat(_val,vector(_tmpval));
                 }
               }

            }


            _tmpcustomcol:=get_keyword('current_location/state',mapping_keywords);
            _tmpval:=trim(xpath_eval('string(current_location/state)',_res));
            if(_tmpval<>'')
            {
               if(usemapping)
               {
                 if(_tmpcustomcol<>'' and _tmpcustomcol<>'skip')
                 {
                    _col:=vector_concat(_col,vector(_tmpcustomcol));
                    _val:=vector_concat(_val,vector(_tmpval));
                 }
               }
            }

            _tmpcustomcol:=get_keyword('current_location/country',mapping_keywords);
            _tmpval:=trim(xpath_eval('string(current_location/country)',_res));
            if(_tmpval<>'')
            {
               if(usemapping)
               {
                 if(_tmpcustomcol<>'' and _tmpcustomcol<>'skip')
                 {
                    _col:=vector_concat(_col,vector(_tmpcustomcol));
                    _val:=vector_concat(_val,vector(_tmpval));
                 }
               }
            }

            _tmpcustomcol:=get_keyword('current_location/zip',mapping_keywords);
            _tmpval:=trim(xpath_eval('string(current_location/zip)',_res));
            if(_tmpval<>'')
            {
               if(usemapping)
               {
                 if(_tmpcustomcol<>'' and _tmpcustomcol<>'skip')
                 {
                    _col:=vector_concat(_col,vector(_tmpcustomcol));
                    _val:=vector_concat(_val,vector(_tmpval));
                 }
               }
            }



            if(length(_col)>0)
            {

              if(addressbook_cid=-1 and (addressbook_cid_arr is null or addressbook_cid_arr[0]=-1))
              {

                declare insert_addressbook_cid integer;
                insert_addressbook_cid:=-1;
                insert_addressbook_cid:=AB.WA.contact_update2 (-1,addressbook_domain_id,'P_NAME',coalesce(full_name,first_name||' '||last_name));

                if(insert_addressbook_cid>-1)
                {
                   addressbook_cid:=insert_addressbook_cid;
                   addressbook_cid_arr:=vector(addressbook_cid);
                }

              }

              if(length(addressbook_cid_arr)=1)
                  AB.WA.contact_update3 (addressbook_cid,addressbook_domain_id,_col,_val,''); -- keep for compatibility
              else
              {

                declare ab_cid_idx integer;
                ab_cid_idx:=0;

                for(ab_cid_idx:=0;ab_cid_idx<length(addressbook_cid_arr);ab_cid_idx:=ab_cid_idx+1)
                    AB.WA.contact_update3 (addressbook_cid_arr[ab_cid_idx],addressbook_domain_id,_col,_val,'');
              }


            }


         }else
         {
             _err_code :=1;
             _err_msg  :='No such facebook contact.';
             goto _end;
         }
       }
      }else
      {
        _err_code :=1;
        _err_msg  :='Addressbook instance invalid.';
        goto _end;
      }

      _xml:='<?xml version="1.0" encoding="UTF-8"?>\r\n'||
      '<resp_addressbook_updatecontact>'||
      '<res_code>'||cast(_err_code as varchar)||'</res_code>'||
      '<err_msg>'||_err_msg||'</err_msg>'||
      '</resp_addressbook_updatecontact>';
      goto _end;


-- here starts secon action of helper dereference fb friend. helpertact=deref
_deref:;
      --
      declare fbp_id,fbf_profile_uri varchar;
      fbp_id:=cast(facebook_cid as varchar);
      fbf_profile_uri:='http://www.facebook.com/profile.php?id='||fbp_id;

      if(facebook_cid = fb_userid)
      {
         _err_code:=DB.DBA.fbf_rdf_load_fql (fbf_profile_uri,fbf_profile_uri,null,_fb,fbp_id,1);
      }else
         _err_code:=DB.DBA.fbf_rdf_load_fql (fbf_profile_uri,fbf_profile_uri,null,_fb,fbp_id,0);

      -- _err_code :=0; --1 - successful;
      _err_msg  :='';


      _xml:='<?xml version="1.0" encoding="UTF-8"?>\r\n'||
      '<resp_fbp_deref>'||
      '<res_code>'||cast(_err_code as varchar)||'</res_code>'||
      '<err_msg>'||_err_msg||'</err_msg>'||
      '</resp_fbp_deref>';
      goto _end;

   }else
   { _err_code :=1;
     _err_msg  :='Authentication invalid.';
     goto _end;
   }

_end:;

  if(length(_xml)=0)
      _xml:='<?xml version="1.0" encoding="UTF-8"?>\r\n'||
      '<resp_addressbook_updatecontact>'||
      '<res_code>'||cast(_err_code as varchar)||'</res_code>'||
      '<err_msg>'||_err_msg||'</err_msg>'||
      '</resp_addressbook_updatecontact>';


  http_rewrite();
  http_header (sprintf ('Content-type: %s\r\n', 'text/html'));
  http(_xml);

?>
