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