]> git.mxchange.org Git - friendica.git/blob - include/notifier.php
Merge remote branch 'upstream/master'
[friendica.git] / include / notifier.php
1 <?php
2
3 require_once("boot.php");
4 require_once('include/queue_fn.php');
5 require_once('include/html2plain.php');
6
7 /*
8  * This file was at one time responsible for doing all deliveries, but this caused
9  * big problems on shared hosting systems, where the process might get killed by the 
10  * hosting provider and nothing would get delivered. 
11  * It now only delivers one message under certain cases, and invokes a queued
12  * delivery mechanism (include/deliver.php) to deliver individual contacts at 
13  * controlled intervals.
14  * This has a much better chance of surviving random processes getting killed
15  * by the hosting provider. 
16  * A lot of this code is duplicated in include/deliver.php until we have time to go back
17  * and re-structure the delivery procedure based on the obstacles that have been thrown at 
18  * us by hosting providers. 
19  */
20
21 function notifier_run($argv, $argc){
22         global $a, $db;
23
24         if(is_null($a)){
25                 $a = new App;
26         }
27   
28         if(is_null($db)) {
29                 @include(".htconfig.php");
30                 require_once("dba.php");
31                 $db = new dba($db_host, $db_user, $db_pass, $db_data);
32                         unset($db_host, $db_user, $db_pass, $db_data);
33         }
34
35         require_once("session.php");
36         require_once("datetime.php");
37         require_once('include/items.php');
38         require_once('include/bbcode.php');
39         require_once('include/email.php');
40         load_config('config');
41         load_config('system');
42
43         load_hooks();
44
45         if($argc < 3)
46                 return;
47
48         $a->set_baseurl(get_config('system','url'));
49
50         logger('notifier: invoked: ' . print_r($argv,true));
51
52         $cmd = $argv[1];
53
54         switch($cmd) {
55                 case 'mail':
56                 default:
57                         $item_id = intval($argv[2]);
58                         if(! $item_id){
59                                 return;
60                         }
61                         break;
62         }
63
64         $expire = false;
65         $mail = false;
66         $fsuggest = false;
67         $top_level = false;
68         $recipients = array();
69         $url_recipients = array();
70
71         $normal_mode = true;
72
73         if($cmd === 'mail') {
74                 $normal_mode = false;
75                 $mail = true;
76                 $message = q("SELECT * FROM `mail` WHERE `id` = %d LIMIT 1",
77                                 intval($item_id)
78                 );
79                 if(! count($message)){
80                         return;
81                 }
82                 $uid = $message[0]['uid'];
83                 $recipients[] = $message[0]['contact-id'];
84                 $item = $message[0];
85
86         }
87         elseif($cmd === 'expire') {
88                 $normal_mode = false;
89                 $expire = true;
90                 $items = q("SELECT * FROM `item` WHERE `uid` = %d AND `wall` = 1 
91                         AND `deleted` = 1 AND `changed` > UTC_TIMESTAMP() - INTERVAL 10 MINUTE",
92                         intval($item_id)
93                 );
94                 $uid = $item_id;
95                 $item_id = 0;
96                 if(! count($items))
97                         return;
98         }
99         elseif($cmd === 'suggest') {
100                 $normal_mode = false;
101                 $fsuggest = true;
102
103                 $suggest = q("SELECT * FROM `fsuggest` WHERE `id` = %d LIMIT 1",
104                         intval($item_id)
105                 );
106                 if(! count($suggest))
107                         return;
108                 $uid = $suggest[0]['uid'];
109                 $recipients[] = $suggest[0]['cid'];
110                 $item = $suggest[0];
111         }
112         else {
113
114                 // find ancestors
115                 $r = q("SELECT * FROM `item` WHERE `id` = %d and visible = 1 and moderated = 0 LIMIT 1",
116                         intval($item_id)
117                 );
118
119                 if((! count($r)) || (! intval($r[0]['parent']))) {
120                         return;
121                 }
122
123                 $target_item = $r[0];
124                 $parent_id = intval($r[0]['parent']);
125                 $uid = $r[0]['uid'];
126                 $updated = $r[0]['edited'];
127
128                 if(! $parent_id)
129                         return;
130
131                 $items = q("SELECT `item`.*, `sign`.`signed_text`,`sign`.`signature`,`sign`.`signer` 
132                         FROM `item` LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id` WHERE `parent` = %d and visible = 1 and moderated = 0 ORDER BY `id` ASC",
133                         intval($parent_id)
134                 );
135
136                 if(! count($items)) {
137                         return;
138                 }
139
140                 // avoid race condition with deleting entries
141
142                 if($items[0]['deleted']) {
143                         foreach($items as $item)
144                                 $item['deleted'] = 1;
145                 }
146
147                 if((count($items) == 1) && ($items[0]['id'] === $target_item['id']) && ($items[0]['uri'] === $items[0]['parent-uri'])) {
148                         logger('notifier: top level post');
149                         $top_level = true;
150                 }
151
152         }
153
154         $r = q("SELECT `contact`.*, `user`.`pubkey` AS `upubkey`, `user`.`prvkey` AS `uprvkey`, 
155                 `user`.`timezone`, `user`.`nickname`, `user`.`sprvkey`, `user`.`spubkey`, 
156                 `user`.`page-flags`, `user`.`prvnets`
157                 FROM `contact` LEFT JOIN `user` ON `user`.`uid` = `contact`.`uid` 
158                 WHERE `contact`.`uid` = %d AND `contact`.`self` = 1 LIMIT 1",
159                 intval($uid)
160         );
161
162         if(! count($r))
163                 return;
164
165         $owner = $r[0];
166
167         $walltowall = ((($top_level) && ($owner['id'] != $items[0]['contact-id'])) ? true : false);
168
169         $hub = get_config('system','huburl');
170
171         // If this is a public conversation, notify the feed hub
172         $public_message = true;
173
174         // fill this in with a single salmon slap if applicable
175         $slap = '';
176
177         if(! ($mail || $fsuggest)) {
178
179                 require_once('include/group.php');
180
181                 $parent = $items[0];
182
183                 // This is IMPORTANT!!!!
184
185                 // We will only send a "notify owner to relay" or followup message if the referenced post
186                 // originated on our system by virtue of having our hostname somewhere
187                 // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
188
189                 // if $parent['wall'] == 1 we will already have the parent message in our array
190                 // and we will relay the whole lot.
191  
192                 // expire sends an entire group of expire messages and cannot be forwarded.
193                 // However the conversation owner will be a part of the conversation and will 
194                 // be notified during this run.
195                 // Other DFRN conversation members will be alerted during polled updates.
196
197
198
199                 // Diaspora members currently are not notified of expirations, and other networks have
200                 // either limited or no ability to process deletions. We should at least fix Diaspora 
201                 // by stringing togther an array of retractions and sending them onward.
202                  
203         
204                 $localhost = $a->get_hostname();
205                 if(strpos($localhost,':'))
206                         $localhost = substr($localhost,0,strpos($localhost,':'));
207
208                 /**
209                  *
210                  * Be VERY CAREFUL if you make any changes to the following several lines. Seemingly innocuous changes 
211                  * have been known to cause runaway conditions which affected several servers, along with 
212                  * permissions issues. 
213                  *
214                  */
215  
216                 $relay_to_owner = false;
217
218                 if((! $top_level) && ($parent['wall'] == 0) && (! $expire) && (stristr($target_item['uri'],$localhost))) {
219                         $relay_to_owner = true;
220                 }
221
222
223                 if(($cmd === 'uplink') && (intval($parent['forum_mode'])) && (! $top_level)) {
224                         $relay_to_owner = true;                 
225                 } 
226
227                 // until the 'origin' flag has been in use for several months
228                 // we will just use it as a fallback test
229                 // later we will be able to use it as the primary test of whether or not to relay.
230
231                 if(! $target_item['origin'])
232                         $relay_to_owner = false;
233
234                 if($parent['origin'])
235                         $relay_to_owner = false;
236
237
238
239                 if($relay_to_owner) {
240                         logger('notifier: followup', LOGGER_DEBUG);
241                         // local followup to remote post
242                         $followup = true;
243                         $public_message = false; // not public
244                         $conversant_str = dbesc($parent['contact-id']);
245                 }
246                 else {
247                         $followup = false;
248
249                         // don't send deletions onward for other people's stuff
250
251                         if($target_item['deleted'] && (! intval($target_item['wall']))) {
252                                 logger('notifier: ignoring delete notification for non-wall item');
253                                 return;
254                         }
255
256                         if((strlen($parent['allow_cid'])) 
257                                 || (strlen($parent['allow_gid'])) 
258                                 || (strlen($parent['deny_cid'])) 
259                                 || (strlen($parent['deny_gid']))) {
260                                 $public_message = false; // private recipients, not public
261                         }
262
263                         $allow_people = expand_acl($parent['allow_cid']);
264                         $allow_groups = expand_groups(expand_acl($parent['allow_gid']));
265                         $deny_people  = expand_acl($parent['deny_cid']);
266                         $deny_groups  = expand_groups(expand_acl($parent['deny_gid']));
267
268                         // if our parent is a forum, uplink to the origional author causing
269                         // a delivery fork
270
271                         if(intval($parent['forum_mode']) && (! $top_level) && ($cmd !== 'uplink')) {
272                                 proc_run('php','include/notifier','uplink',$item_id);
273                         }
274
275                         $conversants = array();
276
277                         foreach($items as $item) {
278                                 $recipients[] = $item['contact-id'];
279                                 $conversants[] = $item['contact-id'];
280                                 // pull out additional tagged people to notify (if public message)
281                                 if($public_message && strlen($item['inform'])) {
282                                         $people = explode(',',$item['inform']);
283                                         foreach($people as $person) {
284                                                 if(substr($person,0,4) === 'cid:') {
285                                                         $recipients[] = intval(substr($person,4));
286                                                         $conversants[] = intval(substr($person,4));
287                                                 }
288                                                 else {
289                                                         $url_recipients[] = substr($person,4);
290                                                 }
291                                         }
292                                 }
293                         }
294
295                         logger('notifier: url_recipients' . print_r($url_recipients,true));
296
297                         $conversants = array_unique($conversants);
298
299
300                         $recipients = array_unique(array_merge($recipients,$allow_people,$allow_groups));
301                         $deny = array_unique(array_merge($deny_people,$deny_groups));
302                         $recipients = array_diff($recipients,$deny);
303
304                         $conversant_str = dbesc(implode(', ',$conversants));
305                 }
306
307                 $r = q("SELECT * FROM `contact` WHERE `id` IN ( $conversant_str ) AND `blocked` = 0 AND `pending` = 0");
308
309                 if(count($r))
310                         $contacts = $r;
311         }
312
313         $feed_template = get_markup_template('atom_feed.tpl');
314         $mail_template = get_markup_template('atom_mail.tpl');
315
316         $atom = '';
317         $slaps = array();
318
319         $hubxml = feed_hublinks();
320
321         $birthday = feed_birthday($owner['uid'],$owner['timezone']);
322
323         if(strlen($birthday))
324                 $birthday = '<dfrn:birthday>' . xmlify($birthday) . '</dfrn:birthday>';
325
326         $atom .= replace_macros($feed_template, array(
327                         '$version'      => xmlify(FRIENDICA_VERSION),
328                         '$feed_id'      => xmlify($a->get_baseurl() . '/profile/' . $owner['nickname'] ),
329                         '$feed_title'   => xmlify($owner['name']),
330                         '$feed_updated' => xmlify(datetime_convert('UTC', 'UTC', $updated . '+00:00' , ATOM_TIME)) ,
331                         '$hub'          => $hubxml,
332                         '$salmon'       => '',  // private feed, we don't use salmon here
333                         '$name'         => xmlify($owner['name']),
334                         '$profile_page' => xmlify($owner['url']),
335                         '$photo'        => xmlify($owner['photo']),
336                         '$thumb'        => xmlify($owner['thumb']),
337                         '$picdate'      => xmlify(datetime_convert('UTC','UTC',$owner['avatar-date'] . '+00:00' , ATOM_TIME)) ,
338                         '$uridate'      => xmlify(datetime_convert('UTC','UTC',$owner['uri-date']    . '+00:00' , ATOM_TIME)) ,
339                         '$namdate'      => xmlify(datetime_convert('UTC','UTC',$owner['name-date']   . '+00:00' , ATOM_TIME)) ,
340                         '$birthday'     => $birthday
341         ));
342
343         if($mail) {
344                 $public_message = false;  // mail is  not public
345
346                 $body = fix_private_photos($item['body'],$owner['uid']);
347
348                 $atom .= replace_macros($mail_template, array(
349                         '$name'         => xmlify($owner['name']),
350                         '$profile_page' => xmlify($owner['url']),
351                         '$thumb'        => xmlify($owner['thumb']),
352                         '$item_id'      => xmlify($item['uri']),
353                         '$subject'      => xmlify($item['title']),
354                         '$created'      => xmlify(datetime_convert('UTC', 'UTC', $item['created'] . '+00:00' , ATOM_TIME)),
355                         '$content'      => xmlify($body),
356                         '$parent_id'    => xmlify($item['parent-uri'])
357                 ));
358         }
359         elseif($fsuggest) {
360                 $public_message = false;  // suggestions are not public
361
362                 $sugg_template = get_markup_template('atom_suggest.tpl');
363
364                 $atom .= replace_macros($sugg_template, array(
365                         '$name'         => xmlify($item['name']),
366                         '$url'          => xmlify($item['url']),
367                         '$photo'        => xmlify($item['photo']),
368                         '$request'      => xmlify($item['request']),
369                         '$note'         => xmlify($item['note'])
370                 ));
371
372                 // We don't need this any more
373
374                 q("DELETE FROM `fsuggest` WHERE `id` = %d LIMIT 1",
375                         intval($item['id'])
376                 );
377
378         }
379         else {
380                 if($followup) {
381                         foreach($items as $item) {  // there is only one item
382                                 if(! $item['parent'])
383                                         continue;
384                                 if($item['id'] == $item_id) {
385                                         logger('notifier: followup: item: ' . print_r($item,true), LOGGER_DATA);
386                                         $slap  = atom_entry($item,'html',null,$owner,false);
387                                         $atom .= atom_entry($item,'text',null,$owner,false);
388                                 }
389                         }
390                 }
391                 else {
392                         foreach($items as $item) {
393
394                                 if(! $item['parent'])
395                                         continue;
396
397                                 // private emails may be in included in public conversations. Filter them.
398
399                                 if(($public_message) && $item['private'])
400                                         continue;
401
402
403                                 $contact = get_item_contact($item,$contacts);
404
405                                 if(! $contact)
406                                         continue;
407
408                                 if($normal_mode) {
409
410                                         // we only need the current item, but include the parent because without it
411                                         // older sites without a corresponding dfrn_notify change may do the wrong thing.
412
413                                     if($item_id == $item['id'] || $item['id'] == $item['parent'])
414                                                 $atom .= atom_entry($item,'text',null,$owner,true);
415                                 }
416                                 else
417                                         $atom .= atom_entry($item,'text',null,$owner,true);
418
419                                 if(($top_level) && ($public_message) && ($item['author-link'] === $item['owner-link']) && (! $expire)) 
420                                         $slaps[] = atom_entry($item,'html',null,$owner,true);
421                         }
422                 }
423         }
424         $atom .= '</feed>' . "\r\n";
425
426         logger('notifier: ' . $atom, LOGGER_DATA);
427
428         logger('notifier: slaps: ' . print_r($slaps,true), LOGGER_DATA);
429
430         // If this is a public message and pubmail is set on the parent, include all your email contacts
431
432         $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
433
434         if(! $mail_disabled) {
435                 if((! strlen($target_item['allow_cid'])) && (! strlen($target_item['allow_gid'])) 
436                         && (! strlen($target_item['deny_cid'])) && (! strlen($target_item['deny_gid'])) 
437                         && (intval($target_item['pubmail']))) {
438                         $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `network` = '%s'",
439                                 intval($uid),
440                                 dbesc(NETWORK_MAIL)
441                         );
442                         if(count($r)) {
443                                 foreach($r as $rr)
444                                         $recipients[] = $rr['id'];
445                         }
446                 }
447         }
448
449         if($followup)
450                 $recip_str = $parent['contact-id'];
451         else
452                 $recip_str = implode(', ', $recipients);
453
454         $r = q("SELECT * FROM `contact` WHERE `id` IN ( %s ) AND `blocked` = 0 AND `pending` = 0 ",
455                 dbesc($recip_str)
456         );
457
458
459         require_once('include/salmon.php');
460
461         $interval = ((get_config('system','delivery_interval') === false) ? 2 : intval(get_config('system','delivery_interval')));
462
463         // delivery loop
464
465         if(count($r)) {
466
467                 foreach($r as $contact) {
468                         if((! $mail) && (! $fsuggest) && (! $followup) && (! $contact['self'])) {
469                                 if(($contact['network'] === NETWORK_DIASPORA) && ($public_message))
470                                         continue;
471                                 q("insert into deliverq ( `cmd`,`item`,`contact` ) values ('%s', %d, %d )",
472                                         dbesc($cmd),
473                                         intval($item_id),
474                                         intval($contact['id'])
475                                 );
476                         }
477                 }
478
479                 foreach($r as $contact) {
480                         if($contact['self'])
481                                 continue;
482
483                         // potentially more than one recipient. Start a new process and space them out a bit.
484                         // we will deliver single recipient types of message and email receipients here. 
485
486                         if((! $mail) && (! $fsuggest) && (! $followup)) {
487                                 proc_run('php','include/delivery.php',$cmd,$item_id,$contact['id']);
488                                 if($interval)
489                                         @time_sleep_until(microtime(true) + (float) $interval);
490                                 continue;
491                         }
492
493                         $deliver_status = 0;
494
495                         logger("main delivery by notifier: followup=$followup mail=$mail fsuggest=$fsuggest");
496
497                         switch($contact['network']) {
498                                 case NETWORK_DFRN:
499
500                                         // perform local delivery if we are on the same site
501
502                                         $basepath =  implode('/', array_slice(explode('/',$contact['url']),0,3));
503
504                                         if(link_compare($basepath,$a->get_baseurl())) {
505
506                                                 $nickname = basename($contact['url']);
507                                                 if($contact['issued-id'])
508                                                         $sql_extra = sprintf(" AND `dfrn-id` = '%s' ", dbesc($contact['issued-id']));
509                                                 else
510                                                         $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($contact['dfrn-id']));
511
512                                                 $x = q("SELECT  `contact`.*, `contact`.`uid` AS `importer_uid`, 
513                                                         `contact`.`pubkey` AS `cpubkey`, 
514                                                         `contact`.`prvkey` AS `cprvkey`, 
515                                                         `contact`.`thumb` AS `thumb`, 
516                                                         `contact`.`url` as `url`,
517                                                         `contact`.`name` as `senderName`,
518                                                         `user`.* 
519                                                         FROM `contact` 
520                                                         LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid` 
521                                                         WHERE `contact`.`blocked` = 0 AND `contact`.`pending` = 0
522                                                         AND `contact`.`network` = '%s' AND `user`.`nickname` = '%s'
523                                                         $sql_extra
524                                                         AND `user`.`account_expired` = 0 LIMIT 1",
525                                                         dbesc(NETWORK_DFRN),
526                                                         dbesc($nickname)
527                                                 );
528
529                                                 if(count($x)) {
530
531                                                         if($owner['page-flags'] == PAGE_COMMUNITY && ! $x[0]['writable']) {
532                                                                 q("update contact set writable = 1 where id = %d limit 1",
533                                                                         intval($x[0]['id'])
534                                                                 );
535                                                                 $x[0]['writable'] = 1;
536                                                         }
537
538                                                         require_once('library/simplepie/simplepie.inc');
539                                                         logger('mod-delivery: local delivery');
540                                                         local_delivery($x[0],$atom);
541                                                         break;                                  
542                                                 }
543                                         }
544
545
546
547                                         logger('notifier: dfrndelivery: ' . $contact['name']);
548                                         $deliver_status = dfrn_deliver($owner,$contact,$atom);
549
550                                         logger('notifier: dfrn_delivery returns ' . $deliver_status);
551         
552                                         if($deliver_status == (-1)) {
553                                                 logger('notifier: delivery failed: queuing message');
554                                                 // queue message for redelivery
555                                                 add_to_queue($contact['id'],NETWORK_DFRN,$atom);
556                                         }
557                                         break;
558                                 case NETWORK_OSTATUS:
559
560                                         // Do not send to otatus if we are not configured to send to public networks
561                                         if($owner['prvnets'])
562                                                 break;
563                                         if(get_config('system','ostatus_disabled') || get_config('system','dfrn_only'))
564                                                 break;
565
566                                         if($followup && $contact['notify']) {
567                                                 logger('notifier: slapdelivery: ' . $contact['name']);
568                                                 $deliver_status = slapper($owner,$contact['notify'],$slap);
569
570                                                 if($deliver_status == (-1)) {
571                                                         // queue message for redelivery
572                                                         add_to_queue($contact['id'],NETWORK_OSTATUS,$slap);
573                                                 }
574                                         }
575                                         else {
576
577                                                 // only send salmon if public - e.g. if it's ok to notify
578                                                 // a public hub, it's ok to send a salmon
579
580                                                 if((count($slaps)) && ($public_message) && (! $expire)) {
581                                                         logger('notifier: slapdelivery: ' . $contact['name']);
582                                                         foreach($slaps as $slappy) {
583                                                                 if($contact['notify']) {
584                                                                         $deliver_status = slapper($owner,$contact['notify'],$slappy);
585                                                                         if($deliver_status == (-1)) {
586                                                                                 // queue message for redelivery
587                                                                                 add_to_queue($contact['id'],NETWORK_OSTATUS,$slappy);
588                                                                         }
589                                                                 }
590                                                         }
591                                                 }
592                                         }
593                                         break;
594
595                                 case NETWORK_MAIL:
596                                 case NETWORK_MAIL2:
597                                                 
598                                         if(get_config('system','dfrn_only'))
599                                                 break;
600
601                                         // WARNING: does not currently convert to RFC2047 header encodings, etc.
602
603                                         $addr = $contact['addr'];
604                                         if(! strlen($addr))
605                                                 break;
606
607                                         if($cmd === 'wall-new' || $cmd === 'comment-new') {
608
609                                                 $it = null;
610                                                 if($cmd === 'wall-new') 
611                                                         $it = $items[0];
612                                                 else {
613                                                         $r = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1", 
614                                                                 intval($argv[2]),
615                                                                 intval($uid)
616                                                         );
617                                                         if(count($r))
618                                                                 $it = $r[0];
619                                                 }
620                                                 if(! $it)
621                                                         break;
622                                                 
623
624
625                                                 $local_user = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
626                                                         intval($uid)
627                                                 );
628                                                 if(! count($local_user))
629                                                         break;
630                                                 
631                                                 $reply_to = '';
632                                                 $r1 = q("SELECT * FROM `mailacct` WHERE `uid` = %d LIMIT 1",
633                                                         intval($uid)
634                                                 );
635                                                 if($r1 && $r1[0]['reply_to'])
636                                                         $reply_to = $r1[0]['reply_to'];
637
638                                                 $subject  = (($it['title']) ? email_header_encode($it['title'],'UTF-8') : t("\x28no subject\x29")) ;
639
640                                                 // only expose our real email address to true friends
641
642                                                 if(($contact['rel'] == CONTACT_IS_FRIEND) && (! $contact['blocked']))
643                                                         $headers  = 'From: ' . email_header_encode($local_user[0]['username'],'UTF-8') . ' <' . $local_user[0]['email'] . '>' . "\n";
644                                                 else
645                                                         $headers  = 'From: ' . email_header_encode($local_user[0]['username'],'UTF-8') . ' <' . t('noreply') . '@' . $a->get_hostname() . '>' . "\n";
646
647                                                 if($reply_to)
648                                                         $headers .= 'Reply-to: ' . $reply_to . "\n";
649
650                                                 // for testing purposes: Collect exported mails
651                                                 $file = tempnam("/tmp/friendica/", "mail-out2-");
652                                                 file_put_contents($file, json_encode($it));
653
654                                                 $headers .= 'Message-Id: <' . iri2msgid($it['uri']) . '>' . "\n";
655
656                                                 if($it['uri'] !== $it['parent-uri']) {
657                                                         $headers .= 'References: <' . iri2msgid($it['parent-uri']) . '>' . "\n";
658                                                         if(! strlen($it['title'])) {
659                                                                 $r = q("SELECT `title` FROM `item` WHERE `parent-uri` = '%s' LIMIT 1",
660                                                                         dbesc($it['parent-uri'])
661                                                                 );
662                                                                 if(count($r)) {
663                                                                         $subtitle = $r[0]['title'];
664                                                                         if($subtitle) {
665                                                                                 if(strncasecmp($subtitle,'RE:',3))
666                                                                                         $subject = $subtitle;
667                                                                                 else
668                                                                                         $subject = 'Re: ' . $subtitle;
669                                                                         }
670                                                                 }
671                                                         }
672                                                 }
673
674                                                 /*$headers .= 'MIME-Version: 1.0' . "\n";
675                                                 //$headers .= 'Content-Type: text/html; charset=UTF-8' . "\n";
676                                                 $headers .= 'Content-Type: text/plain; charset=UTF-8' . "\n";
677                                                 $headers .= 'Content-Transfer-Encoding: 8bit' . "\n\n";
678                                                 $html    = prepare_body($it);
679                                                 //$message = '<html><body>' . $html . '</body></html>';
680                                                 $message = html2plain($html);
681                                                 logger('notifier: email delivery to ' . $addr);
682                                                 mail($addr, $subject, $message, $headers);*/
683                                                 email_send($addr, $subject, $headers, $it);
684                                         }
685                                         break;
686                                 case NETWORK_DIASPORA:
687                                         require_once('include/diaspora.php');
688
689                                         if(get_config('system','dfrn_only') || (! get_config('system','diaspora_enabled')))
690                                                 break;
691
692                                         if($mail) {
693                                                 diaspora_send_mail($item,$owner,$contact);
694                                                 break;
695                                         }
696
697                                         if(! $normal_mode)
698                                                 break;
699
700                                         // special handling for followup to public post
701                                         // all other public posts processed as public batches further below
702
703                                         if($public_message) {
704                                                 if($followup)
705                                                         diaspora_send_followup($target_item,$owner,$contact, true);
706                                                 break;
707                                         }
708
709                                         if(! $contact['pubkey'])
710                                                 break;
711                                         
712                                         if($target_item['verb'] === ACTIVITY_DISLIKE) {
713                                                 // unsupported
714                                                 break;
715                                         }
716                                         elseif(($target_item['deleted']) && ($target_item['verb'] !== ACTIVITY_LIKE)) {
717                                                 // diaspora delete, 
718                                                 diaspora_send_retraction($target_item,$owner,$contact);
719                                                 break;
720                                         }
721                                         elseif($followup) {
722                                                 // send comments, likes and retractions of likes to owner to relay
723                                                 diaspora_send_followup($target_item,$owner,$contact);
724                                                 break;
725                                         }
726                                         elseif($target_item['parent'] != $target_item['id']) {
727                                                 // we are the relay - send comments, likes and unlikes to our conversants
728                                                 diaspora_send_relay($target_item,$owner,$contact);
729                                                 break;
730                                         }
731                                         elseif(($top_level) && (! $walltowall)) {
732                                                 // currently no workable solution for sending walltowall
733                                                 diaspora_send_status($target_item,$owner,$contact);
734                                                 break;
735                                         }
736
737                                         break;
738
739                                 case NETWORK_FEED:
740                                 case NETWORK_FACEBOOK:
741                                         if(get_config('system','dfrn_only'))
742                                                 break;
743                                 default:
744                                         break;
745                         }
746                 }
747         }
748                 
749         // send additional slaps to mentioned remote tags (@foo@example.com)
750
751         if($slap && count($url_recipients) && ($followup || $top_level) && $public_message && (! $expire)) {
752                 if(! get_config('system','dfrn_only')) {
753                         foreach($url_recipients as $url) {
754                                 if($url) {
755                                         logger('notifier: urldelivery: ' . $url);
756                                         $deliver_status = slapper($owner,$url,$slap);
757                                         // TODO: redeliver/queue these items on failure, though there is no contact record
758                                 }
759                         }
760                 }
761         }
762
763
764         if($public_message) {
765
766                 $r1 = q("SELECT DISTINCT(`batch`), `id`, `name`,`network` FROM `contact` WHERE `network` = '%s' 
767                         AND `uid` = %d AND `rel` != %d group by `batch` ORDER BY rand() ",
768                         dbesc(NETWORK_DIASPORA),
769                         intval($owner['uid']),
770                         intval(CONTACT_IS_SHARING)
771                 );
772                         
773                 $r2 = q("SELECT `id`, `name`,`network` FROM `contact` 
774                         WHERE `network` in ( '%s', '%s')  AND `uid` = %d AND `blocked` = 0 AND `pending` = 0
775                         AND `rel` != %d order by rand() ",
776                         dbesc(NETWORK_DFRN),
777                         dbesc(NETWORK_MAIL2),
778                         intval($owner['uid']),
779                         intval(CONTACT_IS_SHARING)
780                 );
781
782                 $r = array_merge($r2,$r1);
783
784                 if(count($r)) {
785                         logger('pubdeliver: ' . print_r($r,true), LOGGER_DEBUG);
786
787                         // throw everything into the queue in case we get killed
788
789                         foreach($r as $rr) {
790                                 if((! $mail) && (! $fsuggest) && (! $followup)) {
791                                         q("insert into deliverq ( `cmd`,`item`,`contact` ) values ('%s', %d, %d )",
792                                                 dbesc($cmd),
793                                                 intval($item_id),
794                                                 intval($rr['id'])
795                                         );
796                                 }
797                         }
798
799                         foreach($r as $rr) {
800
801                                 // except for Diaspora batch jobs
802                                 // Don't deliver to folks who have already been delivered to
803
804                                 if(($rr['network'] !== NETWORK_DIASPORA) && (in_array($rr['id'],$conversants))) {
805                                         logger('notifier: already delivered id=' . $rr['id']);
806                                         continue;
807                                 }
808
809                                 if((! $mail) && (! $fsuggest) && (! $followup)) {
810                                         logger('notifier: delivery agent: ' . $rr['name'] . ' ' . $rr['id']); 
811                                         proc_run('php','include/delivery.php',$cmd,$item_id,$rr['id']);
812                                         if($interval)
813                                                 @time_sleep_until(microtime(true) + (float) $interval);
814                                 }
815                         }
816                 }
817
818
819                 if(strlen($hub)) {
820                         $hubs = explode(',', $hub);
821                         if(count($hubs)) {
822                                 foreach($hubs as $h) {
823                                         $h = trim($h);
824                                         if(! strlen($h))
825                                                 continue;
826                                         $params = 'hub.mode=publish&hub.url=' . urlencode($a->get_baseurl() . '/dfrn_poll/' . $owner['nickname'] );
827                                         post_url($h,$params);
828                                         logger('pubsub: publish: ' . $h . ' ' . $params . ' returned ' . $a->get_curl_code());
829                                         if(count($hubs) > 1)
830                                                 sleep(7);                               // try and avoid multiple hubs responding at precisely the same time
831                                 }
832                         }
833                 }
834
835         }
836
837         if($normal_mode)
838                 call_hooks('notifier_normal',$target_item);
839
840         call_hooks('notifier_end',$target_item);
841
842         return;
843 }
844
845 if (array_search(__file__,get_included_files())===0){
846   notifier_run($argv,$argc);
847   killme();
848 }