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