3 * @file src/Worker/Notifier.php
5 namespace Friendica\Worker;
7 use Friendica\Core\Config;
8 use Friendica\Core\Worker;
9 use Friendica\Database\DBM;
10 use Friendica\Model\Contact;
11 use Friendica\Model\Group;
12 use Friendica\Model\User;
13 use Friendica\Network\Probe;
14 use Friendica\Protocol\Diaspora;
15 use Friendica\Protocol\OStatus;
16 use Friendica\Protocol\Salmon;
19 require_once 'include/dba.php';
20 require_once 'include/html2plain.php';
21 require_once 'include/datetime.php';
22 require_once 'include/items.php';
23 require_once 'include/bbcode.php';
26 * This file was at one time responsible for doing all deliveries, but this caused
27 * big problems when the process was killed or stalled during the delivery process.
28 * It now invokes separate queues that are delivering via delivery.php and pubsubpublish.php.
32 * The notifier is typically called with:
34 * Worker::add(PRIORITY_HIGH, "Notifier", COMMAND, ITEM_ID);
36 * where COMMAND is one of the following:
38 * activity (in diaspora.php, dfrn_confirm.php, profiles.php)
39 * comment-import (in diaspora.php, items.php)
40 * comment-new (in item.php)
41 * drop (in diaspora.php, items.php, photos.php)
42 * edit_post (in item.php)
43 * event (in events.php)
44 * expire (in items.php)
45 * like (in like.php, poke.php)
46 * mail (in message.php)
47 * suggest (in fsuggest.php)
48 * tag (in photos.php, poke.php, tagger.php)
49 * tgroup (in items.php)
50 * wall-new (in photos.php, item.php)
51 * removeme (in Contact.php)
52 * relocate (in uimport.php)
54 * and ITEM_ID is the id of the item in the database that needs to be sent to others.
58 public static function execute($cmd, $item_id) {
61 logger('notifier: invoked: '.$cmd.': '.$item_id, LOGGER_DEBUG);
73 if ($cmd === 'mail') {
76 $message = q("SELECT * FROM `mail` WHERE `id` = %d LIMIT 1",
79 if (!count($message)) {
82 $uid = $message[0]['uid'];
83 $recipients[] = $message[0]['contact-id'];
86 } elseif ($cmd === 'expire') {
89 $items = q("SELECT * FROM `item` WHERE `uid` = %d AND `wall` = 1
90 AND `deleted` = 1 AND `changed` > UTC_TIMESTAMP() - INTERVAL 10 MINUTE",
98 } elseif ($cmd === 'suggest') {
102 $suggest = q("SELECT * FROM `fsuggest` WHERE `id` = %d LIMIT 1",
105 if (!count($suggest)) {
108 $uid = $suggest[0]['uid'];
109 $recipients[] = $suggest[0]['cid'];
111 } elseif ($cmd === 'removeme') {
112 $r = q("SELECT `contact`.*, `user`.`prvkey` AS `uprvkey`,
113 `user`.`timezone`, `user`.`nickname`, `user`.`sprvkey`, `user`.`spubkey`,
114 `user`.`page-flags`, `user`.`prvnets`, `user`.`account-type`, `user`.`guid`
115 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
116 WHERE `contact`.`uid` = %d AND `contact`.`self` LIMIT 1",
123 $r = q("SELECT * FROM `contact` WHERE NOT `self` AND `uid` = %d", intval($item_id));
127 foreach ($r as $contact) {
128 Contact::terminateFriendship($user, $contact);
131 } elseif ($cmd === 'relocate') {
132 $normal_mode = false;
136 $recipients_relocate = q("SELECT * FROM `contact` WHERE `uid` = %d AND NOT `self` AND `network` IN ('%s', '%s')",
137 intval($uid), NETWORK_DFRN, NETWORK_DIASPORA);
140 $target_item = dba::fetch_first("SELECT `item`.*, `contact`.`uid` AS `cuid` FROM `item`
141 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
142 WHERE `item`.`id` = ? AND `visible` AND NOT `moderated`", $item_id);
144 if (!DBM::is_result($target_item) || !intval($target_item['parent'])) {
148 $parent_id = intval($target_item['parent']);
149 $uid = $target_item['cuid'];
150 $updated = $target_item['edited'];
152 $items = q("SELECT `item`.*, `sign`.`signed_text`,`sign`.`signature`,`sign`.`signer`
153 FROM `item` LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id` WHERE `parent` = %d AND visible AND NOT moderated ORDER BY `id` ASC",
157 if (!count($items)) {
161 // avoid race condition with deleting entries
162 if ($items[0]['deleted']) {
163 foreach ($items as $item) {
164 $item['deleted'] = 1;
168 if ((count($items) == 1) && ($items[0]['id'] === $target_item['id']) && ($items[0]['uri'] === $items[0]['parent-uri'])) {
169 logger('notifier: top level post');
174 $owner = User::getOwnerDataById($uid);
179 $walltowall = ($top_level && ($owner['id'] != $items[0]['contact-id']) ? true : false);
181 // Should the post be transmitted to Diaspora?
182 $diaspora_delivery = true;
184 // If this is a public conversation, notify the feed hub
185 $public_message = true;
188 $push_notify = false;
190 // Deliver directly to a forum, don't PuSH
191 $direct_forum_delivery = false;
193 // fill this in with a single salmon slap if applicable
196 if (! ($mail || $fsuggest || $relocate)) {
198 $slap = OStatus::salmon($target_item, $owner);
202 $thr_parent = q("SELECT `network`, `author-link`, `owner-link` FROM `item` WHERE `uri` = '%s' AND `uid` = %d",
203 dbesc($target_item["thr-parent"]), intval($target_item["uid"]));
205 logger('GUID: '.$target_item["guid"].': Parent is '.$parent['network'].'. Thread parent is '.$thr_parent[0]['network'], LOGGER_DEBUG);
207 // This is IMPORTANT!!!!
209 // We will only send a "notify owner to relay" or followup message if the referenced post
210 // originated on our system by virtue of having our hostname somewhere
211 // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
213 // if $parent['wall'] == 1 we will already have the parent message in our array
214 // and we will relay the whole lot.
216 // expire sends an entire group of expire messages and cannot be forwarded.
217 // However the conversation owner will be a part of the conversation and will
218 // be notified during this run.
219 // Other DFRN conversation members will be alerted during polled updates.
223 // Diaspora members currently are not notified of expirations, and other networks have
224 // either limited or no ability to process deletions. We should at least fix Diaspora
225 // by stringing togther an array of retractions and sending them onward.
228 $localhost = str_replace('www.','',$a->get_hostname());
229 if (strpos($localhost,':')) {
230 $localhost = substr($localhost,0,strpos($localhost,':'));
234 * Be VERY CAREFUL if you make any changes to the following several lines. Seemingly innocuous changes
235 * have been known to cause runaway conditions which affected several servers, along with
236 * permissions issues.
240 $relay_to_owner = false;
242 if (!$top_level && ($parent['wall'] == 0) && !$expire && (stristr($target_item['uri'],$localhost))) {
243 $relay_to_owner = true;
247 if (($cmd === 'uplink') && (intval($parent['forum_mode']) == 1) && !$top_level) {
248 $relay_to_owner = true;
251 // until the 'origin' flag has been in use for several months
252 // we will just use it as a fallback test
253 // later we will be able to use it as the primary test of whether or not to relay.
255 if (!$target_item['origin']) {
256 $relay_to_owner = false;
258 if ($parent['origin']) {
259 $relay_to_owner = false;
262 // Special treatment for forum posts
263 if (($target_item['author-link'] != $target_item['owner-link']) &&
264 ($owner['id'] != $target_item['contact-id']) &&
265 ($target_item['uri'] === $target_item['parent-uri'])) {
267 $fields = ['forum', 'prv'];
268 $condition = ['id' => $target_item['contact-id']];
269 $contact = dba::selectFirst('contact', $fields, $condition);
270 if (!DBM::is_result($contact)) {
271 // Should never happen
275 // Is the post from a forum?
276 if ($contact['forum'] || $contact['prv']) {
277 $relay_to_owner = true;
278 $direct_forum_delivery = true;
281 if ($relay_to_owner) {
282 // local followup to remote post
284 $public_message = false; // not public
285 $conversant_str = dbesc($parent['contact-id']);
286 $recipients = [$parent['contact-id']];
287 $recipients_followup = [$parent['contact-id']];
289 logger('notifier: followup '.$target_item["guid"].' to '.$conversant_str, LOGGER_DEBUG);
291 //if (!$target_item['private'] && $target_item['wall'] &&
292 if (!$target_item['private'] &&
293 (strlen($target_item['allow_cid'].$target_item['allow_gid'].
294 $target_item['deny_cid'].$target_item['deny_gid']) == 0))
297 if (($thr_parent && ($thr_parent[0]['network'] == NETWORK_OSTATUS)) || ($parent['network'] == NETWORK_OSTATUS)) {
300 if ($parent["network"] == NETWORK_OSTATUS) {
301 // Distribute the message to the DFRN contacts as if this wasn't a followup since OStatus can't relay comments
302 // Currently it is work at progress
303 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `network` = '%s' AND NOT `blocked` AND NOT `pending` AND NOT `archive`",
307 if (DBM::is_result($r)) {
308 foreach ($r as $rr) {
309 $recipients_followup[] = $rr['id'];
315 if ($direct_forum_delivery) {
316 $push_notify = false;
319 logger("Notify ".$target_item["guid"]." via PuSH: ".($push_notify?"Yes":"No"), LOGGER_DEBUG);
323 logger('Distributing directly '.$target_item["guid"], LOGGER_DEBUG);
325 // don't send deletions onward for other people's stuff
327 if ($target_item['deleted'] && !intval($target_item['wall'])) {
328 logger('notifier: ignoring delete notification for non-wall item');
332 if (strlen($parent['allow_cid'])
333 || strlen($parent['allow_gid'])
334 || strlen($parent['deny_cid'])
335 || strlen($parent['deny_gid'])) {
336 $public_message = false; // private recipients, not public
339 $allow_people = expand_acl($parent['allow_cid']);
340 $allow_groups = Group::expand(expand_acl($parent['allow_gid']),true);
341 $deny_people = expand_acl($parent['deny_cid']);
342 $deny_groups = Group::expand(expand_acl($parent['deny_gid']));
344 // if our parent is a public forum (forum_mode == 1), uplink to the origional author causing
345 // a delivery fork. private groups (forum_mode == 2) do not uplink
347 if ((intval($parent['forum_mode']) == 1) && !$top_level && ($cmd !== 'uplink')) {
348 Worker::add($a->queue['priority'], 'Notifier', 'uplink', $item_id);
353 foreach ($items as $item) {
354 $recipients[] = $item['contact-id'];
355 $conversants[] = $item['contact-id'];
356 // pull out additional tagged people to notify (if public message)
357 if ($public_message && strlen($item['inform'])) {
358 $people = explode(',',$item['inform']);
359 foreach ($people as $person) {
360 if (substr($person,0,4) === 'cid:') {
361 $recipients[] = intval(substr($person,4));
362 $conversants[] = intval(substr($person,4));
364 $url_recipients[] = substr($person,4);
370 if (count($url_recipients)) {
371 logger('notifier: '.$target_item["guid"].' url_recipients ' . print_r($url_recipients,true));
374 $conversants = array_unique($conversants);
376 $recipients = array_unique(array_merge($recipients,$allow_people,$allow_groups));
377 $deny = array_unique(array_merge($deny_people,$deny_groups));
378 $recipients = array_diff($recipients,$deny);
380 $conversant_str = dbesc(implode(', ',$conversants));
383 // If the thread parent is OStatus then do some magic to distribute the messages.
384 // We have not only to look at the parent, since it could be a Friendica thread.
385 if (($thr_parent && ($thr_parent[0]['network'] == NETWORK_OSTATUS)) || ($parent['network'] == NETWORK_OSTATUS)) {
386 $diaspora_delivery = false;
388 logger('Some parent is OStatus for '.$target_item["guid"]." - Author: ".$thr_parent[0]['author-link']." - Owner: ".$thr_parent[0]['owner-link'], LOGGER_DEBUG);
390 // Send a salmon to the parent author
391 $r = q("SELECT `url`, `notify` FROM `contact` WHERE `nurl`='%s' AND `uid` IN (0, %d) AND `notify` != ''",
392 dbesc(normalise_link($thr_parent[0]['author-link'])),
394 if (DBM::is_result($r)) {
395 $probed_contact = $r[0];
397 $probed_contact = Probe::uri($thr_parent[0]['author-link']);
400 if ($probed_contact["notify"] != "") {
401 logger('Notify parent author '.$probed_contact["url"].': '.$probed_contact["notify"]);
402 $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
405 // Send a salmon to the parent owner
406 $r = q("SELECT `url`, `notify` FROM `contact` WHERE `nurl`='%s' AND `uid` IN (0, %d) AND `notify` != ''",
407 dbesc(normalise_link($thr_parent[0]['owner-link'])),
409 if (DBM::is_result($r)) {
410 $probed_contact = $r[0];
412 $probed_contact = Probe::uri($thr_parent[0]['owner-link']);
415 if ($probed_contact["notify"] != "") {
416 logger('Notify parent owner '.$probed_contact["url"].': '.$probed_contact["notify"]);
417 $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
420 // Send a salmon notification to every person we mentioned in the post
421 $arr = explode(',',$target_item['tag']);
422 foreach ($arr as $x) {
423 //logger('Checking tag '.$x, LOGGER_DEBUG);
425 if (preg_match('/@\[url=([^\]]*)\]/',$x,$matches)) {
426 $probed_contact = Probe::uri($matches[1]);
427 if ($probed_contact["notify"] != "") {
428 logger('Notify mentioned user '.$probed_contact["url"].': '.$probed_contact["notify"]);
429 $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
434 // It only makes sense to distribute answers to OStatus messages to Friendica and OStatus - but not Diaspora
435 $sql_extra = " AND `network` IN ('".NETWORK_OSTATUS."', '".NETWORK_DFRN."')";
437 $sql_extra = " AND `network` IN ('".NETWORK_OSTATUS."', '".NETWORK_DFRN."', '".NETWORK_DIASPORA."', '".NETWORK_MAIL."')";
440 $public_message = false;
443 // If this is a public message and pubmail is set on the parent, include all your email contacts
445 $mail_disabled = ((function_exists('imap_open') && (!Config::get('system','imap_disabled'))) ? 0 : 1);
447 if (!$mail_disabled) {
448 if (!strlen($target_item['allow_cid']) && !strlen($target_item['allow_gid'])
449 && !strlen($target_item['deny_cid']) && !strlen($target_item['deny_gid'])
450 && intval($target_item['pubmail'])) {
451 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `network` = '%s'",
455 if (DBM::is_result($r)) {
456 foreach ($r as $rr) {
457 $recipients[] = $rr['id'];
464 $recip_str = implode(', ', $recipients_followup);
466 $recip_str = implode(', ', $recipients);
469 $r = $recipients_relocate;
471 $r = q("SELECT `id`, `url`, `network`, `self` FROM `contact`
472 WHERE `id` IN (%s) AND NOT `blocked` AND NOT `pending` AND NOT `archive`".$sql_extra,
479 if (DBM::is_result($r)) {
480 foreach ($r as $contact) {
481 if ($contact['self']) {
484 logger("Deliver ".$target_item["guid"]." to ".$contact['url']." via network ".$contact['network'], LOGGER_DEBUG);
486 Worker::add(['priority' => $a->queue['priority'], 'created' => $a->queue['created'], 'dont_fork' => true],
487 'Delivery', $cmd, $item_id, (int)$contact['id']);
491 // send salmon slaps to mentioned remote tags (@foo@example.com) in OStatus posts
492 // They are especially used for notifications to OStatus users that don't follow us.
494 if ($slap && count($url_recipients) && ($public_message || $push_notify) && $normal_mode) {
495 if (!Config::get('system', 'dfrn_only')) {
496 foreach ($url_recipients as $url) {
498 logger('notifier: urldelivery: ' . $url);
499 $deliver_status = Salmon::slapper($owner, $url, $slap);
500 /// @TODO Redeliver/queue these items on failure, though there is no contact record
507 if ($public_message) {
512 if ($diaspora_delivery) {
514 $r0 = Diaspora::relayList();
517 $r1 = q("SELECT `batch`, ANY_VALUE(`id`) AS `id`, ANY_VALUE(`name`) AS `name`, ANY_VALUE(`network`) AS `network`
518 FROM `contact` WHERE `network` = '%s' AND `batch` != ''
519 AND `uid` = %d AND `rel` != %d AND NOT `blocked` AND NOT `pending` AND NOT `archive` GROUP BY `batch`",
520 dbesc(NETWORK_DIASPORA),
521 intval($owner['uid']),
522 intval(CONTACT_IS_SHARING)
525 // Fetch the participation list
526 // The function will ensure that there are no duplicates
527 $r1 = Diaspora::participantsForThread($item_id, $r1);
531 $r2 = q("SELECT `id`, `name`,`network` FROM `contact`
532 WHERE `network` in ('%s') AND `uid` = %d AND NOT `blocked` AND NOT `pending` AND NOT `archive` AND `rel` != %d",
534 intval($owner['uid']),
535 intval(CONTACT_IS_SHARING)
539 $r = array_merge($r2, $r1, $r0);
541 if (DBM::is_result($r)) {
542 logger('pubdeliver '.$target_item["guid"].': '.print_r($r,true), LOGGER_DEBUG);
544 foreach ($r as $rr) {
546 // except for Diaspora batch jobs
547 // Don't deliver to folks who have already been delivered to
549 if (($rr['network'] !== NETWORK_DIASPORA) && (in_array($rr['id'],$conversants))) {
550 logger('notifier: already delivered id=' . $rr['id']);
554 if (!$mail && !$fsuggest && !$followup) {
555 logger('notifier: delivery agent: '.$rr['name'].' '.$rr['id'].' '.$rr['network'].' '.$target_item["guid"]);
556 Worker::add(['priority' => $a->queue['priority'], 'created' => $a->queue['created'], 'dont_fork' => true],
557 'Delivery', $cmd, $item_id, (int)$rr['id']);
566 // Notify PuSH subscribers (Used for OStatus distribution of regular posts)
568 // Set push flag for PuSH subscribers to this topic,
569 // they will be notified in queue.php
570 q("UPDATE `push_subscriber` SET `push` = 1 ".
571 "WHERE `nickname` = '%s' AND `push` = 0", dbesc($owner['nickname']));
573 logger('Activating internal PuSH for item '.$item_id, LOGGER_DEBUG);
575 // Handling the pubsubhubbub requests
576 Worker::add(['priority' => PRIORITY_HIGH, 'created' => $a->queue['created'], 'dont_fork' => true],
580 logger('notifier: calling hooks', LOGGER_DEBUG);
583 call_hooks('notifier_normal',$target_item);
586 call_hooks('notifier_end',$target_item);