3 use \Friendica\Core\Config;
5 require_once('include/queue_fn.php');
6 require_once('include/html2plain.php');
7 require_once('include/Scrape.php');
8 require_once('include/diaspora.php');
9 require_once('include/ostatus.php');
10 require_once('include/salmon.php');
13 * This file was at one time responsible for doing all deliveries, but this caused
14 * big problems when the process was killed or stalled during the delivery process.
15 * It now invokes separate queues that are delivering via delivery.php and pubsubpublish.php.
19 * The notifier is typically called with:
21 * proc_run(PRIORITY_HIGH, "include/notifier.php", COMMAND, ITEM_ID);
23 * where COMMAND is one of the following:
25 * activity (in diaspora.php, dfrn_confirm.php, profiles.php)
26 * comment-import (in diaspora.php, items.php)
27 * comment-new (in item.php)
28 * drop (in diaspora.php, items.php, photos.php)
29 * edit_post (in item.php)
30 * event (in events.php)
31 * expire (in items.php)
32 * like (in like.php, poke.php)
33 * mail (in message.php)
34 * suggest (in fsuggest.php)
35 * tag (in photos.php, poke.php, tagger.php)
36 * tgroup (in items.php)
37 * wall-new (in photos.php, item.php)
38 * removeme (in Contact.php)
39 * relocate (in uimport.php)
41 * and ITEM_ID is the id of the item in the database that needs to be sent to others.
45 function notifier_run(&$argv, &$argc){
48 require_once('include/datetime.php');
49 require_once('include/items.php');
50 require_once('include/bbcode.php');
51 require_once('include/email.php');
57 logger('notifier: invoked: ' . print_r($argv,true), LOGGER_DEBUG);
64 $item_id = intval($argv[2]);
76 $recipients = array();
77 $url_recipients = array();
81 if ($cmd === 'mail') {
84 $message = q("SELECT * FROM `mail` WHERE `id` = %d LIMIT 1",
87 if (! count($message)) {
90 $uid = $message[0]['uid'];
91 $recipients[] = $message[0]['contact-id'];
94 } elseif ($cmd === 'expire') {
97 $items = q("SELECT * FROM `item` WHERE `uid` = %d AND `wall` = 1
98 AND `deleted` = 1 AND `changed` > UTC_TIMESTAMP() - INTERVAL 10 MINUTE",
103 if (! count($items)) {
106 } elseif ($cmd === 'suggest') {
107 $normal_mode = false;
110 $suggest = q("SELECT * FROM `fsuggest` WHERE `id` = %d LIMIT 1",
113 if (! count($suggest)) {
116 $uid = $suggest[0]['uid'];
117 $recipients[] = $suggest[0]['cid'];
119 } elseif ($cmd === 'removeme') {
120 $r = q("SELECT `contact`.*, `user`.`pubkey` AS `upubkey`, `user`.`prvkey` AS `uprvkey`,
121 `user`.`timezone`, `user`.`nickname`, `user`.`sprvkey`, `user`.`spubkey`,
122 `user`.`page-flags`, `user`.`prvnets`, `user`.`account-type`, `user`.`guid`
123 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
124 WHERE `contact`.`uid` = %d AND `contact`.`self` LIMIT 1",
131 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` LIMIT 1", intval($item_id));
137 $r = q("SELECT * FROM `contact` WHERE NOT `self` AND `uid` = %d", intval($item_id));
141 require_once('include/Contact.php');
142 foreach ($r as $contact) {
143 terminate_friendship($user, $self, $contact);
146 } elseif ($cmd === 'relocate') {
147 $normal_mode = false;
151 $recipients_relocate = q("SELECT * FROM contact WHERE uid = %d AND self = 0 AND network = '%s'" , intval($uid), NETWORK_DFRN);
154 $r = q("SELECT * FROM `item` WHERE `id` = %d and visible = 1 and moderated = 0 LIMIT 1",
158 if ((! dbm::is_result($r)) || (! intval($r[0]['parent']))) {
162 $target_item = $r[0];
163 $parent_id = intval($r[0]['parent']);
165 $updated = $r[0]['edited'];
167 $items = q("SELECT `item`.*, `sign`.`signed_text`,`sign`.`signature`,`sign`.`signer`
168 FROM `item` LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id` WHERE `parent` = %d and visible = 1 and moderated = 0 ORDER BY `id` ASC",
172 if (! count($items)) {
176 // avoid race condition with deleting entries
178 if ($items[0]['deleted']) {
179 foreach ($items as $item) {
180 $item['deleted'] = 1;
184 if ((count($items) == 1) && ($items[0]['id'] === $target_item['id']) && ($items[0]['uri'] === $items[0]['parent-uri'])) {
185 logger('notifier: top level post');
191 $r = q("SELECT `contact`.*, `user`.`pubkey` AS `upubkey`, `user`.`prvkey` AS `uprvkey`,
192 `user`.`timezone`, `user`.`nickname`, `user`.`sprvkey`, `user`.`spubkey`,
193 `user`.`page-flags`, `user`.`prvnets`, `user`.`account-type`
194 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
195 WHERE `contact`.`uid` = %d AND `contact`.`self` = 1 LIMIT 1",
199 if (! dbm::is_result($r)) {
205 $walltowall = ((($top_level) && ($owner['id'] != $items[0]['contact-id'])) ? true : false);
207 $hub = get_config('system','huburl');
209 // Should the post be transmitted to Diaspora?
210 $diaspora_delivery = true;
212 // If this is a public conversation, notify the feed hub
213 $public_message = true;
216 $push_notify = false;
218 // fill this in with a single salmon slap if applicable
221 if (! ($mail || $fsuggest || $relocate)) {
223 $slap = ostatus::salmon($target_item,$owner);
225 require_once('include/group.php');
229 $thr_parent = q("SELECT `network`, `author-link`, `owner-link` FROM `item` WHERE `uri` = '%s' AND `uid` = %d",
230 dbesc($target_item["thr-parent"]), intval($target_item["uid"]));
232 logger('GUID: '.$target_item["guid"].': Parent is '.$parent['network'].'. Thread parent is '.$thr_parent[0]['network'], LOGGER_DEBUG);
234 // This is IMPORTANT!!!!
236 // We will only send a "notify owner to relay" or followup message if the referenced post
237 // originated on our system by virtue of having our hostname somewhere
238 // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
240 // if $parent['wall'] == 1 we will already have the parent message in our array
241 // and we will relay the whole lot.
243 // expire sends an entire group of expire messages and cannot be forwarded.
244 // However the conversation owner will be a part of the conversation and will
245 // be notified during this run.
246 // Other DFRN conversation members will be alerted during polled updates.
250 // Diaspora members currently are not notified of expirations, and other networks have
251 // either limited or no ability to process deletions. We should at least fix Diaspora
252 // by stringing togther an array of retractions and sending them onward.
255 $localhost = str_replace('www.','',$a->get_hostname());
256 if (strpos($localhost,':')) {
257 $localhost = substr($localhost,0,strpos($localhost,':'));
261 * Be VERY CAREFUL if you make any changes to the following several lines. Seemingly innocuous changes
262 * have been known to cause runaway conditions which affected several servers, along with
263 * permissions issues.
267 $relay_to_owner = false;
269 if (!$top_level && ($parent['wall'] == 0) && !$expire && (stristr($target_item['uri'],$localhost))) {
270 $relay_to_owner = true;
274 if (($cmd === 'uplink') && (intval($parent['forum_mode']) == 1) && !$top_level) {
275 $relay_to_owner = true;
278 // until the 'origin' flag has been in use for several months
279 // we will just use it as a fallback test
280 // later we will be able to use it as the primary test of whether or not to relay.
282 if (! $target_item['origin']) {
283 $relay_to_owner = false;
285 if ($parent['origin']) {
286 $relay_to_owner = false;
288 if ($relay_to_owner) {
289 logger('notifier: followup '.$target_item["guid"], LOGGER_DEBUG);
290 // local followup to remote post
292 $public_message = false; // not public
293 $conversant_str = dbesc($parent['contact-id']);
294 $recipients = array($parent['contact-id']);
295 $recipients_followup = array($parent['contact-id']);
297 //if (!$target_item['private'] AND $target_item['wall'] AND
298 if (!$target_item['private'] AND
299 (strlen($target_item['allow_cid'].$target_item['allow_gid'].
300 $target_item['deny_cid'].$target_item['deny_gid']) == 0))
303 if (($thr_parent AND ($thr_parent[0]['network'] == NETWORK_OSTATUS)) OR ($parent['network'] == NETWORK_OSTATUS)) {
307 if ($parent["network"] == NETWORK_OSTATUS) {
308 // Distribute the message to the DFRN contacts as if this wasn't a followup since OStatus can't relay comments
309 // Currently it is work at progress
310 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `network` = '%s' AND NOT `blocked` AND NOT `pending` AND NOT `archive`",
314 if (dbm::is_result($r)) {
315 foreach ($r as $rr) {
316 $recipients_followup[] = $rr['id'];
321 logger("Notify ".$target_item["guid"]." via PuSH: ".($push_notify?"Yes":"No"), LOGGER_DEBUG);
325 logger('Distributing directly '.$target_item["guid"], LOGGER_DEBUG);
327 // don't send deletions onward for other people's stuff
329 if ($target_item['deleted'] && (! intval($target_item['wall']))) {
330 logger('notifier: ignoring delete notification for non-wall item');
334 if ((strlen($parent['allow_cid']))
335 || (strlen($parent['allow_gid']))
336 || (strlen($parent['deny_cid']))
337 || (strlen($parent['deny_gid']))) {
338 $public_message = false; // private recipients, not public
341 $allow_people = expand_acl($parent['allow_cid']);
342 $allow_groups = expand_groups(expand_acl($parent['allow_gid']),true);
343 $deny_people = expand_acl($parent['deny_cid']);
344 $deny_groups = expand_groups(expand_acl($parent['deny_gid']));
346 // if our parent is a public forum (forum_mode == 1), uplink to the origional author causing
347 // a delivery fork. private groups (forum_mode == 2) do not uplink
349 if ((intval($parent['forum_mode']) == 1) && (! $top_level) && ($cmd !== 'uplink')) {
350 proc_run(PRIORITY_HIGH,'include/notifier.php','uplink',$item_id);
353 $conversants = array();
355 foreach ($items as $item) {
356 $recipients[] = $item['contact-id'];
357 $conversants[] = $item['contact-id'];
358 // pull out additional tagged people to notify (if public message)
359 if ($public_message && strlen($item['inform'])) {
360 $people = explode(',',$item['inform']);
361 foreach ($people as $person) {
362 if (substr($person,0,4) === 'cid:') {
363 $recipients[] = intval(substr($person,4));
364 $conversants[] = intval(substr($person,4));
366 $url_recipients[] = substr($person,4);
372 if (count($url_recipients))
373 logger('notifier: '.$target_item["guid"].' url_recipients ' . print_r($url_recipients,true));
375 $conversants = array_unique($conversants);
378 $recipients = array_unique(array_merge($recipients,$allow_people,$allow_groups));
379 $deny = array_unique(array_merge($deny_people,$deny_groups));
380 $recipients = array_diff($recipients,$deny);
382 $conversant_str = dbesc(implode(', ',$conversants));
385 // If the thread parent is OStatus then do some magic to distribute the messages.
386 // We have not only to look at the parent, since it could be a Friendica thread.
387 if (($thr_parent AND ($thr_parent[0]['network'] == NETWORK_OSTATUS)) OR ($parent['network'] == NETWORK_OSTATUS)) {
389 $diaspora_delivery = false;
391 logger('Some parent is OStatus for '.$target_item["guid"]." - Author: ".$thr_parent[0]['author-link']." - Owner: ".$thr_parent[0]['owner-link'], LOGGER_DEBUG);
393 // Send a salmon to the parent author
394 $r = q("SELECT `url`, `notify` FROM `contact` WHERE `nurl`='%s' AND `uid` IN (0, %d) AND `notify` != ''",
395 dbesc(normalise_link($thr_parent[0]['author-link'])),
397 if (dbm::is_result($r)) {
398 $probed_contact = $r[0];
400 $probed_contact = probe_url($thr_parent[0]['author-link']);
403 if ($probed_contact["notify"] != "") {
404 logger('Notify parent author '.$probed_contact["url"].': '.$probed_contact["notify"]);
405 $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
408 // Send a salmon to the parent owner
409 $r = q("SELECT `url`, `notify` FROM `contact` WHERE `nurl`='%s' AND `uid` IN (0, %d) AND `notify` != ''",
410 dbesc(normalise_link($thr_parent[0]['owner-link'])),
412 if (dbm::is_result($r)) {
413 $probed_contact = $r[0];
415 $probed_contact = probe_url($thr_parent[0]['owner-link']);
418 if ($probed_contact["notify"] != "") {
419 logger('Notify parent owner '.$probed_contact["url"].': '.$probed_contact["notify"]);
420 $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
423 // Send a salmon notification to every person we mentioned in the post
424 $arr = explode(',',$target_item['tag']);
425 foreach ($arr as $x) {
426 //logger('Checking tag '.$x, LOGGER_DEBUG);
428 if (preg_match('/@\[url=([^\]]*)\]/',$x,$matches)) {
429 $probed_contact = probe_url($matches[1]);
430 if ($probed_contact["notify"] != "") {
431 logger('Notify mentioned user '.$probed_contact["url"].': '.$probed_contact["notify"]);
432 $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
437 // It only makes sense to distribute answers to OStatus messages to Friendica and OStatus - but not Diaspora
438 $sql_extra = " AND `network` IN ('".NETWORK_OSTATUS."', '".NETWORK_DFRN."')";
440 $sql_extra = " AND `network` IN ('".NETWORK_OSTATUS."', '".NETWORK_DFRN."', '".NETWORK_DIASPORA."', '".NETWORK_MAIL."', '".NETWORK_MAIL2."')";
443 $public_message = false;
446 // If this is a public message and pubmail is set on the parent, include all your email contacts
448 $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
450 if (! $mail_disabled) {
451 if ((! strlen($target_item['allow_cid'])) && (! strlen($target_item['allow_gid']))
452 && (! strlen($target_item['deny_cid'])) && (! strlen($target_item['deny_gid']))
453 && (intval($target_item['pubmail']))) {
454 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `network` = '%s'",
458 if (dbm::is_result($r)) {
459 foreach ($r as $rr) {
460 $recipients[] = $rr['id'];
467 $recip_str = implode(', ', $recipients_followup);
469 $recip_str = implode(', ', $recipients);
472 $r = $recipients_relocate;
474 $r = q("SELECT * FROM `contact` WHERE `id` IN (%s) AND NOT `blocked` AND NOT `pending` AND NOT `archive`".$sql_extra,
481 if (dbm::is_result($r)) {
482 foreach ($r as $contact) {
483 if (!$contact['self']) {
484 if (($contact['network'] === NETWORK_DIASPORA) && ($public_message)) {
487 q("INSERT INTO `deliverq` (`cmd`,`item`,`contact`) VALUES ('%s', %d, %d)",
490 intval($contact['id'])
495 for ($x = 0; $x < count($r); $x ++) {
498 if ($contact['self']) {
501 logger("Deliver ".$target_item["guid"]." to ".$contact['url']." via network ".$contact['network'], LOGGER_DEBUG);
503 proc_run(PRIORITY_HIGH,'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 DISTINCT(`batch`), `id`, `name`,`network` FROM `contact` WHERE `network` = '%s'
535 AND `uid` = %d AND `rel` != %d AND NOT `blocked` AND NOT `pending` AND NOT `archive` GROUP BY `batch` ORDER BY rand()",
536 dbesc(NETWORK_DIASPORA),
537 intval($owner['uid']),
538 intval(CONTACT_IS_SHARING)
542 $r2 = q("SELECT `id`, `name`,`network` FROM `contact`
543 WHERE `network` in ( '%s', '%s') AND `uid` = %d AND NOT `blocked` AND NOT `pending` AND NOT `archive`
544 AND `rel` != %d order by rand() ",
546 dbesc(NETWORK_MAIL2),
547 intval($owner['uid']),
548 intval(CONTACT_IS_SHARING)
551 $r = array_merge($r2,$r1,$r0);
553 if (dbm::is_result($r)) {
554 logger('pubdeliver '.$target_item["guid"].': '.print_r($r,true), LOGGER_DEBUG);
556 // throw everything into the queue in case we get killed
558 foreach ($r as $rr) {
559 if ((! $mail) && (! $fsuggest) && (! $followup)) {
560 q("INSERT INTO `deliverq` (`cmd`,`item`,`contact`) VALUES ('%s', %d, %d)
561 ON DUPLICATE KEY UPDATE `cmd` = '%s', `item` = %d, `contact` = %d",
562 dbesc($cmd), intval($item_id), intval($rr['id']),
563 dbesc($cmd), intval($item_id), intval($rr['id'])
568 foreach ($r as $rr) {
570 // except for Diaspora batch jobs
571 // Don't deliver to folks who have already been delivered to
573 if (($rr['network'] !== NETWORK_DIASPORA) && (in_array($rr['id'],$conversants))) {
574 logger('notifier: already delivered id=' . $rr['id']);
578 if ((! $mail) && (! $fsuggest) && (! $followup)) {
579 logger('notifier: delivery agent: '.$rr['name'].' '.$rr['id'].' '.$rr['network'].' '.$target_item["guid"]);
580 proc_run(PRIORITY_HIGH,'include/delivery.php',$cmd,$item_id,$rr['id']);
589 // Notify PuSH subscribers (Used for OStatus distribution of regular posts)
590 if ($push_notify AND strlen($hub)) {
591 $hubs = explode(',', $hub);
593 foreach ($hubs as $h) {
599 if ($h === '[internal]') {
600 // Set push flag for PuSH subscribers to this topic,
601 // they will be notified in queue.php
602 q("UPDATE `push_subscriber` SET `push` = 1 ".
603 "WHERE `nickname` = '%s' AND `push` = 0", dbesc($owner['nickname']));
605 logger('Activating internal PuSH for item '.$item_id, LOGGER_DEBUG);
609 $params = 'hub.mode=publish&hub.url=' . urlencode( App::get_baseurl() . '/dfrn_poll/' . $owner['nickname'] );
610 post_url($h,$params);
611 logger('publish for item '.$item_id.' ' . $h . ' ' . $params . ' returned ' . $a->get_curl_code());
613 if (count($hubs) > 1) {
614 sleep(7); // try and avoid multiple hubs responding at precisely the same time
619 // Handling the pubsubhubbub requests
620 proc_run(PRIORITY_HIGH,'include/pubsubpublish.php');
623 logger('notifier: calling hooks', LOGGER_DEBUG);
626 call_hooks('notifier_normal',$target_item);
629 call_hooks('notifier_end',$target_item);