2 require_once("boot.php");
3 require_once('include/queue_fn.php');
4 require_once('include/html2plain.php');
5 require_once("include/Scrape.php");
6 require_once('include/diaspora.php');
9 * This file was at one time responsible for doing all deliveries, but this caused
10 * big problems on shared hosting systems, where the process might get killed by the
11 * hosting provider and nothing would get delivered.
12 * It now only delivers one message under certain cases, and invokes a queued
13 * delivery mechanism (include/deliver.php) to deliver individual contacts at
14 * controlled intervals.
15 * This has a much better chance of surviving random processes getting killed
16 * by the hosting provider.
17 * A lot of this code is duplicated in include/deliver.php until we have time to go back
18 * and re-structure the delivery procedure based on the obstacles that have been thrown at
19 * us by hosting providers.
23 * The notifier is typically called with:
25 * proc_run('php', "include/notifier.php", COMMAND, ITEM_ID);
27 * where COMMAND is one of the following:
29 * activity (in diaspora.php, dfrn_confirm.php, profiles.php)
30 * comment-import (in diaspora.php, items.php)
31 * comment-new (in item.php)
32 * drop (in diaspora.php, items.php, photos.php)
33 * edit_post (in item.php)
34 * event (in events.php)
35 * expire (in items.php)
36 * like (in like.php, poke.php)
37 * mail (in message.php)
38 * suggest (in fsuggest.php)
39 * tag (in photos.php, poke.php, tagger.php)
40 * tgroup (in items.php)
41 * wall-new (in photos.php, item.php)
42 * removeme (in Contact.php)
43 * relocate (in uimport.php)
45 * and ITEM_ID is the id of the item in the database that needs to be sent to others.
49 function notifier_run(&$argv, &$argc){
57 @include(".htconfig.php");
58 require_once("include/dba.php");
59 $db = new dba($db_host, $db_user, $db_pass, $db_data);
60 unset($db_host, $db_user, $db_pass, $db_data);
63 require_once("include/session.php");
64 require_once("include/datetime.php");
65 require_once('include/items.php');
66 require_once('include/bbcode.php');
67 require_once('include/email.php');
68 load_config('config');
69 load_config('system');
76 $a->set_baseurl(get_config('system','url'));
78 logger('notifier: invoked: ' . print_r($argv,true), LOGGER_DEBUG);
85 $item_id = intval($argv[2]);
97 $recipients = array();
98 $url_recipients = array();
102 if($cmd === 'mail') {
103 $normal_mode = false;
105 $message = q("SELECT * FROM `mail` WHERE `id` = %d LIMIT 1",
108 if(! count($message)){
111 $uid = $message[0]['uid'];
112 $recipients[] = $message[0]['contact-id'];
116 elseif($cmd === 'expire') {
117 $normal_mode = false;
119 $items = q("SELECT * FROM `item` WHERE `uid` = %d AND `wall` = 1
120 AND `deleted` = 1 AND `changed` > UTC_TIMESTAMP() - INTERVAL 10 MINUTE",
128 elseif($cmd === 'suggest') {
129 $normal_mode = false;
132 $suggest = q("SELECT * FROM `fsuggest` WHERE `id` = %d LIMIT 1",
135 if(! count($suggest))
137 $uid = $suggest[0]['uid'];
138 $recipients[] = $suggest[0]['cid'];
140 } elseif($cmd === 'removeme') {
141 $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($item_id));
146 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` = 1 LIMIT 1", intval($item_id));
151 $r = q("SELECT * FROM `contact` WHERE `self` = 0 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;
166 $r = q("SELECT * FROM `item` WHERE `id` = %d and visible = 1 and moderated = 0 LIMIT 1",
170 if((! count($r)) || (! intval($r[0]['parent']))) {
174 $target_item = $r[0];
175 $parent_id = intval($r[0]['parent']);
177 $updated = $r[0]['edited'];
179 // POSSIBLE CLEANUP --> The following seems superfluous. We've already checked for "if (! intval($r[0]['parent']))" a few lines up
183 $items = q("SELECT `item`.*, `sign`.`signed_text`,`sign`.`signature`,`sign`.`signer`
184 FROM `item` LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id` WHERE `parent` = %d and visible = 1 and moderated = 0 ORDER BY `id` ASC",
188 if(! count($items)) {
192 // avoid race condition with deleting entries
194 if($items[0]['deleted']) {
195 foreach($items as $item)
196 $item['deleted'] = 1;
199 if((count($items) == 1) && ($items[0]['id'] === $target_item['id']) && ($items[0]['uri'] === $items[0]['parent-uri'])) {
200 logger('notifier: top level post');
206 $r = q("SELECT `contact`.*, `user`.`pubkey` AS `upubkey`, `user`.`prvkey` AS `uprvkey`,
207 `user`.`timezone`, `user`.`nickname`, `user`.`sprvkey`, `user`.`spubkey`,
208 `user`.`page-flags`, `user`.`prvnets`
209 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
210 WHERE `contact`.`uid` = %d AND `contact`.`self` = 1 LIMIT 1",
219 $walltowall = ((($top_level) && ($owner['id'] != $items[0]['contact-id'])) ? true : false);
221 $hub = get_config('system','huburl');
223 // If this is a public conversation, notify the feed hub
224 $public_message = true;
227 $push_notify = false;
229 // fill this in with a single salmon slap if applicable
232 if(! ($mail || $fsuggest || $relocate)) {
234 require_once('include/group.php');
238 $thr_parent = q("SELECT `network` FROM `item` WHERE `uri` = '%s' AND `uid` = %d",
239 dbesc($target_item["thr-parent"]), intval($target_item["uid"]));
241 logger('Parent is '.$parent['network'].'. Thread parent is '.$thr_parent[0]['network'], LOGGER_DEBUG);
243 // This is IMPORTANT!!!!
245 // We will only send a "notify owner to relay" or followup message if the referenced post
246 // originated on our system by virtue of having our hostname somewhere
247 // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
249 // if $parent['wall'] == 1 we will already have the parent message in our array
250 // and we will relay the whole lot.
252 // expire sends an entire group of expire messages and cannot be forwarded.
253 // However the conversation owner will be a part of the conversation and will
254 // be notified during this run.
255 // Other DFRN conversation members will be alerted during polled updates.
259 // Diaspora members currently are not notified of expirations, and other networks have
260 // either limited or no ability to process deletions. We should at least fix Diaspora
261 // by stringing togther an array of retractions and sending them onward.
264 $localhost = str_replace('www.','',$a->get_hostname());
265 if(strpos($localhost,':'))
266 $localhost = substr($localhost,0,strpos($localhost,':'));
270 * Be VERY CAREFUL if you make any changes to the following several lines. Seemingly innocuous changes
271 * have been known to cause runaway conditions which affected several servers, along with
272 * permissions issues.
276 $relay_to_owner = false;
278 if((! $top_level) && ($parent['wall'] == 0) && (! $expire) && (stristr($target_item['uri'],$localhost))) {
279 $relay_to_owner = true;
283 if(($cmd === 'uplink') && (intval($parent['forum_mode']) == 1) && (! $top_level)) {
284 $relay_to_owner = true;
287 // until the 'origin' flag has been in use for several months
288 // we will just use it as a fallback test
289 // later we will be able to use it as the primary test of whether or not to relay.
291 if(! $target_item['origin'])
292 $relay_to_owner = false;
294 if($parent['origin'])
295 $relay_to_owner = false;
297 if($relay_to_owner) {
298 logger('notifier: followup', LOGGER_DEBUG);
299 // local followup to remote post
301 $public_message = false; // not public
302 $conversant_str = dbesc($parent['contact-id']);
303 $recipients = array($parent['contact-id']);
305 if (!$target_item['private'] AND $target_item['wall'] AND
306 (strlen($target_item['allow_cid'].$target_item['allow_gid'].
307 $target_item['deny_cid'].$target_item['deny_gid']) == 0))
310 // We notify Friendica users in the thread when it is an OStatus thread.
311 // Hopefully this transfers the messages to the other Friendica servers. (Untested)
312 if (($thr_parent AND ($thr_parent[0]['network'] == NETWORK_OSTATUS)) OR ($parent['network'] == NETWORK_OSTATUS)) {
316 if ($parent["network"] == NETWORK_OSTATUS) {
317 $r = q("SELECT `author-link` FROM `item` WHERE `parent` = %d AND `author-link` != '%s'",
318 intval($target_item["parent"]), dbesc($owner['url']));
319 foreach($r as $parent_item) {
320 $probed_contact = probe_url($parent_item["author-link"]);
321 if (($probed_contact["notify"] != "") AND ($probed_contact["network"] == NETWORK_DFRN)) {
322 logger('Notify Friendica user '.$probed_contact["url"].': '.$probed_contact["notify"]);
323 $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
328 if (count($url_recipients))
329 logger("url_recipients ".print_r($url_recipients,true));
334 // don't send deletions onward for other people's stuff
336 if($target_item['deleted'] && (! intval($target_item['wall']))) {
337 logger('notifier: ignoring delete notification for non-wall item');
341 if((strlen($parent['allow_cid']))
342 || (strlen($parent['allow_gid']))
343 || (strlen($parent['deny_cid']))
344 || (strlen($parent['deny_gid']))) {
345 $public_message = false; // private recipients, not public
348 $allow_people = expand_acl($parent['allow_cid']);
349 $allow_groups = expand_groups(expand_acl($parent['allow_gid']),true);
350 $deny_people = expand_acl($parent['deny_cid']);
351 $deny_groups = expand_groups(expand_acl($parent['deny_gid']));
353 // if our parent is a public forum (forum_mode == 1), uplink to the origional author causing
354 // a delivery fork. private groups (forum_mode == 2) do not uplink
356 if((intval($parent['forum_mode']) == 1) && (! $top_level) && ($cmd !== 'uplink')) {
357 proc_run('php','include/notifier.php','uplink',$item_id);
360 $conversants = array();
362 foreach($items as $item) {
363 $recipients[] = $item['contact-id'];
364 $conversants[] = $item['contact-id'];
365 // pull out additional tagged people to notify (if public message)
366 if($public_message && strlen($item['inform'])) {
367 $people = explode(',',$item['inform']);
368 foreach($people as $person) {
369 if(substr($person,0,4) === 'cid:') {
370 $recipients[] = intval(substr($person,4));
371 $conversants[] = intval(substr($person,4));
374 $url_recipients[] = substr($person,4);
380 if (count($url_recipients))
381 logger('notifier: url_recipients ' . print_r($url_recipients,true));
383 $conversants = array_unique($conversants);
386 $recipients = array_unique(array_merge($recipients,$allow_people,$allow_groups));
387 $deny = array_unique(array_merge($deny_people,$deny_groups));
388 $recipients = array_diff($recipients,$deny);
390 $conversant_str = dbesc(implode(', ',$conversants));
393 // If the thread parent is OStatus then do some magic to distribute the messages.
394 // We have not only to look at the parent, since it could be a Friendica thread.
395 if (($thr_parent AND ($thr_parent[0]['network'] == NETWORK_OSTATUS)) OR ($parent['network'] == NETWORK_OSTATUS)) {
397 // Send a salmon notification to every person we mentioned in the post
398 $arr = explode(',',$target_item['tag']);
399 foreach($arr as $x) {
400 //logger('Checking tag '.$x, LOGGER_DEBUG);
402 if(preg_match('/@\[url=([^\]]*)\]/',$x,$matches)) {
403 $probed_contact = probe_url($matches[1]);
404 if ($probed_contact["notify"] != "") {
405 logger('Notify mentioned user '.$probed_contact["url"].': '.$probed_contact["notify"]);
406 $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
411 // It only makes sense to distribute answers to OStatus messages to Friendica and OStatus - but not Diaspora
412 $sql_extra = " AND `network` IN ('".NETWORK_OSTATUS."', '".NETWORK_DFRN."')";
416 $r = q("SELECT * FROM `contact` WHERE `id` IN ($conversant_str) AND `blocked` = 0 AND `pending` = 0 AND `archive` = 0".$sql_extra);
422 $feed_template = get_markup_template('atom_feed.tpl');
423 $mail_template = get_markup_template('atom_mail.tpl');
428 $hubxml = feed_hublinks();
430 $birthday = feed_birthday($owner['uid'],$owner['timezone']);
432 if(strlen($birthday))
433 $birthday = '<dfrn:birthday>' . xmlify($birthday) . '</dfrn:birthday>';
435 $atom .= replace_macros($feed_template, array(
436 '$version' => xmlify(FRIENDICA_VERSION),
437 '$feed_id' => xmlify($a->get_baseurl() . '/profile/' . $owner['nickname'] ),
438 '$feed_title' => xmlify($owner['name']),
439 '$feed_updated' => xmlify(datetime_convert('UTC', 'UTC', $updated . '+00:00' , ATOM_TIME)) ,
441 '$salmon' => '', // private feed, we don't use salmon here
442 '$name' => xmlify($owner['name']),
443 '$profile_page' => xmlify($owner['url']),
444 '$photo' => xmlify($owner['photo']),
445 '$thumb' => xmlify($owner['thumb']),
446 '$picdate' => xmlify(datetime_convert('UTC','UTC',$owner['avatar-date'] . '+00:00' , ATOM_TIME)) ,
447 '$uridate' => xmlify(datetime_convert('UTC','UTC',$owner['uri-date'] . '+00:00' , ATOM_TIME)) ,
448 '$namdate' => xmlify(datetime_convert('UTC','UTC',$owner['name-date'] . '+00:00' , ATOM_TIME)) ,
449 '$birthday' => $birthday,
450 '$community' => (($owner['page-flags'] == PAGE_COMMUNITY) ? '<dfrn:community>1</dfrn:community>' : '')
455 $public_message = false; // mail is not public
457 $body = fix_private_photos($item['body'],$owner['uid'],null,$message[0]['contact-id']);
459 $atom .= replace_macros($mail_template, array(
460 '$name' => xmlify($owner['name']),
461 '$profile_page' => xmlify($owner['url']),
462 '$thumb' => xmlify($owner['thumb']),
463 '$item_id' => xmlify($item['uri']),
464 '$subject' => xmlify($item['title']),
465 '$created' => xmlify(datetime_convert('UTC', 'UTC', $item['created'] . '+00:00' , ATOM_TIME)),
466 '$content' => xmlify($body),
467 '$parent_id' => xmlify($item['parent-uri'])
469 } elseif($fsuggest) {
470 $public_message = false; // suggestions are not public
472 $sugg_template = get_markup_template('atom_suggest.tpl');
474 $atom .= replace_macros($sugg_template, array(
475 '$name' => xmlify($item['name']),
476 '$url' => xmlify($item['url']),
477 '$photo' => xmlify($item['photo']),
478 '$request' => xmlify($item['request']),
479 '$note' => xmlify($item['note'])
482 // We don't need this any more
484 q("DELETE FROM `fsuggest` WHERE `id` = %d LIMIT 1",
488 } elseif($relocate) {
489 $public_message = false; // suggestions are not public
491 $sugg_template = get_markup_template('atom_relocate.tpl');
493 /* get site pubkey. this could be a new installation with no site keys*/
494 $pubkey = get_config('system','site_pubkey');
496 $res = new_keypair(1024);
497 set_config('system','site_prvkey', $res['prvkey']);
498 set_config('system','site_pubkey', $res['pubkey']);
501 $rp = q("SELECT `resource-id` , `scale`, type FROM `photo`
502 WHERE `profile` = 1 AND `uid` = %d ORDER BY scale;", $uid);
504 $ext = Photo::supportedTypes();
506 $photos[$p['scale']] = $a->get_baseurl().'/photo/'.$p['resource-id'].'-'.$p['scale'].'.'.$ext[$p['type']];
510 $atom .= replace_macros($sugg_template, array(
511 '$name' => xmlify($owner['name']),
512 '$photo' => xmlify($photos[4]),
513 '$thumb' => xmlify($photos[5]),
514 '$micro' => xmlify($photos[6]),
515 '$url' => xmlify($owner['url']),
516 '$request' => xmlify($owner['request']),
517 '$confirm' => xmlify($owner['confirm']),
518 '$notify' => xmlify($owner['notify']),
519 '$poll' => xmlify($owner['poll']),
520 '$sitepubkey' => xmlify(get_config('system','site_pubkey')),
521 //'$pubkey' => xmlify($owner['pubkey']),
522 //'$prvkey' => xmlify($owner['prvkey']),
524 $recipients_relocate = q("SELECT * FROM contact WHERE uid = %d AND self = 0 AND network = '%s'" , intval($uid), NETWORK_DFRN);
528 $slap = atom_entry($target_item,'html',null,$owner,false);
531 foreach($items as $item) { // there is only one item
532 if(! $item['parent'])
534 if($item['id'] == $item_id) {
535 logger('notifier: followup: item: ' . print_r($item,true), LOGGER_DATA);
536 //$slap = atom_entry($item,'html',null,$owner,false);
537 $atom .= atom_entry($item,'text',null,$owner,false);
541 foreach($items as $item) {
543 if(! $item['parent'])
546 // private emails may be in included in public conversations. Filter them.
548 if(($public_message) && $item['private'] == 1)
552 $contact = get_item_contact($item,$contacts);
559 // we only need the current item, but include the parent because without it
560 // older sites without a corresponding dfrn_notify change may do the wrong thing.
562 if($item_id == $item['id'] || $item['id'] == $item['parent'])
563 $atom .= atom_entry($item,'text',null,$owner,true);
565 $atom .= atom_entry($item,'text',null,$owner,true);
567 if(($top_level) && ($public_message) && ($item['author-link'] === $item['owner-link']) && (! $expire))
568 $slaps[] = atom_entry($item,'html',null,$owner,true);
572 $atom .= '</feed>' . "\r\n";
574 logger('notifier: ' . $atom, LOGGER_DATA);
576 logger('notifier: slaps: ' . print_r($slaps,true), LOGGER_DATA);
578 // If this is a public message and pubmail is set on the parent, include all your email contacts
580 $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
582 if(! $mail_disabled) {
583 if((! strlen($target_item['allow_cid'])) && (! strlen($target_item['allow_gid']))
584 && (! strlen($target_item['deny_cid'])) && (! strlen($target_item['deny_gid']))
585 && (intval($target_item['pubmail']))) {
586 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `network` = '%s'",
592 $recipients[] = $rr['id'];
598 $recip_str = $parent['contact-id'];
600 $recip_str = implode(', ', $recipients);
603 $r = $recipients_relocate;
605 $r = q("SELECT * FROM `contact` WHERE `id` IN ( %s ) AND `blocked` = 0 AND `pending` = 0 ",
610 require_once('include/salmon.php');
612 $interval = ((get_config('system','delivery_interval') === false) ? 2 : intval(get_config('system','delivery_interval')));
618 foreach($r as $contact) {
619 if((! $mail) && (! $fsuggest) && (! $followup) && (!$relocate) && (! $contact['self'])) {
620 if(($contact['network'] === NETWORK_DIASPORA) && ($public_message))
622 q("insert into deliverq ( `cmd`,`item`,`contact` ) values ('%s', %d, %d )",
625 intval($contact['id'])
631 // This controls the number of deliveries to execute with each separate delivery process.
632 // By default we'll perform one delivery per process. Assuming a hostile shared hosting
633 // provider, this provides the greatest chance of deliveries if processes start getting
634 // killed. We can also space them out with the delivery_interval to also help avoid them
637 // If $deliveries_per_process > 1, we will chain this number of multiple deliveries
638 // together into a single process. This will reduce the overall number of processes
639 // spawned for each delivery, but they will run longer.
641 $deliveries_per_process = intval(get_config('system','delivery_batch_count'));
642 if($deliveries_per_process <= 0)
643 $deliveries_per_process = 1;
645 $this_batch = array();
647 for($x = 0; $x < count($r); $x ++) {
653 logger("Deliver to ".$contact['url'], LOGGER_DEBUG);
655 // potentially more than one recipient. Start a new process and space them out a bit.
656 // we will deliver single recipient types of message and email recipients here.
658 if((! $mail) && (! $fsuggest) && (!$relocate) && (! $followup)) {
660 $this_batch[] = $contact['id'];
662 if(count($this_batch) == $deliveries_per_process) {
663 proc_run('php','include/delivery.php',$cmd,$item_id,$this_batch);
664 $this_batch = array();
666 @time_sleep_until(microtime(true) + (float) $interval);
670 // be sure to pick up any stragglers
671 if(count($this_batch))
672 proc_run('php','include/delivery.php',$cmd,$item_id,$this_batch);
677 logger("main delivery by notifier: followup=$followup mail=$mail fsuggest=$fsuggest relocate=$relocate");
679 switch($contact['network']) {
682 // perform local delivery if we are on the same site
684 $basepath = implode('/', array_slice(explode('/',$contact['url']),0,3));
686 if(link_compare($basepath,$a->get_baseurl())) {
688 $nickname = basename($contact['url']);
689 if($contact['issued-id'])
690 $sql_extra = sprintf(" AND `dfrn-id` = '%s' ", dbesc($contact['issued-id']));
692 $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($contact['dfrn-id']));
694 $x = q("SELECT `contact`.*, `contact`.`uid` AS `importer_uid`,
695 `contact`.`pubkey` AS `cpubkey`,
696 `contact`.`prvkey` AS `cprvkey`,
697 `contact`.`thumb` AS `thumb`,
698 `contact`.`url` as `url`,
699 `contact`.`name` as `senderName`,
702 INNER JOIN `user` ON `contact`.`uid` = `user`.`uid`
703 WHERE `contact`.`blocked` = 0 AND `contact`.`archive` = 0
704 AND `contact`.`pending` = 0
705 AND `contact`.`network` = '%s' AND `user`.`nickname` = '%s'
707 AND `user`.`account_expired` = 0 AND `user`.`account_removed` = 0 LIMIT 1",
712 if($x && count($x)) {
713 $write_flag = ((($x[0]['rel']) && ($x[0]['rel'] != CONTACT_IS_SHARING)) ? true : false);
714 if((($owner['page-flags'] == PAGE_COMMUNITY) || ($write_flag)) && (! $x[0]['writable'])) {
715 q("update contact set writable = 1 where id = %d",
718 $x[0]['writable'] = 1;
721 // if contact's ssl policy changed, which we just determined
722 // is on our own server, update our contact links
724 $ssl_policy = get_config('system','ssl_policy');
725 fix_contact_ssl_policy($x[0],$ssl_policy);
727 // If we are setup as a soapbox we aren't accepting input from this person
729 if($x[0]['page-flags'] == PAGE_SOAPBOX)
732 require_once('library/simplepie/simplepie.inc');
733 logger('mod-delivery: local delivery');
734 local_delivery($x[0],$atom);
739 logger('notifier: dfrndelivery: ' . $contact['name']);
740 $deliver_status = dfrn_deliver($owner,$contact,$atom);
742 logger('notifier: dfrn_delivery returns ' . $deliver_status);
744 if($deliver_status == (-1)) {
745 logger('notifier: delivery failed: queuing message');
746 // queue message for redelivery
747 add_to_queue($contact['id'],NETWORK_DFRN,$atom);
750 case NETWORK_OSTATUS:
752 // Do not send to ostatus if we are not configured to send to public networks
753 if($owner['prvnets'])
756 if(get_config('system','ostatus_disabled') || get_config('system','dfrn_only'))
759 if($followup && $contact['notify']) {
760 logger('slapdelivery followup item '.$item_id.' to ' . $contact['name']);
761 $deliver_status = slapper($owner,$contact['notify'],$slap);
763 if($deliver_status == (-1)) {
764 // queue message for redelivery
765 add_to_queue($contact['id'],NETWORK_OSTATUS,$slap);
769 // only send salmon if public - e.g. if it's ok to notify
770 // a public hub, it's ok to send a salmon
772 if((count($slaps)) && ($public_message) && (! $expire)) {
773 logger('slapdelivery item '.$item_id.' to ' . $contact['name']);
774 foreach($slaps as $slappy) {
775 if($contact['notify']) {
776 $deliver_status = slapper($owner,$contact['notify'],$slappy);
777 if($deliver_status == (-1)) {
778 // queue message for redelivery
779 add_to_queue($contact['id'],NETWORK_OSTATUS,$slappy);
790 if(get_config('system','dfrn_only'))
793 // WARNING: does not currently convert to RFC2047 header encodings, etc.
795 $addr = $contact['addr'];
799 if($cmd === 'wall-new' || $cmd === 'comment-new') {
802 if($cmd === 'wall-new')
805 $r = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
817 $local_user = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
820 if(! count($local_user))
824 $r1 = q("SELECT * FROM `mailacct` WHERE `uid` = %d LIMIT 1",
827 if($r1 && $r1[0]['reply_to'])
828 $reply_to = $r1[0]['reply_to'];
830 $subject = (($it['title']) ? email_header_encode($it['title'],'UTF-8') : t("\x28no subject\x29")) ;
832 // only expose our real email address to true friends
833 if(($contact['rel'] == CONTACT_IS_FRIEND) && (! $contact['blocked']))
835 $headers = 'From: ' . email_header_encode($local_user[0]['username'],'UTF-8') . ' <' . $reply_to . '>' . "\n";
836 $headers .= 'Sender: '.$local_user[0]['email']."\n";
838 $headers = 'From: ' . email_header_encode($local_user[0]['username'],'UTF-8') . ' <' . $local_user[0]['email'] . '>' . "\n";
840 $headers = 'From: ' . email_header_encode($local_user[0]['username'],'UTF-8') . ' <' . t('noreply') . '@' . $a->get_hostname() . '>' . "\n";
843 // $headers .= 'Reply-to: ' . $reply_to . "\n";
845 $headers .= 'Message-Id: <' . iri2msgid($it['uri']) . '>' . "\n";
847 if($it['uri'] !== $it['parent-uri']) {
848 $headers .= "References: <".iri2msgid($it["parent-uri"]).">";
850 // If Threading is enabled, write down the correct parent
851 if (($it["thr-parent"] != "") and ($it["thr-parent"] != $it["parent-uri"]))
852 $headers .= " <".iri2msgid($it["thr-parent"]).">";
856 $r = q("SELECT `title` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
857 dbesc($it['parent-uri']),
860 if(count($r) AND ($r[0]['title'] != ''))
861 $subject = $r[0]['title'];
863 $r = q("SELECT `title` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d LIMIT 1",
864 dbesc($it['parent-uri']),
867 if(count($r) AND ($r[0]['title'] != ''))
868 $subject = $r[0]['title'];
871 if(strncasecmp($subject,'RE:',3))
872 $subject = 'Re: '.$subject;
874 email_send($addr, $subject, $headers, $it);
877 case NETWORK_DIASPORA:
878 if(get_config('system','dfrn_only') || (! get_config('system','diaspora_enabled')))
882 diaspora_send_mail($item,$owner,$contact);
889 // special handling for followup to public post
890 // all other public posts processed as public batches further below
892 if($public_message) {
894 diaspora_send_followup($target_item,$owner,$contact, true);
898 if(! $contact['pubkey'])
901 if($target_item['verb'] === ACTIVITY_DISLIKE) {
905 elseif(($target_item['deleted']) && (($target_item['uri'] === $target_item['parent-uri']) || $followup)) {
906 // send both top-level retractions and relayable retractions for owner to relay
907 diaspora_send_retraction($target_item,$owner,$contact);
911 // send comments and likes to owner to relay
912 diaspora_send_followup($target_item,$owner,$contact);
915 elseif($target_item['uri'] !== $target_item['parent-uri']) {
916 // we are the relay - send comments, likes and relayable_retractions
917 // (of comments and likes) to our conversants
918 diaspora_send_relay($target_item,$owner,$contact);
921 elseif(($top_level) && (! $walltowall)) {
922 // currently no workable solution for sending walltowall
923 diaspora_send_status($target_item,$owner,$contact);
930 case NETWORK_FACEBOOK:
931 if(get_config('system','dfrn_only'))
934 if(get_config('system','dfrn_only'))
942 // send additional slaps to mentioned remote tags (@foo@example.com)
944 //if($slap && count($url_recipients) && ($followup || $top_level) && ($public_message || $push_notify) && (! $expire)) {
945 if($slap && count($url_recipients) && ($public_message || $push_notify) && (!$expire)) {
946 if(! get_config('system','dfrn_only')) {
947 foreach($url_recipients as $url) {
949 logger('notifier: urldelivery: ' . $url);
950 $deliver_status = slapper($owner,$url,$slap);
951 // TODO: redeliver/queue these items on failure, though there is no contact record
958 if($public_message) {
961 $r0 = diaspora_fetch_relay();
965 $r1 = q("SELECT DISTINCT(`batch`), `id`, `name`,`network` FROM `contact` WHERE `network` = '%s'
966 AND `uid` = %d AND `rel` != %d group by `batch` ORDER BY rand() ",
967 dbesc(NETWORK_DIASPORA),
968 intval($owner['uid']),
969 intval(CONTACT_IS_SHARING)
972 $r2 = q("SELECT `id`, `name`,`network` FROM `contact`
973 WHERE `network` in ( '%s', '%s') AND `uid` = %d AND `blocked` = 0 AND `pending` = 0 AND `archive` = 0
974 AND `rel` != %d order by rand() ",
976 dbesc(NETWORK_MAIL2),
977 intval($owner['uid']),
978 intval(CONTACT_IS_SHARING)
981 $r = array_merge($r2,$r1,$r0);
984 logger('pubdeliver: ' . print_r($r,true), LOGGER_DEBUG);
986 // throw everything into the queue in case we get killed
989 if((! $mail) && (! $fsuggest) && (! $followup)) {
990 q("insert into deliverq ( `cmd`,`item`,`contact` ) values ('%s', %d, %d )",
1000 // except for Diaspora batch jobs
1001 // Don't deliver to folks who have already been delivered to
1003 if(($rr['network'] !== NETWORK_DIASPORA) && (in_array($rr['id'],$conversants))) {
1004 logger('notifier: already delivered id=' . $rr['id']);
1008 if((! $mail) && (! $fsuggest) && (! $followup)) {
1009 logger('notifier: delivery agent: ' . $rr['name'] . ' ' . $rr['id']);
1010 proc_run('php','include/delivery.php',$cmd,$item_id,$rr['id']);
1012 @time_sleep_until(microtime(true) + (float) $interval);
1017 $push_notify = true;
1022 if($push_notify AND strlen($hub)) {
1023 $hubs = explode(',', $hub);
1025 foreach($hubs as $h) {
1030 if ($h === '[internal]') {
1031 // Set push flag for PuSH subscribers to this topic,
1032 // they will be notified in queue.php
1033 q("UPDATE `push_subscriber` SET `push` = 1 " .
1034 "WHERE `nickname` = '%s'", dbesc($owner['nickname']));
1036 logger('Activating internal PuSH for item '.$item_id, LOGGER_DEBUG);
1040 $params = 'hub.mode=publish&hub.url=' . urlencode( $a->get_baseurl() . '/dfrn_poll/' . $owner['nickname'] );
1041 post_url($h,$params);
1042 logger('publish for item '.$item_id.' ' . $h . ' ' . $params . ' returned ' . $a->get_curl_code());
1044 if(count($hubs) > 1)
1045 sleep(7); // try and avoid multiple hubs responding at precisely the same time
1049 // Handling the pubsubhubbub requests
1050 proc_run('php','include/pubsubpublish.php');
1053 // If the item was deleted, clean up the `sign` table
1054 if($target_item['deleted']) {
1055 $r = q("DELETE FROM sign where `retract_iid` = %d",
1056 intval($target_item['id'])
1060 logger('notifier: calling hooks', LOGGER_DEBUG);
1063 call_hooks('notifier_normal',$target_item);
1065 call_hooks('notifier_end',$target_item);
1071 if (array_search(__file__,get_included_files())===0){
1072 notifier_run($_SERVER["argv"],$_SERVER["argc"]);