]> git.mxchange.org Git - friendica.git/blobdiff - mod/item.php
File was missing
[friendica.git] / mod / item.php
index 8c5a479646ec992c98bd0b701e2a3cbdc51d012a..0deade41811fb4e0811f0063736c0df47c664403 100644 (file)
@@ -24,6 +24,8 @@ require_once('include/threads.php');
 require_once('include/text.php');
 require_once('include/items.php');
 require_once('include/Scrape.php');
+require_once('include/diaspora.php');
+require_once('include/Contact.php');
 
 function item_post(&$a) {
 
@@ -113,7 +115,7 @@ function item_post(&$a) {
                if(($r === false) || (! count($r))) {
                        notice( t('Unable to locate original post.') . EOL);
                        if(x($_REQUEST,'return'))
-                               goaway($a->get_baseurl() . "/" . $return_path );
+                               goaway($return_path);
                        killme();
                }
                $parent_item = $r[0];
@@ -128,7 +130,7 @@ function item_post(&$a) {
                                intval($parent_item['contact-id']),
                                intval($uid)
                        );
-                       if(count($r))
+                       if (dbm::is_result($r))
                                $parent_contact = $r[0];
 
                        // If the contact id doesn't fit with the contact, then set the contact to null
@@ -160,6 +162,9 @@ function item_post(&$a) {
                                logger('no contact found: '.print_r($thrparent, true), LOGGER_DEBUG);
                        } else
                                logger('parent contact: '.print_r($parent_contact, true), LOGGER_DEBUG);
+
+                       if ($parent_contact["nick"] == "")
+                               $parent_contact["nick"] = $parent_contact["name"];
                }
        }
 
@@ -170,6 +175,19 @@ function item_post(&$a) {
        $app         = ((x($_REQUEST,'source'))      ? strip_tags($_REQUEST['source'])  : '');
        $extid       = ((x($_REQUEST,'extid'))       ? strip_tags($_REQUEST['extid'])  : '');
 
+       // Check for multiple posts with the same message id (when the post was created via API)
+       if (($message_id != '') AND ($profile_uid != 0)) {
+               $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
+                       dbesc($message_id),
+                       intval($profile_uid)
+               );
+
+               if (dbm::is_result($r)) {
+                       logger("Message with URI ".$message_id." already exists for user ".$profile_uid, LOGGER_DEBUG);
+                       return;
+               }
+       }
+
        $allow_moderated = false;
 
        // here is where we are going to check for permission to post a moderated comment.
