]> git.mxchange.org Git - friendica-addons.git/blobdiff - fbsync/fbsync.php
Merge pull request #165 from annando/master
[friendica-addons.git] / fbsync / fbsync.php
index c214316ef678cb07c44f9c1ece155bdd5c53b327..d8b1c0c766773cdc8b6b691b4ed0df6bc837e847 100644 (file)
@@ -7,13 +7,14 @@
  */
 
 /* To-Do
-- A: Frontend
-- B: Like für Kommentare senden
-- B: Post auf Seite nicht als Seite
-- B: Leere Posts?
-- C: Threading für Kommentare
-- C: Posts von Seiten, die man nicht selber abonniert hat
-- D: Like für Kommentare empfangen?
+FBSync:
+- B: Threading for incoming comments
+- C: Receiving likes for comments
+
+FBPost:
+- A: Posts to pages currently have the page as sender - not the user
+- B: Sending likes for comments
+- C: Threading for sent comments
 */
 
 require_once("addon/fbpost/fbpost.php");
@@ -24,14 +25,79 @@ function fbsync_install() {
        register_hook('connector_settings',      'addon/fbsync/fbsync.php', 'fbsync_settings');
        register_hook('connector_settings_post', 'addon/fbsync/fbsync.php', 'fbsync_settings_post');
        register_hook('cron', 'addon/fbsync/fbsync.php', 'fbsync_cron');
+       register_hook('follow', 'addon/fbsync/fbsync.php', 'fbsync_follow');
 }
 
 function fbsync_uninstall() {
        unregister_hook('connector_settings',      'addon/fbsync/fbsync.php', 'fbsync_settings');
        unregister_hook('connector_settings_post', 'addon/fbsync/fbsync.php', 'fbsync_settings_post');
        unregister_hook('cron', 'addon/fbsync/fbsync.php', 'fbsync_cron');
+       unregister_hook('follow', 'addon/fbsync/fbsync.php', 'fbsync_follow');
 }
 
