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