]> git.mxchange.org Git - friendica.git/blobdiff - include/items.php
Merge pull request #837 from msjoberg/internal-push
[friendica.git] / include / items.php
index 54b392b3860f8c482adeadea6d67aa56df12c956..58768414356e4e79766630370e54bfddcac20d8f 100755 (executable)
@@ -8,6 +8,7 @@ require_once('include/Photo.php');
 require_once('include/tags.php');
 require_once('include/text.php');
 require_once('include/email.php');
+require_once('include/ostatus_conversation.php');
 
 function get_feed_for(&$a, $dfrn_id, $owner_nick, $last_update, $direction = 0) {
 
@@ -293,7 +294,7 @@ function construct_activity_target($item) {
 if(! function_exists('limit_body_size')) {
 function limit_body_size($body) {
 
-       logger('limit_body_size: start', LOGGER_DEBUG);
+//     logger('limit_body_size: start', LOGGER_DEBUG);
 
        $maxlen = get_max_import_size();
 
@@ -810,7 +811,7 @@ function get_atom_elements($feed,$item) {
                if (($name != "") and ($uri != "") and ($avatar != "") and ($message != "")) {
                        logger('get_atom_elements: fixing sender of repeated message.');
 
-                       if (intval(get_config('system','new_share'))) {
+                       if (!intval(get_config('system','wall-to-wall_share'))) {
                                $prefix = "[share author='".str_replace("'", "'",$name).
                                                "' profile='".$uri.
                                                "' avatar='".$avatar.
@@ -831,15 +832,30 @@ function get_atom_elements($feed,$item) {
                }
        }
 
+       // Search for ostatus conversation url
+       $links = $item->feed->data["child"][SIMPLEPIE_NAMESPACE_ATOM_10]["feed"][0]["child"][SIMPLEPIE_NAMESPACE_ATOM_10]["entry"][0]["child"]["http://www.w3.org/2005/Atom"]["link"];
+
+       if (is_array($links)) {
+               foreach ($links as $link) {
+                       $conversation = array_shift($link["attribs"]);
+
+                       if ($conversation["rel"] == "ostatus:conversation") {
+                               $res["ostatus_conversation"] = $conversation["href"];
+                               logger('get_atom_elements: found conversation url '.$res["ostatus_conversation"]);
+                       }
+               };
+       }
+
        $arr = array('feed' => $feed, 'item' => $item, 'result' => $res);
 
        call_hooks('parse_atom', $arr);
 
        //if (($res["title"] != "") or (strpos($res["body"], "RT @") > 0)) {
        //if (strpos($res["body"], "RT @") !== false) {
-       //      $debugfile = tempnam("/home/ike/log", "item-res2-");
-       //      file_put_contents($debugfile, serialize($arr));
-       //}
+       /*if (strpos($res["body"], "@") !== false) {
+               $debugfile = tempnam("/var/www/virtual/pirati.ca/phptmp/", "item-res2-");
+               file_put_contents($debugfile, serialize($arr));
+       }*/
 
        return $res;
 }
@@ -878,6 +894,15 @@ function item_store($arr,$force_parent = false) {
                unset($arr['dsprsig']);
        }
 
+       // if an OStatus conversation url was passed in, it is stored and then
+       // removed from the array.
+       $ostatus_conversation = null;
+
+       if (isset($arr["ostatus_conversation"])) {
+               $ostatus_conversation = $arr["ostatus_conversation"];
+               unset($arr["ostatus_conversation"]);
+       }
+
        if(x($arr, 'gravity'))
                $arr['gravity'] = intval($arr['gravity']);
        elseif($arr['parent-uri'] === $arr['uri'])
@@ -958,7 +983,23 @@ function item_store($arr,$force_parent = false) {
        $arr['app']           = ((x($arr,'app'))           ? notags(trim($arr['app']))           : '');
        $arr['origin']        = ((x($arr,'origin'))        ? intval($arr['origin'])              : 0 );
        $arr['guid']          = ((x($arr,'guid'))          ? notags(trim($arr['guid']))          : get_guid());
+       $arr['network']       = ((x($arr,'network'))       ? trim($arr['network'])               : '');
+
+       if ($arr['network'] == "") {
+               $r = q("SELECT `network` FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
+                       intval($arr['contact-id']),
+                       intval($arr['uid'])
+               );
 
+               if(count($r))
+                       $arr['network'] = $r[0]["network"];
+
+               // Fallback to friendica (why is it empty in some cases?)
+               if ($arr['network'] == "")
+                       $arr['network'] = NETWORK_DFRN;
+
+               logger("item_store: Set network to ".$arr["network"]." for ".$arr["uri"], LOGGER_DEBUG);
+       }
 
        $arr['thr-parent'] = $arr['parent-uri'];
        if($arr['parent-uri'] === $arr['uri']) {
@@ -969,9 +1010,9 @@ function item_store($arr,$force_parent = false) {
                $deny_cid  = $arr['deny_cid'];
                $deny_gid  = $arr['deny_gid'];
        }
-       else { 
+       else {
 
-               // find the parent and snarf the item id and ACL's
+               // find the parent and snarf the item id and ACLs
                // and anything else we need to inherit
 
                $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d ORDER BY `id` ASC LIMIT 1",
@@ -1100,7 +1141,7 @@ function item_store($arr,$force_parent = false) {
        // Set parent id - and also make sure to inherit the parent's ACL's.
 
        $r = q("UPDATE `item` SET `parent` = %d, `allow_cid` = '%s', `allow_gid` = '%s',
-               `deny_cid` = '%s', `deny_gid` = '%s', `private` = %d, `deleted` = %d WHERE `id` = %d LIMIT 1",
+               `deny_cid` = '%s', `deny_gid` = '%s', `private` = %d, `deleted` = %d WHERE `id` = %d",
                intval($parent_id),
                dbesc($allow_cid),
                dbesc($allow_gid),
@@ -1112,6 +1153,10 @@ function item_store($arr,$force_parent = false) {
        );
        create_tags_from_item($current_post);
 
+       // Complete ostatus threads
+       if ($ostatus_conversation)
+               complete_conversation($current_post, $ostatus_conversation);
+
         $arr['id'] = $current_post;
         $arr['parent'] = $parent_id;
         $arr['allow_cid'] = $allow_cid;
@@ -1120,11 +1165,10 @@ function item_store($arr,$force_parent = false) {
         $arr['deny_gid'] = $deny_gid;
         $arr['private'] = $private;
         $arr['deleted'] = $parent_deleted;
-       call_hooks('post_remote_end',$arr);
 
        // update the commented timestamp on the parent
 
-       q("UPDATE `item` set `commented` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
+       q("UPDATE `item` set `commented` = '%s', `changed` = '%s' WHERE `id` = %d",
                dbesc(datetime_convert()),
                dbesc(datetime_convert()),
                intval($parent_id)
@@ -1152,17 +1196,32 @@ function item_store($arr,$force_parent = false) {
                );
        }
 
-       tag_deliver($arr['uid'],$current_post);
+       $deleted = tag_deliver($arr['uid'],$current_post);
+
+       // current post can be deleted if is for a communuty page and no mention are
+       // in it.
+       if (!$deleted) {
+               
+               // Store the fresh generated item into the cache
+               $cachefile = get_cachefile($arr["guid"]."-".hash("md5", $arr['body']));
 
-       // Store the fresh generated item into the cache
-       $cachefile = get_cachefile($arr["guid"]."-".hash("md5", $arr['body']));
+               if (($cachefile != '') AND !file_exists($cachefile)) {
+                       $s = prepare_text($arr['body']);
+                       $a = get_app();
+                       $stamp1 = microtime(true);
+                       file_put_contents($cachefile, $s);
+                       $a->save_timestamp($stamp1, "file");
+                       logger('item_store: put item '.$current_post.' into cachefile '.$cachefile);
+               }
 
-       if (($cachefile != '') AND !file_exists($cachefile)) {
-               $s = prepare_text($arr['body']);
-               file_put_contents($cachefile, $s);
-               logger('item_store: put item '.$current_post.' into cachefile '.$cachefile);
+        $r = q('SELECT * FROM `item` WHERE id = %d', intval($current_post));
+        if (count($r) == 1) {
+            call_hooks('post_remote_end', $r[0]);
+        }
+        else {
+            logger('item_store: new item not found in DB, id ' . $current_post);
+        }
        }
-
        return $current_post;
 }
 
@@ -1178,10 +1237,15 @@ function get_item_contact($item,$contacts) {
        return false;
 }
 
-
+/**
+ * look for mention tags and setup a second delivery chain for forum/community posts if appropriate
+ * @param int $uid
+ * @param int $item_id
+ * @return bool true if item was deleted, else false
+ */
 function tag_deliver($uid,$item_id) {
 
-       // look for mention tags and setup a second delivery chain for forum/community posts if appropriate
+       // 
 
        $a = get_app();
 
@@ -1223,8 +1287,21 @@ function tag_deliver($uid,$item_id) {
                }
        }
 
-       if(! $mention)
+       if(! $mention){
+               if ( ($community_page || $prvgroup) &&
+                         (!$item['wall']) && (!$item['origin']) && ($item['id'] == $item['parent'])){
+                       // mmh.. no mention.. community page or private group... no wall.. no origin.. top-post (not a comment)
+                       // delete it!
+                       logger("tag_deliver: no-mention top-level post to communuty or private group. delete.");
+                       q("DELETE FROM item WHERE id = %d and uid = %d",
+                               intval($item_id),
+                               intval($uid)
+                       );
+                       return true;
+               }
                return;
+       }
+
 
        // send a notification
 
@@ -1285,8 +1362,8 @@ function tag_deliver($uid,$item_id) {
 
        $forum_mode = (($prvgroup) ? 2 : 1);
 
-       q("update item set wall = 1, origin = 1, forum_mode = %d, `owner-name` = '%s', `owner-link` = '%s', `owner-avatar` = '%s', 
-               `private` = %d, `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s'  where id = %d limit 1",
+       q("update item set wall = 1, origin = 1, forum_mode = %d, `owner-name` = '%s', `owner-link` = '%s', `owner-avatar` = '%s',
+               `private` = %d, `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s'  where id = %d",
                intval($forum_mode),
                dbesc($c[0]['name']),
                dbesc($c[0]['url']),
@@ -1437,7 +1514,7 @@ function dfrn_deliver($owner,$contact,$atom, $dissolve = false) {
        if($perm) {
                if((($perm == 'rw') && (! intval($contact['writable']))) 
                || (($perm == 'r') && (intval($contact['writable'])))) {
-                       q("update contact set writable = %d where id = %d limit 1",
+                       q("update contact set writable = %d where id = %d",
                                intval(($perm == 'rw') ? 1 : 0),
                                intval($contact['id'])
                        );
@@ -1550,6 +1627,26 @@ function dfrn_deliver($owner,$contact,$atom, $dissolve = false) {
 }
 
 
+/*
+  This function returns true if $update has an edited timestamp newer
+  than $existing, i.e. $update contains new data which should override
+  what's already there.  If there is no timestamp yet, the update is
+  assumed to be newer.  If the update has no timestamp, the existing
+  item is assumed to be up-to-date.  If the timestamps are equal it
+  assumes the update has been seen before and should be ignored.
+  */
+function edited_timestamp_is_newer($existing, $update) {
+    if (!x($existing,'edited') || !$existing['edited']) {
+        return true;
+    }
+    if (!x($update,'edited') || !$update['edited']) {
+        return false;
+    }
+    $existing_edited = datetime_convert('UTC', 'UTC', $existing['edited']);
+    $update_edited = datetime_convert('UTC', 'UTC', $update['edited']);
+    return (strcmp($existing_edited, $update_edited) < 0);
+}
+
 /**
  *
  * consume_feed - process atom feed and update anything/everything we might need to update
@@ -1649,12 +1746,12 @@ function consume_feed($xml,$importer,&$contact, &$hub, $datedir = 0, $pass = 0)
                else {
                        $resource_id = photo_new_resource();
                }
-                       
+
                $img_str = fetch_url($photo_url,true);
                // guess mimetype from headers or filename
                $type = guess_image_type($photo_url,true);
-               
-               
+
+
                $img = new Photo($img_str, $type);
                if($img->is_valid()) {
                        if($have_photo) {
@@ -1679,7 +1776,7 @@ function consume_feed($xml,$importer,&$contact, &$hub, $datedir = 0, $pass = 0)
                        $a = get_app();
 
                        q("UPDATE `contact` SET `avatar-date` = '%s', `photo` = '%s', `thumb` = '%s', `micro` = '%s'
-                               WHERE `uid` = %d AND `id` = %d LIMIT 1",
+                               WHERE `uid` = %d AND `id` = %d",
                                dbesc(datetime_convert()),
                                dbesc($a->get_baseurl() . '/photo/' . $hash . '-4.'.$img->getExt()),
                                dbesc($a->get_baseurl() . '/photo/' . $hash . '-5.'.$img->getExt()),
@@ -1696,7 +1793,7 @@ function consume_feed($xml,$importer,&$contact, &$hub, $datedir = 0, $pass = 0)
                        intval($contact['id'])
                );
 
-               $x = q("UPDATE `contact` SET `name` = '%s', `name-date` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
+               $x = q("UPDATE `contact` SET `name` = '%s', `name-date` = '%s' WHERE `uid` = %d AND `id` = %d",
                        dbesc(notags(trim($new_name))),
                        dbesc(datetime_convert()),
                        intval($contact['uid']),
@@ -1749,7 +1846,7 @@ function consume_feed($xml,$importer,&$contact, &$hub, $datedir = 0, $pass = 0)
 
                        // update bdyear
 
-                       q("UPDATE `contact` SET `bdyear` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
+                       q("UPDATE `contact` SET `bdyear` = '%s' WHERE `uid` = %d AND `id` = %d",
                                dbesc(substr($birthday,0,4)),
                                intval($contact['uid']),
                                intval($contact['id'])
@@ -1770,7 +1867,7 @@ function consume_feed($xml,$importer,&$contact, &$hub, $datedir = 0, $pass = 0)
                $community_page = intval($rawtags[0]['data']);
        }
        if(is_array($contact) && intval($contact['forum']) != $community_page) {
-               q("update contact set forum = %d where id = %d limit 1",
+               q("update contact set forum = %d where id = %d",
                        intval($community_page),
                        intval($contact['id'])
                );
@@ -1833,7 +1930,7 @@ function consume_feed($xml,$importer,&$contact, &$hub, $datedir = 0, $pass = 0)
                                                                                        if(trim($tag) !== trim($xo->body))
                                                                                                $newtags[] = trim($tag);
                                                                        }
-                                                                       q("update item set tag = '%s' where id = %d limit 1",
+                                                                       q("update item set tag = '%s' where id = %d",
                                                                                dbesc(implode(',',$newtags)),
                                                                                intval($i[0]['id'])
                                                                        );
@@ -1857,7 +1954,7 @@ function consume_feed($xml,$importer,&$contact, &$hub, $datedir = 0, $pass = 0)
                                        else {
                                                $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
                                                        `body` = '', `title` = '' 
-                                                       WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
+                                                       WHERE `uri` = '%s' AND `uid` = %d",
                                                        dbesc($when),
                                                        dbesc(datetime_convert()),
                                                        dbesc($uri),
@@ -1871,20 +1968,20 @@ function consume_feed($xml,$importer,&$contact, &$hub, $datedir = 0, $pass = 0)
                                                                dbesc($item['parent-uri']),
                                                                intval($item['uid'])
                                                        );
-                                                       // who is the last child now? 
-                                                       $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `moderated` = 0 AND `uid` = %d 
+                                                       // who is the last child now?
+                                                       $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `moderated` = 0 AND `uid` = %d
                                                                ORDER BY `created` DESC LIMIT 1",
                                                                        dbesc($item['parent-uri']),
                                                                        intval($importer['uid'])
                                                        );
                                                        if(count($r)) {
-                                                               q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
+                                                               q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d",
                                                                        intval($r[0]['id'])
                                                                );
                                                        }
-                                               }       
+                                               }
                                        }
-                               }       
+                               }
                        }
                }
        }
@@ -1963,13 +2060,13 @@ function consume_feed($xml,$importer,&$contact, &$hub, $datedir = 0, $pass = 0)
                                // Update content if 'updated' changes
 
                                if(count($r)) {
-                                       if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {  
+                                       if (edited_timestamp_is_newer($r[0], $datarray)) {
 
                                                // do not accept (ignore) an earlier edit than one we currently have.
                                                if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
                                                        continue;
 
-                                               $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
+                                               $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d",
                                                        dbesc($datarray['title']),
                                                        dbesc($datarray['body']),
                                                        dbesc($datarray['tag']),
@@ -1989,7 +2086,7 @@ function consume_feed($xml,$importer,&$contact, &$hub, $datedir = 0, $pass = 0)
                                                        dbesc($parent_uri),
                                                        intval($importer['uid'])
                                                );
-                                               $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s'  WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
+                                               $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s'  WHERE `uri` = '%s' AND `uid` = %d",
                                                        intval($allow[0]['data']),
                                                        dbesc(datetime_convert()),
                                                        dbesc($item_id),
@@ -2038,7 +2135,7 @@ function consume_feed($xml,$importer,&$contact, &$hub, $datedir = 0, $pass = 0)
                                                if($xo->id && $xo->content) {
                                                        $newtag = '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
                                                        if(! (stristr($r[0]['tag'],$newtag))) {
-                                                               q("UPDATE item SET tag = '%s' WHERE id = %d LIMIT 1",
+                                                               q("UPDATE item SET tag = '%s' WHERE id = %d",
                                                                        dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . $newtag),
                                                                        intval($r[0]['id'])
                                                                );
@@ -2112,13 +2209,13 @@ function consume_feed($xml,$importer,&$contact, &$hub, $datedir = 0, $pass = 0)
                                // Update content if 'updated' changes
 
                                if(count($r)) {
-                                       if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {  
+                                       if (edited_timestamp_is_newer($r[0], $datarray)) {  
 
                                                // do not accept (ignore) an earlier edit than one we currently have.
                                                if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
                                                        continue;
 
-                                               $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
+                                               $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d",
                                                        dbesc($datarray['title']),
                                                        dbesc($datarray['body']),
                                                        dbesc($datarray['tag']),
@@ -2133,7 +2230,7 @@ function consume_feed($xml,$importer,&$contact, &$hub, $datedir = 0, $pass = 0)
 
                                        $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
                                        if($allow && $allow[0]['data'] != $r[0]['last-child']) {
-                                               $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
+                                               $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d",
                                                        intval($allow[0]['data']),
                                                        dbesc(datetime_convert()),
                                                        dbesc($item_id),
@@ -2288,12 +2385,12 @@ function local_delivery($importer,$data) {
                else {
                        $resource_id = photo_new_resource();
                }
-                       
+
                $img_str = fetch_url($photo_url,true);
                // guess mimetype from headers or filename
                $type = guess_image_type($photo_url,true);
-               
-               
+
+
                $img = new Photo($img_str, $type);
                if($img->is_valid()) {
                        if($have_photo) {
@@ -2318,7 +2415,7 @@ function local_delivery($importer,$data) {
                        $a = get_app();
 
                        q("UPDATE `contact` SET `avatar-date` = '%s', `photo` = '%s', `thumb` = '%s', `micro` = '%s'
-                               WHERE `uid` = %d AND `id` = %d LIMIT 1",
+                               WHERE `uid` = %d AND `id` = %d",
                                dbesc(datetime_convert()),
                                dbesc($a->get_baseurl() . '/photo/' . $hash . '-4.'.$img->getExt()),
                                dbesc($a->get_baseurl() . '/photo/' . $hash . '-5.'.$img->getExt()),
@@ -2335,7 +2432,7 @@ function local_delivery($importer,$data) {
                        intval($importer['id'])
                );
 
-               $x = q("UPDATE `contact` SET `name` = '%s', `name-date` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
+               $x = q("UPDATE `contact` SET `name` = '%s', `name-date` = '%s' WHERE `uid` = %d AND `id` = %d",
                        dbesc(notags(trim($new_name))),
                        dbesc(datetime_convert()),
                        intval($importer['importer_uid']),
@@ -2594,7 +2691,7 @@ function local_delivery($importer,$data) {
                $community_page = intval($rawtags[0]['data']);
        }
        if(intval($importer['forum']) != $community_page) {
-               q("update contact set forum = %d where id = %d limit 1",
+               q("update contact set forum = %d where id = %d",
                        intval($community_page),
                        intval($importer['id'])
                );
@@ -2623,7 +2720,7 @@ function local_delivery($importer,$data) {
 
                                // check for relayed deletes to our conversation
 
-                               $is_reply = false;              
+                               $is_reply = false;
                                $r = q("select * from item where uri = '%s' and uid = %d limit 1",
                                        dbesc($uri),
                                        intval($importer['importer_uid'])
@@ -2632,7 +2729,7 @@ function local_delivery($importer,$data) {
                                        $parent_uri = $r[0]['parent-uri'];
                                        if($r[0]['id'] != $r[0]['parent'])
                                                $is_reply = true;
-                               }                               
+                               }
 
                                if($is_reply) {
                                        $community = false;
@@ -2725,7 +2822,7 @@ function local_delivery($importer,$data) {
                                                                                        if(trim($tag) !== trim($xo->body))
                                                                                                $newtags[] = trim($tag);
                                                                        }
-                                                                       q("update item set tag = '%s' where id = %d limit 1",
+                                                                       q("update item set tag = '%s' where id = %d",
                                                                                dbesc(implode(',',$newtags)),
                                                                                intval($i[0]['id'])
                                                                        );
@@ -2749,7 +2846,7 @@ function local_delivery($importer,$data) {
                                        else {
                                                $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
                                                        `body` = '', `title` = ''
-                                                       WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
+                                                       WHERE `uri` = '%s' AND `uid` = %d",
                                                        dbesc($when),
                                                        dbesc(datetime_convert()),
                                                        dbesc($uri),
@@ -2770,7 +2867,7 @@ function local_delivery($importer,$data) {
                                                                        intval($importer['importer_uid'])
                                                        );
                                                        if(count($r)) {
-                                                               q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
+                                                               q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d",
                                                                        intval($r[0]['id'])
                                                                );
                                                        }
@@ -2806,13 +2903,13 @@ function local_delivery($importer,$data) {
                        }
                        else
                                $sql_extra = " and contact.self = 1 and item.wall = 1 ";
-                       // was the top-level post for this reply written by somebody on this site? 
-                       // Specifically, the recipient? 
+
+                       // was the top-level post for this reply written by somebody on this site?
+                       // Specifically, the recipient?
 
                        $is_a_remote_comment = false;
                        $top_uri = $parent_uri;
-                       
+
                        $r = q("select `item`.`parent-uri` from `item`
                                WHERE `item`.`uri` = '%s'
                                LIMIT 1",
@@ -2822,11 +2919,11 @@ function local_delivery($importer,$data) {
                                $top_uri = $r[0]['parent-uri'];
 
                                // POSSIBLE CLEANUP --> Why select so many fields when only forum_mode and wall are used?
-                               $r = q("select `item`.`id`, `item`.`uri`, `item`.`tag`, `item`.`forum_mode`,`item`.`origin`,`item`.`wall`, 
-                                       `contact`.`name`, `contact`.`url`, `contact`.`thumb` from `item` 
-                                       LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id` 
+                               $r = q("select `item`.`id`, `item`.`uri`, `item`.`tag`, `item`.`forum_mode`,`item`.`origin`,`item`.`wall`,
+                                       `contact`.`name`, `contact`.`url`, `contact`.`thumb` from `item`
+                                       LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
                                        WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' or `item`.`thr-parent` = '%s')
-                                       AND `item`.`uid` = %d 
+                                       AND `item`.`uid` = %d
                                        $sql_extra
                                        LIMIT 1",
                                        dbesc($top_uri),
@@ -2866,14 +2963,14 @@ function local_delivery($importer,$data) {
 
                                if(count($r)) {
                                        $iid = $r[0]['id'];
-                                       if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
+                                       if (edited_timestamp_is_newer($r[0], $datarray)) {
 
                                                // do not accept (ignore) an earlier edit than one we currently have.
                                                if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
                                                        continue;
 
                                                logger('received updated comment' , LOGGER_DEBUG);
-                                               $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
+                                               $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d",
                                                        dbesc($datarray['title']),
                                                        dbesc($datarray['body']),
                                                        dbesc($datarray['tag']),
@@ -2949,7 +3046,7 @@ function local_delivery($importer,$data) {
                                                                        intval($importer['importer_uid'])
                                                                );
                                                                if(count($i) && ! intval($i[0]['blocktags'])) {
-                                                                       q("UPDATE item SET tag = '%s', `edited` = '%s' WHERE id = %d LIMIT 1",
+                                                                       q("UPDATE item SET tag = '%s', `edited` = '%s' WHERE id = %d",
                                                                                dbesc($tagp[0]['tag'] . (strlen($tagp[0]['tag']) ? ',' : '') . $newtag),
                                                                                intval($tagp[0]['id']),
                                                                                dbesc(datetime_convert())
@@ -2982,7 +3079,7 @@ function local_delivery($importer,$data) {
                                                        intval($r[0]['parent'])
                                                );
 
-                                               $r2 = q("UPDATE `item` SET `last-child` = 1, `changed` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
+                                               $r2 = q("UPDATE `item` SET `last-child` = 1, `changed` = '%s' WHERE `uid` = %d AND `id` = %d",
                                                        dbesc(datetime_convert()),
                                                        intval($importer['importer_uid']),
                                                        intval($posted_id)
@@ -3041,13 +3138,13 @@ function local_delivery($importer,$data) {
                                // Update content if 'updated' changes
 
                                if(count($r)) {
-                                       if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {  
+                                       if (edited_timestamp_is_newer($r[0], $datarray)) {
 
                                                // do not accept (ignore) an earlier edit than one we currently have.
                                                if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
                                                        continue;
 
-                                               $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
+                                               $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d",
                                                        dbesc($datarray['title']),
                                                        dbesc($datarray['body']),
                                                        dbesc($datarray['tag']),
@@ -3067,7 +3164,7 @@ function local_delivery($importer,$data) {
                                                        dbesc($parent_uri),
                                                        intval($importer['importer_uid'])
                                                );
-                                               $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s'  WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
+                                               $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s'  WHERE `uri` = '%s' AND `uid` = %d",
                                                        intval($allow[0]['data']),
                                                        dbesc(datetime_convert()),
                                                        dbesc($item_id),
@@ -3112,7 +3209,7 @@ function local_delivery($importer,$data) {
                                                // extract tag, if not duplicate, add to parent item
                                                if($xo->content) {
                                                        if(! (stristr($r[0]['tag'],trim($xo->content)))) {
-                                                               q("UPDATE item SET tag = '%s' WHERE id = %d LIMIT 1",
+                                                               q("UPDATE item SET tag = '%s' WHERE id = %d",
                                                                        dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]'),
                                                                        intval($r[0]['id'])
                                                                );
@@ -3217,13 +3314,13 @@ function local_delivery($importer,$data) {
                        // Update content if 'updated' changes
 
                        if(count($r)) {
-                               if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {  
+                               if (edited_timestamp_is_newer($r[0], $datarray)) {
 
                                        // do not accept (ignore) an earlier edit than one we currently have.
                                        if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
                                                continue;
 
-                                       $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
+                                       $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d",
                                                dbesc($datarray['title']),
                                                dbesc($datarray['body']),
                                                dbesc($datarray['tag']),
@@ -3238,7 +3335,7 @@ function local_delivery($importer,$data) {
 
                                $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
                                if($allow && $allow[0]['data'] != $r[0]['last-child']) {
-                                       $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
+                                       $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d",
                                                intval($allow[0]['data']),
                                                dbesc(datetime_convert()),
                                                dbesc($item_id),
@@ -3346,7 +3443,7 @@ function new_follower($importer,$contact,$datarray,$item,$sharing = false) {
        if(is_array($contact)) {
                if(($contact['network'] == NETWORK_OSTATUS && $contact['rel'] == CONTACT_IS_SHARING)
                        || ($sharing && $contact['rel'] == CONTACT_IS_FOLLOWER)) {
-                       $r = q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d LIMIT 1",
+                       $r = q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
                                intval(CONTACT_IS_FRIEND),
                                intval($contact['id']),
                                intval($importer['uid'])
@@ -3425,7 +3522,7 @@ function new_follower($importer,$contact,$datarray,$item,$sharing = false) {
 function lose_follower($importer,$contact,$datarray,$item) {
 
        if(($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_SHARING)) {
-               q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d LIMIT 1",
+               q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d",
                        intval(CONTACT_IS_SHARING),
                        intval($contact['id'])
                );
@@ -3438,7 +3535,7 @@ function lose_follower($importer,$contact,$datarray,$item) {
 function lose_sharer($importer,$contact,$datarray,$item) {
 
        if(($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_FOLLOWER)) {
-               q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d LIMIT 1",
+               q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d",
                        intval(CONTACT_IS_FOLLOWER),
                        intval($contact['id'])
                );
@@ -3477,7 +3574,7 @@ function subscribe_to_hub($url,$importer,$contact,$hubmode = 'subscribe') {
        logger('subscribe_to_hub: ' . $hubmode . ' ' . $contact['name'] . ' to hub ' . $url . ' endpoint: '  . $push_url . ' with verifier ' . $verify_token);
 
        if(! strlen($contact['hub-verify'])) {
-               $r = q("UPDATE `contact` SET `hub-verify` = '%s' WHERE `id` = %d LIMIT 1",
+               $r = q("UPDATE `contact` SET `hub-verify` = '%s' WHERE `id` = %d",
                        dbesc($verify_token),
                        intval($contact['id'])
                );
@@ -3612,9 +3709,13 @@ function atom_entry($item,$type,$author,$owner,$comment = false,$cid = 0) {
 }
 
 function fix_private_photos($s, $uid, $item = null, $cid = 0) {
+
+       if(get_config('system','disable_embedded'))
+               return $s;
+
        $a = get_app();
 
-       logger('fix_private_photos', LOGGER_DEBUG);
+       logger('fix_private_photos: check for photos', LOGGER_DEBUG);
        $site = substr($a->get_baseurl(),strpos($a->get_baseurl(),'://'));
 
        $orig_body = $s;
@@ -3635,7 +3736,7 @@ function fix_private_photos($s, $uid, $item = null, $cid = 0) {
                        // Only embed locally hosted photos
                        $replace = false;
                        $i = basename($image);
-                       $i = str_replace(array('.jpg','.png'),array('',''),$i);
+                       $i = str_replace(array('.jpg','.png','.gif'),array('','',''),$i);
                        $x = strpos($i,'-');
 
                        if($x) {
@@ -3646,7 +3747,7 @@ function fix_private_photos($s, $uid, $item = null, $cid = 0) {
                                        intval($res),
                                        intval($uid)
                                );
-                               if(count($r)) {
+                               if($r) {
 
                                        // Check to see if we should replace this photo link with an embedded image
                                        // 1. No need to do so if the photo is public
@@ -3915,10 +4016,38 @@ function drop_item($id,$interactive = true) {
 
        if((local_user() == $item['uid']) || ($cid) || (! $interactive)) {
 
+               // Check if we should do HTML-based delete confirmation
+               if($_REQUEST['confirm']) {
+                       // <form> can't take arguments in its "action" parameter
+                       // so add any arguments as hidden inputs
+                       $query = explode_querystring($a->query_string);
+                       $inputs = array();
+                       foreach($query['args'] as $arg) {
+                               if(strpos($arg, 'confirm=') === false) {
+                                       $arg_parts = explode('=', $arg);
+                                       $inputs[] = array('name' => $arg_parts[0], 'value' => $arg_parts[1]);
+                               }
+                       }
+
+                       return replace_macros(get_markup_template('confirm.tpl'), array(
+                               '$method' => 'get',
+                               '$message' => t('Do you really want to delete this item?'),
+                               '$extra_inputs' => $inputs,
+                               '$confirm' => t('Yes'),
+                               '$confirm_url' => $query['base'],
+                               '$confirm_name' => 'confirmed',
+                               '$cancel' => t('Cancel'),
+                       ));
+               }
+               // Now check how the user responded to the confirmation query
+               if($_REQUEST['canceled']) {
+                       goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
+               }
+
                logger('delete item: ' . $item['id'], LOGGER_DEBUG);
                // delete the item
 
-               $r = q("UPDATE `item` SET `deleted` = 1, `title` = '', `body` = '', `edited` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
+               $r = q("UPDATE `item` SET `deleted` = 1, `title` = '', `body` = '', `edited` = '%s', `changed` = '%s' WHERE `id` = %d",
                        dbesc(datetime_convert()),
                        dbesc(datetime_convert()),
                        intval($item['id'])
@@ -3960,7 +4089,7 @@ function drop_item($id,$interactive = true) {
                // If item is a link to an event, nuke the event record.
 
                if(intval($item['event-id'])) {
-                       q("DELETE FROM `event` WHERE `id` = %d AND `uid` = %d LIMIT 1",
+                       q("DELETE FROM `event` WHERE `id` = %d AND `uid` = %d",
                                intval($item['event-id']),
                                intval($item['uid'])
                        );
@@ -3969,6 +4098,9 @@ function drop_item($id,$interactive = true) {
 
                // clean up item_id and sign meta-data tables
 
+               /*
+               // Old code - caused very long queries and warning entries in the mysql logfiles:
+
                $r = q("DELETE FROM item_id where iid in (select id from item where parent = %d and uid = %d)",
                        intval($item['id']),
                        intval($item['uid'])
@@ -3978,6 +4110,31 @@ function drop_item($id,$interactive = true) {
                        intval($item['id']),
                        intval($item['uid'])
                );
+               */
+
+               // The new code splits the queries since the mysql optimizer really has bad problems with subqueries
+
+               // Creating list of parents
+               $r = q("select id from item where parent = %d and uid = %d",
+                       intval($item['id']),
+                       intval($item['uid'])
+               );
+
+               $parentid = "";
+
+               foreach ($r AS $row) {
+                       if ($parentid != "")
+                               $parentid .= ", ";
+
+                       $parentid .= $row["id"];
+               }
+
+               // Now delete them
+               if ($parentid != "") {
+                       $r = q("DELETE FROM item_id where iid in (%s)", dbesc($parentid));
+
+                       $r = q("DELETE FROM sign where iid in (%s)", dbesc($parentid));
+               }
 
                // If it's the parent of a comment thread, kill all the kids
 
@@ -4005,7 +4162,7 @@ function drop_item($id,$interactive = true) {
                                intval($item['uid'])
                        );
                        if(count($r)) {
-                               q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
+                               q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d",
                                        intval($r[0]['id'])
                                );
                        }