3 * @file src/Worker/Notifier.php
5 namespace Friendica\Worker;
7 use Friendica\BaseObject;
8 use Friendica\Core\Addon;
9 use Friendica\Core\Config;
10 use Friendica\Core\Worker;
11 use Friendica\Database\DBA;
12 use Friendica\Model\Contact;
13 use Friendica\Model\Group;
14 use Friendica\Model\Item;
15 use Friendica\Model\PushSubscriber;
16 use Friendica\Model\User;
17 use Friendica\Network\Probe;
18 use Friendica\Protocol\Diaspora;
19 use Friendica\Protocol\OStatus;
20 use Friendica\Protocol\Salmon;
22 require_once 'include/dba.php';
23 require_once 'include/items.php';
26 * The notifier is typically called with:
28 * Worker::add(PRIORITY_HIGH, "Notifier", COMMAND, ITEM_ID);
30 * where COMMAND is one of the following:
32 * activity (in diaspora.php, dfrn_confirm.php, profiles.php)
33 * comment-import (in diaspora.php, items.php)
34 * comment-new (in item.php)
35 * drop (in diaspora.php, items.php, photos.php)
36 * edit_post (in item.php)
37 * event (in events.php)
38 * like (in like.php, poke.php)
39 * mail (in message.php)
40 * suggest (in fsuggest.php)
41 * tag (in photos.php, poke.php, tagger.php)
42 * tgroup (in items.php)
43 * wall-new (in photos.php, item.php)
44 * removeme (in Contact.php)
45 * relocate (in uimport.php)
47 * 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)
54 $a = BaseObject::getApp();
56 logger('notifier: invoked: '.$cmd.': '.$item_id, LOGGER_DEBUG);
63 $recipients_relocate = [];
65 if ($cmd == Delivery::MAIL) {
67 $message = DBA::selectFirst('mail', ['uid', 'contact-id'], ['id' => $item_id]);
68 if (!DBA::isResult($message)) {
71 $uid = $message['uid'];
72 $recipients[] = $message['contact-id'];
73 } elseif ($cmd == Delivery::SUGGESTION) {
75 $suggest = DBA::selectFirst('fsuggest', ['uid', 'cid'], ['id' => $item_id]);
76 if (!DBA::isResult($suggest)) {
79 $uid = $suggest['uid'];
80 $recipients[] = $suggest['cid'];
81 } elseif ($cmd == Delivery::REMOVAL) {
82 $r = q("SELECT `contact`.*, `user`.`prvkey` AS `uprvkey`,
83 `user`.`timezone`, `user`.`nickname`, `user`.`sprvkey`, `user`.`spubkey`,
84 `user`.`page-flags`, `user`.`prvnets`, `user`.`account-type`, `user`.`guid`
85 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
86 WHERE `contact`.`uid` = %d AND `contact`.`self` LIMIT 1",
93 $r = q("SELECT * FROM `contact` WHERE NOT `self` AND `uid` = %d", intval($item_id));
97 foreach ($r as $contact) {
98 Contact::terminateFriendship($user, $contact);
101 } elseif ($cmd == Delivery::RELOCATION) {
102 $normal_mode = false;
105 $recipients_relocate = q("SELECT * FROM `contact` WHERE `uid` = %d AND NOT `self` AND `network` IN ('%s', '%s')",
106 intval($uid), NETWORK_DFRN, NETWORK_DIASPORA);
109 $condition = ['id' => $item_id, 'visible' => true, 'moderated' => false];
110 $target_item = Item::selectFirst([], $condition);
112 if (!DBA::isResult($target_item) || !intval($target_item['parent'])) {
116 $parent_id = intval($target_item['parent']);
117 $uid = $target_item['contact-uid'];
118 $updated = $target_item['edited'];
120 $condition = ['parent' => $parent_id, 'visible' => true, 'moderated' => false];
121 $params = ['order' => ['id']];
122 $ret = Item::select([], $condition, $params);
124 if (!DBA::isResult($ret)) {
128 $items = Item::inArray($ret);
130 // avoid race condition with deleting entries
131 if ($items[0]['deleted']) {
132 foreach ($items as $item) {
133 $item['deleted'] = 1;
137 if ((count($items) == 1) && ($items[0]['id'] === $target_item['id']) && ($items[0]['uri'] === $items[0]['parent-uri'])) {
138 logger('notifier: top level post');
143 $owner = User::getOwnerDataById($uid);
148 $walltowall = ($top_level && ($owner['id'] != $items[0]['contact-id']) ? true : false);
150 // Should the post be transmitted to Diaspora?
151 $diaspora_delivery = true;
153 // If this is a public conversation, notify the feed hub
154 $public_message = true;
157 $push_notify = false;
159 // Deliver directly to a forum, don't PuSH
160 $direct_forum_delivery = false;
163 $recipients_followup = [];
166 if (!in_array($cmd, [Delivery::MAIL, Delivery::SUGGESTION, Delivery::RELOCATION])) {
169 $fields = ['network', 'author-id', 'owner-id'];
170 $condition = ['uri' => $target_item["thr-parent"], 'uid' => $target_item["uid"]];
171 $thr_parent = Item::selectFirst($fields, $condition);
173 logger('GUID: '.$target_item["guid"].': Parent is '.$parent['network'].'. Thread parent is '.$thr_parent['network'], LOGGER_DEBUG);
175 // This is IMPORTANT!!!!
177 // We will only send a "notify owner to relay" or followup message if the referenced post
178 // originated on our system by virtue of having our hostname somewhere
179 // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
181 // if $parent['wall'] == 1 we will already have the parent message in our array
182 // and we will relay the whole lot.
184 $localhost = str_replace('www.','',$a->get_hostname());
185 if (strpos($localhost,':')) {
186 $localhost = substr($localhost,0,strpos($localhost,':'));
190 * Be VERY CAREFUL if you make any changes to the following several lines. Seemingly innocuous changes
191 * have been known to cause runaway conditions which affected several servers, along with
192 * permissions issues.
196 $relay_to_owner = false;
198 if (!$top_level && ($parent['wall'] == 0) && (stristr($target_item['uri'],$localhost))) {
199 $relay_to_owner = true;
203 if (($cmd === 'uplink') && (intval($parent['forum_mode']) == 1) && !$top_level) {
204 $relay_to_owner = true;
207 // until the 'origin' flag has been in use for several months
208 // we will just use it as a fallback test
209 // later we will be able to use it as the primary test of whether or not to relay.
211 if (!$target_item['origin']) {
212 $relay_to_owner = false;
214 if ($parent['origin']) {
215 $relay_to_owner = false;
218 // Special treatment for forum posts
219 if (($target_item['author-id'] != $target_item['owner-id']) &&
220 ($owner['id'] != $target_item['contact-id']) &&
221 ($target_item['uri'] === $target_item['parent-uri'])) {
223 $fields = ['forum', 'prv'];
224 $condition = ['id' => $target_item['contact-id']];
225 $contact = DBA::selectFirst('contact', $fields, $condition);
226 if (!DBA::isResult($contact)) {
227 // Should never happen
231 // Is the post from a forum?
232 if ($contact['forum'] || $contact['prv']) {
233 $relay_to_owner = true;
234 $direct_forum_delivery = true;
237 if ($relay_to_owner) {
238 // local followup to remote post
240 $public_message = false; // not public
241 $conversant_str = dbesc($parent['contact-id']);
242 $recipients = [$parent['contact-id']];
243 $recipients_followup = [$parent['contact-id']];
245 logger('notifier: followup '.$target_item["guid"].' to '.$conversant_str, LOGGER_DEBUG);
247 //if (!$target_item['private'] && $target_item['wall'] &&
248 if (!$target_item['private'] &&
249 (strlen($target_item['allow_cid'].$target_item['allow_gid'].
250 $target_item['deny_cid'].$target_item['deny_gid']) == 0))
253 if (($thr_parent && ($thr_parent['network'] == NETWORK_OSTATUS)) || ($parent['network'] == NETWORK_OSTATUS)) {
256 if ($parent["network"] == NETWORK_OSTATUS) {
257 // Distribute the message to the DFRN contacts as if this wasn't a followup since OStatus can't relay comments
258 // Currently it is work at progress
259 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `network` = '%s' AND NOT `blocked` AND NOT `pending` AND NOT `archive`",
263 if (DBA::isResult($r)) {
264 foreach ($r as $rr) {
265 $recipients_followup[] = $rr['id'];
271 if ($direct_forum_delivery) {
272 $push_notify = false;
275 logger("Notify ".$target_item["guid"]." via PuSH: ".($push_notify?"Yes":"No"), LOGGER_DEBUG);
279 logger('Distributing directly '.$target_item["guid"], LOGGER_DEBUG);
281 // don't send deletions onward for other people's stuff
283 if ($target_item['deleted'] && !intval($target_item['wall'])) {
284 logger('notifier: ignoring delete notification for non-wall item');
288 if (strlen($parent['allow_cid'])
289 || strlen($parent['allow_gid'])
290 || strlen($parent['deny_cid'])
291 || strlen($parent['deny_gid'])) {
292 $public_message = false; // private recipients, not public
295 $allow_people = expand_acl($parent['allow_cid']);
296 $allow_groups = Group::expand(expand_acl($parent['allow_gid']),true);
297 $deny_people = expand_acl($parent['deny_cid']);
298 $deny_groups = Group::expand(expand_acl($parent['deny_gid']));
300 // if our parent is a public forum (forum_mode == 1), uplink to the origional author causing
301 // a delivery fork. private groups (forum_mode == 2) do not uplink
303 if ((intval($parent['forum_mode']) == 1) && !$top_level && ($cmd !== 'uplink')) {
304 Worker::add($a->queue['priority'], 'Notifier', 'uplink', $item_id);
307 foreach ($items as $item) {
308 $recipients[] = $item['contact-id'];
309 $conversants[] = $item['contact-id'];
310 // pull out additional tagged people to notify (if public message)
311 if ($public_message && strlen($item['inform'])) {
312 $people = explode(',',$item['inform']);
313 foreach ($people as $person) {
314 if (substr($person,0,4) === 'cid:') {
315 $recipients[] = intval(substr($person,4));
316 $conversants[] = intval(substr($person,4));
318 $url_recipients[] = substr($person,4);
324 if (count($url_recipients)) {
325 logger('notifier: '.$target_item["guid"].' url_recipients ' . print_r($url_recipients,true));
328 $conversants = array_unique($conversants);
330 $recipients = array_unique(array_merge($recipients,$allow_people,$allow_groups));
331 $deny = array_unique(array_merge($deny_people,$deny_groups));
332 $recipients = array_diff($recipients,$deny);
334 $conversant_str = dbesc(implode(', ',$conversants));
337 // If the thread parent is OStatus then do some magic to distribute the messages.
338 // We have not only to look at the parent, since it could be a Friendica thread.
339 if (($thr_parent && ($thr_parent['network'] == NETWORK_OSTATUS)) || ($parent['network'] == NETWORK_OSTATUS)) {
340 $diaspora_delivery = false;
342 logger('Some parent is OStatus for '.$target_item["guid"]." - Author: ".$thr_parent['author-id']." - Owner: ".$thr_parent['owner-id'], LOGGER_DEBUG);
344 // Send a salmon to the parent author
345 $probed_contact = DBA::selectFirst('contact', ['url', 'notify'], ['id' => $thr_parent['author-id']]);
346 if (DBA::isResult($probed_contact) && !empty($probed_contact["notify"])) {
347 logger('Notify parent author '.$probed_contact["url"].': '.$probed_contact["notify"]);
348 $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
351 // Send a salmon to the parent owner
352 $probed_contact = DBA::selectFirst('contact', ['url', 'notify'], ['id' => $thr_parent['owner-id']]);
353 if (DBA::isResult($probed_contact) && !empty($probed_contact["notify"])) {
354 logger('Notify parent owner '.$probed_contact["url"].': '.$probed_contact["notify"]);
355 $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
358 // Send a salmon notification to every person we mentioned in the post
359 $arr = explode(',',$target_item['tag']);
360 foreach ($arr as $x) {
361 //logger('Checking tag '.$x, LOGGER_DEBUG);
363 if (preg_match('/@\[url=([^\]]*)\]/',$x,$matches)) {
364 $probed_contact = Probe::uri($matches[1]);
365 if ($probed_contact["notify"] != "") {
366 logger('Notify mentioned user '.$probed_contact["url"].': '.$probed_contact["notify"]);
367 $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
372 // It only makes sense to distribute answers to OStatus messages to Friendica and OStatus - but not Diaspora
373 $networks = [NETWORK_OSTATUS, NETWORK_DFRN];
375 $networks = [NETWORK_OSTATUS, NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_MAIL];
378 $public_message = false;
381 // If this is a public message and pubmail is set on the parent, include all your email contacts
382 if (!empty($target_item) && function_exists('imap_open') && !Config::get('system','imap_disabled')) {
383 if (!strlen($target_item['allow_cid']) && !strlen($target_item['allow_gid'])
384 && !strlen($target_item['deny_cid']) && !strlen($target_item['deny_gid'])
385 && intval($target_item['pubmail'])) {
386 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `network` = '%s'",
390 if (DBA::isResult($r)) {
391 foreach ($r as $rr) {
392 $recipients[] = $rr['id'];
398 if (($cmd == Delivery::RELOCATION)) {
399 $r = $recipients_relocate;
402 $recipients = $recipients_followup;
404 $condition = ['id' => $recipients, 'self' => false,
405 'blocked' => false, 'pending' => false, 'archive' => false];
406 if (!empty($networks)) {
407 $condition['network'] = $networks;
409 $contacts = DBA::select('contact', ['id', 'url', 'network'], $condition);
410 $r = DBA::toArray($contacts);
414 if (DBA::isResult($r)) {
415 foreach ($r as $contact) {
416 logger("Deliver ".$item_id." to ".$contact['url']." via network ".$contact['network'], LOGGER_DEBUG);
418 Worker::add(['priority' => $a->queue['priority'], 'created' => $a->queue['created'], 'dont_fork' => true],
419 'Delivery', $cmd, $item_id, (int)$contact['id']);
423 // send salmon slaps to mentioned remote tags (@foo@example.com) in OStatus posts
424 // They are especially used for notifications to OStatus users that don't follow us.
425 if (!Config::get('system', 'dfrn_only') && count($url_recipients) && ($public_message || $push_notify) && $normal_mode) {
426 $slap = OStatus::salmon($target_item, $owner);
427 foreach ($url_recipients as $url) {
429 logger('notifier: urldelivery: ' . $url);
430 $deliver_status = Salmon::slapper($owner, $url, $slap);
431 /// @TODO Redeliver/queue these items on failure, though there is no contact record
436 if ($public_message) {
439 if ($diaspora_delivery) {
440 $r1 = q("SELECT `batch`, ANY_VALUE(`id`) AS `id`, ANY_VALUE(`name`) AS `name`, ANY_VALUE(`network`) AS `network`
441 FROM `contact` WHERE `network` = '%s' AND `batch` != ''
442 AND `uid` = %d AND `rel` != %d AND NOT `blocked` AND NOT `pending` AND NOT `archive` GROUP BY `batch`",
443 dbesc(NETWORK_DIASPORA),
444 intval($owner['uid']),
445 intval(CONTACT_IS_SHARING)
448 // Fetch the participation list
449 // The function will ensure that there are no duplicates
450 $r1 = Diaspora::participantsForThread($item_id, $r1);
452 // Add the relay to the list, avoid duplicates
454 $r1 = Diaspora::relayList($item_id, $r1);
458 $condition = ['network' => NETWORK_DFRN, 'uid' => $owner['uid'], 'blocked' => false,
459 'pending' => false, 'archive' => false, 'rel' => [CONTACT_IS_FOLLOWER, CONTACT_IS_FRIEND]];
460 $r2 = DBA::toArray(DBA::select('contact', ['id', 'name', 'network'], $condition));
462 $r = array_merge($r2, $r1);
464 if (DBA::isResult($r)) {
465 logger('pubdeliver '.$target_item["guid"].': '.print_r($r,true), LOGGER_DEBUG);
467 foreach ($r as $rr) {
468 // except for Diaspora batch jobs
469 // Don't deliver to folks who have already been delivered to
471 if (($rr['network'] !== NETWORK_DIASPORA) && (in_array($rr['id'], $conversants))) {
472 logger('notifier: already delivered id=' . $rr['id']);
476 if (!in_array($cmd, [Delivery::MAIL, Delivery::SUGGESTION]) && !$followup) {
477 logger('notifier: delivery agent: '.$rr['name'].' '.$rr['id'].' '.$rr['network'].' '.$target_item["guid"]);
478 Worker::add(['priority' => $a->queue['priority'], 'created' => $a->queue['created'], 'dont_fork' => true],
479 'Delivery', $cmd, $item_id, (int)$rr['id']);
487 // Notify PuSH subscribers (Used for OStatus distribution of regular posts)
489 logger('Activating internal PuSH for item '.$item_id, LOGGER_DEBUG);
491 // Handling the pubsubhubbub requests
492 PushSubscriber::publishFeed($owner['uid'], $a->queue['priority']);
495 logger('notifier: calling hooks for ' . $cmd . ' ' . $item_id, LOGGER_DEBUG);
498 Addon::forkHooks($a->queue['priority'], 'notifier_normal', $target_item);
501 Addon::callHooks('notifier_end',$target_item);