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