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\Network\Probe;
11 use Friendica\Object\Contact;
12 use Friendica\Protocol\Diaspora;
13 use Friendica\Protocol\OStatus;
16 require_once 'include/queue_fn.php';
17 require_once 'include/html2plain.php';
18 require_once 'include/salmon.php';
19 require_once 'include/datetime.php';
20 require_once 'include/items.php';
21 require_once 'include/bbcode.php';
22 require_once 'include/email.php';
25 * This file was at one time responsible for doing all deliveries, but this caused
26 * big problems when the process was killed or stalled during the delivery process.
27 * It now invokes separate queues that are delivering via delivery.php and pubsubpublish.php.
31 * The notifier is typically called with:
33 * Worker::add(PRIORITY_HIGH, "Notifier", COMMAND, ITEM_ID);
35 * where COMMAND is one of the following:
37 * activity (in diaspora.php, dfrn_confirm.php, profiles.php)
38 * comment-import (in diaspora.php, items.php)
39 * comment-new (in item.php)
40 * drop (in diaspora.php, items.php, photos.php)
41 * edit_post (in item.php)
42 * event (in events.php)
43 * expire (in items.php)
44 * like (in like.php, poke.php)
45 * mail (in message.php)
46 * suggest (in fsuggest.php)
47 * tag (in photos.php, poke.php, tagger.php)
48 * tgroup (in items.php)
49 * wall-new (in photos.php, item.php)
50 * removeme (in Contact.php)
51 * relocate (in uimport.php)
53 * and ITEM_ID is the id of the item in the database that needs to be sent to others.
57 public static function execute($cmd, $item_id) {
60 logger('notifier: invoked: '.$cmd.': '.$item_id, LOGGER_DEBUG);
67 $recipients = array();
68 $url_recipients = array();
72 if ($cmd === 'mail') {
75 $message = q("SELECT * FROM `mail` WHERE `id` = %d LIMIT 1",
78 if (! count($message)) {
81 $uid = $message[0]['uid'];
82 $recipients[] = $message[0]['contact-id'];
85 } elseif ($cmd === 'expire') {
88 $items = q("SELECT * FROM `item` WHERE `uid` = %d AND `wall` = 1
89 AND `deleted` = 1 AND `changed` > UTC_TIMESTAMP() - INTERVAL 10 MINUTE",
94 if (! count($items)) {
97 } elseif ($cmd === 'suggest') {
101 $suggest = q("SELECT * FROM `fsuggest` WHERE `id` = %d LIMIT 1",
104 if (! count($suggest)) {
107 $uid = $suggest[0]['uid'];
108 $recipients[] = $suggest[0]['cid'];
110 } elseif ($cmd === 'removeme') {
111 $r = q("SELECT `contact`.*, `user`.`pubkey` AS `upubkey`, `user`.`prvkey` AS `uprvkey`,
112 `user`.`timezone`, `user`.`nickname`, `user`.`sprvkey`, `user`.`spubkey`,
113 `user`.`page-flags`, `user`.`prvnets`, `user`.`account-type`, `user`.`guid`
114 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
115 WHERE `contact`.`uid` = %d AND `contact`.`self` LIMIT 1",
122 $r = q("SELECT * FROM `contact` WHERE NOT `self` AND `uid` = %d", intval($item_id));
126 foreach ($r as $contact) {
127 Contact::terminateFriendship($user, $contact);
130 } elseif ($cmd === 'relocate') {
131 $normal_mode = false;
135 $recipients_relocate = q("SELECT * FROM `contact` WHERE `uid` = %d AND NOT `self` AND `network` IN ('%s', '%s')",
136 intval($uid), NETWORK_DFRN, NETWORK_DIASPORA);
139 $r = q("SELECT * FROM `item` WHERE `id` = %d AND visible = 1 AND moderated = 0 LIMIT 1",
143 if ((! DBM::is_result($r)) || (! intval($r[0]['parent']))) {
147 $target_item = $r[0];
148 $parent_id = intval($r[0]['parent']);
150 $updated = $r[0]['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 = 1 AND moderated = 0 ORDER BY `id` ASC",
157 if (! count($items)) {
161 // avoid race condition with deleting entries
163 if ($items[0]['deleted']) {
164 foreach ($items as $item) {
165 $item['deleted'] = 1;
169 if ((count($items) == 1) && ($items[0]['id'] === $target_item['id']) && ($items[0]['uri'] === $items[0]['parent-uri'])) {
170 logger('notifier: top level post');
176 $r = q("SELECT `contact`.*, `user`.`pubkey` AS `upubkey`, `user`.`prvkey` AS `uprvkey`,
177 `user`.`timezone`, `user`.`nickname`, `user`.`sprvkey`, `user`.`spubkey`,
178 `user`.`page-flags`, `user`.`prvnets`, `user`.`account-type`
179 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
180 WHERE `contact`.`uid` = %d AND `contact`.`self` = 1 LIMIT 1",
184 if (! DBM::is_result($r)) {
190 $walltowall = ((($top_level) && ($owner['id'] != $items[0]['contact-id'])) ? true : false);
192 // Should the post be transmitted to Diaspora?
193 $diaspora_delivery = true;
195 // If this is a public conversation, notify the feed hub
196 $public_message = true;
199 $push_notify = false;
201 // Deliver directly to a forum, don't PuSH
202 $direct_forum_delivery = false;
204 // fill this in with a single salmon slap if applicable
207 if (! ($mail || $fsuggest || $relocate)) {
209 $slap = OStatus::salmon($target_item, $owner);
211 require_once 'include/group.php';
215 $thr_parent = q("SELECT `network`, `author-link`, `owner-link` FROM `item` WHERE `uri` = '%s' AND `uid` = %d",
216 dbesc($target_item["thr-parent"]), intval($target_item["uid"]));
218 logger('GUID: '.$target_item["guid"].': Parent is '.$parent['network'].'. Thread parent is '.$thr_parent[0]['network'], LOGGER_DEBUG);
220 // This is IMPORTANT!!!!
222 // We will only send a "notify owner to relay" or followup message if the referenced post
223 // originated on our system by virtue of having our hostname somewhere
224 // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
226 // if $parent['wall'] == 1 we will already have the parent message in our array
227 // and we will relay the whole lot.
229 // expire sends an entire group of expire messages and cannot be forwarded.
230 // However the conversation owner will be a part of the conversation and will
231 // be notified during this run.
232 // Other DFRN conversation members will be alerted during polled updates.
236 // Diaspora members currently are not notified of expirations, and other networks have
237 // either limited or no ability to process deletions. We should at least fix Diaspora
238 // by stringing togther an array of retractions and sending them onward.
241 $localhost = str_replace('www.','',$a->get_hostname());
242 if (strpos($localhost,':')) {
243 $localhost = substr($localhost,0,strpos($localhost,':'));
247 * Be VERY CAREFUL if you make any changes to the following several lines. Seemingly innocuous changes
248 * have been known to cause runaway conditions which affected several servers, along with
249 * permissions issues.
253 $relay_to_owner = false;
255 if (!$top_level && ($parent['wall'] == 0) && !$expire && (stristr($target_item['uri'],$localhost))) {
256 $relay_to_owner = true;
260 if (($cmd === 'uplink') && (intval($parent['forum_mode']) == 1) && !$top_level) {
261 $relay_to_owner = true;
264 // until the 'origin' flag has been in use for several months
265 // we will just use it as a fallback test
266 // later we will be able to use it as the primary test of whether or not to relay.
268 if (! $target_item['origin']) {
269 $relay_to_owner = false;
271 if ($parent['origin']) {
272 $relay_to_owner = false;
275 // Special treatment for forum posts
276 if (($target_item['author-link'] != $target_item['owner-link']) &&
277 ($owner['id'] != $target_item['contact-id']) &&
278 ($target_item['uri'] === $target_item['parent-uri'])) {
280 $fields = array('forum', 'prv');
281 $condition = array('id' => $target_item['contact-id']);
282 $contact = dba::select('contact', $fields, $condition, array('limit' => 1));
283 if (!DBM::is_result($contact)) {
284 // Should never happen
288 // Is the post from a forum?
289 if ($contact['forum'] || $contact['prv']) {
290 $relay_to_owner = true;
291 $direct_forum_delivery = true;
294 if ($relay_to_owner) {
295 logger('notifier: followup '.$target_item["guid"], LOGGER_DEBUG);
296 // local followup to remote post
298 $public_message = false; // not public
299 $conversant_str = dbesc($parent['contact-id']);
300 $recipients = array($parent['contact-id']);
301 $recipients_followup = array($parent['contact-id']);
303 //if (!$target_item['private'] && $target_item['wall'] &&
304 if (!$target_item['private'] &&
305 (strlen($target_item['allow_cid'].$target_item['allow_gid'].
306 $target_item['deny_cid'].$target_item['deny_gid']) == 0))
309 if (($thr_parent && ($thr_parent[0]['network'] == NETWORK_OSTATUS)) || ($parent['network'] == NETWORK_OSTATUS)) {
313 if ($parent["network"] == NETWORK_OSTATUS) {
314 // Distribute the message to the DFRN contacts as if this wasn't a followup since OStatus can't relay comments
315 // Currently it is work at progress
316 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `network` = '%s' AND NOT `blocked` AND NOT `pending` AND NOT `archive`",
320 if (DBM::is_result($r)) {
321 foreach ($r as $rr) {
322 $recipients_followup[] = $rr['id'];
328 if ($direct_forum_delivery) {
329 $push_notify = false;
332 logger("Notify ".$target_item["guid"]." via PuSH: ".($push_notify?"Yes":"No"), LOGGER_DEBUG);
336 logger('Distributing directly '.$target_item["guid"], LOGGER_DEBUG);
338 // don't send deletions onward for other people's stuff
340 if ($target_item['deleted'] && (! intval($target_item['wall']))) {
341 logger('notifier: ignoring delete notification for non-wall item');
345 if ((strlen($parent['allow_cid']))
346 || (strlen($parent['allow_gid']))
347 || (strlen($parent['deny_cid']))
348 || (strlen($parent['deny_gid']))) {
349 $public_message = false; // private recipients, not public
352 $allow_people = expand_acl($parent['allow_cid']);
353 $allow_groups = expand_groups(expand_acl($parent['allow_gid']),true);
354 $deny_people = expand_acl($parent['deny_cid']);
355 $deny_groups = expand_groups(expand_acl($parent['deny_gid']));
357 // if our parent is a public forum (forum_mode == 1), uplink to the origional author causing
358 // a delivery fork. private groups (forum_mode == 2) do not uplink
360 if ((intval($parent['forum_mode']) == 1) && (! $top_level) && ($cmd !== 'uplink')) {
361 Worker::add($a->queue['priority'], 'Notifier', 'uplink', $item_id);
364 $conversants = array();
366 foreach ($items as $item) {
367 $recipients[] = $item['contact-id'];
368 $conversants[] = $item['contact-id'];
369 // pull out additional tagged people to notify (if public message)
370 if ($public_message && strlen($item['inform'])) {
371 $people = explode(',',$item['inform']);
372 foreach ($people as $person) {
373 if (substr($person,0,4) === 'cid:') {
374 $recipients[] = intval(substr($person,4));
375 $conversants[] = intval(substr($person,4));
377 $url_recipients[] = substr($person,4);
383 if (count($url_recipients))
384 logger('notifier: '.$target_item["guid"].' url_recipients ' . print_r($url_recipients,true));
386 $conversants = array_unique($conversants);
389 $recipients = array_unique(array_merge($recipients,$allow_people,$allow_groups));
390 $deny = array_unique(array_merge($deny_people,$deny_groups));
391 $recipients = array_diff($recipients,$deny);
393 $conversant_str = dbesc(implode(', ',$conversants));
396 // If the thread parent is OStatus then do some magic to distribute the messages.
397 // We have not only to look at the parent, since it could be a Friendica thread.
398 if (($thr_parent && ($thr_parent[0]['network'] == NETWORK_OSTATUS)) || ($parent['network'] == NETWORK_OSTATUS)) {
400 $diaspora_delivery = false;
402 logger('Some parent is OStatus for '.$target_item["guid"]." - Author: ".$thr_parent[0]['author-link']." - Owner: ".$thr_parent[0]['owner-link'], LOGGER_DEBUG);
404 // Send a salmon to the parent author
405 $r = q("SELECT `url`, `notify` FROM `contact` WHERE `nurl`='%s' AND `uid` IN (0, %d) AND `notify` != ''",
406 dbesc(normalise_link($thr_parent[0]['author-link'])),
408 if (DBM::is_result($r)) {
409 $probed_contact = $r[0];
411 $probed_contact = Probe::uri($thr_parent[0]['author-link']);
414 if ($probed_contact["notify"] != "") {
415 logger('Notify parent author '.$probed_contact["url"].': '.$probed_contact["notify"]);
416 $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
419 // Send a salmon to the parent owner
420 $r = q("SELECT `url`, `notify` FROM `contact` WHERE `nurl`='%s' AND `uid` IN (0, %d) AND `notify` != ''",
421 dbesc(normalise_link($thr_parent[0]['owner-link'])),
423 if (DBM::is_result($r)) {
424 $probed_contact = $r[0];
426 $probed_contact = Probe::uri($thr_parent[0]['owner-link']);
429 if ($probed_contact["notify"] != "") {
430 logger('Notify parent owner '.$probed_contact["url"].': '.$probed_contact["notify"]);
431 $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
434 // Send a salmon notification to every person we mentioned in the post
435 $arr = explode(',',$target_item['tag']);
436 foreach ($arr as $x) {
437 //logger('Checking tag '.$x, LOGGER_DEBUG);
439 if (preg_match('/@\[url=([^\]]*)\]/',$x,$matches)) {
440 $probed_contact = Probe::uri($matches[1]);
441 if ($probed_contact["notify"] != "") {
442 logger('Notify mentioned user '.$probed_contact["url"].': '.$probed_contact["notify"]);
443 $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
448 // It only makes sense to distribute answers to OStatus messages to Friendica and OStatus - but not Diaspora
449 $sql_extra = " AND `network` IN ('".NETWORK_OSTATUS."', '".NETWORK_DFRN."')";
451 $sql_extra = " AND `network` IN ('".NETWORK_OSTATUS."', '".NETWORK_DFRN."', '".NETWORK_DIASPORA."', '".NETWORK_MAIL."', '".NETWORK_MAIL2."')";
454 $public_message = false;
457 // If this is a public message and pubmail is set on the parent, include all your email contacts
459 $mail_disabled = ((function_exists('imap_open') && (!Config::get('system','imap_disabled'))) ? 0 : 1);
461 if (! $mail_disabled) {
462 if ((! strlen($target_item['allow_cid'])) && (! strlen($target_item['allow_gid']))
463 && (! strlen($target_item['deny_cid'])) && (! strlen($target_item['deny_gid']))
464 && (intval($target_item['pubmail']))) {
465 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `network` = '%s'",
469 if (DBM::is_result($r)) {
470 foreach ($r as $rr) {
471 $recipients[] = $rr['id'];
478 $recip_str = implode(', ', $recipients_followup);
480 $recip_str = implode(', ', $recipients);
483 $r = $recipients_relocate;
485 $r = q("SELECT `id`, `url`, `network`, `self` FROM `contact`
486 WHERE `id` IN (%s) AND NOT `blocked` AND NOT `pending` AND NOT `archive`".$sql_extra,
493 if (DBM::is_result($r)) {
494 foreach ($r as $contact) {
495 if ($contact['self']) {
498 logger("Deliver ".$target_item["guid"]." to ".$contact['url']." via network ".$contact['network'], LOGGER_DEBUG);
500 Worker::add(array('priority' => $a->queue['priority'], 'created' => $a->queue['created'], 'dont_fork' => true),
501 'Delivery', $cmd, $item_id, (int)$contact['id']);
505 // send salmon slaps to mentioned remote tags (@foo@example.com) in OStatus posts
506 // They are especially used for notifications to OStatus users that don't follow us.
508 if ($slap && count($url_recipients) && ($public_message || $push_notify) && $normal_mode) {
509 if (!Config::get('system','dfrn_only')) {
510 foreach ($url_recipients as $url) {
512 logger('notifier: urldelivery: ' . $url);
513 $deliver_status = slapper($owner,$url,$slap);
514 /// @TODO Redeliver/queue these items on failure, though there is no contact record
521 if ($public_message) {
526 if ($diaspora_delivery) {
528 $r0 = Diaspora::relayList();
531 $r1 = q("SELECT `batch`, ANY_VALUE(`id`) AS `id`, ANY_VALUE(`name`) AS `name`, ANY_VALUE(`network`) AS `network`
532 FROM `contact` WHERE `network` = '%s' AND `batch` != ''
533 AND `uid` = %d AND `rel` != %d AND NOT `blocked` AND NOT `pending` AND NOT `archive` GROUP BY `batch`",
534 dbesc(NETWORK_DIASPORA),
535 intval($owner['uid']),
536 intval(CONTACT_IS_SHARING)
540 $r2 = q("SELECT `id`, `name`,`network` FROM `contact`
541 WHERE `network` in ('%s', '%s') AND `uid` = %d AND NOT `blocked` AND NOT `pending` AND NOT `archive` AND `rel` != %d",
543 dbesc(NETWORK_MAIL2),
544 intval($owner['uid']),
545 intval(CONTACT_IS_SHARING)
548 $r = array_merge($r2,$r1,$r0);
550 if (DBM::is_result($r)) {
551 logger('pubdeliver '.$target_item["guid"].': '.print_r($r,true), LOGGER_DEBUG);
553 foreach ($r as $rr) {
555 // except for Diaspora batch jobs
556 // Don't deliver to folks who have already been delivered to
558 if (($rr['network'] !== NETWORK_DIASPORA) && (in_array($rr['id'],$conversants))) {
559 logger('notifier: already delivered id=' . $rr['id']);
563 if ((! $mail) && (! $fsuggest) && (! $followup)) {
564 logger('notifier: delivery agent: '.$rr['name'].' '.$rr['id'].' '.$rr['network'].' '.$target_item["guid"]);
565 Worker::add(array('priority' => $a->queue['priority'], 'created' => $a->queue['created'], 'dont_fork' => true),
566 'Delivery', $cmd, $item_id, (int)$rr['id']);
575 // Notify PuSH subscribers (Used for OStatus distribution of regular posts)
577 // Set push flag for PuSH subscribers to this topic,
578 // they will be notified in queue.php
579 q("UPDATE `push_subscriber` SET `push` = 1 ".
580 "WHERE `nickname` = '%s' AND `push` = 0", dbesc($owner['nickname']));
582 logger('Activating internal PuSH for item '.$item_id, LOGGER_DEBUG);
584 // Handling the pubsubhubbub requests
585 Worker::add(array('priority' => PRIORITY_HIGH, 'created' => $a->queue['created'], 'dont_fork' => true),
589 logger('notifier: calling hooks', LOGGER_DEBUG);
592 call_hooks('notifier_normal',$target_item);
595 call_hooks('notifier_end',$target_item);