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\Network\Probe;
15 use Friendica\Protocol\Diaspora;
16 use Friendica\Protocol\OStatus;
17 use Friendica\Protocol\Salmon;
18 use Friendica\Worker\Delivery;
21 require_once 'include/dba.php';
22 require_once 'include/items.php';
25 * The notifier is typically called with:
27 * Worker::add(PRIORITY_HIGH, "Notifier", COMMAND, ITEM_ID);
29 * where COMMAND is one of the following:
31 * activity (in diaspora.php, dfrn_confirm.php, profiles.php)
32 * comment-import (in diaspora.php, items.php)
33 * comment-new (in item.php)
34 * drop (in diaspora.php, items.php, photos.php)
35 * edit_post (in item.php)
36 * event (in events.php)
37 * like (in like.php, poke.php)
38 * mail (in message.php)
39 * suggest (in fsuggest.php)
40 * tag (in photos.php, poke.php, tagger.php)
41 * tgroup (in items.php)
42 * wall-new (in photos.php, item.php)
43 * removeme (in Contact.php)
44 * relocate (in uimport.php)
46 * and ITEM_ID is the id of the item in the database that needs to be sent to others.
50 public static function execute($cmd, $item_id) {
53 logger('notifier: invoked: '.$cmd.': '.$item_id, LOGGER_DEBUG);
60 $recipients_relocate = [];
62 if ($cmd == Delivery::MAIL) {
64 $message = dba::selectFirst('mail', ['uid', 'contact-id'], ['id' => $item_id]);
65 if (!DBM::is_result($message)) {
68 $uid = $message['uid'];
69 $recipients[] = $message['contact-id'];
70 } elseif ($cmd == Delivery::SUGGESTION) {
72 $suggest = dba::selectFirst('fsuggest', ['uid', 'cid'], ['id' => $item_id]);
73 if (!DBM::is_result($suggest)) {
76 $uid = $suggest['uid'];
77 $recipients[] = $suggest['cid'];
78 } elseif ($cmd == Delivery::REMOVAL) {
79 $r = q("SELECT `contact`.*, `user`.`prvkey` AS `uprvkey`,
80 `user`.`timezone`, `user`.`nickname`, `user`.`sprvkey`, `user`.`spubkey`,
81 `user`.`page-flags`, `user`.`prvnets`, `user`.`account-type`, `user`.`guid`
82 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
83 WHERE `contact`.`uid` = %d AND `contact`.`self` LIMIT 1",
90 $r = q("SELECT * FROM `contact` WHERE NOT `self` AND `uid` = %d", intval($item_id));
94 foreach ($r as $contact) {
95 Contact::terminateFriendship($user, $contact);
98 } elseif ($cmd == Delivery::RELOCATION) {
102 $recipients_relocate = q("SELECT * FROM `contact` WHERE `uid` = %d AND NOT `self` AND `network` IN ('%s', '%s')",
103 intval($uid), NETWORK_DFRN, NETWORK_DIASPORA);
106 $target_item = dba::fetch_first("SELECT `item`.*, `contact`.`uid` AS `cuid` FROM `item`
107 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
108 WHERE `item`.`id` = ? AND `visible` AND NOT `moderated`", $item_id);
110 if (!DBM::is_result($target_item) || !intval($target_item['parent'])) {
114 $parent_id = intval($target_item['parent']);
115 $uid = $target_item['cuid'];
116 $updated = $target_item['edited'];
118 $items = q("SELECT `item`.*, `sign`.`signed_text`,`sign`.`signature`,`sign`.`signer`
119 FROM `item` LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id` WHERE `parent` = %d AND visible AND NOT moderated ORDER BY `id` ASC",
123 if (!count($items)) {
127 // avoid race condition with deleting entries
128 if ($items[0]['deleted']) {
129 foreach ($items as $item) {
130 $item['deleted'] = 1;
134 if ((count($items) == 1) && ($items[0]['id'] === $target_item['id']) && ($items[0]['uri'] === $items[0]['parent-uri'])) {
135 logger('notifier: top level post');
140 $owner = User::getOwnerDataById($uid);
145 $walltowall = ($top_level && ($owner['id'] != $items[0]['contact-id']) ? true : false);
147 // Should the post be transmitted to Diaspora?
148 $diaspora_delivery = true;
150 // If this is a public conversation, notify the feed hub
151 $public_message = true;
154 $push_notify = false;
156 // Deliver directly to a forum, don't PuSH
157 $direct_forum_delivery = false;
160 $recipients_followup = [];
163 if (!in_array($cmd, [Delivery::MAIL, Delivery::SUGGESTION, Delivery::RELOCATION])) {
166 $thr_parent = q("SELECT `network`, `author-link`, `owner-link` FROM `item` WHERE `uri` = '%s' AND `uid` = %d",
167 dbesc($target_item["thr-parent"]), intval($target_item["uid"]));
169 logger('GUID: '.$target_item["guid"].': Parent is '.$parent['network'].'. Thread parent is '.$thr_parent[0]['network'], LOGGER_DEBUG);
171 // This is IMPORTANT!!!!
173 // We will only send a "notify owner to relay" or followup message if the referenced post
174 // originated on our system by virtue of having our hostname somewhere
175 // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
177 // if $parent['wall'] == 1 we will already have the parent message in our array
178 // and we will relay the whole lot.
180 $localhost = str_replace('www.','',$a->get_hostname());
181 if (strpos($localhost,':')) {
182 $localhost = substr($localhost,0,strpos($localhost,':'));
186 * Be VERY CAREFUL if you make any changes to the following several lines. Seemingly innocuous changes
187 * have been known to cause runaway conditions which affected several servers, along with
188 * permissions issues.
192 $relay_to_owner = false;
194 if (!$top_level && ($parent['wall'] == 0) && (stristr($target_item['uri'],$localhost))) {
195 $relay_to_owner = true;
199 if (($cmd === 'uplink') && (intval($parent['forum_mode']) == 1) && !$top_level) {
200 $relay_to_owner = true;
203 // until the 'origin' flag has been in use for several months
204 // we will just use it as a fallback test
205 // later we will be able to use it as the primary test of whether or not to relay.
207 if (!$target_item['origin']) {
208 $relay_to_owner = false;
210 if ($parent['origin']) {
211 $relay_to_owner = false;
214 // Special treatment for forum posts
215 if (($target_item['author-link'] != $target_item['owner-link']) &&
216 ($owner['id'] != $target_item['contact-id']) &&
217 ($target_item['uri'] === $target_item['parent-uri'])) {
219 $fields = ['forum', 'prv'];
220 $condition = ['id' => $target_item['contact-id']];
221 $contact = dba::selectFirst('contact', $fields, $condition);
222 if (!DBM::is_result($contact)) {
223 // Should never happen
227 // Is the post from a forum?
228 if ($contact['forum'] || $contact['prv']) {
229 $relay_to_owner = true;
230 $direct_forum_delivery = true;
233 if ($relay_to_owner) {
234 // local followup to remote post
236 $public_message = false; // not public
237 $conversant_str = dbesc($parent['contact-id']);
238 $recipients = [$parent['contact-id']];
239 $recipients_followup = [$parent['contact-id']];
241 logger('notifier: followup '.$target_item["guid"].' to '.$conversant_str, LOGGER_DEBUG);
243 //if (!$target_item['private'] && $target_item['wall'] &&
244 if (!$target_item['private'] &&
245 (strlen($target_item['allow_cid'].$target_item['allow_gid'].
246 $target_item['deny_cid'].$target_item['deny_gid']) == 0))
249 if (($thr_parent && ($thr_parent[0]['network'] == NETWORK_OSTATUS)) || ($parent['network'] == NETWORK_OSTATUS)) {
252 if ($parent["network"] == NETWORK_OSTATUS) {
253 // Distribute the message to the DFRN contacts as if this wasn't a followup since OStatus can't relay comments
254 // Currently it is work at progress
255 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `network` = '%s' AND NOT `blocked` AND NOT `pending` AND NOT `archive`",
259 if (DBM::is_result($r)) {
260 foreach ($r as $rr) {
261 $recipients_followup[] = $rr['id'];
267 if ($direct_forum_delivery) {
268 $push_notify = false;
271 logger("Notify ".$target_item["guid"]." via PuSH: ".($push_notify?"Yes":"No"), LOGGER_DEBUG);
275 logger('Distributing directly '.$target_item["guid"], LOGGER_DEBUG);
277 // don't send deletions onward for other people's stuff
279 if ($target_item['deleted'] && !intval($target_item['wall'])) {
280 logger('notifier: ignoring delete notification for non-wall item');
284 if (strlen($parent['allow_cid'])
285 || strlen($parent['allow_gid'])
286 || strlen($parent['deny_cid'])
287 || strlen($parent['deny_gid'])) {
288 $public_message = false; // private recipients, not public
291 $allow_people = expand_acl($parent['allow_cid']);
292 $allow_groups = Group::expand(expand_acl($parent['allow_gid']),true);
293 $deny_people = expand_acl($parent['deny_cid']);
294 $deny_groups = Group::expand(expand_acl($parent['deny_gid']));
296 // if our parent is a public forum (forum_mode == 1), uplink to the origional author causing
297 // a delivery fork. private groups (forum_mode == 2) do not uplink
299 if ((intval($parent['forum_mode']) == 1) && !$top_level && ($cmd !== 'uplink')) {
300 Worker::add($a->queue['priority'], 'Notifier', 'uplink', $item_id);
303 foreach ($items as $item) {
304 $recipients[] = $item['contact-id'];
305 $conversants[] = $item['contact-id'];
306 // pull out additional tagged people to notify (if public message)
307 if ($public_message && strlen($item['inform'])) {
308 $people = explode(',',$item['inform']);
309 foreach ($people as $person) {
310 if (substr($person,0,4) === 'cid:') {
311 $recipients[] = intval(substr($person,4));
312 $conversants[] = intval(substr($person,4));
314 $url_recipients[] = substr($person,4);
320 if (count($url_recipients)) {
321 logger('notifier: '.$target_item["guid"].' url_recipients ' . print_r($url_recipients,true));
324 $conversants = array_unique($conversants);
326 $recipients = array_unique(array_merge($recipients,$allow_people,$allow_groups));
327 $deny = array_unique(array_merge($deny_people,$deny_groups));
328 $recipients = array_diff($recipients,$deny);
330 $conversant_str = dbesc(implode(', ',$conversants));
333 // If the thread parent is OStatus then do some magic to distribute the messages.
334 // We have not only to look at the parent, since it could be a Friendica thread.
335 if (($thr_parent && ($thr_parent[0]['network'] == NETWORK_OSTATUS)) || ($parent['network'] == NETWORK_OSTATUS)) {
336 $diaspora_delivery = false;
338 logger('Some parent is OStatus for '.$target_item["guid"]." - Author: ".$thr_parent[0]['author-link']." - Owner: ".$thr_parent[0]['owner-link'], LOGGER_DEBUG);
340 // Send a salmon to the parent author
341 $r = q("SELECT `url`, `notify` FROM `contact` WHERE `nurl`='%s' AND `uid` IN (0, %d) AND `notify` != ''",
342 dbesc(normalise_link($thr_parent[0]['author-link'])),
344 if (DBM::is_result($r)) {
345 $probed_contact = $r[0];
347 $probed_contact = Probe::uri($thr_parent[0]['author-link']);
350 if ($probed_contact["notify"] != "") {
351 logger('Notify parent author '.$probed_contact["url"].': '.$probed_contact["notify"]);
352 $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
355 // Send a salmon to the parent owner
356 $r = q("SELECT `url`, `notify` FROM `contact` WHERE `nurl`='%s' AND `uid` IN (0, %d) AND `notify` != ''",
357 dbesc(normalise_link($thr_parent[0]['owner-link'])),
359 if (DBM::is_result($r)) {
360 $probed_contact = $r[0];
362 $probed_contact = Probe::uri($thr_parent[0]['owner-link']);
365 if ($probed_contact["notify"] != "") {
366 logger('Notify parent owner '.$probed_contact["url"].': '.$probed_contact["notify"]);
367 $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
370 // Send a salmon notification to every person we mentioned in the post
371 $arr = explode(',',$target_item['tag']);
372 foreach ($arr as $x) {
373 //logger('Checking tag '.$x, LOGGER_DEBUG);
375 if (preg_match('/@\[url=([^\]]*)\]/',$x,$matches)) {
376 $probed_contact = Probe::uri($matches[1]);
377 if ($probed_contact["notify"] != "") {
378 logger('Notify mentioned user '.$probed_contact["url"].': '.$probed_contact["notify"]);
379 $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
384 // It only makes sense to distribute answers to OStatus messages to Friendica and OStatus - but not Diaspora
385 $networks = [NETWORK_OSTATUS, NETWORK_DFRN];
387 $networks = [NETWORK_OSTATUS, NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_MAIL];
390 $public_message = false;
393 // If this is a public message and pubmail is set on the parent, include all your email contacts
394 if (function_exists('imap_open') && !Config::get('system','imap_disabled')) {
395 if (!strlen($target_item['allow_cid']) && !strlen($target_item['allow_gid'])
396 && !strlen($target_item['deny_cid']) && !strlen($target_item['deny_gid'])
397 && intval($target_item['pubmail'])) {
398 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `network` = '%s'",
402 if (DBM::is_result($r)) {
403 foreach ($r as $rr) {
404 $recipients[] = $rr['id'];
410 if (($cmd == Delivery::RELOCATION)) {
411 $r = $recipients_relocate;
414 $recipients = $recipients_followup;
416 $condition = ['id' => $recipients, 'self' => false,
417 'blocked' => false, 'pending' => false, 'archive' => false];
418 if (!empty($networks)) {
419 $condition['network'] = $networks;
421 $contacts = dba::select('contact', ['id', 'url', 'network'], $condition);
422 $r = dba::inArray($contacts);
426 if (DBM::is_result($r)) {
427 foreach ($r as $contact) {
428 logger("Deliver ".$target_item["guid"]." to ".$contact['url']." via network ".$contact['network'], LOGGER_DEBUG);
430 Worker::add(['priority' => $a->queue['priority'], 'created' => $a->queue['created'], 'dont_fork' => true],
431 'Delivery', $cmd, $item_id, (int)$contact['id']);
435 // send salmon slaps to mentioned remote tags (@foo@example.com) in OStatus posts
436 // They are especially used for notifications to OStatus users that don't follow us.
437 if (!Config::get('system', 'dfrn_only') && count($url_recipients) && ($public_message || $push_notify) && $normal_mode) {
438 $slap = OStatus::salmon($target_item, $owner);
439 foreach ($url_recipients as $url) {
441 logger('notifier: urldelivery: ' . $url);
442 $deliver_status = Salmon::slapper($owner, $url, $slap);
443 /// @TODO Redeliver/queue these items on failure, though there is no contact record
448 if ($public_message) {
451 if ($diaspora_delivery) {
452 $r1 = q("SELECT `batch`, ANY_VALUE(`id`) AS `id`, ANY_VALUE(`name`) AS `name`, ANY_VALUE(`network`) AS `network`
453 FROM `contact` WHERE `network` = '%s' AND `batch` != ''
454 AND `uid` = %d AND `rel` != %d AND NOT `blocked` AND NOT `pending` AND NOT `archive` GROUP BY `batch`",
455 dbesc(NETWORK_DIASPORA),
456 intval($owner['uid']),
457 intval(CONTACT_IS_SHARING)
460 // Fetch the participation list
461 // The function will ensure that there are no duplicates
462 $r1 = Diaspora::participantsForThread($item_id, $r1);
464 // Add the relay to the list, avoid duplicates
466 $r1 = Diaspora::relayList($item_id, $r1);
470 $condition = ['network' => NETWORK_DFRN, 'uid' => $owner['uid'], 'blocked' => false,
471 'pending' => false, 'archive' => false, 'rel' => [CONTACT_IS_FOLLOWER, CONTACT_IS_FRIEND]];
472 $r2 = dba::inArray(dba::select('contact', ['id', 'name', 'network'], $condition));
474 $r = array_merge($r2, $r1);
476 if (DBM::is_result($r)) {
477 logger('pubdeliver '.$target_item["guid"].': '.print_r($r,true), LOGGER_DEBUG);
479 foreach ($r as $rr) {
480 // except for Diaspora batch jobs
481 // Don't deliver to folks who have already been delivered to
483 if (($rr['network'] !== NETWORK_DIASPORA) && (in_array($rr['id'], $conversants))) {
484 logger('notifier: already delivered id=' . $rr['id']);
488 if (!in_array($cmd, [Delivery::MAIL, Delivery::SUGGESTION]) && !$followup) {
489 logger('notifier: delivery agent: '.$rr['name'].' '.$rr['id'].' '.$rr['network'].' '.$target_item["guid"]);
490 Worker::add(['priority' => $a->queue['priority'], 'created' => $a->queue['created'], 'dont_fork' => true],
491 'Delivery', $cmd, $item_id, (int)$rr['id']);
499 // Notify PuSH subscribers (Used for OStatus distribution of regular posts)
501 // Set push flag for PuSH subscribers to this topic,
502 // they will be notified in queue.php
503 $condition = ['push' => false, 'nickname' => $owner['nickname']];
504 dba::update('push_subscriber', ['push' => true, 'next_try' => NULL_DATE], $condition);
506 logger('Activating internal PuSH for item '.$item_id, LOGGER_DEBUG);
508 // Handling the pubsubhubbub requests
509 Worker::add(['priority' => $a->queue['priority'], 'created' => $a->queue['created'], 'dont_fork' => true],
513 logger('notifier: calling hooks for ' . $cmd . ' ' . $item_id, LOGGER_DEBUG);
516 Addon::forkHooks($a->queue['priority'], 'notifier_normal', $target_item);
519 Addon::callHooks('notifier_end',$target_item);