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 $thr_parent = q("SELECT `network`, `author-link`, `owner-link` FROM `item` WHERE `uri` = '%s' AND `uid` = %d",
168 dbesc($target_item["thr-parent"]), intval($target_item["uid"]));
170 logger('GUID: '.$target_item["guid"].': Parent is '.$parent['network'].'. Thread parent is '.$thr_parent[0]['network'], LOGGER_DEBUG);
172 // This is IMPORTANT!!!!
174 // We will only send a "notify owner to relay" or followup message if the referenced post
175 // originated on our system by virtue of having our hostname somewhere
176 // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
178 // if $parent['wall'] == 1 we will already have the parent message in our array
179 // and we will relay the whole lot.
181 $localhost = str_replace('www.','',$a->get_hostname());
182 if (strpos($localhost,':')) {
183 $localhost = substr($localhost,0,strpos($localhost,':'));
187 * Be VERY CAREFUL if you make any changes to the following several lines. Seemingly innocuous changes
188 * have been known to cause runaway conditions which affected several servers, along with
189 * permissions issues.
193 $relay_to_owner = false;
195 if (!$top_level && ($parent['wall'] == 0) && (stristr($target_item['uri'],$localhost))) {
196 $relay_to_owner = true;
200 if (($cmd === 'uplink') && (intval($parent['forum_mode']) == 1) && !$top_level) {
201 $relay_to_owner = true;
204 // until the 'origin' flag has been in use for several months
205 // we will just use it as a fallback test
206 // later we will be able to use it as the primary test of whether or not to relay.
208 if (!$target_item['origin']) {
209 $relay_to_owner = false;
211 if ($parent['origin']) {
212 $relay_to_owner = false;
215 // Special treatment for forum posts
216 if (($target_item['author-link'] != $target_item['owner-link']) &&
217 ($owner['id'] != $target_item['contact-id']) &&
218 ($target_item['uri'] === $target_item['parent-uri'])) {
220 $fields = ['forum', 'prv'];
221 $condition = ['id' => $target_item['contact-id']];
222 $contact = dba::selectFirst('contact', $fields, $condition);
223 if (!DBM::is_result($contact)) {
224 // Should never happen
228 // Is the post from a forum?
229 if ($contact['forum'] || $contact['prv']) {
230 $relay_to_owner = true;
231 $direct_forum_delivery = true;
234 if ($relay_to_owner) {
235 // local followup to remote post
237 $public_message = false; // not public
238 $conversant_str = dbesc($parent['contact-id']);
239 $recipients = [$parent['contact-id']];
240 $recipients_followup = [$parent['contact-id']];
242 logger('notifier: followup '.$target_item["guid"].' to '.$conversant_str, LOGGER_DEBUG);
244 //if (!$target_item['private'] && $target_item['wall'] &&
245 if (!$target_item['private'] &&
246 (strlen($target_item['allow_cid'].$target_item['allow_gid'].
247 $target_item['deny_cid'].$target_item['deny_gid']) == 0))
250 if (($thr_parent && ($thr_parent[0]['network'] == NETWORK_OSTATUS)) || ($parent['network'] == NETWORK_OSTATUS)) {
253 if ($parent["network"] == NETWORK_OSTATUS) {
254 // Distribute the message to the DFRN contacts as if this wasn't a followup since OStatus can't relay comments
255 // Currently it is work at progress
256 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `network` = '%s' AND NOT `blocked` AND NOT `pending` AND NOT `archive`",
260 if (DBM::is_result($r)) {
261 foreach ($r as $rr) {
262 $recipients_followup[] = $rr['id'];
268 if ($direct_forum_delivery) {
269 $push_notify = false;
272 logger("Notify ".$target_item["guid"]." via PuSH: ".($push_notify?"Yes":"No"), LOGGER_DEBUG);
276 logger('Distributing directly '.$target_item["guid"], LOGGER_DEBUG);
278 // don't send deletions onward for other people's stuff
280 if ($target_item['deleted'] && !intval($target_item['wall'])) {
281 logger('notifier: ignoring delete notification for non-wall item');
285 if (strlen($parent['allow_cid'])
286 || strlen($parent['allow_gid'])
287 || strlen($parent['deny_cid'])
288 || strlen($parent['deny_gid'])) {
289 $public_message = false; // private recipients, not public
292 $allow_people = expand_acl($parent['allow_cid']);
293 $allow_groups = Group::expand(expand_acl($parent['allow_gid']),true);
294 $deny_people = expand_acl($parent['deny_cid']);
295 $deny_groups = Group::expand(expand_acl($parent['deny_gid']));
297 // if our parent is a public forum (forum_mode == 1), uplink to the origional author causing
298 // a delivery fork. private groups (forum_mode == 2) do not uplink
300 if ((intval($parent['forum_mode']) == 1) && !$top_level && ($cmd !== 'uplink')) {
301 Worker::add($a->queue['priority'], 'Notifier', 'uplink', $item_id);
304 foreach ($items as $item) {
305 $recipients[] = $item['contact-id'];
306 $conversants[] = $item['contact-id'];
307 // pull out additional tagged people to notify (if public message)
308 if ($public_message && strlen($item['inform'])) {
309 $people = explode(',',$item['inform']);
310 foreach ($people as $person) {
311 if (substr($person,0,4) === 'cid:') {
312 $recipients[] = intval(substr($person,4));
313 $conversants[] = intval(substr($person,4));
315 $url_recipients[] = substr($person,4);
321 if (count($url_recipients)) {
322 logger('notifier: '.$target_item["guid"].' url_recipients ' . print_r($url_recipients,true));
325 $conversants = array_unique($conversants);
327 $recipients = array_unique(array_merge($recipients,$allow_people,$allow_groups));
328 $deny = array_unique(array_merge($deny_people,$deny_groups));
329 $recipients = array_diff($recipients,$deny);
331 $conversant_str = dbesc(implode(', ',$conversants));
334 // If the thread parent is OStatus then do some magic to distribute the messages.
335 // We have not only to look at the parent, since it could be a Friendica thread.
336 if (($thr_parent && ($thr_parent[0]['network'] == NETWORK_OSTATUS)) || ($parent['network'] == NETWORK_OSTATUS)) {
337 $diaspora_delivery = false;
339 logger('Some parent is OStatus for '.$target_item["guid"]." - Author: ".$thr_parent[0]['author-link']." - Owner: ".$thr_parent[0]['owner-link'], LOGGER_DEBUG);
341 // Send a salmon to the parent author
342 $r = q("SELECT `url`, `notify` FROM `contact` WHERE `nurl`='%s' AND `uid` IN (0, %d) AND `notify` != ''",
343 dbesc(normalise_link($thr_parent[0]['author-link'])),
345 if (DBM::is_result($r)) {
346 $probed_contact = $r[0];
348 $probed_contact = Probe::uri($thr_parent[0]['author-link']);
351 if ($probed_contact["notify"] != "") {
352 logger('Notify parent author '.$probed_contact["url"].': '.$probed_contact["notify"]);
353 $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
356 // Send a salmon to the parent owner
357 $r = q("SELECT `url`, `notify` FROM `contact` WHERE `nurl`='%s' AND `uid` IN (0, %d) AND `notify` != ''",
358 dbesc(normalise_link($thr_parent[0]['owner-link'])),
360 if (DBM::is_result($r)) {
361 $probed_contact = $r[0];
363 $probed_contact = Probe::uri($thr_parent[0]['owner-link']);
366 if ($probed_contact["notify"] != "") {
367 logger('Notify parent owner '.$probed_contact["url"].': '.$probed_contact["notify"]);
368 $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
371 // Send a salmon notification to every person we mentioned in the post
372 $arr = explode(',',$target_item['tag']);
373 foreach ($arr as $x) {
374 //logger('Checking tag '.$x, LOGGER_DEBUG);
376 if (preg_match('/@\[url=([^\]]*)\]/',$x,$matches)) {
377 $probed_contact = Probe::uri($matches[1]);
378 if ($probed_contact["notify"] != "") {
379 logger('Notify mentioned user '.$probed_contact["url"].': '.$probed_contact["notify"]);
380 $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
385 // It only makes sense to distribute answers to OStatus messages to Friendica and OStatus - but not Diaspora
386 $networks = [NETWORK_OSTATUS, NETWORK_DFRN];
388 $networks = [NETWORK_OSTATUS, NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_MAIL];
391 $public_message = false;
394 // If this is a public message and pubmail is set on the parent, include all your email contacts
395 if (function_exists('imap_open') && !Config::get('system','imap_disabled')) {
396 if (!strlen($target_item['allow_cid']) && !strlen($target_item['allow_gid'])
397 && !strlen($target_item['deny_cid']) && !strlen($target_item['deny_gid'])
398 && intval($target_item['pubmail'])) {
399 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `network` = '%s'",
403 if (DBM::is_result($r)) {
404 foreach ($r as $rr) {
405 $recipients[] = $rr['id'];
411 if (($cmd == Delivery::RELOCATION)) {
412 $r = $recipients_relocate;
415 $recipients = $recipients_followup;
417 $condition = ['id' => $recipients, 'self' => false,
418 'blocked' => false, 'pending' => false, 'archive' => false];
419 if (!empty($networks)) {
420 $condition['network'] = $networks;
422 $contacts = dba::select('contact', ['id', 'url', 'network'], $condition);
423 $r = dba::inArray($contacts);
427 if (DBM::is_result($r)) {
428 foreach ($r as $contact) {
429 logger("Deliver ".$target_item["guid"]." to ".$contact['url']." via network ".$contact['network'], LOGGER_DEBUG);
431 Worker::add(['priority' => $a->queue['priority'], 'created' => $a->queue['created'], 'dont_fork' => true],
432 'Delivery', $cmd, $item_id, (int)$contact['id']);
436 // send salmon slaps to mentioned remote tags (@foo@example.com) in OStatus posts
437 // They are especially used for notifications to OStatus users that don't follow us.
438 if (!Config::get('system', 'dfrn_only') && count($url_recipients) && ($public_message || $push_notify) && $normal_mode) {
439 $slap = OStatus::salmon($target_item, $owner);
440 foreach ($url_recipients as $url) {
442 logger('notifier: urldelivery: ' . $url);
443 $deliver_status = Salmon::slapper($owner, $url, $slap);
444 /// @TODO Redeliver/queue these items on failure, though there is no contact record
449 if ($public_message) {
452 if ($diaspora_delivery) {
453 $r1 = q("SELECT `batch`, ANY_VALUE(`id`) AS `id`, ANY_VALUE(`name`) AS `name`, ANY_VALUE(`network`) AS `network`
454 FROM `contact` WHERE `network` = '%s' AND `batch` != ''
455 AND `uid` = %d AND `rel` != %d AND NOT `blocked` AND NOT `pending` AND NOT `archive` GROUP BY `batch`",
456 dbesc(NETWORK_DIASPORA),
457 intval($owner['uid']),
458 intval(CONTACT_IS_SHARING)
461 // Fetch the participation list
462 // The function will ensure that there are no duplicates
463 $r1 = Diaspora::participantsForThread($item_id, $r1);
465 // Add the relay to the list, avoid duplicates
467 $r1 = Diaspora::relayList($item_id, $r1);
471 $condition = ['network' => NETWORK_DFRN, 'uid' => $owner['uid'], 'blocked' => false,
472 'pending' => false, 'archive' => false, 'rel' => [CONTACT_IS_FOLLOWER, CONTACT_IS_FRIEND]];
473 $r2 = dba::inArray(dba::select('contact', ['id', 'name', 'network'], $condition));
475 $r = array_merge($r2, $r1);
477 if (DBM::is_result($r)) {
478 logger('pubdeliver '.$target_item["guid"].': '.print_r($r,true), LOGGER_DEBUG);
480 foreach ($r as $rr) {
481 // except for Diaspora batch jobs
482 // Don't deliver to folks who have already been delivered to
484 if (($rr['network'] !== NETWORK_DIASPORA) && (in_array($rr['id'], $conversants))) {
485 logger('notifier: already delivered id=' . $rr['id']);
489 if (!in_array($cmd, [Delivery::MAIL, Delivery::SUGGESTION]) && !$followup) {
490 logger('notifier: delivery agent: '.$rr['name'].' '.$rr['id'].' '.$rr['network'].' '.$target_item["guid"]);
491 Worker::add(['priority' => $a->queue['priority'], 'created' => $a->queue['created'], 'dont_fork' => true],
492 'Delivery', $cmd, $item_id, (int)$rr['id']);
500 // Notify PuSH subscribers (Used for OStatus distribution of regular posts)
502 logger('Activating internal PuSH for item '.$item_id, LOGGER_DEBUG);
504 // Handling the pubsubhubbub requests
505 PushSubscriber::publishFeed($owner['uid'], $a->queue['priority']);
508 logger('notifier: calling hooks for ' . $cmd . ' ' . $item_id, LOGGER_DEBUG);
511 Addon::forkHooks($a->queue['priority'], 'notifier_normal', $target_item);
514 Addon::callHooks('notifier_end',$target_item);