4 use Friendica\Core\Config;
6 require_once 'include/queue_fn.php';
7 require_once 'include/html2plain.php';
8 require_once 'include/probe.php';
9 require_once 'include/diaspora.php';
10 require_once 'include/ostatus.php';
11 require_once 'include/salmon.php';
14 * This file was at one time responsible for doing all deliveries, but this caused
15 * big problems when the process was killed or stalled during the delivery process.
16 * It now invokes separate queues that are delivering via delivery.php and pubsubpublish.php.
20 * The notifier is typically called with:
22 * proc_run(PRIORITY_HIGH, "include/notifier.php", COMMAND, ITEM_ID);
24 * where COMMAND is one of the following:
26 * activity (in diaspora.php, dfrn_confirm.php, profiles.php)
27 * comment-import (in diaspora.php, items.php)
28 * comment-new (in item.php)
29 * drop (in diaspora.php, items.php, photos.php)
30 * edit_post (in item.php)
31 * event (in events.php)
32 * expire (in items.php)
33 * like (in like.php, poke.php)
34 * mail (in message.php)
35 * suggest (in fsuggest.php)
36 * tag (in photos.php, poke.php, tagger.php)
37 * tgroup (in items.php)
38 * wall-new (in photos.php, item.php)
39 * removeme (in Contact.php)
40 * relocate (in uimport.php)
42 * and ITEM_ID is the id of the item in the database that needs to be sent to others.
46 function notifier_run(&$argv, &$argc){
49 require_once 'include/datetime.php';
50 require_once 'include/items.php';
51 require_once 'include/bbcode.php';
52 require_once 'include/email.php';
58 logger('notifier: invoked: ' . print_r($argv,true), LOGGER_DEBUG);
65 $item_id = intval($argv[2]);
77 $recipients = array();
78 $url_recipients = array();
82 if ($cmd === 'mail') {
85 $message = q("SELECT * FROM `mail` WHERE `id` = %d LIMIT 1",
88 if (! count($message)) {
91 $uid = $message[0]['uid'];
92 $recipients[] = $message[0]['contact-id'];
95 } elseif ($cmd === 'expire') {
98 $items = q("SELECT * FROM `item` WHERE `uid` = %d AND `wall` = 1
99 AND `deleted` = 1 AND `changed` > UTC_TIMESTAMP() - INTERVAL 10 MINUTE",
104 if (! count($items)) {
107 } elseif ($cmd === 'suggest') {
108 $normal_mode = false;
111 $suggest = q("SELECT * FROM `fsuggest` WHERE `id` = %d LIMIT 1",
114 if (! count($suggest)) {
117 $uid = $suggest[0]['uid'];
118 $recipients[] = $suggest[0]['cid'];
120 } elseif ($cmd === 'removeme') {
121 $r = q("SELECT `contact`.*, `user`.`pubkey` AS `upubkey`, `user`.`prvkey` AS `uprvkey`,
122 `user`.`timezone`, `user`.`nickname`, `user`.`sprvkey`, `user`.`spubkey`,
123 `user`.`page-flags`, `user`.`prvnets`, `user`.`account-type`, `user`.`guid`
124 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
125 WHERE `contact`.`uid` = %d AND `contact`.`self` LIMIT 1",
132 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` LIMIT 1", intval($item_id));
138 $r = q("SELECT * FROM `contact` WHERE NOT `self` AND `uid` = %d", intval($item_id));
142 require_once 'include/Contact.php';
143 foreach ($r as $contact) {
144 terminate_friendship($user, $self, $contact);
147 } elseif ($cmd === 'relocate') {
148 $normal_mode = false;
152 $recipients_relocate = q("SELECT * FROM contact WHERE uid = %d AND self = 0 AND network = '%s'" , intval($uid), NETWORK_DFRN);
155 $r = q("SELECT * FROM `item` WHERE `id` = %d and visible = 1 and moderated = 0 LIMIT 1",
159 if ((! dbm::is_result($r)) || (! intval($r[0]['parent']))) {
163 $target_item = $r[0];
164 $parent_id = intval($r[0]['parent']);
166 $updated = $r[0]['edited'];
168 $items = q("SELECT `item`.*, `sign`.`signed_text`,`sign`.`signature`,`sign`.`signer`
169 FROM `item` LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id` WHERE `parent` = %d and visible = 1 and moderated = 0 ORDER BY `id` ASC",
173 if (! count($items)) {
177 // avoid race condition with deleting entries
179 if ($items[0]['deleted']) {
180 foreach ($items as $item) {
181 $item['deleted'] = 1;
185 if ((count($items) == 1) && ($items[0]['id'] === $target_item['id']) && ($items[0]['uri'] === $items[0]['parent-uri'])) {
186 logger('notifier: top level post');
192 $r = q("SELECT `contact`.*, `user`.`pubkey` AS `upubkey`, `user`.`prvkey` AS `uprvkey`,
193 `user`.`timezone`, `user`.`nickname`, `user`.`sprvkey`, `user`.`spubkey`,
194 `user`.`page-flags`, `user`.`prvnets`, `user`.`account-type`
195 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
196 WHERE `contact`.`uid` = %d AND `contact`.`self` = 1 LIMIT 1",
200 if (! dbm::is_result($r)) {
206 $walltowall = ((($top_level) && ($owner['id'] != $items[0]['contact-id'])) ? true : false);
208 $hub = get_config('system','huburl');
210 // Should the post be transmitted to Diaspora?
211 $diaspora_delivery = true;
213 // If this is a public conversation, notify the feed hub
214 $public_message = true;
217 $push_notify = false;
219 // fill this in with a single salmon slap if applicable
222 if (! ($mail || $fsuggest || $relocate)) {
224 $slap = ostatus::salmon($target_item,$owner);
226 require_once 'include/group.php';
230 $thr_parent = q("SELECT `network`, `author-link`, `owner-link` FROM `item` WHERE `uri` = '%s' AND `uid` = %d",
231 dbesc($target_item["thr-parent"]), intval($target_item["uid"]));
233 logger('GUID: '.$target_item["guid"].': Parent is '.$parent['network'].'. Thread parent is '.$thr_parent[0]['network'], LOGGER_DEBUG);
235 // This is IMPORTANT!!!!
237 // We will only send a "notify owner to relay" or followup message if the referenced post
238 // originated on our system by virtue of having our hostname somewhere
239 // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
241 // if $parent['wall'] == 1 we will already have the parent message in our array
242 // and we will relay the whole lot.
244 // expire sends an entire group of expire messages and cannot be forwarded.
245 // However the conversation owner will be a part of the conversation and will
246 // be notified during this run.
247 // Other DFRN conversation members will be alerted during polled updates.
251 // Diaspora members currently are not notified of expirations, and other networks have
252 // either limited or no ability to process deletions. We should at least fix Diaspora
253 // by stringing togther an array of retractions and sending them onward.
256 $localhost = str_replace('www.','',$a->get_hostname());
257 if (strpos($localhost,':')) {
258 $localhost = substr($localhost,0,strpos($localhost,':'));
262 * Be VERY CAREFUL if you make any changes to the following several lines. Seemingly innocuous changes
263 * have been known to cause runaway conditions which affected several servers, along with
264 * permissions issues.
268 $relay_to_owner = false;
270 if (!$top_level && ($parent['wall'] == 0) && !$expire && (stristr($target_item['uri'],$localhost))) {
271 $relay_to_owner = true;
275 if (($cmd === 'uplink') && (intval($parent['forum_mode']) == 1) && !$top_level) {
276 $relay_to_owner = true;
279 // until the 'origin' flag has been in use for several months
280 // we will just use it as a fallback test
281 // later we will be able to use it as the primary test of whether or not to relay.
283 if (! $target_item['origin']) {
284 $relay_to_owner = false;
286 if ($parent['origin']) {
287 $relay_to_owner = false;
289 if ($relay_to_owner) {
290 logger('notifier: followup '.$target_item["guid"], LOGGER_DEBUG);
291 // local followup to remote post
293 $public_message = false; // not public
294 $conversant_str = dbesc($parent['contact-id']);
295 $recipients = array($parent['contact-id']);
296 $recipients_followup = array($parent['contact-id']);
298 //if (!$target_item['private'] AND $target_item['wall'] AND
299 if (!$target_item['private'] AND
300 (strlen($target_item['allow_cid'].$target_item['allow_gid'].
301 $target_item['deny_cid'].$target_item['deny_gid']) == 0))
304 if (($thr_parent AND ($thr_parent[0]['network'] == NETWORK_OSTATUS)) OR ($parent['network'] == NETWORK_OSTATUS)) {
308 if ($parent["network"] == NETWORK_OSTATUS) {
309 // Distribute the message to the DFRN contacts as if this wasn't a followup since OStatus can't relay comments
310 // Currently it is work at progress
311 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `network` = '%s' AND NOT `blocked` AND NOT `pending` AND NOT `archive`",
315 if (dbm::is_result($r)) {
316 foreach ($r as $rr) {
317 $recipients_followup[] = $rr['id'];
322 logger("Notify ".$target_item["guid"]." via PuSH: ".($push_notify?"Yes":"No"), LOGGER_DEBUG);
326 logger('Distributing directly '.$target_item["guid"], LOGGER_DEBUG);
328 // don't send deletions onward for other people's stuff
330 if ($target_item['deleted'] && (! intval($target_item['wall']))) {
331 logger('notifier: ignoring delete notification for non-wall item');
335 if ((strlen($parent['allow_cid']))
336 || (strlen($parent['allow_gid']))
337 || (strlen($parent['deny_cid']))
338 || (strlen($parent['deny_gid']))) {
339 $public_message = false; // private recipients, not public
342 $allow_people = expand_acl($parent['allow_cid']);
343 $allow_groups = expand_groups(expand_acl($parent['allow_gid']),true);
344 $deny_people = expand_acl($parent['deny_cid']);
345 $deny_groups = expand_groups(expand_acl($parent['deny_gid']));
347 // if our parent is a public forum (forum_mode == 1), uplink to the origional author causing
348 // a delivery fork. private groups (forum_mode == 2) do not uplink
350 if ((intval($parent['forum_mode']) == 1) && (! $top_level) && ($cmd !== 'uplink')) {
351 proc_run(PRIORITY_HIGH,'include/notifier.php','uplink',$item_id);
354 $conversants = array();
356 foreach ($items as $item) {
357 $recipients[] = $item['contact-id'];
358 $conversants[] = $item['contact-id'];
359 // pull out additional tagged people to notify (if public message)
360 if ($public_message && strlen($item['inform'])) {
361 $people = explode(',',$item['inform']);
362 foreach ($people as $person) {
363 if (substr($person,0,4) === 'cid:') {
364 $recipients[] = intval(substr($person,4));
365 $conversants[] = intval(substr($person,4));
367 $url_recipients[] = substr($person,4);
373 if (count($url_recipients))
374 logger('notifier: '.$target_item["guid"].' url_recipients ' . print_r($url_recipients,true));
376 $conversants = array_unique($conversants);
379 $recipients = array_unique(array_merge($recipients,$allow_people,$allow_groups));
380 $deny = array_unique(array_merge($deny_people,$deny_groups));
381 $recipients = array_diff($recipients,$deny);
383 $conversant_str = dbesc(implode(', ',$conversants));
386 // If the thread parent is OStatus then do some magic to distribute the messages.
387 // We have not only to look at the parent, since it could be a Friendica thread.
388 if (($thr_parent AND ($thr_parent[0]['network'] == NETWORK_OSTATUS)) OR ($parent['network'] == NETWORK_OSTATUS)) {
390 $diaspora_delivery = false;
392 logger('Some parent is OStatus for '.$target_item["guid"]." - Author: ".$thr_parent[0]['author-link']." - Owner: ".$thr_parent[0]['owner-link'], LOGGER_DEBUG);
394 // Send a salmon to the parent author
395 $r = q("SELECT `url`, `notify` FROM `contact` WHERE `nurl`='%s' AND `uid` IN (0, %d) AND `notify` != ''",
396 dbesc(normalise_link($thr_parent[0]['author-link'])),
398 if (dbm::is_result($r)) {
399 $probed_contact = $r[0];
401 $probed_contact = probe_url($thr_parent[0]['author-link']);
404 if ($probed_contact["notify"] != "") {
405 logger('Notify parent author '.$probed_contact["url"].': '.$probed_contact["notify"]);
406 $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
409 // Send a salmon to the parent owner
410 $r = q("SELECT `url`, `notify` FROM `contact` WHERE `nurl`='%s' AND `uid` IN (0, %d) AND `notify` != ''",
411 dbesc(normalise_link($thr_parent[0]['owner-link'])),
413 if (dbm::is_result($r)) {
414 $probed_contact = $r[0];
416 $probed_contact = probe_url($thr_parent[0]['owner-link']);
419 if ($probed_contact["notify"] != "") {
420 logger('Notify parent owner '.$probed_contact["url"].': '.$probed_contact["notify"]);
421 $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
424 // Send a salmon notification to every person we mentioned in the post
425 $arr = explode(',',$target_item['tag']);
426 foreach ($arr as $x) {
427 //logger('Checking tag '.$x, LOGGER_DEBUG);
429 if (preg_match('/@\[url=([^\]]*)\]/',$x,$matches)) {
430 $probed_contact = probe_url($matches[1]);
431 if ($probed_contact["notify"] != "") {
432 logger('Notify mentioned user '.$probed_contact["url"].': '.$probed_contact["notify"]);
433 $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
438 // It only makes sense to distribute answers to OStatus messages to Friendica and OStatus - but not Diaspora
439 $sql_extra = " AND `network` IN ('".NETWORK_OSTATUS."', '".NETWORK_DFRN."')";
441 $sql_extra = " AND `network` IN ('".NETWORK_OSTATUS."', '".NETWORK_DFRN."', '".NETWORK_DIASPORA."', '".NETWORK_MAIL."', '".NETWORK_MAIL2."')";
444 $public_message = false;
447 // If this is a public message and pubmail is set on the parent, include all your email contacts
449 $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
451 if (! $mail_disabled) {
452 if ((! strlen($target_item['allow_cid'])) && (! strlen($target_item['allow_gid']))
453 && (! strlen($target_item['deny_cid'])) && (! strlen($target_item['deny_gid']))
454 && (intval($target_item['pubmail']))) {
455 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `network` = '%s'",
459 if (dbm::is_result($r)) {
460 foreach ($r as $rr) {
461 $recipients[] = $rr['id'];
468 $recip_str = implode(', ', $recipients_followup);
470 $recip_str = implode(', ', $recipients);
473 $r = $recipients_relocate;
475 $r = q("SELECT `id`, `url`, `network`, `self` FROM `contact`
476 WHERE `id` IN (%s) AND NOT `blocked` AND NOT `pending` AND NOT `archive`".$sql_extra,
483 if (dbm::is_result($r)) {
484 foreach ($r as $contact) {
485 if ($contact['self']) {
488 logger("Deliver ".$target_item["guid"]." to ".$contact['url']." via network ".$contact['network'], LOGGER_DEBUG);
490 proc_run(PRIORITY_HIGH,'include/delivery.php', $cmd, $item_id, $contact['id']);
494 // send salmon slaps to mentioned remote tags (@foo@example.com) in OStatus posts
495 // They are especially used for notifications to OStatus users that don't follow us.
497 if ($slap && count($url_recipients) && ($public_message || $push_notify) && $normal_mode) {
498 if (!get_config('system','dfrn_only')) {
499 foreach ($url_recipients as $url) {
501 logger('notifier: urldelivery: ' . $url);
502 $deliver_status = slapper($owner,$url,$slap);
503 /// @TODO Redeliver/queue these items on failure, though there is no contact record
510 if ($public_message) {
515 if ($diaspora_delivery) {
517 $r0 = Diaspora::relay_list();
520 $r1 = q("SELECT `batch`, ANY_VALUE(`id`) AS `id`, ANY_VALUE(`name`) AS `name`, ANY_VALUE(`network`) AS `network`
521 FROM `contact` WHERE `network` = '%s'
522 AND `uid` = %d AND `rel` != %d AND NOT `blocked` AND NOT `pending` AND NOT `archive` GROUP BY `batch` ORDER BY rand()",
523 dbesc(NETWORK_DIASPORA),
524 intval($owner['uid']),
525 intval(CONTACT_IS_SHARING)
529 $r2 = q("SELECT `id`, `name`,`network` FROM `contact`
530 WHERE `network` in ( '%s', '%s') AND `uid` = %d AND NOT `blocked` AND NOT `pending` AND NOT `archive`
531 AND `rel` != %d order by rand() ",
533 dbesc(NETWORK_MAIL2),
534 intval($owner['uid']),
535 intval(CONTACT_IS_SHARING)
538 $r = array_merge($r2,$r1,$r0);
540 if (dbm::is_result($r)) {
541 logger('pubdeliver '.$target_item["guid"].': '.print_r($r,true), LOGGER_DEBUG);
543 foreach ($r as $rr) {
545 // except for Diaspora batch jobs
546 // Don't deliver to folks who have already been delivered to
548 if (($rr['network'] !== NETWORK_DIASPORA) && (in_array($rr['id'],$conversants))) {
549 logger('notifier: already delivered id=' . $rr['id']);
553 if ((! $mail) && (! $fsuggest) && (! $followup)) {
554 logger('notifier: delivery agent: '.$rr['name'].' '.$rr['id'].' '.$rr['network'].' '.$target_item["guid"]);
555 proc_run(PRIORITY_HIGH,'include/delivery.php',$cmd,$item_id,$rr['id']);
564 // Notify PuSH subscribers (Used for OStatus distribution of regular posts)
565 if ($push_notify AND strlen($hub)) {
566 $hubs = explode(',', $hub);
568 foreach ($hubs as $h) {
574 if ($h === '[internal]') {
575 // Set push flag for PuSH subscribers to this topic,
576 // they will be notified in queue.php
577 q("UPDATE `push_subscriber` SET `push` = 1 ".
578 "WHERE `nickname` = '%s' AND `push` = 0", dbesc($owner['nickname']));
580 logger('Activating internal PuSH for item '.$item_id, LOGGER_DEBUG);
584 $params = 'hub.mode=publish&hub.url=' . urlencode( App::get_baseurl() . '/dfrn_poll/' . $owner['nickname'] );
585 post_url($h,$params);
586 logger('publish for item '.$item_id.' ' . $h . ' ' . $params . ' returned ' . $a->get_curl_code());
588 if (count($hubs) > 1) {
589 sleep(7); // try and avoid multiple hubs responding at precisely the same time
594 // Handling the pubsubhubbub requests
595 proc_run(PRIORITY_HIGH,'include/pubsubpublish.php');
598 logger('notifier: calling hooks', LOGGER_DEBUG);
601 call_hooks('notifier_normal',$target_item);
604 call_hooks('notifier_end',$target_item);