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