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 // Inherit the priority
59 $queue = dba::select('workerqueue', array('priority', 'created'), array('pid' => getmypid()), array('limit' => 1));
60 if (dbm::is_result($queue)) {
61 $priority = (int)$queue['priority'];
62 $process_created = $queue['created'];
63 logger('inherited priority: '.$priority);
65 // Normally this shouldn't happen.
66 $priority = PRIORITY_HIGH;
67 $process_created = datetime_convert();
68 logger('no inherited priority! Something is wrong.');
71 logger('notifier: invoked: ' . print_r($argv,true), LOGGER_DEBUG);
78 $item_id = intval($argv[2]);
90 $recipients = array();
91 $url_recipients = array();
95 if ($cmd === 'mail') {
98 $message = q("SELECT * FROM `mail` WHERE `id` = %d LIMIT 1",
101 if (! count($message)) {
104 $uid = $message[0]['uid'];
105 $recipients[] = $message[0]['contact-id'];
108 } elseif ($cmd === 'expire') {
109 $normal_mode = false;
111 $items = q("SELECT * FROM `item` WHERE `uid` = %d AND `wall` = 1
112 AND `deleted` = 1 AND `changed` > UTC_TIMESTAMP() - INTERVAL 10 MINUTE",
117 if (! count($items)) {
120 } elseif ($cmd === 'suggest') {
121 $normal_mode = false;
124 $suggest = q("SELECT * FROM `fsuggest` WHERE `id` = %d LIMIT 1",
127 if (! count($suggest)) {
130 $uid = $suggest[0]['uid'];
131 $recipients[] = $suggest[0]['cid'];
133 } elseif ($cmd === 'removeme') {
134 $r = q("SELECT `contact`.*, `user`.`pubkey` AS `upubkey`, `user`.`prvkey` AS `uprvkey`,
135 `user`.`timezone`, `user`.`nickname`, `user`.`sprvkey`, `user`.`spubkey`,
136 `user`.`page-flags`, `user`.`prvnets`, `user`.`account-type`, `user`.`guid`
137 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
138 WHERE `contact`.`uid` = %d AND `contact`.`self` LIMIT 1",
145 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` LIMIT 1", intval($item_id));
151 $r = q("SELECT * FROM `contact` WHERE NOT `self` AND `uid` = %d", intval($item_id));
155 require_once 'include/Contact.php';
156 foreach ($r as $contact) {
157 terminate_friendship($user, $self, $contact);
160 } elseif ($cmd === 'relocate') {
161 $normal_mode = false;
165 $recipients_relocate = q("SELECT * FROM contact WHERE uid = %d AND self = 0 AND network = '%s'" , intval($uid), NETWORK_DFRN);
168 $r = q("SELECT * FROM `item` WHERE `id` = %d AND visible = 1 AND moderated = 0 LIMIT 1",
172 if ((! dbm::is_result($r)) || (! intval($r[0]['parent']))) {
176 $target_item = $r[0];
177 $parent_id = intval($r[0]['parent']);
179 $updated = $r[0]['edited'];
181 $items = q("SELECT `item`.*, `sign`.`signed_text`,`sign`.`signature`,`sign`.`signer`
182 FROM `item` LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id` WHERE `parent` = %d AND visible = 1 AND moderated = 0 ORDER BY `id` ASC",
186 if (! count($items)) {
190 // avoid race condition with deleting entries
192 if ($items[0]['deleted']) {
193 foreach ($items as $item) {
194 $item['deleted'] = 1;
198 if ((count($items) == 1) && ($items[0]['id'] === $target_item['id']) && ($items[0]['uri'] === $items[0]['parent-uri'])) {
199 logger('notifier: top level post');
205 $r = q("SELECT `contact`.*, `user`.`pubkey` AS `upubkey`, `user`.`prvkey` AS `uprvkey`,
206 `user`.`timezone`, `user`.`nickname`, `user`.`sprvkey`, `user`.`spubkey`,
207 `user`.`page-flags`, `user`.`prvnets`, `user`.`account-type`
208 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
209 WHERE `contact`.`uid` = %d AND `contact`.`self` = 1 LIMIT 1",
213 if (! dbm::is_result($r)) {
219 $walltowall = ((($top_level) && ($owner['id'] != $items[0]['contact-id'])) ? true : false);
221 $hub = get_config('system','huburl');
223 // Should the post be transmitted to Diaspora?
224 $diaspora_delivery = true;
226 // If this is a public conversation, notify the feed hub
227 $public_message = true;
230 $push_notify = false;
232 // fill this in with a single salmon slap if applicable
235 if (! ($mail || $fsuggest || $relocate)) {
237 $slap = ostatus::salmon($target_item,$owner);
239 require_once 'include/group.php';
243 $thr_parent = q("SELECT `network`, `author-link`, `owner-link` FROM `item` WHERE `uri` = '%s' AND `uid` = %d",
244 dbesc($target_item["thr-parent"]), intval($target_item["uid"]));
246 logger('GUID: '.$target_item["guid"].': Parent is '.$parent['network'].'. Thread parent is '.$thr_parent[0]['network'], LOGGER_DEBUG);
248 // This is IMPORTANT!!!!
250 // We will only send a "notify owner to relay" or followup message if the referenced post
251 // originated on our system by virtue of having our hostname somewhere
252 // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
254 // if $parent['wall'] == 1 we will already have the parent message in our array
255 // and we will relay the whole lot.
257 // expire sends an entire group of expire messages and cannot be forwarded.
258 // However the conversation owner will be a part of the conversation and will
259 // be notified during this run.
260 // Other DFRN conversation members will be alerted during polled updates.
264 // Diaspora members currently are not notified of expirations, and other networks have
265 // either limited or no ability to process deletions. We should at least fix Diaspora
266 // by stringing togther an array of retractions and sending them onward.
269 $localhost = str_replace('www.','',$a->get_hostname());
270 if (strpos($localhost,':')) {
271 $localhost = substr($localhost,0,strpos($localhost,':'));
275 * Be VERY CAREFUL if you make any changes to the following several lines. Seemingly innocuous changes
276 * have been known to cause runaway conditions which affected several servers, along with
277 * permissions issues.
281 $relay_to_owner = false;
283 if (!$top_level && ($parent['wall'] == 0) && !$expire && (stristr($target_item['uri'],$localhost))) {
284 $relay_to_owner = true;
288 if (($cmd === 'uplink') && (intval($parent['forum_mode']) == 1) && !$top_level) {
289 $relay_to_owner = true;
292 // until the 'origin' flag has been in use for several months
293 // we will just use it as a fallback test
294 // later we will be able to use it as the primary test of whether or not to relay.
296 if (! $target_item['origin']) {
297 $relay_to_owner = false;
299 if ($parent['origin']) {
300 $relay_to_owner = false;
302 if ($relay_to_owner) {
303 logger('notifier: followup '.$target_item["guid"], LOGGER_DEBUG);
304 // local followup to remote post
306 $public_message = false; // not public
307 $conversant_str = dbesc($parent['contact-id']);
308 $recipients = array($parent['contact-id']);
309 $recipients_followup = array($parent['contact-id']);
311 //if (!$target_item['private'] && $target_item['wall'] &&
312 if (!$target_item['private'] &&
313 (strlen($target_item['allow_cid'].$target_item['allow_gid'].
314 $target_item['deny_cid'].$target_item['deny_gid']) == 0))
317 if (($thr_parent && ($thr_parent[0]['network'] == NETWORK_OSTATUS)) || ($parent['network'] == NETWORK_OSTATUS)) {
321 if ($parent["network"] == NETWORK_OSTATUS) {
322 // Distribute the message to the DFRN contacts as if this wasn't a followup since OStatus can't relay comments
323 // Currently it is work at progress
324 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `network` = '%s' AND NOT `blocked` AND NOT `pending` AND NOT `archive`",
328 if (dbm::is_result($r)) {
329 foreach ($r as $rr) {
330 $recipients_followup[] = $rr['id'];
335 logger("Notify ".$target_item["guid"]." via PuSH: ".($push_notify?"Yes":"No"), LOGGER_DEBUG);
339 logger('Distributing directly '.$target_item["guid"], LOGGER_DEBUG);
341 // don't send deletions onward for other people's stuff
343 if ($target_item['deleted'] && (! intval($target_item['wall']))) {
344 logger('notifier: ignoring delete notification for non-wall item');
348 if ((strlen($parent['allow_cid']))
349 || (strlen($parent['allow_gid']))
350 || (strlen($parent['deny_cid']))
351 || (strlen($parent['deny_gid']))) {
352 $public_message = false; // private recipients, not public
355 $allow_people = expand_acl($parent['allow_cid']);
356 $allow_groups = expand_groups(expand_acl($parent['allow_gid']),true);
357 $deny_people = expand_acl($parent['deny_cid']);
358 $deny_groups = expand_groups(expand_acl($parent['deny_gid']));
360 // if our parent is a public forum (forum_mode == 1), uplink to the origional author causing
361 // a delivery fork. private groups (forum_mode == 2) do not uplink
363 if ((intval($parent['forum_mode']) == 1) && (! $top_level) && ($cmd !== 'uplink')) {
364 proc_run($priority, 'include/notifier.php', 'uplink', $item_id);
367 $conversants = array();
369 foreach ($items as $item) {
370 $recipients[] = $item['contact-id'];
371 $conversants[] = $item['contact-id'];
372 // pull out additional tagged people to notify (if public message)
373 if ($public_message && strlen($item['inform'])) {
374 $people = explode(',',$item['inform']);
375 foreach ($people as $person) {
376 if (substr($person,0,4) === 'cid:') {
377 $recipients[] = intval(substr($person,4));
378 $conversants[] = intval(substr($person,4));
380 $url_recipients[] = substr($person,4);
386 if (count($url_recipients))
387 logger('notifier: '.$target_item["guid"].' url_recipients ' . print_r($url_recipients,true));
389 $conversants = array_unique($conversants);
392 $recipients = array_unique(array_merge($recipients,$allow_people,$allow_groups));
393 $deny = array_unique(array_merge($deny_people,$deny_groups));
394 $recipients = array_diff($recipients,$deny);
396 $conversant_str = dbesc(implode(', ',$conversants));
399 // If the thread parent is OStatus then do some magic to distribute the messages.
400 // We have not only to look at the parent, since it could be a Friendica thread.
401 if (($thr_parent && ($thr_parent[0]['network'] == NETWORK_OSTATUS)) || ($parent['network'] == NETWORK_OSTATUS)) {
403 $diaspora_delivery = false;
405 logger('Some parent is OStatus for '.$target_item["guid"]." - Author: ".$thr_parent[0]['author-link']." - Owner: ".$thr_parent[0]['owner-link'], LOGGER_DEBUG);
407 // Send a salmon to the parent author
408 $r = q("SELECT `url`, `notify` FROM `contact` WHERE `nurl`='%s' AND `uid` IN (0, %d) AND `notify` != ''",
409 dbesc(normalise_link($thr_parent[0]['author-link'])),
411 if (dbm::is_result($r)) {
412 $probed_contact = $r[0];
414 $probed_contact = probe_url($thr_parent[0]['author-link']);
417 if ($probed_contact["notify"] != "") {
418 logger('Notify parent author '.$probed_contact["url"].': '.$probed_contact["notify"]);
419 $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
422 // Send a salmon to the parent owner
423 $r = q("SELECT `url`, `notify` FROM `contact` WHERE `nurl`='%s' AND `uid` IN (0, %d) AND `notify` != ''",
424 dbesc(normalise_link($thr_parent[0]['owner-link'])),
426 if (dbm::is_result($r)) {
427 $probed_contact = $r[0];
429 $probed_contact = probe_url($thr_parent[0]['owner-link']);
432 if ($probed_contact["notify"] != "") {
433 logger('Notify parent owner '.$probed_contact["url"].': '.$probed_contact["notify"]);
434 $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
437 // Send a salmon notification to every person we mentioned in the post
438 $arr = explode(',',$target_item['tag']);
439 foreach ($arr as $x) {
440 //logger('Checking tag '.$x, LOGGER_DEBUG);
442 if (preg_match('/@\[url=([^\]]*)\]/',$x,$matches)) {
443 $probed_contact = probe_url($matches[1]);
444 if ($probed_contact["notify"] != "") {
445 logger('Notify mentioned user '.$probed_contact["url"].': '.$probed_contact["notify"]);
446 $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
451 // It only makes sense to distribute answers to OStatus messages to Friendica and OStatus - but not Diaspora
452 $sql_extra = " AND `network` IN ('".NETWORK_OSTATUS."', '".NETWORK_DFRN."')";
454 $sql_extra = " AND `network` IN ('".NETWORK_OSTATUS."', '".NETWORK_DFRN."', '".NETWORK_DIASPORA."', '".NETWORK_MAIL."', '".NETWORK_MAIL2."')";
457 $public_message = false;
460 // If this is a public message and pubmail is set on the parent, include all your email contacts
462 $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
464 if (! $mail_disabled) {
465 if ((! strlen($target_item['allow_cid'])) && (! strlen($target_item['allow_gid']))
466 && (! strlen($target_item['deny_cid'])) && (! strlen($target_item['deny_gid']))
467 && (intval($target_item['pubmail']))) {
468 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `network` = '%s'",
472 if (dbm::is_result($r)) {
473 foreach ($r as $rr) {
474 $recipients[] = $rr['id'];
481 $recip_str = implode(', ', $recipients_followup);
483 $recip_str = implode(', ', $recipients);
486 $r = $recipients_relocate;
488 $r = q("SELECT `id`, `url`, `network`, `self` FROM `contact`
489 WHERE `id` IN (%s) AND NOT `blocked` AND NOT `pending` AND NOT `archive`".$sql_extra,
496 if (dbm::is_result($r)) {
497 foreach ($r as $contact) {
498 if ($contact['self']) {
501 logger("Deliver ".$target_item["guid"]." to ".$contact['url']." via network ".$contact['network'], LOGGER_DEBUG);
503 proc_run(array('priority' => $priority, 'created' => $process_created, 'dont_fork' => true),
504 'include/delivery.php', $cmd, $item_id, $contact['id']);
508 // send salmon slaps to mentioned remote tags (@foo@example.com) in OStatus posts
509 // They are especially used for notifications to OStatus users that don't follow us.
511 if ($slap && count($url_recipients) && ($public_message || $push_notify) && $normal_mode) {
512 if (!get_config('system','dfrn_only')) {
513 foreach ($url_recipients as $url) {
515 logger('notifier: urldelivery: ' . $url);
516 $deliver_status = slapper($owner,$url,$slap);
517 /// @TODO Redeliver/queue these items on failure, though there is no contact record
524 if ($public_message) {
529 if ($diaspora_delivery) {
531 $r0 = Diaspora::relay_list();
534 $r1 = q("SELECT `batch`, ANY_VALUE(`id`) AS `id`, ANY_VALUE(`name`) AS `name`, ANY_VALUE(`network`) AS `network`
535 FROM `contact` WHERE `network` = '%s'
536 AND `uid` = %d AND `rel` != %d AND NOT `blocked` AND NOT `pending` AND NOT `archive` GROUP BY `batch` ORDER BY rand()",
537 dbesc(NETWORK_DIASPORA),
538 intval($owner['uid']),
539 intval(CONTACT_IS_SHARING)
543 $r2 = q("SELECT `id`, `name`,`network` FROM `contact`
544 WHERE `network` in ( '%s', '%s') AND `uid` = %d AND NOT `blocked` AND NOT `pending` AND NOT `archive`
545 AND `rel` != %d order by rand() ",
547 dbesc(NETWORK_MAIL2),
548 intval($owner['uid']),
549 intval(CONTACT_IS_SHARING)
552 $r = array_merge($r2,$r1,$r0);
554 if (dbm::is_result($r)) {
555 logger('pubdeliver '.$target_item["guid"].': '.print_r($r,true), LOGGER_DEBUG);
557 foreach ($r as $rr) {
559 // except for Diaspora batch jobs
560 // Don't deliver to folks who have already been delivered to
562 if (($rr['network'] !== NETWORK_DIASPORA) && (in_array($rr['id'],$conversants))) {
563 logger('notifier: already delivered id=' . $rr['id']);
567 if ((! $mail) && (! $fsuggest) && (! $followup)) {
568 logger('notifier: delivery agent: '.$rr['name'].' '.$rr['id'].' '.$rr['network'].' '.$target_item["guid"]);
569 proc_run(array('priority' => $priority, 'created' => $process_created, 'dont_fork' => true),
570 'include/delivery.php', $cmd, $item_id, $rr['id']);
579 // Notify PuSH subscribers (Used for OStatus distribution of regular posts)
580 if ($push_notify && strlen($hub)) {
581 $hubs = explode(',', $hub);
583 foreach ($hubs as $h) {
589 if ($h === '[internal]') {
590 // Set push flag for PuSH subscribers to this topic,
591 // they will be notified in queue.php
592 q("UPDATE `push_subscriber` SET `push` = 1 ".
593 "WHERE `nickname` = '%s' AND `push` = 0", dbesc($owner['nickname']));
595 logger('Activating internal PuSH for item '.$item_id, LOGGER_DEBUG);
599 $params = 'hub.mode=publish&hub.url=' . urlencode( App::get_baseurl() . '/dfrn_poll/' . $owner['nickname'] );
600 post_url($h,$params);
601 logger('publish for item '.$item_id.' ' . $h . ' ' . $params . ' returned ' . $a->get_curl_code());
603 if (count($hubs) > 1) {
604 sleep(7); // try and avoid multiple hubs responding at precisely the same time
609 // Handling the pubsubhubbub requests
610 proc_run(array('priority' => PRIORITY_HIGH, 'created' => $process_created, 'dont_fork' => true),
611 'include/pubsubpublish.php');
614 logger('notifier: calling hooks', LOGGER_DEBUG);
617 call_hooks('notifier_normal',$target_item);
620 call_hooks('notifier_end',$target_item);