@@ -179,7 +197,7 @@ function item_post(&$a) {
        if((x($_REQUEST,'commenter')) && ((! $parent) || (! $parent_item['wall']))) {
                notice( t('Permission denied.') . EOL) ;
                if(x($_REQUEST,'return'))
-                       goaway($a->get_baseurl() . "/" . $return_path );
+                       goaway($return_path);
                killme();
        }
 
@@ -191,7 +209,7 @@ function item_post(&$a) {
        if((! can_write_wall($a,$profile_uid)) && (! $allow_moderated)) {
                notice( t('Permission denied.') . EOL) ;
                if(x($_REQUEST,'return'))
-                       goaway($a->get_baseurl() . "/" . $return_path );
+                       goaway($return_path);
                killme();
        }
 
@@ -215,7 +233,7 @@ function item_post(&$a) {
        $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
                intval($profile_uid)
        );
-       if(count($r))
+       if (dbm::is_result($r))
                $user = $r[0];
 
        if($orig_post) {
@@ -287,7 +305,6 @@ function item_post(&$a) {
                // If this is a comment, set the permissions from the parent.
 
                if($parent_item) {
-                       $private = 0;
 
                        // for non native networks use the network of the original post as network of the item
                        if (($parent_item['network'] != NETWORK_DIASPORA)
@@ -295,19 +312,13 @@ function item_post(&$a) {
                                AND ($network == ""))
                                $network = $parent_item['network'];
 
-                       if(($parent_item['private'])
-                               || strlen($parent_item['allow_cid'])
-                               || strlen($parent_item['allow_gid'])
-                               || strlen($parent_item['deny_cid'])
-                               || strlen($parent_item['deny_gid'])) {
-                               $private = (($parent_item['private']) ? $parent_item['private'] : 1);
-                       }
-
                        $str_contact_allow = $parent_item['allow_cid'];
                        $str_group_allow   = $parent_item['allow_gid'];
                        $str_contact_deny  = $parent_item['deny_cid'];
                        $str_group_deny    = $parent_item['deny_gid'];
+                       $private           = $parent_item['private'];
                }
+
                $pubmail_enable    = ((x($_REQUEST,'pubmail_enable') && intval($_REQUEST['pubmail_enable']) && (! $private)) ? 1 : 0);
 
                // if using the API, we won't see pubmail_enable - figure out if it should be set
@@ -328,7 +339,7 @@ function item_post(&$a) {
                                killme();
                        info( t('Empty post discarded.') . EOL );
                        if(x($_REQUEST,'return'))
-                               goaway($a->get_baseurl() . "/" . $return_path );
+                               goaway($return_path);
                        killme();
                }
        }
@@ -387,7 +398,7 @@ function item_post(&$a) {
                }
        }
 
-       if(count($r)) {
+       if (dbm::is_result($r)) {
                $author = $r[0];
                $contact_id = $author['id'];
        }
@@ -401,7 +412,7 @@ function item_post(&$a) {
                $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` = 1 LIMIT 1",
                        intval($profile_uid)
                );
-               if(count($r))
+               if (dbm::is_result($r))
                        $contact_record = $r[0];
        }
 
@@ -455,7 +466,6 @@ function item_post(&$a) {
                                if(! count($r))
                                        continue;
 
-
                                $r = q("UPDATE `photo` SET `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s'
                                        WHERE `resource-id` = '%s' AND `uid` = %d AND `album` = '%s' ",
                                        dbesc($str_contact_allow),
@@ -466,7 +476,6 @@ function item_post(&$a) {
                                        intval($profile_uid),
                                        dbesc( t('Wall Photos'))
                                );
-
                        }
                }
        }
@@ -486,7 +495,7 @@ function item_post(&$a) {
                                        intval($profile_uid),
                                        intval($attach)
                                );
-                               if(count($r)) {
+                               if (dbm::is_result($r)) {
                                        $r = q("UPDATE `attach` SET `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s'
                                                WHERE `uid` = %d AND `id` = %d",
                                                dbesc($str_contact_allow),
@@ -501,10 +510,11 @@ function item_post(&$a) {
                }
        }
 
-       // embedded bookmark in post? set bookmark flag
+       // embedded bookmark or attachment in post? set bookmark flag
 
        $bookmark = 0;
-       if(preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism",$body,$match,PREG_SET_ORDER)) {
+       $data = get_attachment_data($body);
+        if (preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $body, $match, PREG_SET_ORDER) OR isset($data["type"])) {
                $objecttype = ACTIVITY_OBJ_BOOKMARK;
                $bookmark = 1;
        }
@@ -626,7 +636,7 @@ function item_post(&$a) {
                                intval($profile_uid),
                                intval($mtch)
                        );
-                       if(count($r)) {
+                       if (dbm::is_result($r)) {
                                if(strlen($attachments))
                                        $attachments .= ',';
                                $attachments .= '[attach]href="' . $a->get_baseurl() . '/attach/' . $r[0]['id'] . '" length="' . $r[0]['filesize'] . '" type="' . $r[0]['filetype'] . '" title="' . (($r[0]['filename']) ? $r[0]['filename'] : '') . '"[/attach]';
@@ -671,9 +681,11 @@ function item_post(&$a) {
        $datarray['owner-name']    = $contact_record['name'];
        $datarray['owner-link']    = $contact_record['url'];
        $datarray['owner-avatar']  = $contact_record['thumb'];
+       $datarray["owner-id"]      = get_contact($datarray["owner-link"], 0);
        $datarray['author-name']   = $author['name'];
        $datarray['author-link']   = $author['url'];
        $datarray['author-avatar'] = $author['thumb'];
+       $datarray["author-id"]     = get_contact($datarray["author-link"], 0);
        $datarray['created']       = datetime_convert();
        $datarray['edited']        = datetime_convert();
        $datarray['commented']     = datetime_convert();
@@ -706,6 +718,7 @@ function item_post(&$a) {
        $datarray['moderated']     = $allow_moderated;
        $datarray['gcontact-id']   = get_gcontact_id(array("url" => $datarray['author-link'], "network" => $datarray['network'],
                                                        "photo" => $datarray['author-avatar'], "name" => $datarray['author-name']));
+
        /**
         * These fields are for the convenience of plugins...
         * 'self' if true indicates the owner is posting on their own wall
@@ -716,6 +729,11 @@ function item_post(&$a) {
        $datarray['self']          = $self;
 //     $datarray['prvnets']       = $user['prvnets'];
 
+       $datarray['parent-uri'] = ($parent == 0) ? $uri : $parent_item['uri'];
+       $datarray['plink'] = $a->get_baseurl().'/display/'.urlencode($datarray['guid']);
+       $datarray['last-child'] = 1;
+       $datarray['visible'] = 1;
+
        if($orig_post)
                $datarray['edit']      = true;
 
@@ -726,6 +744,9 @@ function item_post(&$a) {
 
        if($preview) {
                require_once('include/conversation.php');
+               // We set the datarray ID to -1 because in preview mode the dataray
+               // doesn't have an ID.
+               $datarray["id"] = -1;
                $o = conversation($a,array(array_merge($contact_record,$datarray)),'search', false, true);
                logger('preview: ' . $o);
                echo json_encode(array('preview' => $o));
@@ -738,7 +759,7 @@ function item_post(&$a) {
        if(x($datarray,'cancel')) {
                logger('mod_item: post cancelled by plugin.');
                if($return_path) {
-                       goaway($a->get_baseurl() . "/" . $return_path);
+                       goaway($return_path);
                }
 
                $json = array('cancel' => 1);
@@ -774,21 +795,38 @@ function item_post(&$a) {
                // update filetags in pconfig
                file_tag_update_pconfig($uid,$categories_old,$categories_new,'category');
 
-               proc_run('php', "include/notifier.php", 'edit_post', "$post_id");
+               proc_run(PRIORITY_HIGH, "include/notifier.php", 'edit_post', $post_id);
                if((x($_REQUEST,'return')) && strlen($return_path)) {
                        logger('return: ' . $return_path);
-                       goaway($a->get_baseurl() . "/" . $return_path );
+                       goaway($return_path);
                }
                killme();
-       }
-       else
+       } else
                $post_id = 0;
 
-
-       $r = q("INSERT INTO `item` (`guid`, `extid`, `uid`,`type`,`wall`,`gravity`, `network`, `contact-id`,`owner-name`,`owner-link`,`owner-avatar`, `author-name`, `author-link`, `author-avatar`,
-               `created`, `edited`, `commented`, `received`, `changed`, `uri`, `thr-parent`, `title`, `body`, `app`, `location`, `coord`, `tag`, `inform`, `verb`, `object-type`, `postopts`,
-               `allow_cid`, `allow_gid`, `deny_cid`, `deny_gid`, `private`, `pubmail`, `attach`, `bookmark`,`origin`, `moderated`, `file`, `rendered-html`, `rendered-hash`)
-               VALUES( '%s', '%s', %d, '%s', %d, %d, '%s', %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', %d, %d, %d, '%s', '%s', '%s')",
+       q("COMMIT");
+       q("START TRANSACTION;");
+
+       $r = q("INSERT INTO `item` (`guid`, `extid`, `uid`,`type`,`wall`,`gravity`, `network`, `contact-id`,
+                                       `owner-name`,`owner-link`,`owner-avatar`, `owner-id`,
+                                       `author-name`, `author-link`, `author-avatar`, `author-id`,
+                                       `created`, `edited`, `commented`, `received`, `changed`,
+                                       `uri`, `thr-parent`, `title`, `body`, `app`, `location`, `coord`,
+                                       `tag`, `inform`, `verb`, `object-type`, `postopts`,
+                                       `allow_cid`, `allow_gid`, `deny_cid`, `deny_gid`, `private`,
+                                       `pubmail`, `attach`, `bookmark`,`origin`, `moderated`, `file`,
+                                       `rendered-html`, `rendered-hash`,
+                                       `parent`, `parent-uri`, `plink`, `last-child`, `visible`)
+               VALUES('%s', '%s', %d, '%s', %d, %d, '%s', %d,
+                       '%s', '%s', '%s', %d,
+                       '%s', '%s', '%s', %d,
+                       '%s', '%s', '%s', '%s', '%s',
+                       '%s', '%s', '%s', '%s', '%s', '%s', '%s',
+                       '%s', '%s', '%s', '%s', '%s',
+                       '%s', '%s', '%s', '%s', %d,
+                       %d, '%s', %d, %d, %d, '%s',
+                       '%s', '%s',
+                       %d, '%s', '%s', %d, %d)",
                dbesc($datarray['guid']),
                dbesc($datarray['extid']),
                intval($datarray['uid']),
@@ -800,9 +838,11 @@ function item_post(&$a) {
                dbesc($datarray['owner-name']),
                dbesc($datarray['owner-link']),
                dbesc($datarray['owner-avatar']),
+               intval($datarray['owner-id']),
                dbesc($datarray['author-name']),
                dbesc($datarray['author-link']),
                dbesc($datarray['author-avatar']),
+               intval($datarray['author-id']),
                dbesc($datarray['created']),
                dbesc($datarray['edited']),
                dbesc($datarray['commented']),
@@ -832,26 +872,39 @@ function item_post(&$a) {
                intval($datarray['moderated']),
                dbesc($datarray['file']),
                dbesc($datarray['rendered-html']),
-               dbesc($datarray['rendered-hash'])
+               dbesc($datarray['rendered-hash']),
+               intval($datarray['parent']),
+               dbesc($datarray['parent-uri']),
+               dbesc($datarray['plink']),
+               intval($datarray['last-child']),
+               intval($datarray['visible'])
               );
 
-       $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' LIMIT 1",
-               dbesc($datarray['uri']));
-       if(!count($r)) {
+       if (dbm::is_result($r)) {
+               $r = q("SELECT LAST_INSERT_ID() AS `item-id`");
+               if (dbm::is_result($r)) {
+                       $post_id = $r[0]['item-id'];
+               } else {
+                       $post_id = 0;
+               }
+       } else {
+               logger('mod_item: unable to create post.');
+               $post_id = 0;
+       }
+
+       if ($post_id == 0) {
+               q("COMMIT");
                logger('mod_item: unable to retrieve post that was just stored.');
-               notice( t('System error. Post not saved.') . EOL);
-               goaway($a->get_baseurl() . "/" . $return_path );
+               notice(t('System error. Post not saved.') . EOL);
+               goaway($return_path);
                // NOTREACHED
        }
 
-       // Store the guid and other relevant data
-       add_guid($datarray);
-
-       $post_id = $r[0]['id'];
        logger('mod_item: saved item ' . $post_id);
 
        $datarray["id"] = $post_id;
-       $datarray["plink"] = $a->get_baseurl().'/display/'.urlencode($datarray["guid"]);
+
+       item_set_last_item($datarray);
 
        // update filetags in pconfig
        file_tag_update_pconfig($uid,$categories_old,$categories_new,'category');
@@ -859,22 +912,17 @@ function item_post(&$a) {
        if($parent) {
 
                // This item is the last leaf and gets the comment box, clear any ancestors
-               $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent` = %d ",
+               $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent` = %d AND `last-child` AND `id` != %d",
                        dbesc(datetime_convert()),
-                       intval($parent)
+                       intval($parent),
+                       intval($post_id)
                );
-               update_thread($parent, true);
-
-               // Inherit ACLs from the parent item.
 
-               $r = q("UPDATE `item` SET `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s', `private` = %d
-                       WHERE `id` = %d",
-                       dbesc($parent_item['allow_cid']),
-                       dbesc($parent_item['allow_gid']),
-                       dbesc($parent_item['deny_cid']),
-                       dbesc($parent_item['deny_gid']),
-                       intval($parent_item['private']),
-                       intval($post_id)
+               // update the commented timestamp on the parent
+               q("UPDATE `item` SET `visible` = 1, `commented` = '%s', `changed` = '%s' WHERE `id` = %d",
+                       dbesc(datetime_convert()),
+                       dbesc(datetime_convert()),
+                       intval($parent)
                );
 
                if($contact_record != $author) {
@@ -900,11 +948,15 @@ function item_post(&$a) {
 
 
                // Store the comment signature information in case we need to relay to Diaspora
-               store_diaspora_comment_sig($datarray, $author, ($self ? $user['prvkey'] : false), $parent_item, $post_id);
+               diaspora::store_comment_signature($datarray, $author, ($self ? $user['prvkey'] : false), $post_id);
 
        } else {
                $parent = $post_id;
 
+               $r = q("UPDATE `item` SET `parent` = %d WHERE `id` = %d",
+                       intval($parent),
+                       intval($post_id));
+
                if($contact_record != $author) {
                        notification(array(
                                'type'         => NOTIFY_WALL,
@@ -924,41 +976,6 @@ function item_post(&$a) {
                }
        }
 
-       // fallback so that parent always gets set to non-zero.
-
-       if(! $parent)
-               $parent = $post_id;
-
-       $r = q("UPDATE `item` SET `parent` = %d, `parent-uri` = '%s', `plink` = '%s', `changed` = '%s', `last-child` = 1, `visible` = 1
-               WHERE `id` = %d",
-               intval($parent),
-               dbesc(($parent == $post_id) ? $uri : $parent_item['uri']),
-               dbesc($a->get_baseurl().'/display/'.urlencode($datarray['guid'])),
-               dbesc(datetime_convert()),
-               intval($post_id)
-       );
-
-       // photo comments turn the corresponding item visible to the profile wall
-       // This way we don't see every picture in your new photo album posted to your wall at once.
-       // They will show up as people comment on them.
-
-       if(! $parent_item['visible']) {
-               $r = q("UPDATE `item` SET `visible` = 1 WHERE `id` = %d",
-                       intval($parent_item['id'])
-               );
-               update_thread($parent_item['id']);
-       }
-
-       // update the commented timestamp on the parent
-
-       q("UPDATE `item` set `commented` = '%s', `changed` = '%s' WHERE `id` = %d",
-               dbesc(datetime_convert()),
-               dbesc(datetime_convert()),
-               intval($parent)
-       );
-       if ($post_id != $parent)
-               update_thread($parent);
-
        call_hooks('post_local_end', $datarray);
 
        if(strlen($emailcc) && $profile_uid == local_user()) {
@@ -995,22 +1012,25 @@ function item_post(&$a) {
                }
        }
 
+       if ($post_id == $parent) {
+               add_thread($post_id);
+       } else {
+               update_thread($parent, true);
+       }
+
+       q("COMMIT");
+
        create_tags_from_item($post_id);
        create_files_from_item($post_id);
 
-       if ($post_id == $parent)
-               add_thread($post_id);
-
-       // This is a real juggling act on shared hosting services which kill your processes
-       // e.g. dreamhost. We used to start delivery to our native delivery agents in the background
-       // and then run our plugin delivery from the foreground. We're now doing plugin delivery first,
-       // because as soon as you start loading up a bunch of remote delivey processes, *this* page is
-       // likely to get killed off. If you end up looking at an /item URL and a blank page,
-       // it's very likely the delivery got killed before all your friends could be notified.
-       // Currently the only realistic fixes are to use a reliable server - which precludes shared hosting,
-       // or cut back on plugins which do remote deliveries.
+       // Insert an item entry for UID=0 for global entries.
+       // We now do it in the background to save some time.
+       // This is important in interactive environments like the frontend or the API.
+       // We don't fork a new process since this is done anyway with the following command
+       proc_run(array('priority' => PRIORITY_HIGH, 'dont_fork' => true), "include/create_shadowentry.php", $post_id);
 
-       proc_run('php', "include/notifier.php", $notify_type, "$post_id");
+       // Call the background process that is delivering the item to the receivers
+       proc_run(PRIORITY_HIGH, "include/notifier.php", $notify_type, $post_id);
 
        logger('post_complete');
 
@@ -1025,7 +1045,7 @@ function item_post_return($baseurl, $api_source, $return_path) {
                return;
 
        if($return_path) {
-               goaway($baseurl . "/" . $return_path);
+               goaway($return_path);
        }
 
        $json = array('success' => 1);
@@ -1064,10 +1084,11 @@ function item_content(&$a) {
  * the appropiate link.
  *
  * @param unknown_type $body the text to replace the tag in
- * @param unknown_type $inform a comma-seperated string containing everybody to inform
- * @param unknown_type $str_tags string to add the tag to
- * @param unknown_type $profile_uid
- * @param unknown_type $tag the tag to replace
+ * @param string $inform a comma-seperated string containing everybody to inform
+ * @param string $str_tags string to add the tag to
+ * @param integer $profile_uid
+ * @param string $tag the tag to replace
+ * @param string $network The network of the post
  *
  * @return boolean true if replaced, false if not replaced
  */
@@ -1092,7 +1113,17 @@ function handle_tag($a, &$body, &$inform, &$str_tags, $profile_uid, $tag, $netwo
                        // Checking for the alias that is used for OStatus
                        $pattern = "/@\[url\=(.*?)\](.*?)\[\/url\]/ism";
                        if (preg_match($pattern, $tag, $matches)) {
-                               $data = probe_url($matches[1]);
+
+                               $r = q("SELECT `alias`, `name` FROM `contact` WHERE `nurl` = '%s' AND `alias` != '' AND `uid` = 0",
+                                       normalise_link($matches[1]));
+                               if (!$r)
+                                       $r = q("SELECT `alias`, `name` FROM `gcontact` WHERE `nurl` = '%s' AND `alias` != ''",
+                                               normalise_link($matches[1]));
+                               if ($r)
+                                       $data = $r[0];
+                               else
+                                       $data = probe_url($matches[1]);
+
                                if ($data["alias"] != "") {
                                        $newtag = '@[url='.$data["alias"].']'.$data["name"].'[/url]';
                                        if(!stristr($str_tags,$newtag)) {
@@ -1119,33 +1150,47 @@ function handle_tag($a, &$body, &$inform, &$str_tags, $profile_uid, $tag, $netwo
                        // Is it in format @user@domain.tld or @http://domain.tld/...?
 
                        // First check the contact table for the address
-                       $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network`, `notify` FROM `contact` WHERE `addr` = '%s' AND `uid` = %d LIMIT 1",
+                       $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network`, `notify` FROM `contact`
+                               WHERE `addr` = '%s' AND `uid` = %d AND
+                                       (`network` != '%s' OR (`notify` != '' AND `alias` != ''))
+                               LIMIT 1",
                                        dbesc($name),
-                                       intval($profile_uid)
+                                       intval($profile_uid),
+                                       dbesc(NETWORK_OSTATUS)
                        );
 
                        // Then check in the contact table for the url
                        if (!$r)
-                               $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `notify`, `network` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
+                               $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network`, `notify` FROM `contact`
+                                       WHERE `nurl` = '%s' AND `uid` = %d AND
+                                               (`network` != '%s' OR (`notify` != '' AND `alias` != ''))
+                                       LIMIT 1",
                                                dbesc(normalise_link($name)),
-                                               intval($profile_uid)
+                                               intval($profile_uid),
+                                               dbesc(NETWORK_OSTATUS)
                                );
 
                        // Then check in the global contacts for the address
                        if (!$r)
-                               $r = q("SELECT `url`, `name`, `nick`, `network`, `alias`, `notify` FROM `gcontact` WHERE `addr` = '%s' LIMIT 1", dbesc($name));
+                               $r = q("SELECT `url`, `nick`, `name`, `alias`, `network`, `notify` FROM `gcontact`
+                                       WHERE `addr` = '%s' AND (`network` != '%s' OR (`notify` != '' AND `alias` != ''))
+                                       LIMIT 1",
+                                               dbesc($name),
+                                               dbesc(NETWORK_OSTATUS)
+                               );
 
                        // Then check in the global contacts for the url
                        if (!$r)
-                               $r = q("SELECT `url`, `name`, `nick`, `network`, `alias`, `notify` FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1", dbesc(normalise_link($name)));
-
-                       // If the data isn't complete then refetch the data
-                       if ($r AND ($r[0]["network"] == NETWORK_OSTATUS) AND (($r[0]["notify"] == "") OR ($r[0]["alias"] == "")))
-                               $r = false;
+                               $r = q("SELECT `url`, `nick`, `name`, `alias`, `network`, `notify` FROM `gcontact`
+                                       WHERE `nurl` = '%s' AND (`network` != '%s' OR (`notify` != '' AND `alias` != ''))
+                                       LIMIT 1",
+                                               dbesc(normalise_link($name)),
+                                               dbesc(NETWORK_OSTATUS)
+                               );
 
                        if (!$r) {
                                $probed = probe_url($name);
-                               if (isset($probed["url"])) {
+                               if ($result['network'] != NETWORK_PHANTOM) {
                                        update_gcontact($probed);
                                        $r = q("SELECT `url`, `name`, `nick`, `network`, `alias`, `notify` FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
                                                dbesc(normalise_link($probed["url"])));
@@ -1175,7 +1220,7 @@ function handle_tag($a, &$body, &$inform, &$str_tags, $profile_uid, $tag, $netwo
                        //select someone from this user's contacts by name in the current network
                        if (!$r AND ($network != ""))
                                $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network` FROM `contact` WHERE `name` = '%s' AND `network` = '%s' AND `uid` = %d LIMIT 1",
-                                               dbesc($newname),
+                                               dbesc($name),
                                                dbesc($network),
                                                intval($profile_uid)
                                );
@@ -1192,7 +1237,7 @@ function handle_tag($a, &$body, &$inform, &$str_tags, $profile_uid, $tag, $netwo
                        //select someone from this user's contacts by name
                        if(!$r)
                                $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network` FROM `contact` WHERE `name` = '%s' AND `uid` = %d LIMIT 1",
-                                               dbesc($newname),
+                                               dbesc($name),
                                                intval($profile_uid)
                                );
                }
@@ -1215,13 +1260,13 @@ function handle_tag($a, &$body, &$inform, &$str_tags, $profile_uid, $tag, $netwo
                }
 
                //if there is an url for this persons profile
-               if(isset($profile)) {
+               if (isset($profile) AND ($newname != "")) {
 
                        $replaced = true;
                        //create profile link
                        $profile = str_replace(',','%2c',$profile);
-                       $newtag = '@[url=' . $profile . ']' . $newname  . '[/url]';
-                       $body = str_replace('@' . $name, $newtag, $body);
+                       $newtag = '@[url='.$profile.']'.$newname.'[/url]';
+                       $body = str_replace('@'.$name, $newtag, $body);
                        //append tag to str_tags
                        if(! stristr($str_tags,$newtag)) {
                                if(strlen($str_tags))
@@ -1233,7 +1278,7 @@ function handle_tag($a, &$body, &$inform, &$str_tags, $profile_uid, $tag, $netwo
                        // subscribed to you. But the nickname URL is OK if they are. Grrr. We'll tag both.
 
                        if(strlen($alias)) {
-                               $newtag = '@[url=' . $alias . ']' . $newname    . '[/url]';
+                               $newtag = '@[url='.$alias.']'.$newname.'[/url]';
                                if(! stristr($str_tags,$newtag)) {
                                        if(strlen($str_tags))
                                                $str_tags .= ',';
@@ -1245,42 +1290,3 @@ function handle_tag($a, &$body, &$inform, &$str_tags, $profile_uid, $tag, $netwo
 
        return array('replaced' => $replaced, 'contact' => $r[0]);
 }
-
-
-function store_diaspora_comment_sig($datarray, $author, $uprvkey, $parent_item, $post_id) {
-       // We won't be able to sign Diaspora comments for authenticated visitors - we don't have their private key
-
-       $enabled = intval(get_config('system','diaspora_enabled'));
-       if(! $enabled) {
-               logger('mod_item: diaspora support disabled, not storing comment signature', LOGGER_DEBUG);
-               return;
-       }
-
-
-       logger('mod_item: storing diaspora comment signature');
-
-       require_once('include/bb2diaspora.php');
-       $signed_body = html_entity_decode(bb2diaspora($datarray['body']));
-
-       // Only works for NETWORK_DFRN
-       $contact_baseurl_start = strpos($author['url'],'://') + 3;
-       $contact_baseurl_length = strpos($author['url'],'/profile') - $contact_baseurl_start;
-       $contact_baseurl = substr($author['url'], $contact_baseurl_start, $contact_baseurl_length);
-       $diaspora_handle = $author['nick'] . '@' . $contact_baseurl;
-
-       $signed_text = $datarray['guid'] . ';' . $parent_item['guid'] . ';' . $signed_body . ';' . $diaspora_handle;
-
-       if( $uprvkey !== false )
-               $authorsig = rsa_sign($signed_text,$uprvkey,'sha256');
-       else
-               $authorsig = '';
-
-       q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
-               intval($post_id),
-               dbesc($signed_text),
-               dbesc(base64_encode($authorsig)),
-               dbesc($diaspora_handle)
-       );
-
-       return;
-}