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