+function fbsync_follow($a, &$contact) {
+
+       logger("fbsync_follow: Check if contact is facebook contact. ".$contact["url"], LOGGER_DEBUG);
+
+       if (!strstr($contact["url"], "://www.facebook.com") AND !strstr($contact["url"], "://facebook.com") AND !strstr($contact["url"], "@facebook.com"))
+               return;
+
+       // contact seems to be a facebook contact, so continue
+       $nickname = preg_replace("=https?://.*facebook.com/([\w.]*).*=ism", "$1", $contact["url"]);
+       $nickname = str_replace("@facebook.com", "", $nickname);
+
+       $uid = $a->user["uid"];
+
+       $access_token = get_pconfig($uid,'facebook','access_token');
+
+       $fql = array(
+                       "profile" => "SELECT id, pic_square, url, username, name FROM profile WHERE username = '$nickname'",
+                       "avatar" => "SELECT url FROM square_profile_pic WHERE id IN (SELECT id FROM #profile) AND size = 256");
+
+       $url = "https://graph.facebook.com/fql?q=".urlencode(json_encode($fql))."&access_token=".$access_token;
+
+       $feed = fetch_url($url);
+       $data = json_decode($feed);
+
+       $id = 0;
+
+       logger("fbsync_follow: Query id for nickname ".$nickname, LOGGER_DEBUG);
+
+       if (!is_array($data->data))
+               return;
+
+       $contactdata = new stdClass;
+
+       foreach($data->data AS $query) {
+               switch ($query->name) {
+                       case "profile":
+                               $contactdata->id =  number_format($query->fql_result_set[0]->id, 0, '', '');
+                               $contactdata->pic_square = $query->fql_result_set[0]->pic_square;
+                               $contactdata->url = $query->fql_result_set[0]->url;
+                               $contactdata->username = $query->fql_result_set[0]->username;
+                               $contactdata->name = $query->fql_result_set[0]->name;
+                               break;
+
+                       case "avatar":
+                               $contactdata->pic_square = $query->fql_result_set[0]->url;
+                               break;
+               }
+       }
+
+       logger("fbsync_follow: Got contact for nickname ".$nickname." ".print_r($contactdata, true), LOGGER_DEBUG);
+
+       // Create contact
+       fbsync_fetch_contact($uid, $contactdata, true);
+
+       $r = q("SELECT name,nick,url,addr,batch,notify,poll,request,confirm,poco,photo,priority,network,alias,pubkey
+               FROM `contact` WHERE `uid` = %d AND `alias` = '%s'",
+                               intval($uid),
+                               dbesc("facebook::".$contactdata->id));
+       if (count($r))
+               $contact["contact"] = $r[0];
+}
+
+
 function fbsync_settings(&$a,&$s) {
 
        if(! local_user())
@@ -68,7 +134,7 @@ function fbsync_settings(&$a,&$s) {
 
        /* provide a submit button */
 
-       $s .= '<div class="settings-submit-wrapper" ><input type="submit" id="fbsync-submit" name="fbsync-submit" class="settings-submit" value="' . t('Submit') . '" /></div></div>';
+       $s .= '<div class="settings-submit-wrapper" ><input type="submit" id="fbsync-submit" name="fbsync-submit" class="settings-submit" value="' . t('Save Settings') . '" /></div></div>';
 
 }
 
@@ -111,7 +177,15 @@ function fbsync_cron($a,$b) {
        set_config('fbsync','last_poll', time());
 }
 
-function fbsync_createpostarray($a, $uid, $self, $contacts, $applications, $post) {
+function fbsync_createpost($a, $uid, $self, $contacts, $applications, $post, $create_user) {
+
+       // check if it was already imported
+       $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
+               intval($uid),
+               dbesc('fb::'.$post->post_id)
+       );
+       if(count($r))
+               return;
 
        $postarray = array();
        $postarray['gravity'] = 0;
@@ -125,22 +199,61 @@ function fbsync_createpostarray($a, $uid, $self, $contacts, $applications, $post
        $postarray['parent-uri'] = $postarray['uri'];
        $postarray['plink'] = $post->permalink;
 
-       $contact_id = fbsync_fetch_contact($uid, $contacts[$post->source_id], true);
-
-       if ($contact_id < 0)
-               return($postarray);
-       elseif ($contact_id == 0)
-               $contact_id = $self[0]["id"];
-
-       $postarray['contact-id'] = $contact_id;
+       $postarray['author-name'] = $contacts[$post->actor_id]->name;
+       $postarray['author-link'] = $contacts[$post->actor_id]->url;
+       $postarray['author-avatar'] = $contacts[$post->actor_id]->pic_square;
 
        $postarray['owner-name'] = $contacts[$post->source_id]->name;
        $postarray['owner-link'] = $contacts[$post->source_id]->url;
        $postarray['owner-avatar'] = $contacts[$post->source_id]->pic_square;
 
-       $postarray['author-name'] = $contacts[$post->actor_id]->name;
-       $postarray['author-link'] = $contacts[$post->actor_id]->url;
-       $postarray['author-avatar'] = $contacts[$post->actor_id]->pic_square;
+       $contact_id = 0;
+
+       if (($post->parent_post_id != "") AND ($post->actor_id == $post->source_id)) {
+               $pos = strpos($post->parent_post_id, "_");
+
+               if ($pos != 0) {
+                       $user_id = substr($post->parent_post_id, 0, $pos);
+
+                       $userdata = fbsync_fetchuser($a, $uid, $user_id);
+
+                       $contact_id = $userdata["contact-id"];
+
+                       $postarray['contact-id'] = $contact_id;
+
+                       if (array_key_exists("name", $userdata) AND ($userdata["name"] != "") AND !link_compare($userdata["link"], $postarray['author-link'])) {
+                               $postarray['owner-name'] = $userdata["name"];
+                               $postarray['owner-link'] = $userdata["link"];
+                               $postarray['owner-avatar'] = $userdata["avatar"];
+
+                               if (!intval(get_config('system','wall-to-wall_share'))) {
+
+                                       $prebody = "[share author='".$postarray['author-name'].
+                                               "' profile='".$postarray['author-link'].
+                                               "' avatar='".$postarray['author-avatar']."']";
+
+                                       $postarray['author-name'] = $postarray['owner-name'];
+                                       $postarray['author-link'] = $postarray['owner-link'];
+                                       $postarray['author-avatar'] = $postarray['owner-avatar'];
+                               }
+                       }
+               }
+       }
+
+       if ($contact_id == 0) {
+               $contact_id = fbsync_fetch_contact($uid, $contacts[$post->source_id], $create_user);
+
+               if (($contact_id <= 0) AND !$create_user) {
+                       logger('fbsync_createpost: No matching contact found. Post not imported '.print_r($post, true), LOGGER_DEBUG);
+                       return;
+               } elseif ($contact_id == 0) {
+                       // This case should never happen
+                       logger('fbsync_createpost: No matching contact found. Using own id. (Should never happen) '.print_r($post, true), LOGGER_DEBUG);
+                       $contact_id = $self[0]["id"];
+               }
+
+               $postarray['contact-id'] = $contact_id;
+       }
 
        $postarray["body"] = (isset($post->message) ? escape_tags($post->message) : '');
 
@@ -161,6 +274,9 @@ function fbsync_createpostarray($a, $uid, $self, $contacts, $applications, $post
        if(isset($post->attachment->caption) and ($post->attachment->fb_object_type == "photo"))
                $quote = $post->attachment->caption;
 
+       if ($quote.$post->attachment->href.$postarray["body"] == "")
+               return;
+
        if (isset($post->attachment->media) AND !strstr($post->attachment->href, "://www.youtube.com/")
                AND !strstr($post->attachment->href, "://youtu.be/")
                AND !strstr($post->attachment->href, ".vimeo.com/")) {
@@ -172,10 +288,10 @@ function fbsync_createpostarray($a, $uid, $self, $contacts, $applications, $post
                        //      $postarray['author-avatar'] = $contacts[$media->photo->owner]->pic_square;
                        //}
 
-                       if(isset($media->src) && isset($media->href))
+                       if(isset($media->src) && isset($media->href) AND ($media->src != "") AND ($media->href != ""))
                                $postarray["body"] .= "\n".'[url='.$media->href.'][img]'.fpost_cleanpicture($media->src).'[/img][/url]';
                        else {
-                               if (isset($media->src))
+                               if (isset($media->src) AND ($media->src != ""))
                                        $postarray["body"] .= "\n".'[img]'.fpost_cleanpicture($media->src).'[/img]';
 
                                // if just a link, it may be a wall photo - check
@@ -190,6 +306,12 @@ function fbsync_createpostarray($a, $uid, $self, $contacts, $applications, $post
 
        $postarray["body"] = trim($postarray["body"]);
 
+       if (trim($postarray["body"]) == "")
+               return;
+
+       if ($prebody != "")
+               $postarray["body"] = $prebody.$postarray["body"]."[/share]";
+
        $postarray['created'] = datetime_convert('UTC','UTC',date("c", $post->created_time));
        $postarray['edited'] = datetime_convert('UTC','UTC',date("c", $post->updated_time));
 
@@ -208,13 +330,20 @@ function fbsync_createpostarray($a, $uid, $self, $contacts, $applications, $post
        postarray["coord"] = $post->geo->coordinates[0]." ".$post->geo->coordinates[1];
        */
 
-       return($postarray);
+       //$types = array(46, 80, 237, 247, 308);
+       //if (!in_array($post->type, $types))
+       //      $postarray["body"] = "Type: ".$post->type."\n".$postarray["body"];
+       //print_r($post);
+       //print_r($postarray);
+
+       $item = item_store($postarray);
+       logger('fbsync_createpost: User '.$self[0]["nick"].' posted feed item '.$item, LOGGER_DEBUG);
 }
 
-function fbsync_createcommentpostarray($a, $uid, $self_id, $self, $user, $contacts, $applications, $comment) {
+function fbsync_createcomment($a, $uid, $self_id, $self, $user, $contacts, $applications, $comment) {
 
        // check if it was already imported
-       $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
+       $r = q("SELECT `uri` FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
                intval($uid),
                dbesc('fb::'.$comment->id)
        );
@@ -222,13 +351,35 @@ function fbsync_createcommentpostarray($a, $uid, $self_id, $self, $user, $contac
                return;
 
        // check if it was an own post (separate posting for performance reasons)
-       $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `extid` = '%s' LIMIT 1",
+       $r = q("SELECT `uri` FROM `item` WHERE `uid` = %d AND `extid` = '%s' LIMIT 1",
                intval($uid),
                dbesc('fb::'.$comment->id)
        );
        if(count($r))
                return;
 
+       $parent_uri = "";
+
+       // Fetch the parent uri (Checking if the parent exists)
+       $r = q("SELECT `uri` FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
+               intval($uid),
+               dbesc('fb::'.$comment->post_id)
+       );
+       if(count($r))
+               $parent_uri = $r[0]["uri"];
+
+       // check if it is a reply to an own post (separate posting for performance reasons)
+       $r = q("SELECT `uri` FROM `item` WHERE `uid` = %d AND `extid` = '%s' LIMIT 1",
+               intval($uid),
+               dbesc('fb::'.$comment->post_id)
+       );
+       if(count($r))
+               $parent_uri = $r[0]["uri"];
+
+       // No parent? Then quit
+       if ($parent_uri == "")
+               return;
+
        $postarray = array();
        $postarray['gravity'] = 0;
        $postarray['uid'] = $uid;
@@ -237,8 +388,8 @@ function fbsync_createcommentpostarray($a, $uid, $self_id, $self, $user, $contac
        $postarray['verb'] = ACTIVITY_POST;
 
        $postarray['uri'] = "fb::".$comment->id;
-       $postarray['thr-parent'] = "fb::".$comment->post_id;
-       $postarray['parent-uri'] = "fb::".$comment->post_id;
+       $postarray['thr-parent'] = $parent_uri;
+       $postarray['parent-uri'] = $parent_uri;
        //$postarray['plink'] = $comment->permalink;
 
        $contact_id = fbsync_fetch_contact($uid, $contacts[$comment->fromid], array(), false);
@@ -275,6 +426,15 @@ function fbsync_createcommentpostarray($a, $uid, $self_id, $self, $user, $contac
        if ($postarray['app'] == "")
                $postarray['app'] = "Facebook";
 
+       if (trim($postarray["body"]) == "")
+               return;
+
+       $item = item_store($postarray);
+       logger('fbsync_createcomment: User '.$self[0]["nick"].' posted comment '.$item, LOGGER_DEBUG);
+
+       if ($item == 0)
+               return;
+
        $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0",
                dbesc($postarray['parent-uri']),
                intval($uid)
@@ -295,16 +455,6 @@ function fbsync_createcommentpostarray($a, $uid, $self_id, $self, $user, $contac
                        if(!link_compare($conv['author-link'],$importer_url) AND !link_compare($conv['author-link'],$own_contact[0]["url"]))
                                continue;
 
-                       // Fetching the item number
-                       $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
-                               intval($uid),
-                               dbesc('fb::'.$comment->post_id)
-                       );
-                       if(!count($r))
-                               return;
-                       else
-                               $item = $r[0]["id"];
-
                        require_once('include/enotify.php');
 
                        $conv_parent = $conv['parent'];
@@ -332,11 +482,9 @@ function fbsync_createcommentpostarray($a, $uid, $self_id, $self, $user, $contac
                        break;
                }
        }
-
-       return($postarray);
 }
 
-function fbsync_createlikepostarray($a, $uid, $self_id, $self, $contacts, $like) {
+function fbsync_createlike($a, $uid, $self_id, $self, $contacts, $like) {
 
        $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
                                dbesc("fb::".$like->post_id),
@@ -346,7 +494,7 @@ function fbsync_createlikepostarray($a, $uid, $self_id, $self, $contacts, $like)
         if (count($r))
                 $orig_post = $r[0];
        else
-               return(array("uri"=>""));
+               return;
 
        // If we posted the like locally, it will be found with our url, not the FB url.
 
@@ -362,7 +510,7 @@ function fbsync_createlikepostarray($a, $uid, $self_id, $self, $contacts, $like)
        );
 
        if (count($r))
-        return;
+               return;
 
        $contact_id = fbsync_fetch_contact($uid, $contacts[$like->user_id], array(), false);
 
@@ -414,9 +562,10 @@ function fbsync_createlikepostarray($a, $uid, $self_id, $self, $contacts, $like)
                );
 
         if (count($r))
-               return(array("uri"=>""));
+               return;
 
-       return($likedata);
+       $item = item_store($likedata);
+       logger('fbsync_createlike: liked item '.$item.'. User '.$self[0]["nick"], LOGGER_DEBUG);
 }
 
 function fbsync_fetch_contact($uid, $contact, $create_user) {
@@ -597,12 +746,52 @@ function fbsync_convertmsg($a, $body) {
 
 }
 
+function fbsync_fetchuser($a, $uid, $id) {
+       $access_token = get_pconfig($uid,'facebook','access_token');
+       $self_id = get_pconfig($uid,'fbsync','self_id');
+
+       $user = array();
+
+       $contact = q("SELECT `id`, `name`, `url`, `photo`  FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
+               intval($uid), dbesc("facebook::".$id));
+
+       if (count($contact)) {
+               $user["contact-id"] = $contact[0]["id"];
+               $user["name"] = $contact[0]["name"];
+               $user["link"] = $contact[0]["url"];
+               $user["avatar"] = $contact[0]["photo"];
+
+               return($user);
+       }
+
+       $own_contact = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
+               intval($uid), dbesc("facebook::".$self_id));
+
+       if (!count($own_contact))
+               return($user);
+
+       $fql = "SELECT name, url, pic_square FROM profile WHERE id = ".$id;
+
+       $url = "https://graph.facebook.com/fql?q=".urlencode($fql)."&access_token=".$access_token;
+
+       $feed = fetch_url($url);
+       $data = json_decode($feed);
+
+       if (is_array($data->data)) {
+               $user["contact-id"] = $own_contact[0]["id"];
+               $user["name"] = $data->data[0]->name;
+               $user["link"] = $data->data[0]->url;
+               $user["avatar"] = $data->data[0]->pic_square;
+       }
+       return($user);
+}
+
 function fbsync_fetchfeed($a, $uid) {
        $access_token = get_pconfig($uid,'facebook','access_token');
        $last_updated = get_pconfig($uid,'fbsync','last_updated');
        $self_id = get_pconfig($uid,'fbsync','self_id');
 
-       $create_user = get_pconfig($uid, 'fbsybc', 'create_user');
+       $create_user = get_pconfig($uid, 'fbsync', 'create_user');
        $do_likes = get_config('fbsync', 'do_likes');
 
        $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
@@ -623,11 +812,11 @@ function fbsync_fetchfeed($a, $uid) {
        logger("fbsync_fetchfeed: fetching content for user ".$self_id);
 
        $fql = array(
-               "posts" => "SELECT action_links, actor_id, app_data, app_id, attachment, attribution, comment_info, created_time, filter_key, like_info, message, message_tags, parent_post_id, permalink, place, post_id, privacy, share_count, share_info, source_id, subscribed, tagged_ids, type, updated_time, with_tags FROM stream where filter_key in (SELECT filter_key FROM stream_filter WHERE uid=me() AND type='newsfeed') AND updated_time > $last_updated ORDER BY created_time DESC",
-               "comments" => "SELECT app_id, attachment, post_id, id, likes, fromid, time, text, text_tags, user_likes, likes FROM comment WHERE post_id IN (SELECT post_id FROM #posts) order by time desc",
-               "profiles" => "SELECT id, name, username, url, pic_square FROM profile WHERE id IN (SELECT actor_id FROM #posts) OR id IN (SELECT fromid FROM #comments) OR id IN (SELECT source_id FROM #posts)",
-               "applications" => "SELECT app_id, display_name FROM application WHERE app_id IN (SELECT app_id FROM #posts) OR app_id IN (SELECT app_id FROM #comments)",
-               "avatars" => "SELECT id, real_size, size, url FROM square_profile_pic WHERE id IN (SELECT id FROM #profiles) AND size = 256");
+               "posts" => "SELECT action_links, actor_id, app_data, app_id, attachment, attribution, comment_info, created_time, filter_key, like_info, message, message_tags, parent_post_id, permalink, place, post_id, privacy, share_count, share_info, source_id, subscribed, tagged_ids, type, updated_time, with_tags FROM stream where filter_key in (SELECT filter_key FROM stream_filter WHERE uid=me() AND type='newsfeed') AND updated_time > $last_updated ORDER BY updated_time DESC LIMIT 500",
+               "comments" => "SELECT app_id, attachment, post_id, id, likes, fromid, time, text, text_tags, user_likes, likes FROM comment WHERE post_id IN (SELECT post_id FROM #posts) ORDER BY time DESC LIMIT 500",
+               "profiles" => "SELECT id, name, username, url, pic_square FROM profile WHERE id IN (SELECT actor_id FROM #posts) OR id IN (SELECT fromid FROM #comments) OR id IN (SELECT source_id FROM #posts) LIMIT 500",
+               "applications" => "SELECT app_id, display_name FROM application WHERE app_id IN (SELECT app_id FROM #posts) OR app_id IN (SELECT app_id FROM #comments) LIMIT 500",
+               "avatars" => "SELECT id, real_size, size, url FROM square_profile_pic WHERE id IN (SELECT id FROM #profiles) AND size = 256 LIMIT 500");
 
        if ($do_likes) {
                $fql["likes"] = "SELECT post_id, user_id FROM like WHERE post_id IN (SELECT post_id FROM #posts)";
@@ -640,6 +829,11 @@ function fbsync_fetchfeed($a, $uid) {
 
        $data = json_decode($feed);
 
+       if (!is_array($data->data)) {
+               logger("fbsync_fetchfeed: Error fetching data for user ".$uid.": ".print_r($data, true));
+               return;
+       }
+
        $posts = array();
        $comments = array();
        $likes = array();
@@ -714,40 +908,22 @@ function fbsync_fetchfeed($a, $uid) {
        unset($comments);
 
        foreach ($post_data AS $post) {
-               //print_r($post);
                if ($post->updated_time > $last_updated)
                        $last_updated = $post->updated_time;
 
-               $postarray = fbsync_createpostarray($a, $uid, $self, $contacts, $application_data, $post);
-               //print_r($postarray);
-               if (trim($postarray["body"]) != "") {
-                       $item = item_store($postarray);
-                       logger('fbsync_fetchfeed: User '.$self[0]["nick"].' posted feed item '.$item, LOGGER_DEBUG);
-               }
+               fbsync_createpost($a, $uid, $self, $contacts, $application_data, $post, $create_user);
        }
 
        foreach ($comment_data AS $comment) {
-               $postarray = fbsync_createcommentpostarray($a, $uid, $self_id, $self, $user, $contacts, $application_data, $comment);
-
-               if (trim($postarray["body"]) != "") {
-                       $item = item_store($postarray);
-                       logger('fbsync_fetchfeed: User '.$self[0]["nick"].' posted comment '.$item, LOGGER_DEBUG);
-               }
+               fbsync_createcomment($a, $uid, $self_id, $self, $user, $contacts, $application_data, $comment);
        }
 
        foreach($likes AS $like) {
                $like->user_id = number_format($like->user_id, 0, '', '');
 
-               $postarray = fbsync_createlikepostarray($a, $uid, $self_id, $self, $contacts, $like);
-
-               if ($postarray["uri"] != "") {
-                       $item = item_store($postarray);
-                       logger('fbsync_fetchfeed: User '.$self[0]["nick"].' liked '.$item, LOGGER_DEBUG);
-               }
-
+               fbsync_createlike($a, $uid, $self_id, $self, $contacts, $like);
        }
 
        set_pconfig($uid,'fbsync','last_updated', $last_updated);
-
 }
 ?>