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