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\User;
14 use Friendica\Model\PushSubscriber;
15 use Friendica\Network\Probe;
16 use Friendica\Protocol\Diaspora;
17 use Friendica\Protocol\OStatus;
18 use Friendica\Protocol\Salmon;
19 use Friendica\Worker\Delivery;
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.
51 public static function execute($cmd, $item_id) {
54 logger('notifier: invoked: '.$cmd.': '.$item_id, LOGGER_DEBUG);
61 $recipients_relocate = [];
63 if ($cmd == Delivery::MAIL) {
65 $message = dba::selectFirst('mail', ['uid', 'contact-id'], ['id' => $item_id]);
66 if (!DBM::is_result($message)) {
69 $uid = $message['uid'];
70 $recipients[] = $message['contact-id'];
71 } elseif ($cmd == Delivery::SUGGESTION) {
73 $suggest = dba::selectFirst('fsuggest', ['uid', 'cid'], ['id' => $item_id]);
74 if (!DBM::is_result($suggest)) {
77 $uid = $suggest['uid'];
78 $recipients[] = $suggest['cid'];
79 } elseif ($cmd == Delivery::REMOVAL) {
80 $r = q("SELECT `contact`.*, `user`.`prvkey` AS `uprvkey`,
81 `user`.`timezone`, `user`.`nickname`, `user`.`sprvkey`, `user`.`spubkey`,
82 `user`.`page-flags`, `user`.`prvnets`, `user`.`account-type`, `user`.`guid`
83 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
84 WHERE `contact`.`uid` = %d AND `contact`.`self` LIMIT 1",
91 $r = q("SELECT * FROM `contact` WHERE NOT `self` AND `uid` = %d", intval($item_id));
95 foreach ($r as $contact) {
96 Contact::terminateFriendship($user, $contact);
99 } elseif ($cmd == Delivery::RELOCATION) {
100 $normal_mode = false;
103 $recipients_relocate = q("SELECT * FROM `contact` WHERE `uid` = %d AND NOT `self` AND `network` IN ('%s', '%s')",
104 intval($uid), NETWORK_DFRN, NETWORK_DIASPORA);
107 $target_item = dba::fetch_first("SELECT `item`.*, `contact`.`uid` AS `cuid` FROM `item`
108 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
109 WHERE `item`.`id` = ? AND `visible` AND NOT `moderated`", $item_id);
111 if (!DBM::is_result($target_item) || !intval($target_item['parent'])) {
115 $parent_id = intval($target_item['parent']);
116 $uid = $target_item['cuid'];
117 $updated = $target_item['edited'];
119 $items = q("SELECT `item`.*, `sign`.`signed_text`,`sign`.`signature`,`sign`.`signer`
120 FROM `item` LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id` WHERE `parent` = %d AND visible AND NOT moderated ORDER BY `id` ASC",
124 if (!count($items)) {
128 // avoid race condition with deleting entries
129 if ($items[0]['deleted']) {
130 foreach ($items as $item) {
131 $item['deleted'] = 1;
135 if ((count($items) == 1) && ($items[0]['id'] === $target_item['id']) && ($items[0]['uri'] === $items[0]['parent-uri'])) {
136 logger('notifier: top level post');
141 $owner = User::getOwnerDataById($uid);
146 $walltowall = ($top_level && ($owner['id'] != $items[0]['contact-id']) ? true : false);
148 // Should the post be transmitted to Diaspora?
149 $diaspora_delivery = true;
151 // If this is a public conversation, notify the feed hub
152 $public_message = true;
155 $push_notify = false;
157 // Deliver directly to a forum, don't PuSH
158 $direct_forum_delivery = false;
161 $recipients_followup = [];
164 if (!in_array($cmd, [Delivery::MAIL, Delivery::SUGGESTION, Delivery::RELOCATION])) {
167 $fields = ['network', 'author-id', 'owner-id'];
168 $condition = ['uri' => $target_item["thr-parent"], 'uid' => $target_item["uid"]];
169 $thr_parent = dba::selectFirst('item', $fields, $condition);
171 logger('GUID: '.$target_item["guid"].': Parent is '.$parent['network'].'. Thread parent is '.$thr_parent['network'], LOGGER_DEBUG);
173 // This is IMPORTANT!!!!
175 // We will only send a "notify owner to relay" or followup message if the referenced post
176 // originated on our system by virtue of having our hostname somewhere
177 // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
179 // if $parent['wall'] == 1 we will already have the parent message in our array
180 // and we will relay the whole lot.
182 $localhost = str_replace('www.','',$a->get_hostname());
183 if (strpos($localhost,':')) {
184 $localhost = substr($localhost,0,strpos($localhost,':'));
188 * Be VERY CAREFUL if you make any changes to the following several lines. Seemingly innocuous changes
189 * have been known to cause runaway conditions which affected several servers, along with
190 * permissions issues.
194 $relay_to_owner = false;
196 if (!$top_level && ($parent['wall'] == 0) && (stristr($target_item['uri'],$localhost))) {
197 $relay_to_owner = true;
201 if (($cmd === 'uplink') && (intval($parent['forum_mode']) == 1) && !$top_level) {
202 $relay_to_owner = true;
205 // until the 'origin' flag has been in use for several months
206 // we will just use it as a fallback test
207 // later we will be able to use it as the primary test of whether or not to relay.
209 if (!$target_item['origin']) {
210 $relay_to_owner = false;
212 if ($parent['origin']) {
213 $relay_to_owner = false;
216 // Special treatment for forum posts
217 if (($target_item['author-id'] != $target_item['owner-id']) &&
218 ($owner['id'] != $target_item['contact-id']) &&
219 ($target_item['uri'] === $target_item['parent-uri'])) {
221 $fields = ['forum', 'prv'];
222 $condition = ['id' => $target_item['contact-id']];
223 $contact = dba::selectFirst('contact', $fields, $condition);
224 if (!DBM::is_result($contact)) {
225 // Should never happen
229 // Is the post from a forum?
230 if ($contact['forum'] || $contact['prv']) {
231 $relay_to_owner = true;
232 $direct_forum_delivery = true;
235 if ($relay_to_owner) {
236 // local followup to remote post
238 $public_message = false; // not public
239 $conversant_str = dbesc($parent['contact-id']);
240 $recipients = [$parent['contact-id']];
241 $recipients_followup = [$parent['contact-id']];
243 logger('notifier: followup '.$target_item["guid"].' to '.$conversant_str, LOGGER_DEBUG);
245 //if (!$target_item['private'] && $target_item['wall'] &&
246 if (!$target_item['private'] &&
247 (strlen($target_item['allow_cid'].$target_item['allow_gid'].
248 $target_item['deny_cid'].$target_item['deny_gid']) == 0))
251 if (($thr_parent && ($thr_parent['network'] == NETWORK_OSTATUS)) || ($parent['network'] == NETWORK_OSTATUS)) {
254 if ($parent["network"] == NETWORK_OSTATUS) {
255 // Distribute the message to the DFRN contacts as if this wasn't a followup since OStatus can't relay comments
256 // Currently it is work at progress
257 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `network` = '%s' AND NOT `blocked` AND NOT `pending` AND NOT `archive`",
261 if (DBM::is_result($r)) {
262 foreach ($r as $rr) {
263 $recipients_followup[] = $rr['id'];
269 if ($direct_forum_delivery) {
270 $push_notify = false;
273 logger("Notify ".$target_item["guid"]." via PuSH: ".($push_notify?"Yes":"No"), LOGGER_DEBUG);
277 logger('Distributing directly '.$target_item["guid"], LOGGER_DEBUG);
279 // don't send deletions onward for other people's stuff
281 if ($target_item['deleted'] && !intval($target_item['wall'])) {
282 logger('notifier: ignoring delete notification for non-wall item');
286 if (strlen($parent['allow_cid'])
287 || strlen($parent['allow_gid'])
288 || strlen($parent['deny_cid'])
289 || strlen($parent['deny_gid'])) {
290 $public_message = false; // private recipients, not public
293 $allow_people = expand_acl($parent['allow_cid']);
294 $allow_groups = Group::expand(expand_acl($parent['allow_gid']),true);
295 $deny_people = expand_acl($parent['deny_cid']);
296 $deny_groups = Group::expand(expand_acl($parent['deny_gid']));
298 // if our parent is a public forum (forum_mode == 1), uplink to the origional author causing
299 // a delivery fork. private groups (forum_mode == 2) do not uplink
301 if ((intval($parent['forum_mode']) == 1) && !$top_level && ($cmd !== 'uplink')) {
302 Worker::add($a->queue['priority'], 'Notifier', 'uplink', $item_id);
305 foreach ($items as $item) {
306 $recipients[] = $item['contact-id'];
307 $conversants[] = $item['contact-id'];
308 // pull out additional tagged people to notify (if public message)
309 if ($public_message && strlen($item['inform'])) {
310 $people = explode(',',$item['inform']);
311 foreach ($people as $person) {
312 if (substr($person,0,4) === 'cid:') {
313 $recipients[] = intval(substr($person,4));
314 $conversants[] = intval(substr($person,4));
316 $url_recipients[] = substr($person,4);
322 if (count($url_recipients)) {
323 logger('notifier: '.$target_item["guid"].' url_recipients ' . print_r($url_recipients,true));
326 $conversants = array_unique($conversants);
328 $recipients = array_unique(array_merge($recipients,$allow_people,$allow_groups));
329 $deny = array_unique(array_merge($deny_people,$deny_groups));
330 $recipients = array_diff($recipients,$deny);
332 $conversant_str = dbesc(implode(', ',$conversants));
335 // If the thread parent is OStatus then do some magic to distribute the messages.
336 // We have not only to look at the parent, since it could be a Friendica thread.
337 if (($thr_parent && ($thr_parent['network'] == NETWORK_OSTATUS)) || ($parent['network'] == NETWORK_OSTATUS)) {
338 $diaspora_delivery = false;
340 logger('Some parent is OStatus for '.$target_item["guid"]." - Author: ".$thr_parent['author-id']." - Owner: ".$thr_parent['owner-id'], LOGGER_DEBUG);
342 // Send a salmon to the parent author
343 $probed_contact = dba::selectFirst('contact', ['url', 'notify'], ['id' => $thr_parent['author-id']]);
344 if (DBM::is_result($probed_contact) && !empty($probed_contact["notify"])) {
345 logger('Notify parent author '.$probed_contact["url"].': '.$probed_contact["notify"]);
346 $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
349 // Send a salmon to the parent owner
350 $probed_contact = dba::selectFirst('contact', ['url', 'notify'], ['id' => $thr_parent['owner-id']]);
351 if (DBM::is_result($probed_contact) && !empty($probed_contact["notify"])) {
352 logger('Notify parent owner '.$probed_contact["url"].': '.$probed_contact["notify"]);
353 $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
356 // Send a salmon notification to every person we mentioned in the post
357 $arr = explode(',',$target_item['tag']);
358 foreach ($arr as $x) {
359 //logger('Checking tag '.$x, LOGGER_DEBUG);
361 if (preg_match('/@\[url=([^\]]*)\]/',$x,$matches)) {
362 $probed_contact = Probe::uri($matches[1]);
363 if ($probed_contact["notify"] != "") {
364 logger('Notify mentioned user '.$probed_contact["url"].': '.$probed_contact["notify"]);
365 $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
370 // It only makes sense to distribute answers to OStatus messages to Friendica and OStatus - but not Diaspora
371 $networks = [NETWORK_OSTATUS, NETWORK_DFRN];
373 $networks = [NETWORK_OSTATUS, NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_MAIL];
376 $public_message = false;
379 // If this is a public message and pubmail is set on the parent, include all your email contacts
380 if (function_exists('imap_open') && !Config::get('system','imap_disabled')) {
381 if (!strlen($target_item['allow_cid']) && !strlen($target_item['allow_gid'])
382 && !strlen($target_item['deny_cid']) && !strlen($target_item['deny_gid'])
383 && intval($target_item['pubmail'])) {
384 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `network` = '%s'",
388 if (DBM::is_result($r)) {
389 foreach ($r as $rr) {
390 $recipients[] = $rr['id'];
396 if (($cmd == Delivery::RELOCATION)) {
397 $r = $recipients_relocate;
400 $recipients = $recipients_followup;
402 $condition = ['id' => $recipients, 'self' => false,
403 'blocked' => false, 'pending' => false, 'archive' => false];
404 if (!empty($networks)) {
405 $condition['network'] = $networks;
407 $contacts = dba::select('contact', ['id', 'url', 'network'], $condition);
408 $r = dba::inArray($contacts);
412 if (DBM::is_result($r)) {
413 foreach ($r as $contact) {
414 logger("Deliver ".$target_item["guid"]." to ".$contact['url']." via network ".$contact['network'], LOGGER_DEBUG);
416 Worker::add(['priority' => $a->queue['priority'], 'created' => $a->queue['created'], 'dont_fork' => true],
417 'Delivery', $cmd, $item_id, (int)$contact['id']);
421 // send salmon slaps to mentioned remote tags (@foo@example.com) in OStatus posts
422 // They are especially used for notifications to OStatus users that don't follow us.
423 if (!Config::get('system', 'dfrn_only') && count($url_recipients) && ($public_message || $push_notify) && $normal_mode) {
424 $slap = OStatus::salmon($target_item, $owner);
425 foreach ($url_recipients as $url) {
427 logger('notifier: urldelivery: ' . $url);
428 $deliver_status = Salmon::slapper($owner, $url, $slap);
429 /// @TODO Redeliver/queue these items on failure, though there is no contact record
434 if ($public_message) {
437 if ($diaspora_delivery) {
438 $r1 = q("SELECT `batch`, ANY_VALUE(`id`) AS `id`, ANY_VALUE(`name`) AS `name`, ANY_VALUE(`network`) AS `network`
439 FROM `contact` WHERE `network` = '%s' AND `batch` != ''
440 AND `uid` = %d AND `rel` != %d AND NOT `blocked` AND NOT `pending` AND NOT `archive` GROUP BY `batch`",
441 dbesc(NETWORK_DIASPORA),
442 intval($owner['uid']),
443 intval(CONTACT_IS_SHARING)
446 // Fetch the participation list
447 // The function will ensure that there are no duplicates
448 $r1 = Diaspora::participantsForThread($item_id, $r1);
450 // Add the relay to the list, avoid duplicates
452 $r1 = Diaspora::relayList($item_id, $r1);
456 $condition = ['network' => NETWORK_DFRN, 'uid' => $owner['uid'], 'blocked' => false,
457 'pending' => false, 'archive' => false, 'rel' => [CONTACT_IS_FOLLOWER, CONTACT_IS_FRIEND]];
458 $r2 = dba::inArray(dba::select('contact', ['id', 'name', 'network'], $condition));
460 $r = array_merge($r2, $r1);
462 if (DBM::is_result($r)) {
463 logger('pubdeliver '.$target_item["guid"].': '.print_r($r,true), LOGGER_DEBUG);
465 foreach ($r as $rr) {
466 // except for Diaspora batch jobs
467 // Don't deliver to folks who have already been delivered to
469 if (($rr['network'] !== NETWORK_DIASPORA) && (in_array($rr['id'], $conversants))) {
470 logger('notifier: already delivered id=' . $rr['id']);
474 if (!in_array($cmd, [Delivery::MAIL, Delivery::SUGGESTION]) && !$followup) {
475 logger('notifier: delivery agent: '.$rr['name'].' '.$rr['id'].' '.$rr['network'].' '.$target_item["guid"]);
476 Worker::add(['priority' => $a->queue['priority'], 'created' => $a->queue['created'], 'dont_fork' => true],
477 'Delivery', $cmd, $item_id, (int)$rr['id']);
485 // Notify PuSH subscribers (Used for OStatus distribution of regular posts)
487 logger('Activating internal PuSH for item '.$item_id, LOGGER_DEBUG);
489 // Handling the pubsubhubbub requests
490 PushSubscriber::publishFeed($owner['uid'], $a->queue['priority']);
493 logger('notifier: calling hooks for ' . $cmd . ' ' . $item_id, LOGGER_DEBUG);
496 Addon::forkHooks($a->queue['priority'], 'notifier_normal', $target_item);
499 Addon::callHooks('notifier_end',$target_item);