]> git.mxchange.org Git - friendica-addons.git/blobdiff - appnet/appnet.php
App.net/Pump.io/GNU Social/Twitter: Support for new notifications
[friendica-addons.git] / appnet / appnet.php
index 03be48203e680f3400057bed80216e8cae400fd8..bbcf9208ae835553b936e97c8290c29c378c8131 100644 (file)
@@ -2,7 +2,7 @@
 
 /**
  * Name: App.net Connector
- * Description: app.net postings import and export
+ * Description: Bidirectional (posting and reading) connector for app.net.
  * Version: 0.2
  * Author: Michael Vogel <https://pirati.ca/profile/heluecht>
  */
  - Use embedded pictures for the attachment information (large attachment)
  - Sound links must be handled
  - https://alpha.app.net/sr_rolando/post/32365203 - double pictures
+ - https://alpha.app.net/opendev/post/34396399 - location data
 */
 
+require_once('include/enotify.php');
+
 define('APPNET_DEFAULT_POLL_INTERVAL', 5); // given in minutes
 
 function appnet_install() {
@@ -23,6 +26,8 @@ function appnet_install() {
        register_hook('cron',                   'addon/appnet/appnet.php', 'appnet_cron');
        register_hook('connector_settings',     'addon/appnet/appnet.php', 'appnet_settings');
        register_hook('connector_settings_post','addon/appnet/appnet.php', 'appnet_settings_post');
+       register_hook('prepare_body',           'addon/appnet/appnet.php', 'appnet_prepare_body');
+       register_hook('check_item_notification','addon/appnet/appnet.php', 'appnet_check_item_notification');
 }
 
 
@@ -31,8 +36,10 @@ function appnet_uninstall() {
        unregister_hook('notifier_normal',  'addon/appnet/appnet.php', 'appnet_send');
        unregister_hook('jot_networks',     'addon/appnet/appnet.php', 'appnet_jot_nets');
        unregister_hook('cron',                 'addon/appnet/appnet.php', 'appnet_cron');
-       unregister_hook('connector_settings',      'addon/appnet/appnet.php', 'appnet_settings');
+       unregister_hook('connector_settings',   'addon/appnet/appnet.php', 'appnet_settings');
        unregister_hook('connector_settings_post', 'addon/appnet/appnet.php', 'appnet_settings_post');
+       unregister_hook('prepare_body',         'addon/appnet/appnet.php', 'appnet_prepare_body');
+       unregister_hook('check_item_notification','addon/appnet/appnet.php', 'appnet_check_item_notification');
 }
 
 function appnet_module() {}
@@ -61,11 +68,47 @@ function appnet_content(&$a) {
        return $o;
 }
 
+function appnet_check_item_notification($a, &$notification_data) {
+        $own_id = get_pconfig($notification_data["uid"], 'appnet', 'ownid');
+
+        $own_user = q("SELECT `url` FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
+                        intval($notification_data["uid"]),
+                        dbesc("adn::".$own_id)
+                );
+
+        if ($own_user)
+                $notification_data["profiles"][] = $own_user[0]["url"];
+}
+
+function appnet_plugin_admin(&$a, &$o){
+        $t = get_markup_template( "admin.tpl", "addon/appnet/" );
+
+        $o = replace_macros($t, array(
+                '$submit' => t('Save Settings'),
+                                                                // name, label, value, help, [extra values]
+                '$clientid' => array('clientid', t('Client ID'),  get_config('appnet', 'clientid' ), ''),
+                '$clientsecret' => array('clientsecret', t('Client Secret'),  get_config('appnet', 'clientsecret' ), ''),
+        ));
+}
+
+function appnet_plugin_admin_post(&$a){
+        $clientid     =       ((x($_POST,'clientid'))              ? notags(trim($_POST['clientid']))   : '');
+        $clientsecret =       ((x($_POST,'clientsecret'))   ? notags(trim($_POST['clientsecret'])): '');
+        set_config('appnet','clientid',$clientid);
+        set_config('appnet','clientsecret',$clientsecret);
+        info( t('Settings updated.'). EOL );
+}
+
 function appnet_connect(&$a) {
        require_once 'addon/appnet/AppDotNet.php';
 
-       $clientId     = get_pconfig(local_user(),'appnet','clientid');
-       $clientSecret = get_pconfig(local_user(),'appnet','clientsecret');
+       $clientId     = get_config('appnet','clientid');
+       $clientSecret = get_config('appnet','clientsecret');
+
+       if (($clientId == "") OR ($clientSecret == "")) {
+               $clientId     = get_pconfig(local_user(),'appnet','clientid');
+               $clientSecret = get_pconfig(local_user(),'appnet','clientsecret');
+       }
 
        $app = new AppDotNet($clientId, $clientSecret);
 
@@ -105,8 +148,14 @@ function appnet_settings(&$a,&$s) {
                return;
 
        $token = get_pconfig(local_user(),'appnet','token');
-       $app_clientId     = get_pconfig(local_user(),'appnet','clientid');
-       $app_clientSecret = get_pconfig(local_user(),'appnet','clientsecret');
+
+       $app_clientId     = get_config('appnet','clientid');
+       $app_clientSecret = get_config('appnet','clientsecret');
+
+       if (($app_clientId == "") OR ($app_clientSecret == "")) {
+               $app_clientId     = get_pconfig(local_user(),'appnet','clientid');
+               $app_clientSecret = get_pconfig(local_user(),'appnet','clientsecret');
+       }
 
        /* Add our stylesheet to the page so we can make our settings look nice */
        $a->page['htmlhead'] .= '<link rel="stylesheet"  type="text/css" href="' . $a->get_baseurl() . '/addon/appnet/appnet.css' . '" media="all" />' . "\r\n";
@@ -169,11 +218,11 @@ function appnet_settings(&$a,&$s) {
                $s .= sprintf(t("Use '%s' as Redirect URI<p>"), $a->get_baseurl().'/appnet/connect');
                $s .= '<div id="appnet-clientid-wrapper">';
                $s .= '<label id="appnet-clientid-label" for="appnet-clientid">' . t('Client ID') . '</label>';
-               $s .= '<input id="appnet-clientid" type="text" name="clientid" value="'.$app_clientId.'" />';
+               $s .= '<input id="appnet-clientid" type="text" name="clientid" value="" />';
                $s .= '</div><div class="clear"></div>';
                $s .= '<div id="appnet-clientsecret-wrapper">';
                $s .= '<label id="appnet-clientsecret-label" for="appnet-clientsecret">' . t('Client Secret') . '</label>';
-               $s .= '<input id="appnet-clientsecret" type="text" name="clientsecret" value="'.$app_clientSecret.'" />';
+               $s .= '<input id="appnet-clientsecret" type="text" name="clientsecret" value="" />';
                $s .= '</div><div class="clear"></div>';
                $s .= "<hr />";
                $s .= t('<p>Second way: fetch a token at <a href="http://dev-lite.jonathonduerig.com/">http://dev-lite.jonathonduerig.com/</a>. ');
@@ -274,12 +323,13 @@ function appnet_create_entities($a, $b, $postdata) {
        $bbcode = preg_replace("/@\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'@$2',$bbcode);
        $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",'[url=$1]$2[/url]',$bbcode);
        $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism",'[url=$1]$1[/url]',$bbcode);
+       $bbcode = preg_replace("/\[youtube\]https?:\/\/(.*?)\[\/youtube\]/ism",'[url=https://$1]https://$1[/url]',$bbcode);
        $bbcode = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
                               '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]', $bbcode);
-       $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism",'[url=$1]$1[/url]',$bbcode);
+       $bbcode = preg_replace("/\[vimeo\]https?:\/\/(.*?)\[\/vimeo\]/ism",'[url=https://$1]https://$1[/url]',$bbcode);
        $bbcode = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
                                '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]', $bbcode);
-       $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism",'[url=$1]$1[/url]',$bbcode);
+       //$bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism",'[url=$1]$1[/url]',$bbcode);
 
        $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
 
@@ -312,6 +362,7 @@ function appnet_create_entities($a, $b, $postdata) {
                $mid = $url[2];
                $html = bbcode($mid, false, false, 6);
                $mid = html2plain($html, 0, true);
+
                $mid = trim(html_entity_decode($mid,ENT_QUOTES,'UTF-8'));
 
                $text = $pre.$mid.$post;
@@ -322,20 +373,28 @@ function appnet_create_entities($a, $b, $postdata) {
                $start = $pos + 1;
        }
 
-       if (isset($postdata["url"]) AND isset($postdata["title"])) {
+       if (isset($postdata["url"]) AND isset($postdata["title"]) AND ($postdata["type"] != "photo")) {
                $postdata["title"] = shortenmsg($postdata["title"], 90);
-               $text = shortenmsg($text, 256 - strlen($postdata["title"]));
+               $max = 256 - strlen($postdata["title"]);
+               $text = shortenmsg($text, $max);
                $text .= "\n[".$postdata["title"]."](".$postdata["url"].")";
-       } elseif (isset($postdata["url"])) {
+       } elseif (isset($postdata["url"]) AND ($postdata["type"] != "photo")) {
                $postdata["url"] = short_link($postdata["url"]);
-               $text = shortenmsg($text, 240);
+               $max = 240;
+               $text = shortenmsg($text, $max);
                $text .= " [".$postdata["url"]."](".$postdata["url"].")";
-       } else
-               $text = shortenmsg($text, 256);
+       } else {
+               $max = 256;
+               $text = shortenmsg($text, $max);
+       }
+
+       if (iconv_strlen($text, "UTF-8") < $max)
+               $max = iconv_strlen($text, "UTF-8");
 
        krsort($entities);
        foreach ($entities AS $entity) {
-               if (iconv_strlen($text) >= $entity["pos"] + $entity["len"]) {
+               //if (iconv_strlen($text, "UTF-8") >= $entity["pos"] + $entity["len"]) {
+               if (($entity["pos"] + $entity["len"]) <= $max) {
                        $pre = iconv_substr($text, 0, $entity["pos"], "UTF-8");
                        $post = iconv_substr($text, $entity["pos"] + $entity["len"], 1000000, "UTF-8");
 
@@ -343,6 +402,7 @@ function appnet_create_entities($a, $b, $postdata) {
                }
        }
 
+
        return($text);
 }
 
@@ -435,7 +495,7 @@ function appnet_send(&$a,&$b) {
 
                if (isset($post["image"])) {
                        $img_str = fetch_url($post['image'],true, $redirects, 10);
-                       $tempfile = tempnam(get_config("system","temppath"), "cache");
+                       $tempfile = tempnam(get_temppath(), "cache");
                        file_put_contents($tempfile, $img_str);
 
                        try {
@@ -452,7 +512,7 @@ function appnet_send(&$a,&$b) {
                                                                );
                        }
                        catch (AppDotNetException $e) {
-                               logger("appnet_send: Error creating file ".$e->getMessage());
+                               logger("appnet_send: Error creating file ".appnet_error($e->getMessage()));
                        }
 
                        unlink($tempfile);
@@ -480,7 +540,7 @@ function appnet_send(&$a,&$b) {
                                                "value" => $attached_data
                                                );
 
-               if (isset($post["url"]) AND !isset($post["title"])) {
+               if (isset($post["url"]) AND !isset($post["title"]) AND ($post["type"] != "photo")) {
                        $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $post["url"]);
                        $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
 
@@ -510,7 +570,7 @@ function appnet_send(&$a,&$b) {
                        }
                }
                catch (AppDotNetException $e) {
-                       logger("appnet_send: Error sending message ".$b["id"]." ".$e->getMessage());
+                       logger("appnet_send: Error sending message ".$b["id"]." ".appnet_error($e->getMessage()));
                }
        }
 }
@@ -542,7 +602,7 @@ function appnet_action($a, $uid, $pid, $action) {
                logger("appnet_action '".$action."' send, result: " . print_r($result, true), LOGGER_DEBUG);
        }
        catch (AppDotNetException $e) {
-               logger("appnet_action: Error sending action ".$action." pid ".$pid." ".$e->getMessage(), LOGGER_DEBUG);
+               logger("appnet_action: Error sending action ".$action." pid ".$pid." ".appnet_error($e->getMessage()), LOGGER_DEBUG);
        }
 }
 
@@ -593,7 +653,7 @@ function appnet_is_repost($a, $uid, $body) {
                return true;
        }
        catch (AppDotNetException $e) {
-               logger('appnet_is_repost: error doing repost '.$e->getMessage(), LOGGER_DEBUG);
+               logger('appnet_is_repost: error doing repost '.appnet_error($e->getMessage()), LOGGER_DEBUG);
                return false;
        }
 }
@@ -645,19 +705,25 @@ function appnet_fetchstream($a, $uid) {
                $stream = $app->getUserStream($param);
        }
        catch (AppDotNetException $e) {
-               logger("appnet_fetchstream: Error fetching stream for user ".$uid." ".$e->getMessage());
+               logger("appnet_fetchstream: Error fetching stream for user ".$uid." ".appnet_error($e->getMessage()));
+               return;
        }
 
+       if (!is_array($stream))
+               $stream = array();
+
        $stream = array_reverse($stream);
        foreach ($stream AS $post) {
                $postarray = appnet_createpost($a, $uid, $post, $me, $user, $ownid, true);
 
                $item = item_store($postarray);
+               $postarray["id"] = $item;
+
                logger('appnet_fetchstream: User '.$uid.' posted stream item '.$item);
 
                $lastid = $post["id"];
 
-               if (($item != 0) AND ($postarray['contact-id'] != $me["id"])) {
+               if (($item != 0) AND ($postarray['contact-id'] != $me["id"]) AND !function_exists("check_item_notification")) {
                        $r = q("SELECT `thread`.`iid` AS `parent` FROM `thread`
                                INNER JOIN `item` ON `thread`.`iid` = `item`.`parent` AND `thread`.`uid` = `item`.`uid`
                                WHERE `item`.`id` = %d AND `thread`.`mention` LIMIT 1", dbesc($item));
@@ -672,7 +738,7 @@ function appnet_fetchstream($a, $uid) {
                                        'to_email'     => $user['email'],
                                        'uid'          => $user['uid'],
                                        'item'         => $postarray,
-                                       'link'         => $a->get_baseurl() . '/display/' . $user['nickname'] . '/' . $item,
+                                       'link'         => $a->get_baseurl().'/display/'.urlencode(get_item_guid($item)),
                                        'source_name'  => $postarray['author-name'],
                                        'source_link'  => $postarray['author-link'],
                                        'source_photo' => $postarray['author-avatar'],
@@ -699,24 +765,52 @@ function appnet_fetchstream($a, $uid) {
                $mentions = $app->getUserMentions("me", $param);
        }
        catch (AppDotNetException $e) {
-               logger("appnet_fetchstream: Error fetching mentions for user ".$uid." ".$e->getMessage());
+               logger("appnet_fetchstream: Error fetching mentions for user ".$uid." ".appnet_error($e->getMessage()));
+               return;
        }
 
+       if (!is_array($mentions))
+               $mentions = array();
+
        $mentions = array_reverse($mentions);
        foreach ($mentions AS $post) {
                $postarray = appnet_createpost($a, $uid, $post, $me, $user, $ownid, false);
 
-               if (isset($postarray["id"]))
+               if (isset($postarray["id"])) {
                        $item = $postarray["id"];
-               elseif (isset($postarray["body"])) {
+                       $parent_id = $postarray['parent'];
+               } elseif (isset($postarray["body"])) {
                        $item = item_store($postarray);
+                       $postarray["id"] = $item;
+
+                       $parent_id = 0;
                        logger('appnet_fetchstream: User '.$uid.' posted mention item '.$item);
-               } else
+
+                       if ($item AND function_exists("check_item_notification"))
+                               check_item_notification($item, $uid, NOTIFY_TAGSELF);
+
+               } else {
                        $item = 0;
+                       $parent_id = 0;
+               }
+
+               // Fetch the parent and id
+               if (($parent_id == 0) AND ($postarray['uri'] != "")) {
+                       $r = q("SELECT `id`, `parent` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
+                               dbesc($postarray['uri']),
+                               intval($uid)
+                       );
+
+                       if (count($r)) {
+                               $item = $r[0]['id'];
+                               $parent_id = $r[0]['parent'];
+                       }
+               }
 
                $lastid = $post["id"];
 
-               if (($item != 0) AND ($postarray['contact-id'] != $me["id"])) {
+               //if (($item != 0) AND ($postarray['contact-id'] != $me["id"])) {
+               if (($item != 0) AND !function_exists("check_item_notification")) {
                        require_once('include/enotify.php');
                        notification(array(
                                'type'         => NOTIFY_TAGSELF,
@@ -726,12 +820,13 @@ function appnet_fetchstream($a, $uid) {
                                'to_email'     => $user['email'],
                                'uid'          => $user['uid'],
                                'item'         => $postarray,
-                               'link'         => $a->get_baseurl() . '/display/' . $user['nickname'] . '/' . $item,
+                               'link'         => $a->get_baseurl().'/display/'.urlencode(get_item_guid($item)),
                                'source_name'  => $postarray['author-name'],
                                'source_link'  => $postarray['author-link'],
                                'source_photo' => $postarray['author-avatar'],
                                'verb'         => ACTIVITY_TAG,
-                               'otype'        => 'item'
+                               'otype'        => 'item',
+                               'parent'       => $parent_id,
                        ));
                }
        }
@@ -747,7 +842,7 @@ function appnet_fetchstream($a, $uid) {
 */
 }
 
-function appnet_createpost($a, $uid, $post, $me, $user, $ownid, $createuser, $threadcompletion = true) {
+function appnet_createpost($a, $uid, $post, $me, $user, $ownid, $createuser, $threadcompletion = true, $nodupcheck = false) {
        require_once('include/items.php');
 
        if ($post["machine_only"])
@@ -762,35 +857,45 @@ function appnet_createpost($a, $uid, $post, $me, $user, $ownid, $createuser, $th
        $postarray['wall'] = 0;
        $postarray['verb'] = ACTIVITY_POST;
        $postarray['network'] =  dbesc(NETWORK_APPNET);
-       $postarray['uri'] = "adn::".$post["id"];
+       if (is_array($post["repost_of"])) {
+               // You can't reply to reposts. So use the original id and thread-id
+               $postarray['uri'] = "adn::".$post["repost_of"]["id"];
+               $postarray['parent-uri'] = "adn::".$post["repost_of"]["thread_id"];
+       } else {
+               $postarray['uri'] = "adn::".$post["id"];
+               $postarray['parent-uri'] = "adn::".$post["thread_id"];
+       }
 
-       $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
-               dbesc($postarray['uri']),
-               intval($uid)
-               );
+       if (!$nodupcheck) {
+               $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
+                       dbesc($postarray['uri']),
+                       intval($uid)
+                       );
 
-       if (count($r))
-               return($r[0]);
+               if (count($r))
+                       return($r[0]);
 
-       $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
-               dbesc($postarray['uri']),
-               intval($uid)
-               );
+               $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
+                       dbesc($postarray['uri']),
+                       intval($uid)
+                       );
 
-       if (count($r))
-               return($r[0]);
+               if (count($r))
+                       return($r[0]);
+       }
 
-       $postarray['parent-uri'] = "adn::".$post["thread_id"];
        if (isset($post["reply_to"]) AND ($post["reply_to"] != "")) {
                $postarray['thr-parent'] = "adn::".$post["reply_to"];
 
-               // Complete the thread if the parent doesn't exists
+               // Complete the thread (if the parent doesn't exists)
                if ($threadcompletion) {
-                       $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
-                               dbesc($postarray['thr-parent']),
-                               intval($uid)
-                               );
-                       if (!count($r)) {
+                       //$r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
+                       //      dbesc($postarray['thr-parent']),
+                       //      intval($uid)
+                       //      );
+                       //if (!count($r)) {
+                               logger("appnet_createpost: completing thread ".$post["thread_id"]." for user ".$uid, LOGGER_DEBUG);
+
                                require_once("addon/appnet/AppDotNet.php");
 
                                $token = get_pconfig($uid,'appnet','token');
@@ -806,19 +911,29 @@ function appnet_createpost($a, $uid, $post, $me, $user, $ownid, $createuser, $th
                                        $thread = $app->getPostReplies($post["thread_id"], $param);
                                }
                                catch (AppDotNetException $e) {
-                                       logger("appnet_createpost: Error fetching thread for user ".$uid." ".$e->getMessage());
+                                       logger("appnet_createpost: Error fetching thread for user ".$uid." ".appnet_error($e->getMessage()));
                                }
                                $thread = array_reverse($thread);
+
+                               logger("appnet_createpost: fetched ".count($thread)." items for thread ".$post["thread_id"]." for user ".$uid, LOGGER_DEBUG);
+
                                foreach ($thread AS $tpost) {
-                                       $threadpost = appnet_createpost($a, $uid, $tpost, $me, $user, $ownid, $createuser, false);
+                                       $threadpost = appnet_createpost($a, $uid, $tpost, $me, $user, $ownid, false, false);
                                        $item = item_store($threadpost);
+                                       $threadpost["id"] = $item;
+
+                                       logger("appnet_createpost: stored post ".$post["id"]." thread ".$post["thread_id"]." in item ".$item, LOGGER_DEBUG);
                                }
-                       }
+                       //}
                }
-       } else
-               $postarray['thr-parent'] = $postarray['uri'];
+               // Don't create accounts of people who just comment something
+               $createuser = false;
 
-       $postarray['plink'] = $post["canonical_url"];
+               $postarray['object-type'] = ACTIVITY_OBJ_COMMENT;
+       } else {
+               $postarray['thr-parent'] = $postarray['uri'];
+               $postarray['object-type'] = ACTIVITY_OBJ_NOTE;
+       }
 
        if (($post["user"]["id"] != $ownid) OR ($postarray['thr-parent'] == $postarray['uri'])) {
                $postarray['owner-name'] = $post["user"]["name"];
@@ -848,6 +963,8 @@ function appnet_createpost($a, $uid, $post, $me, $user, $ownid, $createuser, $th
                $content = $post;
        }
 
+       $postarray['plink'] = $content["canonical_url"];
+
        if (is_array($content["entities"])) {
                $converted = appnet_expand_entities($a, $content["text"], $content["entities"]);
                $postarray['body'] = $converted["body"];
@@ -861,7 +978,7 @@ function appnet_createpost($a, $uid, $post, $me, $user, $ownid, $createuser, $th
                        $links[$url] = $link["url"];
                }
 
-       if (sizeof($content["annotations"]))
+       /* if (sizeof($content["annotations"]))
                foreach($content["annotations"] AS $annotation) {
                        if ($annotation[type] == "net.app.core.oembed") {
                                if (isset($annotation["value"]["embeddable_url"])) {
@@ -870,7 +987,6 @@ function appnet_createpost($a, $uid, $post, $me, $user, $ownid, $createuser, $th
                                                unset($links[$url]);
                                }
                        } elseif ($annotation[type] == "com.friendica.post") {
-                               // Nur zum Testen deaktiviert
                                //$links = array();
                                //if (isset($annotation["value"]["post-title"]))
                                //      $postarray['title'] = $annotation["value"]["post-title"];
@@ -891,7 +1007,7 @@ function appnet_createpost($a, $uid, $post, $me, $user, $ownid, $createuser, $th
                                        $postarray['author-avatar'] = $annotation["value"]["author-avatar"];
                        }
 
-               }
+               } */
 
        $page_info = "";
 
@@ -901,19 +1017,24 @@ function appnet_createpost($a, $uid, $post, $me, $user, $ownid, $createuser, $th
                        $page_info = "\n[url=".$photo["url"]."][img]".$photo["large"]."[/img][/url]";
                elseif ($photo["url"] != "")
                        $page_info = "\n[img]".$photo["url"]."[/img]";
+
+               if ($photo["url"] != "")
+                       $postarray['object-type'] = ACTIVITY_OBJ_IMAGE;
+
        } else
                $photo = array("url" => "", "large" => "");
 
        if (sizeof($links)) {
                $link = array_pop($links);
-               $url = "[url=".$link."]".$link."[/url]";
-
-               $removedlink = trim(str_replace($url, "", $postarray['body']));
-
-               if (($removedlink == "") OR strstr($postarray['body'], $removedlink))
-                       $postarray['body'] = $removedlink;
+               $url = str_replace(array('/', '.'), array('\/', '\.'), $link);
 
                $page_info = add_page_info($link, false, $photo["url"]);
+
+               if (trim($page_info) != "") {
+                       $removedlink = preg_replace("/\[url\=".$url."\](.*?)\[\/url\]/ism", '', $postarray['body']);
+                       if (($removedlink == "") OR strstr($postarray['body'], $removedlink))
+                               $postarray['body'] = $removedlink;
+               }
        }
 
        $postarray['body'] .= $page_info;
@@ -995,12 +1116,46 @@ function appnet_expand_annotations($a, $annotations) {
 }
 
 function appnet_fetchcontact($a, $uid, $contact, $me, $create_user) {
+
+       if (function_exists("update_gcontact"))
+               update_gcontact(array("url" => $contact["canonical_url"], "generation" => 2,
+                               "network" => NETWORK_APPNET, "photo" => $contact["avatar_image"]["url"],
+                               "name" => $contact["name"], "nick" => $contact["username"],
+                               "about" => $contact["description"]["text"], "hide" => true,
+                               "addr" => $contact["username"]."@app.net"));
+       else {
+               // Old Code
+               $r = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
+                               dbesc(normalise_link($contact["canonical_url"])));
+
+               if (count($r) == 0)
+                       q("INSERT INTO unique_contacts (url, name, nick, avatar) VALUES ('%s', '%s', '%s', '%s')",
+                               dbesc(normalise_link($contact["canonical_url"])),
+                               dbesc($contact["name"]),
+                               dbesc($contact["username"]),
+                               dbesc($contact["avatar_image"]["url"]));
+               else
+                       q("UPDATE unique_contacts SET name = '%s', nick = '%s', avatar = '%s' WHERE url = '%s'",
+                               dbesc($contact["name"]),
+                               dbesc($contact["username"]),
+                               dbesc($contact["avatar_image"]["url"]),
+                               dbesc(normalise_link($contact["canonical_url"])));
+
+               if (DB_UPDATE_VERSION >= "1177")
+                       q("UPDATE `unique_contacts` SET `location` = '%s', `about` = '%s' WHERE url = '%s'",
+                               dbesc(""),
+                               dbesc($contact["description"]["text"]),
+                               dbesc(normalise_link($contact["canonical_url"])));
+       }
+
        $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
                intval($uid), dbesc("adn::".$contact["id"]));
 
        if(!count($r) AND !$create_user)
-               return($me);
+               return($me["id"]);
 
+       if ($contact["canonical_url"] == "")
+               return($me["id"]);
 
        if (count($r) AND ($r[0]["readonly"] OR $r[0]["blocked"])) {
                logger("appnet_fetchcontact: Contact '".$r[0]["nick"]."' is blocked or readonly.", LOGGER_DEBUG);
@@ -1008,6 +1163,13 @@ function appnet_fetchcontact($a, $uid, $contact, $me, $create_user) {
        }
 
        if(!count($r)) {
+
+               if ($contact["name"] == "")
+                       $contact["name"] = $contact["username"];
+
+               if ($contact["username"] == "")
+                       $contact["username"] = $contact["name"];
+
                // create contact record
                q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
                                        `name`, `nick`, `photo`, `network`, `rel`, `priority`,
@@ -1069,6 +1231,14 @@ function appnet_fetchcontact($a, $uid, $contact, $me, $create_user) {
                        intval($contact_id)
                );
 
+               if (DB_UPDATE_VERSION >= "1177")
+                       q("UPDATE `contact` SET `location` = '%s',
+                                               `about` = '%s'
+                                       WHERE `id` = %d",
+                               dbesc(""),
+                               dbesc($contact["description"]["text"]),
+                               intval($contact_id)
+                       );
        } else {
                // update profile photos once every two weeks as we have no notification of when they change.
 
@@ -1110,12 +1280,57 @@ function appnet_fetchcontact($a, $uid, $contact, $me, $create_user) {
                                dbesc($contact["username"]),
                                intval($r[0]['id'])
                        );
+                       if (DB_UPDATE_VERSION >= "1177")
+                               q("UPDATE `contact` SET `location` = '%s',
+                                                       `about` = '%s'
+                                               WHERE `id` = %d",
+                                       dbesc(""),
+                                       dbesc($contact["description"]["text"]),
+                                       intval($r[0]['id'])
+                               );
                }
        }
 
        return($r[0]["id"]);
 }
 
+function appnet_prepare_body(&$a,&$b) {
+        if ($b["item"]["network"] != NETWORK_APPNET)
+                return;
+
+        if ($b["preview"]) {
+                $max_char = 256;
+                require_once("include/plaintext.php");
+                $item = $b["item"];
+                $item["plink"] = $a->get_baseurl()."/display/".$a->user["nickname"]."/".$item["parent"];
+
+                $r = q("SELECT `author-link` FROM item WHERE item.uri = '%s' AND item.uid = %d LIMIT 1",
+                        dbesc($item["thr-parent"]),
+                        intval(local_user()));
+
+                if(count($r)) {
+                        $orig_post = $r[0];
+
+                       $nicknameplain = preg_replace("=https?://alpha.app.net/(.*)=ism", "$1", $orig_post["author-link"]);
+                       $nickname = "@[url=".$orig_post["author-link"]."]".$nicknameplain."[/url]";
+                       $nicknameplain = "@".$nicknameplain;
+
+                       if ((strpos($item["body"], $nickname) === false) AND (strpos($item["body"], $nicknameplain) === false))
+                               $item["body"] = $nickname." ".$item["body"];
+                }
+
+
+
+                $msgarr = plaintext($a, $item, $max_char, true);
+               $msg = appnet_create_entities($a, $item, $msgarr);
+
+               require_once("library/markdown.php");
+               $msg = Markdown($msg);
+
+                $b['html'] = $msg;
+        }
+}
+
 function appnet_cron($a,$b) {
        $last = get_config('appnet','last_poll');
 
@@ -1132,9 +1347,23 @@ function appnet_cron($a,$b) {
        }
        logger('appnet_cron: cron_start');
 
+       $abandon_days = intval(get_config('system','account_abandon_days'));
+       if ($abandon_days < 1)
+               $abandon_days = 0;
+
+       $abandon_limit = date("Y-m-d H:i:s", time() - $abandon_days * 86400);
+
        $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'appnet' AND `k` = 'import' AND `v` = '1' ORDER BY RAND()");
        if(count($r)) {
                foreach($r as $rr) {
+                       if ($abandon_days != 0) {
+                               $user = q("SELECT `login_date` FROM `user` WHERE uid=%d AND `login_date` >= '%s'", $rr['uid'], $abandon_limit);
+                               if (!count($user)) {
+                                       logger('abandoned account: timeline from user '.$rr['uid'].' will not be imported');
+                                       continue;
+                               }
+                       }
+
                        logger('appnet_cron: importing timeline from user '.$rr['uid']);
                        appnet_fetchstream($a, $rr["uid"]);
                }
@@ -1144,3 +1373,23 @@ function appnet_cron($a,$b) {
 
        set_config('appnet','last_poll', time());
 }
+
+function appnet_error($msg) {
+        $msg = trim($msg);
+        $pos = strrpos($msg, "\r\n\r\n");
+
+        if (!$pos)
+                return($msg);
+
+        $msg = substr($msg, $pos + 4);
+
+        $error = json_decode($msg);
+
+        if ($error == NULL)
+                return($msg);
+
+       if (isset($error->meta->error_message))
+               return($error->meta->error_message);
+        else
+                return(print_r($error));
+}