From f2efd583669c095db8df6153a2ad429972f55662 Mon Sep 17 00:00:00 2001
From: Michael <heluecht@pirati.ca>
Date: Sun, 7 Jan 2018 11:08:36 +0000
Subject: [PATCH 1/6] Sends notifications for public posts with "uid=0"

---
 include/enotify.php | 33 ++++++++++++++++++++++-----------
 include/items.php   |  2 +-
 mod/item.php        |  2 ++
 3 files changed, 25 insertions(+), 12 deletions(-)

diff --git a/include/enotify.php b/include/enotify.php
index 58f40fe2dd..bccc5a9bed 100644
--- a/include/enotify.php
+++ b/include/enotify.php
@@ -106,9 +106,8 @@ function notification($params)
 	}
 
 	if ($params['type'] == NOTIFY_COMMENT) {
-		$p = q("SELECT `ignored` FROM `thread` WHERE `iid` = %d AND `uid` = %d LIMIT 1",
-			intval($parent_id),
-			intval($params['uid'])
+		$p = q("SELECT `ignored` FROM `thread` WHERE `iid` = %d LIMIT 1",
+			intval($parent_id)
 		);
 		if ($p && count($p) && ($p[0]["ignored"])) {
 			logger("Thread ".$parent_id." will be ignored", LOGGER_DEBUG);
@@ -134,9 +133,8 @@ function notification($params)
 		$p = null;
 
 		if ($params['otype'] === 'item' && $parent_id) {
-			$p = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
-				intval($parent_id),
-				intval($params['uid'])
+			$p = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1",
+				intval($parent_id)
 			);
 		}
 
@@ -648,6 +646,20 @@ function notification($params)
 	return false;
 }
 
+/**
+ * @brief Checks for users who should be notified
+ *
+ * @param int $itemid ID of the item for which the check should be done
+ */
+function check_user_notification($itemid) {
+	// fetch all users in the thread
+	$users = dba::p("SELECT DISTINCT(`uid`) FROM `item` WHERE `parent` IN (SELECT `parent` FROM `item` WHERE `id`=?) AND `uid` != 0", $itemid);
+	while ($user = dba::fetch($users)) {
+		check_item_notification($itemid, $user['uid']);
+	}
+	dba::close($users);
+}
+
 /**
  * @brief Checks for item related notifications and sends them
  *
@@ -735,9 +747,8 @@ function check_item_notification($itemid, $uid, $defaulttype = "") {
 
 	if ($item[0]["parent-uri"] === $item[0]["uri"]) {
 		// Send a notification for every new post?
-		$r = q("SELECT `notify_new_posts` FROM `contact` WHERE `id` = %d AND `uid` = %d AND `notify_new_posts` LIMIT 1",
-			intval($item[0]['contact-id']),
-			intval($uid)
+		$r = q("SELECT `notify_new_posts` FROM `contact` WHERE `id` = %d AND `notify_new_posts` LIMIT 1",
+			intval($item[0]['contact-id'])
 		);
 		$send_notification = DBM::is_result($r);
 
@@ -776,10 +787,10 @@ function check_item_notification($itemid, $uid, $defaulttype = "") {
 
 	// Is it a post that the user had started or where he interacted?
 	$parent = q("SELECT `thread`.`iid` FROM `thread` INNER JOIN `item` ON `item`.`parent` = `thread`.`iid`
-			WHERE `thread`.`iid` = %d AND `thread`.`uid` = %d AND NOT `thread`.`ignored` AND
+			WHERE `thread`.`iid` = %d AND NOT `thread`.`ignored` AND
 				(`thread`.`mention` OR `item`.`author-link` IN ($profile_list))
 			LIMIT 1",
-			intval($item[0]["parent"]), intval($uid));
+			intval($item[0]["parent"]));
 
 	if ($parent && !isset($params["type"])) {
 		$params["type"] = NOTIFY_COMMENT;
diff --git a/include/items.php b/include/items.php
index 9e7a4621af..3ddb1f2793 100644
--- a/include/items.php
+++ b/include/items.php
@@ -1129,7 +1129,7 @@ function item_store($arr, $force_parent = false, $notify = false, $dontcache = f
 		add_shadow_entry($current_post);
 	}
 
-	check_item_notification($current_post, $uid);
+	check_user_notification($current_post);
 
 	if ($notify) {
 		Worker::add(array('priority' => PRIORITY_HIGH, 'dont_fork' => true), "Notifier", $notify_type, $current_post);
diff --git a/mod/item.php b/mod/item.php
index 16c3ce442a..1053919b77 100644
--- a/mod/item.php
+++ b/mod/item.php
@@ -1067,6 +1067,8 @@ function item_post(App $a) {
 	create_tags_from_item($post_id);
 	create_files_from_item($post_id);
 
+	check_user_notification($post_id);
+
 	// 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.

From 592ef50e417a74cee40f021720c6b6a4694d69d0 Mon Sep 17 00:00:00 2001
From: Michael <heluecht@pirati.ca>
Date: Sun, 7 Jan 2018 11:59:54 +0000
Subject: [PATCH 2/6] Dropping is now possible as well

---
 src/Object/Post.php | 1 +
 1 file changed, 1 insertion(+)

diff --git a/src/Object/Post.php b/src/Object/Post.php
index ebeaccb7ed..b0d4425638 100644
--- a/src/Object/Post.php
+++ b/src/Object/Post.php
@@ -151,6 +151,7 @@ class Post extends BaseObject
 			} else {
 				$edpost = array("editpost/" . $item['id'], t("Edit"));
 			}
+			$dropping = in_array($item['uid'], [0, local_user()]);
 		} else {
 			$edpost = false;
 		}

From 708d034c6de330a7b3d2d3f3138cd139fdd3f69f Mon Sep 17 00:00:00 2001
From: Michael <heluecht@pirati.ca>
Date: Sun, 7 Jan 2018 12:10:31 +0000
Subject: [PATCH 3/6] We have to check for the contact`s uid not the item`s uid

---
 include/enotify.php | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)

diff --git a/include/enotify.php b/include/enotify.php
index bccc5a9bed..13298ce76c 100644
--- a/include/enotify.php
+++ b/include/enotify.php
@@ -653,7 +653,9 @@ function notification($params)
  */
 function check_user_notification($itemid) {
 	// fetch all users in the thread
-	$users = dba::p("SELECT DISTINCT(`uid`) FROM `item` WHERE `parent` IN (SELECT `parent` FROM `item` WHERE `id`=?) AND `uid` != 0", $itemid);
+	$users = dba::p("SELECT DISTINCT(`contact`.`uid`) FROM `item`
+			INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` != 0
+			WHERE `parent` IN (SELECT `parent` FROM `item` WHERE `id`=?)", $itemid);
 	while ($user = dba::fetch($users)) {
 		check_item_notification($itemid, $user['uid']);
 	}

From e12b6e01a23ede9e7e134bc4615d14dc618ebebd Mon Sep 17 00:00:00 2001
From: Michael <heluecht@pirati.ca>
Date: Sun, 7 Jan 2018 17:14:43 +0000
Subject: [PATCH 4/6] Best "uid" for sending comments, refresh after commenting
 might work now

---
 boot.php                     |  2 +-
 database.sql                 |  4 ++--
 mod/community.php            |  4 ++--
 src/Database/DBStructure.php |  2 +-
 src/Object/Post.php          | 10 +++++++++-
 src/Object/Thread.php        |  2 +-
 6 files changed, 16 insertions(+), 8 deletions(-)

diff --git a/boot.php b/boot.php
index 5607260d97..e47665f94d 100644
--- a/boot.php
+++ b/boot.php
@@ -43,7 +43,7 @@ define('FRIENDICA_PLATFORM',     'Friendica');
 define('FRIENDICA_CODENAME',     'Asparagus');
 define('FRIENDICA_VERSION',      '3.6-dev');
 define('DFRN_PROTOCOL_VERSION',  '2.23');
-define('DB_UPDATE_VERSION',      1238);
+define('DB_UPDATE_VERSION',      1239);
 define('NEW_UPDATE_ROUTINE_VERSION', 1170);
 
 /**
diff --git a/database.sql b/database.sql
index a8c12f272b..48c2e7ecee 100644
--- a/database.sql
+++ b/database.sql
@@ -1,6 +1,6 @@
 -- ------------------------------------------
 -- Friendica 3.6-dev (Asparagus)
--- DB_UPDATE_VERSION 1238
+-- DB_UPDATE_VERSION 1239
 -- ------------------------------------------
 
 
@@ -972,7 +972,7 @@ CREATE TABLE IF NOT EXISTS `thread` (
 	 INDEX `uid_created` (`uid`,`created`),
 	 INDEX `uid_commented` (`uid`,`commented`),
 	 INDEX `uid_wall_created` (`uid`,`wall`,`created`),
-	 INDEX `private_wall_received` (`private`,`wall`,`received`)
+	 INDEX `private_wall_commented` (`private`,`wall`,`commented`)
 ) DEFAULT COLLATE utf8mb4_general_ci;
 
 --
diff --git a/mod/community.php b/mod/community.php
index 7c480d259e..4b755e18ce 100644
--- a/mod/community.php
+++ b/mod/community.php
@@ -190,14 +190,14 @@ function community_getitems($start, $itemspage, $content)
 			item_joins() . " AND `contact`.`self`
 			WHERE `thread`.`visible` AND NOT `thread`.`deleted` AND NOT `thread`.`moderated`
 			AND NOT `thread`.`private` AND `thread`.`wall`
-			ORDER BY `thread`.`received` DESC LIMIT " . intval($start) . ", " . intval($itemspage)
+			ORDER BY `thread`.`commented` DESC LIMIT " . intval($start) . ", " . intval($itemspage)
 		);
 		return dba::inArray($r);
 	} elseif ($content == 'global') {
 		$r = dba::p("SELECT " . item_fieldlists() . " FROM `thread`
 			INNER JOIN `item` ON `item`.`id` = `thread`.`iid` " . item_joins() .
 				"WHERE `thread`.`uid` = 0 AND `verb` = ?
-			ORDER BY `thread`.`created` DESC LIMIT " . intval($start) . ", " . intval($itemspage),
+			ORDER BY `thread`.`commented` DESC LIMIT " . intval($start) . ", " . intval($itemspage),
 			ACTIVITY_POST
 		);
 		return dba::inArray($r);
diff --git a/src/Database/DBStructure.php b/src/Database/DBStructure.php
index c7bdeabe3d..b33f023450 100644
--- a/src/Database/DBStructure.php
+++ b/src/Database/DBStructure.php
@@ -1601,7 +1601,7 @@ class DBStructure {
 						"uid_created" => array("uid","created"),
 						"uid_commented" => array("uid","commented"),
 						"uid_wall_created" => array("uid","wall","created"),
-						"private_wall_received" => array("private","wall","received"),
+						"private_wall_commented" => array("private","wall","commented"),
 						)
 				);
 		$database["tokens"] = array(
diff --git a/src/Object/Post.php b/src/Object/Post.php
index b0d4425638..97768bf56c 100644
--- a/src/Object/Post.php
+++ b/src/Object/Post.php
@@ -765,6 +765,14 @@ class Post extends BaseObject
 				$qcomment = (($qc) ? explode("\n", $qc) : null);
 			}
 
+			// Fetch the user id from the parent when the owner user is empty
+			$uid = $conv->getProfileOwner();
+			$parent_uid = $this->getDataValue('uid');
+
+			if (!empty($parent_uid) && empty($uid) && ($uid != $parent_uid)) {
+				$uid = $parent_uid;
+			}
+
 			$template = get_markup_template($this->getCommentBoxTemplate());
 			$comment_box = replace_macros($template, array(
 				'$return_path' => $a->query_string,
@@ -774,7 +782,7 @@ class Post extends BaseObject
 				'$id'          => $this->getId(),
 				'$parent'      => $this->getId(),
 				'$qcomment'    => $qcomment,
-				'$profile_uid' => $conv->getProfileOwner(),
+				'$profile_uid' => $uid,
 				'$mylink'      => $a->remove_baseurl($a->contact['url']),
 				'$mytitle'     => t('This is you'),
 				'$myphoto'     => $a->remove_baseurl($a->contact['thumb']),
diff --git a/src/Object/Thread.php b/src/Object/Thread.php
index 534095efbb..cf1ddceac2 100644
--- a/src/Object/Thread.php
+++ b/src/Object/Thread.php
@@ -67,7 +67,7 @@ class Thread extends BaseObject
 				$this->writable = can_write_wall($this->profile_owner) || $writable;
 				break;
 			case 'community':
-				$this->profile_owner = local_user();
+				$this->profile_owner = 0;
 				$this->writable = $writable;
 				break;
 			default:

From 28d3980fabbc7b30874c5d0afc983608b6279d42 Mon Sep 17 00:00:00 2001
From: Michael <heluecht@pirati.ca>
Date: Sun, 7 Jan 2018 18:06:06 +0000
Subject: [PATCH 5/6] Changed queries

---
 include/enotify.php | 41 ++++++++++++++++++++---------------------
 1 file changed, 20 insertions(+), 21 deletions(-)

diff --git a/include/enotify.php b/include/enotify.php
index 13298ce76c..4e3c7bb1dd 100644
--- a/include/enotify.php
+++ b/include/enotify.php
@@ -106,10 +106,8 @@ function notification($params)
 	}
 
 	if ($params['type'] == NOTIFY_COMMENT) {
-		$p = q("SELECT `ignored` FROM `thread` WHERE `iid` = %d LIMIT 1",
-			intval($parent_id)
-		);
-		if ($p && count($p) && ($p[0]["ignored"])) {
+		$p = dba::select('thread', ['ignored'], ['iid' => $parent_id], ['limit' => 1]);
+		if (DBM::is_result($p) && $p["ignored"]) {
 			logger("Thread ".$parent_id." will be ignored", LOGGER_DEBUG);
 			return;
 		}
@@ -675,19 +673,22 @@ function check_item_notification($itemid, $uid, $defaulttype = "") {
 
 	$profiles = $notification_data["profiles"];
 
-	$user = q("SELECT `notify-flags`, `language`, `username`, `email`, `nickname` FROM `user` WHERE `uid` = %d", intval($uid));
-	if (!$user)
+	$fields = ['notify-flags', 'language', 'username', 'email', 'nickname'];
+	$user = dba::select('user', $fields, ['uid' => $uid], ['limit' => 1]);
+	if (!DBM::is_result($user)) {
 		return false;
+	}
 
-	$owner = q("SELECT `id`, `url` FROM `contact` WHERE `self` AND `uid` = %d LIMIT 1", intval($uid));
-	if (!$owner)
+	$owner = dba::select('contact', ['url'], ['self' => true, 'uid' => $uid], ['limit' => 1]);
+	if (!DBM::is_result($owner)) {
 		return false;
+	}
 
 	// This is our regular URL format
-	$profiles[] = $owner[0]["url"];
+	$profiles[] = $owner["url"];
 
 	// Notifications from Diaspora are often with an URL in the Diaspora format
-	$profiles[] = System::baseUrl()."/u/".$user[0]["nickname"];
+	$profiles[] = System::baseUrl()."/u/".$user["nickname"];
 
 	$profiles2 = array();
 
@@ -735,10 +736,10 @@ function check_item_notification($itemid, $uid, $defaulttype = "") {
 	// Generate the notification array
 	$params = array();
 	$params["uid"] = $uid;
-	$params["notify_flags"] = $user[0]["notify-flags"];
-	$params["language"] = $user[0]["language"];
-	$params["to_name"] = $user[0]["username"];
-	$params["to_email"] = $user[0]["email"];
+	$params["notify_flags"] = $user["notify-flags"];
+	$params["language"] = $user["language"];
+	$params["to_name"] = $user["username"];
+	$params["to_email"] = $user["email"];
 	$params["item"] = $item[0];
 	$params["parent"] = $item[0]["parent"];
 	$params["link"] = System::baseUrl().'/display/'.urlencode($item[0]["guid"]);
@@ -749,10 +750,7 @@ function check_item_notification($itemid, $uid, $defaulttype = "") {
 
 	if ($item[0]["parent-uri"] === $item[0]["uri"]) {
 		// Send a notification for every new post?
-		$r = q("SELECT `notify_new_posts` FROM `contact` WHERE `id` = %d AND `notify_new_posts` LIMIT 1",
-			intval($item[0]['contact-id'])
-		);
-		$send_notification = DBM::is_result($r);
+		$send_notification = dba::exists('contact', ['id' => $item[0]['contact-id'], 'notify_new_posts' => true]);
 
 		if (!$send_notification) {
 			$tags = q("SELECT `url` FROM `term` WHERE `otype` = %d AND `oid` = %d AND `type` = %d AND `uid` = %d",
@@ -760,10 +758,11 @@ function check_item_notification($itemid, $uid, $defaulttype = "") {
 
 			if (DBM::is_result($tags)) {
 				foreach ($tags AS $tag) {
-					$r = q("SELECT `id` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `notify_new_posts`",
-						normalise_link($tag["url"]), intval($uid));
-					if (DBM::is_result($r))
+					$condition = ['nurl' => normalise_link($tag["url"]), 'uid' => $uid, 'notify_new_posts' => true];
+					$r = dba::exists('contact', $condition);
+					if ($r) {
 						$send_notification = true;
+					}
 				}
 			}
 		}

From 24d7b2af82034853f6941b0405ff1aa0ff3423c3 Mon Sep 17 00:00:00 2001
From: Michael <heluecht@pirati.ca>
Date: Sun, 7 Jan 2018 18:11:48 +0000
Subject: [PATCH 6/6] One more query

---
 include/enotify.php | 10 ++++------
 1 file changed, 4 insertions(+), 6 deletions(-)

diff --git a/include/enotify.php b/include/enotify.php
index 4e3c7bb1dd..79c5df3f51 100644
--- a/include/enotify.php
+++ b/include/enotify.php
@@ -131,12 +131,10 @@ function notification($params)
 		$p = null;
 
 		if ($params['otype'] === 'item' && $parent_id) {
-			$p = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1",
-				intval($parent_id)
-			);
+			$p = dba::select('item', [], ['id' => $parent_id], ['limit' => 1]);
 		}
 
-		$item_post_type = item_post_type($p[0]);
+		$item_post_type = item_post_type($p);
 
 		// "a post"
 		$dest_str = sprintf(t('%1$s commented on [url=%2$s]a %3$s[/url]'),
@@ -149,12 +147,12 @@ function notification($params)
 			$dest_str = sprintf(t('%1$s commented on [url=%2$s]%3$s\'s %4$s[/url]'),
 						'[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
 						$itemlink,
-						$p[0]['author-name'],
+						$p['author-name'],
 						$item_post_type);
 		}
 
 		// "your post"
-		if ($p[0]['owner-name'] == $p[0]['author-name'] && $p[0]['wall']) {
+		if ($p['owner-name'] == $p['author-name'] && $p['wall']) {
 			$dest_str = sprintf(t('%1$s commented on [url=%2$s]your %3$s[/url]'),
 								'[url='.$params['source_link'].']'.$params['source_name'].'[/url]',
 								$itemlink,