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