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\Protocol;
11 use Friendica\Core\Worker;
12 use Friendica\Database\DBA;
13 use Friendica\Model\Contact;
14 use Friendica\Model\Group;
15 use Friendica\Model\Item;
16 use Friendica\Model\PushSubscriber;
17 use Friendica\Model\User;
18 use Friendica\Network\Probe;
19 use Friendica\Protocol\Diaspora;
20 use Friendica\Protocol\OStatus;
21 use Friendica\Protocol\Salmon;
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.
53 public static function execute($cmd, $item_id)
55 $a = BaseObject::getApp();
57 logger('notifier: invoked: '.$cmd.': '.$item_id, LOGGER_DEBUG);
64 $recipients_relocate = [];
66 if ($cmd == Delivery::MAIL) {
68 $message = DBA::selectFirst('mail', ['uid', 'contact-id'], ['id' => $item_id]);
69 if (!DBA::isResult($message)) {
72 $uid = $message['uid'];
73 $recipients[] = $message['contact-id'];
74 } elseif ($cmd == Delivery::SUGGESTION) {
76 $suggest = DBA::selectFirst('fsuggest', ['uid', 'cid'], ['id' => $item_id]);
77 if (!DBA::isResult($suggest)) {
80 $uid = $suggest['uid'];
81 $recipients[] = $suggest['cid'];
82 } elseif ($cmd == Delivery::REMOVAL) {
83 $r = q("SELECT `contact`.*, `user`.`prvkey` AS `uprvkey`,
84 `user`.`timezone`, `user`.`nickname`, `user`.`sprvkey`, `user`.`spubkey`,
85 `user`.`page-flags`, `user`.`prvnets`, `user`.`account-type`, `user`.`guid`
86 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
87 WHERE `contact`.`uid` = %d AND `contact`.`self` LIMIT 1",
94 $r = q("SELECT * FROM `contact` WHERE NOT `self` AND `uid` = %d", intval($item_id));
98 foreach ($r as $contact) {
99 Contact::terminateFriendship($user, $contact);
102 } elseif ($cmd == Delivery::RELOCATION) {
103 $normal_mode = false;
106 $recipients_relocate = q("SELECT * FROM `contact` WHERE `uid` = %d AND NOT `self` AND `network` IN ('%s', '%s')",
107 intval($uid), Protocol::DFRN, Protocol::DIASPORA);
110 $condition = ['id' => $item_id, 'visible' => true, 'moderated' => false];
111 $target_item = Item::selectFirst([], $condition);
113 if (!DBA::isResult($target_item) || !intval($target_item['parent'])) {
117 $parent_id = intval($target_item['parent']);
118 $uid = $target_item['contact-uid'];
119 $updated = $target_item['edited'];
121 $condition = ['parent' => $parent_id, 'visible' => true, 'moderated' => false];
122 $params = ['order' => ['id']];
123 $ret = Item::select([], $condition, $params);
125 if (!DBA::isResult($ret)) {
129 $items = Item::inArray($ret);
131 // avoid race condition with deleting entries
132 if ($items[0]['deleted']) {
133 foreach ($items as $item) {
134 $item['deleted'] = 1;
138 if ((count($items) == 1) && ($items[0]['id'] === $target_item['id']) && ($items[0]['uri'] === $items[0]['parent-uri'])) {
139 logger('notifier: top level post');
144 $owner = User::getOwnerDataById($uid);
149 $walltowall = ($top_level && ($owner['id'] != $items[0]['contact-id']) ? true : false);
151 // Should the post be transmitted to Diaspora?
152 $diaspora_delivery = true;
154 // If this is a public conversation, notify the feed hub
155 $public_message = true;
158 $push_notify = false;
160 // Deliver directly to a forum, don't PuSH
161 $direct_forum_delivery = false;
164 $recipients_followup = [];
167 if (!in_array($cmd, [Delivery::MAIL, Delivery::SUGGESTION, Delivery::RELOCATION])) {
170 $fields = ['network', 'author-id', 'owner-id'];
171 $condition = ['uri' => $target_item["thr-parent"], 'uid' => $target_item["uid"]];
172 $thr_parent = Item::selectFirst($fields, $condition);
174 logger('GUID: '.$target_item["guid"].': Parent is '.$parent['network'].'. Thread parent is '.$thr_parent['network'], LOGGER_DEBUG);
176 // This is IMPORTANT!!!!
178 // We will only send a "notify owner to relay" or followup message if the referenced post
179 // originated on our system by virtue of having our hostname somewhere
180 // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
182 // if $parent['wall'] == 1 we will already have the parent message in our array
183 // and we will relay the whole lot.
185 $localhost = str_replace('www.','',$a->get_hostname());
186 if (strpos($localhost,':')) {
187 $localhost = substr($localhost,0,strpos($localhost,':'));
191 * Be VERY CAREFUL if you make any changes to the following several lines. Seemingly innocuous changes
192 * have been known to cause runaway conditions which affected several servers, along with
193 * permissions issues.
197 $relay_to_owner = false;
199 if (!$top_level && ($parent['wall'] == 0) && (stristr($target_item['uri'],$localhost))) {
200 $relay_to_owner = true;
204 if (($cmd === 'uplink') && (intval($parent['forum_mode']) == 1) && !$top_level) {
205 $relay_to_owner = true;
208 // until the 'origin' flag has been in use for several months
209 // we will just use it as a fallback test
210 // later we will be able to use it as the primary test of whether or not to relay.
212 if (!$target_item['origin']) {
213 $relay_to_owner = false;
215 if ($parent['origin']) {
216 $relay_to_owner = false;
219 // Special treatment for forum posts
220 if (($target_item['author-id'] != $target_item['owner-id']) &&
221 ($owner['id'] != $target_item['contact-id']) &&
222 ($target_item['uri'] === $target_item['parent-uri'])) {
224 $fields = ['forum', 'prv'];
225 $condition = ['id' => $target_item['contact-id']];
226 $contact = DBA::selectFirst('contact', $fields, $condition);
227 if (!DBA::isResult($contact)) {
228 // Should never happen
232 // Is the post from a forum?
233 if ($contact['forum'] || $contact['prv']) {
234 $relay_to_owner = true;
235 $direct_forum_delivery = true;
238 if ($relay_to_owner) {
239 // local followup to remote post
241 $public_message = false; // not public
242 $conversant_str = DBA::escape($parent['contact-id']);
243 $recipients = [$parent['contact-id']];
244 $recipients_followup = [$parent['contact-id']];
246 logger('notifier: followup '.$target_item["guid"].' to '.$conversant_str, LOGGER_DEBUG);
248 //if (!$target_item['private'] && $target_item['wall'] &&
249 if (!$target_item['private'] &&
250 (strlen($target_item['allow_cid'].$target_item['allow_gid'].
251 $target_item['deny_cid'].$target_item['deny_gid']) == 0))
254 if (($thr_parent && ($thr_parent['network'] == Protocol::OSTATUS)) || ($parent['network'] == Protocol::OSTATUS)) {
257 if ($parent["network"] == Protocol::OSTATUS) {
258 // Distribute the message to the DFRN contacts as if this wasn't a followup since OStatus can't relay comments
259 // Currently it is work at progress
260 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `network` = '%s' AND NOT `blocked` AND NOT `pending` AND NOT `archive`",
262 DBA::escape(Protocol::DFRN)
264 if (DBA::isResult($r)) {
265 foreach ($r as $rr) {
266 $recipients_followup[] = $rr['id'];
272 if ($direct_forum_delivery) {
273 $push_notify = false;
276 logger("Notify ".$target_item["guid"]." via PuSH: ".($push_notify?"Yes":"No"), LOGGER_DEBUG);
280 logger('Distributing directly '.$target_item["guid"], LOGGER_DEBUG);
282 // don't send deletions onward for other people's stuff
284 if ($target_item['deleted'] && !intval($target_item['wall'])) {
285 logger('notifier: ignoring delete notification for non-wall item');
289 if (strlen($parent['allow_cid'])
290 || strlen($parent['allow_gid'])
291 || strlen($parent['deny_cid'])
292 || strlen($parent['deny_gid'])) {
293 $public_message = false; // private recipients, not public
296 $allow_people = expand_acl($parent['allow_cid']);
297 $allow_groups = Group::expand(expand_acl($parent['allow_gid']),true);
298 $deny_people = expand_acl($parent['deny_cid']);
299 $deny_groups = Group::expand(expand_acl($parent['deny_gid']));
301 // if our parent is a public forum (forum_mode == 1), uplink to the origional author causing
302 // a delivery fork. private groups (forum_mode == 2) do not uplink
304 if ((intval($parent['forum_mode']) == 1) && !$top_level && ($cmd !== 'uplink')) {
305 Worker::add($a->queue['priority'], 'Notifier', 'uplink', $item_id);
308 foreach ($items as $item) {
309 $recipients[] = $item['contact-id'];
310 $conversants[] = $item['contact-id'];
311 // pull out additional tagged people to notify (if public message)
312 if ($public_message && strlen($item['inform'])) {
313 $people = explode(',',$item['inform']);
314 foreach ($people as $person) {
315 if (substr($person,0,4) === 'cid:') {
316 $recipients[] = intval(substr($person,4));
317 $conversants[] = intval(substr($person,4));
319 $url_recipients[] = substr($person,4);
325 if (count($url_recipients)) {
326 logger('notifier: '.$target_item["guid"].' url_recipients ' . print_r($url_recipients,true));
329 $conversants = array_unique($conversants);
331 $recipients = array_unique(array_merge($recipients,$allow_people,$allow_groups));
332 $deny = array_unique(array_merge($deny_people,$deny_groups));
333 $recipients = array_diff($recipients,$deny);
335 $conversant_str = DBA::escape(implode(', ',$conversants));
338 // If the thread parent is OStatus then do some magic to distribute the messages.
339 // We have not only to look at the parent, since it could be a Friendica thread.
340 if (($thr_parent && ($thr_parent['network'] == Protocol::OSTATUS)) || ($parent['network'] == Protocol::OSTATUS)) {
341 $diaspora_delivery = false;
343 logger('Some parent is OStatus for '.$target_item["guid"]." - Author: ".$thr_parent['author-id']." - Owner: ".$thr_parent['owner-id'], LOGGER_DEBUG);
345 // Send a salmon to the parent author
346 $probed_contact = DBA::selectFirst('contact', ['url', 'notify'], ['id' => $thr_parent['author-id']]);
347 if (DBA::isResult($probed_contact) && !empty($probed_contact["notify"])) {
348 logger('Notify parent author '.$probed_contact["url"].': '.$probed_contact["notify"]);
349 $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
352 // Send a salmon to the parent owner
353 $probed_contact = DBA::selectFirst('contact', ['url', 'notify'], ['id' => $thr_parent['owner-id']]);
354 if (DBA::isResult($probed_contact) && !empty($probed_contact["notify"])) {
355 logger('Notify parent owner '.$probed_contact["url"].': '.$probed_contact["notify"]);
356 $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
359 // Send a salmon notification to every person we mentioned in the post
360 $arr = explode(',',$target_item['tag']);
361 foreach ($arr as $x) {
362 //logger('Checking tag '.$x, LOGGER_DEBUG);
364 if (preg_match('/@\[url=([^\]]*)\]/',$x,$matches)) {
365 $probed_contact = Probe::uri($matches[1]);
366 if ($probed_contact["notify"] != "") {
367 logger('Notify mentioned user '.$probed_contact["url"].': '.$probed_contact["notify"]);
368 $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
373 // It only makes sense to distribute answers to OStatus messages to Friendica and OStatus - but not Diaspora
374 $networks = [Protocol::OSTATUS, Protocol::DFRN];
376 $networks = [Protocol::OSTATUS, Protocol::DFRN, Protocol::DIASPORA, Protocol::MAIL];
379 $public_message = false;
382 // If this is a public message and pubmail is set on the parent, include all your email contacts
383 if (!empty($target_item) && function_exists('imap_open') && !Config::get('system','imap_disabled')) {
384 if (!strlen($target_item['allow_cid']) && !strlen($target_item['allow_gid'])
385 && !strlen($target_item['deny_cid']) && !strlen($target_item['deny_gid'])
386 && intval($target_item['pubmail'])) {
387 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `network` = '%s'",
389 DBA::escape(Protocol::MAIL)
391 if (DBA::isResult($r)) {
392 foreach ($r as $rr) {
393 $recipients[] = $rr['id'];
399 if (($cmd == Delivery::RELOCATION)) {
400 $r = $recipients_relocate;
403 $recipients = $recipients_followup;
405 $condition = ['id' => $recipients, 'self' => false,
406 'blocked' => false, 'pending' => false, 'archive' => false];
407 if (!empty($networks)) {
408 $condition['network'] = $networks;
410 $contacts = DBA::select('contact', ['id', 'url', 'network'], $condition);
411 $r = DBA::toArray($contacts);
415 if (DBA::isResult($r)) {
416 foreach ($r as $contact) {
417 logger("Deliver ".$item_id." to ".$contact['url']." via network ".$contact['network'], LOGGER_DEBUG);
419 Worker::add(['priority' => $a->queue['priority'], 'created' => $a->queue['created'], 'dont_fork' => true],
420 'Delivery', $cmd, $item_id, (int)$contact['id']);
424 // send salmon slaps to mentioned remote tags (@foo@example.com) in OStatus posts
425 // They are especially used for notifications to OStatus users that don't follow us.
426 if (!Config::get('system', 'dfrn_only') && count($url_recipients) && ($public_message || $push_notify) && $normal_mode) {
427 $slap = OStatus::salmon($target_item, $owner);
428 foreach ($url_recipients as $url) {
430 logger('notifier: urldelivery: ' . $url);
431 $deliver_status = Salmon::slapper($owner, $url, $slap);
432 /// @TODO Redeliver/queue these items on failure, though there is no contact record
437 if ($public_message) {
440 if ($diaspora_delivery) {
441 $r1 = q("SELECT `batch`, ANY_VALUE(`id`) AS `id`, ANY_VALUE(`name`) AS `name`, ANY_VALUE(`network`) AS `network`
442 FROM `contact` WHERE `network` = '%s' AND `batch` != ''
443 AND `uid` = %d AND `rel` != %d AND NOT `blocked` AND NOT `pending` AND NOT `archive` GROUP BY `batch`",
444 DBA::escape(Protocol::DIASPORA),
445 intval($owner['uid']),
446 intval(Contact::SHARING)
449 // Fetch the participation list
450 // The function will ensure that there are no duplicates
451 $r1 = Diaspora::participantsForThread($item_id, $r1);
453 // Add the relay to the list, avoid duplicates
455 $r1 = Diaspora::relayList($item_id, $r1);
459 $condition = ['network' => Protocol::DFRN, 'uid' => $owner['uid'], 'blocked' => false,
460 'pending' => false, 'archive' => false, 'rel' => [Contact::FOLLOWER, Contact::FRIEND]];
462 $r2 = DBA::toArray(DBA::select('contact', ['id', 'name', 'network'], $condition));
464 $r = array_merge($r2, $r1);
466 if (DBA::isResult($r)) {
467 logger('pubdeliver '.$target_item["guid"].': '.print_r($r,true), LOGGER_DEBUG);
469 foreach ($r as $rr) {
470 // except for Diaspora batch jobs
471 // Don't deliver to folks who have already been delivered to
473 if (($rr['network'] !== Protocol::DIASPORA) && (in_array($rr['id'], $conversants))) {
474 logger('notifier: already delivered id=' . $rr['id']);
478 if (!in_array($cmd, [Delivery::MAIL, Delivery::SUGGESTION]) && !$followup) {
479 logger('notifier: delivery agent: '.$rr['name'].' '.$rr['id'].' '.$rr['network'].' '.$target_item["guid"]);
480 Worker::add(['priority' => $a->queue['priority'], 'created' => $a->queue['created'], 'dont_fork' => true],
481 'Delivery', $cmd, $item_id, (int)$rr['id']);
489 // Notify PuSH subscribers (Used for OStatus distribution of regular posts)
491 logger('Activating internal PuSH for item '.$item_id, LOGGER_DEBUG);
493 // Handling the pubsubhubbub requests
494 PushSubscriber::publishFeed($owner['uid'], $a->queue['priority']);
497 logger('notifier: calling hooks for ' . $cmd . ' ' . $item_id, LOGGER_DEBUG);
500 Addon::forkHooks($a->queue['priority'], 'notifier_normal', $target_item);
503 Addon::callHooks('notifier_end',$target_item);