3 * @file src/Worker/Notifier.php
5 namespace Friendica\Worker;
8 use Friendica\Core\Config;
9 use Friendica\Core\Worker;
10 use Friendica\Database\DBM;
11 use Friendica\Network\Probe;
12 use Friendica\Object\Contact;
13 use Friendica\Protocol\Diaspora;
14 use Friendica\Protocol\OStatus;
17 require_once 'include/queue_fn.php';
18 require_once 'include/html2plain.php';
19 require_once 'include/salmon.php';
20 require_once 'include/datetime.php';
21 require_once 'include/items.php';
22 require_once 'include/bbcode.php';
23 require_once 'include/email.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);
68 $recipients = array();
69 $url_recipients = array();
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",
95 if (! count($items)) {
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`.`pubkey` AS `upubkey`, `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 $r = q("SELECT * FROM `item` WHERE `id` = %d AND visible = 1 AND moderated = 0 LIMIT 1",
144 if ((! DBM::is_result($r)) || (! intval($r[0]['parent']))) {
148 $target_item = $r[0];
149 $parent_id = intval($r[0]['parent']);
151 $updated = $r[0]['edited'];
153 $items = q("SELECT `item`.*, `sign`.`signed_text`,`sign`.`signature`,`sign`.`signer`
154 FROM `item` LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id` WHERE `parent` = %d AND visible = 1 AND moderated = 0 ORDER BY `id` ASC",
158 if (! count($items)) {
162 // avoid race condition with deleting entries
164 if ($items[0]['deleted']) {
165 foreach ($items as $item) {
166 $item['deleted'] = 1;
170 if ((count($items) == 1) && ($items[0]['id'] === $target_item['id']) && ($items[0]['uri'] === $items[0]['parent-uri'])) {
171 logger('notifier: top level post');
177 $r = q("SELECT `contact`.*, `user`.`pubkey` AS `upubkey`, `user`.`prvkey` AS `uprvkey`,
178 `user`.`timezone`, `user`.`nickname`, `user`.`sprvkey`, `user`.`spubkey`,
179 `user`.`page-flags`, `user`.`prvnets`, `user`.`account-type`
180 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
181 WHERE `contact`.`uid` = %d AND `contact`.`self` = 1 LIMIT 1",
185 if (! DBM::is_result($r)) {
191 $walltowall = ((($top_level) && ($owner['id'] != $items[0]['contact-id'])) ? true : false);
193 // Should the post be transmitted to Diaspora?
194 $diaspora_delivery = true;
196 // If this is a public conversation, notify the feed hub
197 $public_message = true;
200 $push_notify = false;
202 // Deliver directly to a forum, don't PuSH
203 $direct_forum_delivery = false;
205 // fill this in with a single salmon slap if applicable
208 if (! ($mail || $fsuggest || $relocate)) {
210 $slap = OStatus::salmon($target_item, $owner);
212 require_once 'include/group.php';
216 $thr_parent = q("SELECT `network`, `author-link`, `owner-link` FROM `item` WHERE `uri` = '%s' AND `uid` = %d",
217 dbesc($target_item["thr-parent"]), intval($target_item["uid"]));
219 logger('GUID: '.$target_item["guid"].': Parent is '.$parent['network'].'. Thread parent is '.$thr_parent[0]['network'], LOGGER_DEBUG);
221 // This is IMPORTANT!!!!
223 // We will only send a "notify owner to relay" or followup message if the referenced post
224 // originated on our system by virtue of having our hostname somewhere
225 // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
227 // if $parent['wall'] == 1 we will already have the parent message in our array
228 // and we will relay the whole lot.
230 // expire sends an entire group of expire messages and cannot be forwarded.
231 // However the conversation owner will be a part of the conversation and will
232 // be notified during this run.
233 // Other DFRN conversation members will be alerted during polled updates.
237 // Diaspora members currently are not notified of expirations, and other networks have
238 // either limited or no ability to process deletions. We should at least fix Diaspora
239 // by stringing togther an array of retractions and sending them onward.
242 $localhost = str_replace('www.','',$a->get_hostname());
243 if (strpos($localhost,':')) {
244 $localhost = substr($localhost,0,strpos($localhost,':'));
248 * Be VERY CAREFUL if you make any changes to the following several lines. Seemingly innocuous changes
249 * have been known to cause runaway conditions which affected several servers, along with
250 * permissions issues.
254 $relay_to_owner = false;
256 if (!$top_level && ($parent['wall'] == 0) && !$expire && (stristr($target_item['uri'],$localhost))) {
257 $relay_to_owner = true;
261 if (($cmd === 'uplink') && (intval($parent['forum_mode']) == 1) && !$top_level) {
262 $relay_to_owner = true;
265 // until the 'origin' flag has been in use for several months
266 // we will just use it as a fallback test
267 // later we will be able to use it as the primary test of whether or not to relay.
269 if (! $target_item['origin']) {
270 $relay_to_owner = false;
272 if ($parent['origin']) {
273 $relay_to_owner = false;
276 // Special treatment for forum posts
277 if (($target_item['author-link'] != $target_item['owner-link']) &&
278 ($owner['id'] != $target_item['contact-id']) &&
279 ($target_item['uri'] === $target_item['parent-uri'])) {
281 $fields = array('forum', 'prv');
282 $condition = array('id' => $target_item['contact-id']);
283 $contact = dba::select('contact', $fields, $condition, array('limit' => 1));
284 if (!DBM::is_result($contact)) {
285 // Should never happen
289 // Is the post from a forum?
290 if ($contact['forum'] || $contact['prv']) {
291 $relay_to_owner = true;
292 $direct_forum_delivery = true;
295 if ($relay_to_owner) {
296 logger('notifier: followup '.$target_item["guid"], LOGGER_DEBUG);
297 // local followup to remote post
299 $public_message = false; // not public
300 $conversant_str = dbesc($parent['contact-id']);
301 $recipients = array($parent['contact-id']);
302 $recipients_followup = array($parent['contact-id']);
304 //if (!$target_item['private'] && $target_item['wall'] &&
305 if (!$target_item['private'] &&
306 (strlen($target_item['allow_cid'].$target_item['allow_gid'].
307 $target_item['deny_cid'].$target_item['deny_gid']) == 0))
310 if (($thr_parent && ($thr_parent[0]['network'] == NETWORK_OSTATUS)) || ($parent['network'] == NETWORK_OSTATUS)) {
314 if ($parent["network"] == NETWORK_OSTATUS) {
315 // Distribute the message to the DFRN contacts as if this wasn't a followup since OStatus can't relay comments
316 // Currently it is work at progress
317 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `network` = '%s' AND NOT `blocked` AND NOT `pending` AND NOT `archive`",
321 if (DBM::is_result($r)) {
322 foreach ($r as $rr) {
323 $recipients_followup[] = $rr['id'];
329 if ($direct_forum_delivery) {
330 $push_notify = false;
333 logger("Notify ".$target_item["guid"]." via PuSH: ".($push_notify?"Yes":"No"), LOGGER_DEBUG);
337 logger('Distributing directly '.$target_item["guid"], LOGGER_DEBUG);
339 // don't send deletions onward for other people's stuff
341 if ($target_item['deleted'] && (! intval($target_item['wall']))) {
342 logger('notifier: ignoring delete notification for non-wall item');
346 if ((strlen($parent['allow_cid']))
347 || (strlen($parent['allow_gid']))
348 || (strlen($parent['deny_cid']))
349 || (strlen($parent['deny_gid']))) {
350 $public_message = false; // private recipients, not public
353 $allow_people = expand_acl($parent['allow_cid']);
354 $allow_groups = expand_groups(expand_acl($parent['allow_gid']),true);
355 $deny_people = expand_acl($parent['deny_cid']);
356 $deny_groups = expand_groups(expand_acl($parent['deny_gid']));
358 // if our parent is a public forum (forum_mode == 1), uplink to the origional author causing
359 // a delivery fork. private groups (forum_mode == 2) do not uplink
361 if ((intval($parent['forum_mode']) == 1) && (! $top_level) && ($cmd !== 'uplink')) {
362 Worker::add($a->queue['priority'], 'Notifier', 'uplink', $item_id);
365 $conversants = array();
367 foreach ($items as $item) {
368 $recipients[] = $item['contact-id'];
369 $conversants[] = $item['contact-id'];
370 // pull out additional tagged people to notify (if public message)
371 if ($public_message && strlen($item['inform'])) {
372 $people = explode(',',$item['inform']);
373 foreach ($people as $person) {
374 if (substr($person,0,4) === 'cid:') {
375 $recipients[] = intval(substr($person,4));
376 $conversants[] = intval(substr($person,4));
378 $url_recipients[] = substr($person,4);
384 if (count($url_recipients))
385 logger('notifier: '.$target_item["guid"].' url_recipients ' . print_r($url_recipients,true));
387 $conversants = array_unique($conversants);
390 $recipients = array_unique(array_merge($recipients,$allow_people,$allow_groups));
391 $deny = array_unique(array_merge($deny_people,$deny_groups));
392 $recipients = array_diff($recipients,$deny);
394 $conversant_str = dbesc(implode(', ',$conversants));
397 // If the thread parent is OStatus then do some magic to distribute the messages.
398 // We have not only to look at the parent, since it could be a Friendica thread.
399 if (($thr_parent && ($thr_parent[0]['network'] == NETWORK_OSTATUS)) || ($parent['network'] == NETWORK_OSTATUS)) {
401 $diaspora_delivery = false;
403 logger('Some parent is OStatus for '.$target_item["guid"]." - Author: ".$thr_parent[0]['author-link']." - Owner: ".$thr_parent[0]['owner-link'], LOGGER_DEBUG);
405 // Send a salmon to the parent author
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]['author-link'])),
409 if (DBM::is_result($r)) {
410 $probed_contact = $r[0];
412 $probed_contact = Probe::uri($thr_parent[0]['author-link']);
415 if ($probed_contact["notify"] != "") {
416 logger('Notify parent author '.$probed_contact["url"].': '.$probed_contact["notify"]);
417 $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
420 // Send a salmon to the parent owner
421 $r = q("SELECT `url`, `notify` FROM `contact` WHERE `nurl`='%s' AND `uid` IN (0, %d) AND `notify` != ''",
422 dbesc(normalise_link($thr_parent[0]['owner-link'])),
424 if (DBM::is_result($r)) {
425 $probed_contact = $r[0];
427 $probed_contact = Probe::uri($thr_parent[0]['owner-link']);
430 if ($probed_contact["notify"] != "") {
431 logger('Notify parent owner '.$probed_contact["url"].': '.$probed_contact["notify"]);
432 $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
435 // Send a salmon notification to every person we mentioned in the post
436 $arr = explode(',',$target_item['tag']);
437 foreach ($arr as $x) {
438 //logger('Checking tag '.$x, LOGGER_DEBUG);
440 if (preg_match('/@\[url=([^\]]*)\]/',$x,$matches)) {
441 $probed_contact = Probe::uri($matches[1]);
442 if ($probed_contact["notify"] != "") {
443 logger('Notify mentioned user '.$probed_contact["url"].': '.$probed_contact["notify"]);
444 $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
449 // It only makes sense to distribute answers to OStatus messages to Friendica and OStatus - but not Diaspora
450 $sql_extra = " AND `network` IN ('".NETWORK_OSTATUS."', '".NETWORK_DFRN."')";
452 $sql_extra = " AND `network` IN ('".NETWORK_OSTATUS."', '".NETWORK_DFRN."', '".NETWORK_DIASPORA."', '".NETWORK_MAIL."', '".NETWORK_MAIL2."')";
455 $public_message = false;
458 // If this is a public message and pubmail is set on the parent, include all your email contacts
460 $mail_disabled = ((function_exists('imap_open') && (!Config::get('system','imap_disabled'))) ? 0 : 1);
462 if (! $mail_disabled) {
463 if ((! strlen($target_item['allow_cid'])) && (! strlen($target_item['allow_gid']))
464 && (! strlen($target_item['deny_cid'])) && (! strlen($target_item['deny_gid']))
465 && (intval($target_item['pubmail']))) {
466 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `network` = '%s'",
470 if (DBM::is_result($r)) {
471 foreach ($r as $rr) {
472 $recipients[] = $rr['id'];
479 $recip_str = implode(', ', $recipients_followup);
481 $recip_str = implode(', ', $recipients);
484 $r = $recipients_relocate;
486 $r = q("SELECT `id`, `url`, `network`, `self` FROM `contact`
487 WHERE `id` IN (%s) AND NOT `blocked` AND NOT `pending` AND NOT `archive`".$sql_extra,
494 if (DBM::is_result($r)) {
495 foreach ($r as $contact) {
496 if ($contact['self']) {
499 logger("Deliver ".$target_item["guid"]." to ".$contact['url']." via network ".$contact['network'], LOGGER_DEBUG);
501 Worker::add(array('priority' => $a->queue['priority'], 'created' => $a->queue['created'], 'dont_fork' => true),
502 'Delivery', $cmd, $item_id, (int)$contact['id']);
506 // send salmon slaps to mentioned remote tags (@foo@example.com) in OStatus posts
507 // They are especially used for notifications to OStatus users that don't follow us.
509 if ($slap && count($url_recipients) && ($public_message || $push_notify) && $normal_mode) {
510 if (!Config::get('system','dfrn_only')) {
511 foreach ($url_recipients as $url) {
513 logger('notifier: urldelivery: ' . $url);
514 $deliver_status = slapper($owner,$url,$slap);
515 /// @TODO Redeliver/queue these items on failure, though there is no contact record
522 if ($public_message) {
527 if ($diaspora_delivery) {
529 $r0 = Diaspora::relay_list();
532 $r1 = q("SELECT `batch`, ANY_VALUE(`id`) AS `id`, ANY_VALUE(`name`) AS `name`, ANY_VALUE(`network`) AS `network`
533 FROM `contact` WHERE `network` = '%s' AND `batch` != ''
534 AND `uid` = %d AND `rel` != %d AND NOT `blocked` AND NOT `pending` AND NOT `archive` GROUP BY `batch`",
535 dbesc(NETWORK_DIASPORA),
536 intval($owner['uid']),
537 intval(CONTACT_IS_SHARING)
541 $r2 = q("SELECT `id`, `name`,`network` FROM `contact`
542 WHERE `network` in ('%s', '%s') AND `uid` = %d AND NOT `blocked` AND NOT `pending` AND NOT `archive` AND `rel` != %d",
544 dbesc(NETWORK_MAIL2),
545 intval($owner['uid']),
546 intval(CONTACT_IS_SHARING)
549 $r = array_merge($r2,$r1,$r0);
551 if (DBM::is_result($r)) {
552 logger('pubdeliver '.$target_item["guid"].': '.print_r($r,true), LOGGER_DEBUG);
554 foreach ($r as $rr) {
556 // except for Diaspora batch jobs
557 // Don't deliver to folks who have already been delivered to
559 if (($rr['network'] !== NETWORK_DIASPORA) && (in_array($rr['id'],$conversants))) {
560 logger('notifier: already delivered id=' . $rr['id']);
564 if ((! $mail) && (! $fsuggest) && (! $followup)) {
565 logger('notifier: delivery agent: '.$rr['name'].' '.$rr['id'].' '.$rr['network'].' '.$target_item["guid"]);
566 Worker::add(array('priority' => $a->queue['priority'], 'created' => $a->queue['created'], 'dont_fork' => true),
567 'Delivery', $cmd, $item_id, (int)$rr['id']);
576 // Notify PuSH subscribers (Used for OStatus distribution of regular posts)
578 // Set push flag for PuSH subscribers to this topic,
579 // they will be notified in queue.php
580 q("UPDATE `push_subscriber` SET `push` = 1 ".
581 "WHERE `nickname` = '%s' AND `push` = 0", dbesc($owner['nickname']));
583 logger('Activating internal PuSH for item '.$item_id, LOGGER_DEBUG);
585 // Handling the pubsubhubbub requests
586 Worker::add(array('priority' => PRIORITY_HIGH, 'created' => $a->queue['created'], 'dont_fork' => true),
590 logger('notifier: calling hooks', LOGGER_DEBUG);
593 call_hooks('notifier_normal',$target_item);
596 call_hooks('notifier_end',$target_item);