3 * @file src/Worker/Notifier.php
5 namespace Friendica\Worker;
7 use Friendica\Core\Addon;
8 use Friendica\Core\Config;
9 use Friendica\Core\Worker;
10 use Friendica\Database\DBM;
11 use Friendica\Model\Contact;
12 use Friendica\Model\Group;
13 use Friendica\Model\Item;
14 use Friendica\Model\User;
15 use Friendica\Model\PushSubscriber;
16 use Friendica\Network\Probe;
17 use Friendica\Protocol\Diaspora;
18 use Friendica\Protocol\OStatus;
19 use Friendica\Protocol\Salmon;
20 use Friendica\Worker\Delivery;
23 require_once 'include/dba.php';
24 require_once 'include/items.php';
27 * The notifier is typically called with:
29 * Worker::add(PRIORITY_HIGH, "Notifier", COMMAND, ITEM_ID);
31 * where COMMAND is one of the following:
33 * activity (in diaspora.php, dfrn_confirm.php, profiles.php)
34 * comment-import (in diaspora.php, items.php)
35 * comment-new (in item.php)
36 * drop (in diaspora.php, items.php, photos.php)
37 * edit_post (in item.php)
38 * event (in events.php)
39 * like (in like.php, poke.php)
40 * mail (in message.php)
41 * suggest (in fsuggest.php)
42 * tag (in photos.php, poke.php, tagger.php)
43 * tgroup (in items.php)
44 * wall-new (in photos.php, item.php)
45 * removeme (in Contact.php)
46 * relocate (in uimport.php)
48 * and ITEM_ID is the id of the item in the database that needs to be sent to others.
52 public static function execute($cmd, $item_id) {
55 logger('notifier: invoked: '.$cmd.': '.$item_id, LOGGER_DEBUG);
62 $recipients_relocate = [];
64 if ($cmd == Delivery::MAIL) {
66 $message = dba::selectFirst('mail', ['uid', 'contact-id'], ['id' => $item_id]);
67 if (!DBM::is_result($message)) {
70 $uid = $message['uid'];
71 $recipients[] = $message['contact-id'];
72 } elseif ($cmd == Delivery::SUGGESTION) {
74 $suggest = dba::selectFirst('fsuggest', ['uid', 'cid'], ['id' => $item_id]);
75 if (!DBM::is_result($suggest)) {
78 $uid = $suggest['uid'];
79 $recipients[] = $suggest['cid'];
80 } elseif ($cmd == Delivery::REMOVAL) {
81 $r = q("SELECT `contact`.*, `user`.`prvkey` AS `uprvkey`,
82 `user`.`timezone`, `user`.`nickname`, `user`.`sprvkey`, `user`.`spubkey`,
83 `user`.`page-flags`, `user`.`prvnets`, `user`.`account-type`, `user`.`guid`
84 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
85 WHERE `contact`.`uid` = %d AND `contact`.`self` LIMIT 1",
92 $r = q("SELECT * FROM `contact` WHERE NOT `self` AND `uid` = %d", intval($item_id));
96 foreach ($r as $contact) {
97 Contact::terminateFriendship($user, $contact);
100 } elseif ($cmd == Delivery::RELOCATION) {
101 $normal_mode = false;
104 $recipients_relocate = q("SELECT * FROM `contact` WHERE `uid` = %d AND NOT `self` AND `network` IN ('%s', '%s')",
105 intval($uid), NETWORK_DFRN, NETWORK_DIASPORA);
108 $condition = ['id' => $item_id, 'visible' => true, 'moderated' => false];
109 $target_item = Item::selectFirst([], $condition);
111 if (!DBM::is_result($target_item) || !intval($target_item['parent'])) {
115 $parent_id = intval($target_item['parent']);
116 $uid = $target_item['contact-uid'];
117 $updated = $target_item['edited'];
119 $condition = ['parent' => $parent_id, 'visible' => true, 'moderated' => false];
120 $params = ['order' => ['id']];
121 $ret = Item::select([], $condition, $params);
123 if (!DBM::is_result($ret)) {
127 $items = dba::inArray($ret);
129 // avoid race condition with deleting entries
130 if ($items[0]['deleted']) {
131 foreach ($items as $item) {
132 $item['deleted'] = 1;
136 if ((count($items) == 1) && ($items[0]['id'] === $target_item['id']) && ($items[0]['uri'] === $items[0]['parent-uri'])) {
137 logger('notifier: top level post');
142 $owner = User::getOwnerDataById($uid);
147 $walltowall = ($top_level && ($owner['id'] != $items[0]['contact-id']) ? true : false);
149 // Should the post be transmitted to Diaspora?
150 $diaspora_delivery = true;
152 // If this is a public conversation, notify the feed hub
153 $public_message = true;
156 $push_notify = false;
158 // Deliver directly to a forum, don't PuSH
159 $direct_forum_delivery = false;
162 $recipients_followup = [];
165 if (!in_array($cmd, [Delivery::MAIL, Delivery::SUGGESTION, Delivery::RELOCATION])) {
168 $fields = ['network', 'author-id', 'owner-id'];
169 $condition = ['uri' => $target_item["thr-parent"], 'uid' => $target_item["uid"]];
170 $thr_parent = dba::selectFirst('item', $fields, $condition);
172 logger('GUID: '.$target_item["guid"].': Parent is '.$parent['network'].'. Thread parent is '.$thr_parent['network'], LOGGER_DEBUG);
174 // This is IMPORTANT!!!!
176 // We will only send a "notify owner to relay" or followup message if the referenced post
177 // originated on our system by virtue of having our hostname somewhere
178 // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
180 // if $parent['wall'] == 1 we will already have the parent message in our array
181 // and we will relay the whole lot.
183 $localhost = str_replace('www.','',$a->get_hostname());
184 if (strpos($localhost,':')) {
185 $localhost = substr($localhost,0,strpos($localhost,':'));
189 * Be VERY CAREFUL if you make any changes to the following several lines. Seemingly innocuous changes
190 * have been known to cause runaway conditions which affected several servers, along with
191 * permissions issues.
195 $relay_to_owner = false;
197 if (!$top_level && ($parent['wall'] == 0) && (stristr($target_item['uri'],$localhost))) {
198 $relay_to_owner = true;
202 if (($cmd === 'uplink') && (intval($parent['forum_mode']) == 1) && !$top_level) {
203 $relay_to_owner = true;
206 // until the 'origin' flag has been in use for several months
207 // we will just use it as a fallback test
208 // later we will be able to use it as the primary test of whether or not to relay.
210 if (!$target_item['origin']) {
211 $relay_to_owner = false;
213 if ($parent['origin']) {
214 $relay_to_owner = false;
217 // Special treatment for forum posts
218 if (($target_item['author-id'] != $target_item['owner-id']) &&
219 ($owner['id'] != $target_item['contact-id']) &&
220 ($target_item['uri'] === $target_item['parent-uri'])) {
222 $fields = ['forum', 'prv'];
223 $condition = ['id' => $target_item['contact-id']];
224 $contact = dba::selectFirst('contact', $fields, $condition);
225 if (!DBM::is_result($contact)) {
226 // Should never happen
230 // Is the post from a forum?
231 if ($contact['forum'] || $contact['prv']) {
232 $relay_to_owner = true;
233 $direct_forum_delivery = true;
236 if ($relay_to_owner) {
237 // local followup to remote post
239 $public_message = false; // not public
240 $conversant_str = dbesc($parent['contact-id']);
241 $recipients = [$parent['contact-id']];
242 $recipients_followup = [$parent['contact-id']];
244 logger('notifier: followup '.$target_item["guid"].' to '.$conversant_str, LOGGER_DEBUG);
246 //if (!$target_item['private'] && $target_item['wall'] &&
247 if (!$target_item['private'] &&
248 (strlen($target_item['allow_cid'].$target_item['allow_gid'].
249 $target_item['deny_cid'].$target_item['deny_gid']) == 0))
252 if (($thr_parent && ($thr_parent['network'] == NETWORK_OSTATUS)) || ($parent['network'] == NETWORK_OSTATUS)) {
255 if ($parent["network"] == NETWORK_OSTATUS) {
256 // Distribute the message to the DFRN contacts as if this wasn't a followup since OStatus can't relay comments
257 // Currently it is work at progress
258 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `network` = '%s' AND NOT `blocked` AND NOT `pending` AND NOT `archive`",
262 if (DBM::is_result($r)) {
263 foreach ($r as $rr) {
264 $recipients_followup[] = $rr['id'];
270 if ($direct_forum_delivery) {
271 $push_notify = false;
274 logger("Notify ".$target_item["guid"]." via PuSH: ".($push_notify?"Yes":"No"), LOGGER_DEBUG);
278 logger('Distributing directly '.$target_item["guid"], LOGGER_DEBUG);
280 // don't send deletions onward for other people's stuff
282 if ($target_item['deleted'] && !intval($target_item['wall'])) {
283 logger('notifier: ignoring delete notification for non-wall item');
287 if (strlen($parent['allow_cid'])
288 || strlen($parent['allow_gid'])
289 || strlen($parent['deny_cid'])
290 || strlen($parent['deny_gid'])) {
291 $public_message = false; // private recipients, not public
294 $allow_people = expand_acl($parent['allow_cid']);
295 $allow_groups = Group::expand(expand_acl($parent['allow_gid']),true);
296 $deny_people = expand_acl($parent['deny_cid']);
297 $deny_groups = Group::expand(expand_acl($parent['deny_gid']));
299 // if our parent is a public forum (forum_mode == 1), uplink to the origional author causing
300 // a delivery fork. private groups (forum_mode == 2) do not uplink
302 if ((intval($parent['forum_mode']) == 1) && !$top_level && ($cmd !== 'uplink')) {
303 Worker::add($a->queue['priority'], 'Notifier', 'uplink', $item_id);
306 foreach ($items as $item) {
307 $recipients[] = $item['contact-id'];
308 $conversants[] = $item['contact-id'];
309 // pull out additional tagged people to notify (if public message)
310 if ($public_message && strlen($item['inform'])) {
311 $people = explode(',',$item['inform']);
312 foreach ($people as $person) {
313 if (substr($person,0,4) === 'cid:') {
314 $recipients[] = intval(substr($person,4));
315 $conversants[] = intval(substr($person,4));
317 $url_recipients[] = substr($person,4);
323 if (count($url_recipients)) {
324 logger('notifier: '.$target_item["guid"].' url_recipients ' . print_r($url_recipients,true));
327 $conversants = array_unique($conversants);
329 $recipients = array_unique(array_merge($recipients,$allow_people,$allow_groups));
330 $deny = array_unique(array_merge($deny_people,$deny_groups));
331 $recipients = array_diff($recipients,$deny);
333 $conversant_str = dbesc(implode(', ',$conversants));
336 // If the thread parent is OStatus then do some magic to distribute the messages.
337 // We have not only to look at the parent, since it could be a Friendica thread.
338 if (($thr_parent && ($thr_parent['network'] == NETWORK_OSTATUS)) || ($parent['network'] == NETWORK_OSTATUS)) {
339 $diaspora_delivery = false;
341 logger('Some parent is OStatus for '.$target_item["guid"]." - Author: ".$thr_parent['author-id']." - Owner: ".$thr_parent['owner-id'], LOGGER_DEBUG);
343 // Send a salmon to the parent author
344 $probed_contact = dba::selectFirst('contact', ['url', 'notify'], ['id' => $thr_parent['author-id']]);
345 if (DBM::is_result($probed_contact) && !empty($probed_contact["notify"])) {
346 logger('Notify parent author '.$probed_contact["url"].': '.$probed_contact["notify"]);
347 $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
350 // Send a salmon to the parent owner
351 $probed_contact = dba::selectFirst('contact', ['url', 'notify'], ['id' => $thr_parent['owner-id']]);
352 if (DBM::is_result($probed_contact) && !empty($probed_contact["notify"])) {
353 logger('Notify parent owner '.$probed_contact["url"].': '.$probed_contact["notify"]);
354 $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
357 // Send a salmon notification to every person we mentioned in the post
358 $arr = explode(',',$target_item['tag']);
359 foreach ($arr as $x) {
360 //logger('Checking tag '.$x, LOGGER_DEBUG);
362 if (preg_match('/@\[url=([^\]]*)\]/',$x,$matches)) {
363 $probed_contact = Probe::uri($matches[1]);
364 if ($probed_contact["notify"] != "") {
365 logger('Notify mentioned user '.$probed_contact["url"].': '.$probed_contact["notify"]);
366 $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
371 // It only makes sense to distribute answers to OStatus messages to Friendica and OStatus - but not Diaspora
372 $networks = [NETWORK_OSTATUS, NETWORK_DFRN];
374 $networks = [NETWORK_OSTATUS, NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_MAIL];
377 $public_message = false;
380 // If this is a public message and pubmail is set on the parent, include all your email contacts
381 if (function_exists('imap_open') && !Config::get('system','imap_disabled')) {
382 if (!strlen($target_item['allow_cid']) && !strlen($target_item['allow_gid'])
383 && !strlen($target_item['deny_cid']) && !strlen($target_item['deny_gid'])
384 && intval($target_item['pubmail'])) {
385 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `network` = '%s'",
389 if (DBM::is_result($r)) {
390 foreach ($r as $rr) {
391 $recipients[] = $rr['id'];
397 if (($cmd == Delivery::RELOCATION)) {
398 $r = $recipients_relocate;
401 $recipients = $recipients_followup;
403 $condition = ['id' => $recipients, 'self' => false,
404 'blocked' => false, 'pending' => false, 'archive' => false];
405 if (!empty($networks)) {
406 $condition['network'] = $networks;
408 $contacts = dba::select('contact', ['id', 'url', 'network'], $condition);
409 $r = dba::inArray($contacts);
413 if (DBM::is_result($r)) {
414 foreach ($r as $contact) {
415 logger("Deliver ".$target_item["guid"]." to ".$contact['url']." via network ".$contact['network'], LOGGER_DEBUG);
417 Worker::add(['priority' => $a->queue['priority'], 'created' => $a->queue['created'], 'dont_fork' => true],
418 'Delivery', $cmd, $item_id, (int)$contact['id']);
422 // send salmon slaps to mentioned remote tags (@foo@example.com) in OStatus posts
423 // They are especially used for notifications to OStatus users that don't follow us.
424 if (!Config::get('system', 'dfrn_only') && count($url_recipients) && ($public_message || $push_notify) && $normal_mode) {
425 $slap = OStatus::salmon($target_item, $owner);
426 foreach ($url_recipients as $url) {
428 logger('notifier: urldelivery: ' . $url);
429 $deliver_status = Salmon::slapper($owner, $url, $slap);
430 /// @TODO Redeliver/queue these items on failure, though there is no contact record
435 if ($public_message) {
438 if ($diaspora_delivery) {
439 $r1 = q("SELECT `batch`, ANY_VALUE(`id`) AS `id`, ANY_VALUE(`name`) AS `name`, ANY_VALUE(`network`) AS `network`
440 FROM `contact` WHERE `network` = '%s' AND `batch` != ''
441 AND `uid` = %d AND `rel` != %d AND NOT `blocked` AND NOT `pending` AND NOT `archive` GROUP BY `batch`",
442 dbesc(NETWORK_DIASPORA),
443 intval($owner['uid']),
444 intval(CONTACT_IS_SHARING)
447 // Fetch the participation list
448 // The function will ensure that there are no duplicates
449 $r1 = Diaspora::participantsForThread($item_id, $r1);
451 // Add the relay to the list, avoid duplicates
453 $r1 = Diaspora::relayList($item_id, $r1);
457 $condition = ['network' => NETWORK_DFRN, 'uid' => $owner['uid'], 'blocked' => false,
458 'pending' => false, 'archive' => false, 'rel' => [CONTACT_IS_FOLLOWER, CONTACT_IS_FRIEND]];
459 $r2 = dba::inArray(dba::select('contact', ['id', 'name', 'network'], $condition));
461 $r = array_merge($r2, $r1);
463 if (DBM::is_result($r)) {
464 logger('pubdeliver '.$target_item["guid"].': '.print_r($r,true), LOGGER_DEBUG);
466 foreach ($r as $rr) {
467 // except for Diaspora batch jobs
468 // Don't deliver to folks who have already been delivered to
470 if (($rr['network'] !== NETWORK_DIASPORA) && (in_array($rr['id'], $conversants))) {
471 logger('notifier: already delivered id=' . $rr['id']);
475 if (!in_array($cmd, [Delivery::MAIL, Delivery::SUGGESTION]) && !$followup) {
476 logger('notifier: delivery agent: '.$rr['name'].' '.$rr['id'].' '.$rr['network'].' '.$target_item["guid"]);
477 Worker::add(['priority' => $a->queue['priority'], 'created' => $a->queue['created'], 'dont_fork' => true],
478 'Delivery', $cmd, $item_id, (int)$rr['id']);
486 // Notify PuSH subscribers (Used for OStatus distribution of regular posts)
488 logger('Activating internal PuSH for item '.$item_id, LOGGER_DEBUG);
490 // Handling the pubsubhubbub requests
491 PushSubscriber::publishFeed($owner['uid'], $a->queue['priority']);
494 logger('notifier: calling hooks for ' . $cmd . ' ' . $item_id, LOGGER_DEBUG);
497 Addon::forkHooks($a->queue['priority'], 'notifier_normal', $target_item);
500 Addon::callHooks('notifier_end',$target_item);