]> git.mxchange.org Git - friendica.git/blob - include/notifier.php
332cd19e36bee51117391b4f75f50d40d25c8c9c
[friendica.git] / include / notifier.php
1 <?php
2 require_once("boot.php");
3
4 function notifier_run($argv, $argc){
5         global $a, $db;
6
7         if(is_null($a)){
8                 $a = new App;
9         }
10   
11         if(is_null($db)) {
12                 @include(".htconfig.php");
13                 require_once("dba.php");
14                 $db = new dba($db_host, $db_user, $db_pass, $db_data);
15                         unset($db_host, $db_user, $db_pass, $db_data);
16         }
17
18         require_once("session.php");
19         require_once("datetime.php");
20         require_once('include/items.php');
21         require_once('include/bbcode.php');
22
23         load_config('config');
24         load_config('system');
25
26         load_hooks();
27
28         if($argc < 3)
29                 return;
30
31         $a->set_baseurl(get_config('system','url'));
32
33         logger('notifier: invoked: ' . print_r($argv,true));
34
35         $cmd = $argv[1];
36
37         switch($cmd) {
38
39                 case 'mail':
40                 default:
41                         $item_id = intval($argv[2]);
42                         if(! $item_id){
43                                 return;
44                         }
45                         break;
46         }
47
48         $expire = false;
49         $top_level = false;
50         $recipients = array();
51         $url_recipients = array();
52
53         if($cmd === 'mail') {
54
55                 $message = q("SELECT * FROM `mail` WHERE `id` = %d LIMIT 1",
56                                 intval($item_id)
57                 );
58                 if(! count($message)){
59                         return;
60                 }
61                 $uid = $message[0]['uid'];
62                 $recipients[] = $message[0]['contact-id'];
63                 $item = $message[0];
64
65         }
66         elseif($cmd === 'expire') {
67                 $expire = true;
68                 $items = q("SELECT * FROM `item` WHERE `uid` = %d AND `wall` = 1 
69                         AND `deleted` = 1 AND `changed` > UTC_TIMESTAMP - INTERVAL 10 MINUTE",
70                         intval($item_id)
71                 );
72                 $uid = $item_id;
73                 $item_id = 0;
74                 if(! count($items))
75                         return;
76         }
77         elseif($cmd === 'suggest') {
78                 $suggest = q("SELECT * FROM `fsuggest` WHERE `id` = %d LIMIT 1",
79                         intval($item_id)
80                 );
81                 if(! count($suggest))
82                         return;
83                 $uid = $suggest[0]['uid'];
84                 $recipients[] = $suggest[0]['cid'];
85                 $item = $suggest[0];
86         }
87         else {
88
89                 // find ancestors
90                 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1",
91                         intval($item_id)
92                 );
93
94                 if((! count($r)) || (! intval($r[0]['parent']))) {
95                         return;
96                 }
97
98                 $parent_item = $r[0];
99                 $parent_id = intval($r[0]['parent']);
100                 $uid = $r[0]['uid'];
101                 $updated = $r[0]['edited'];
102
103                 $items = q("SELECT * FROM `item` WHERE `parent` = %d ORDER BY `id` ASC",
104                         intval($parent_id)
105                 );
106
107                 if(! count($items)) {
108                         return;
109                 }
110
111                 // avoid race condition with deleting entries
112
113                 if($items[0]['deleted']) {
114                         foreach($items as $item)
115                                 $item['deleted'] = 1;
116                 }
117
118                 if(count($items) == 1 && $items[0]['uri'] === $items[0]['parent-uri'])
119                         $top_level = true;
120         }
121
122         $r = q("SELECT `contact`.*, `user`.`pubkey` AS `upubkey`, `user`.`prvkey` AS `uprvkey`, 
123                 `user`.`timezone`, `user`.`nickname`, `user`.`sprvkey`, `user`.`spubkey`, 
124                 `user`.`page-flags`, `user`.`prvnets`
125                 FROM `contact` LEFT JOIN `user` ON `user`.`uid` = `contact`.`uid` 
126                 WHERE `contact`.`uid` = %d AND `contact`.`self` = 1 LIMIT 1",
127                 intval($uid)
128         );
129
130         if(! count($r))
131                 return;
132
133         $owner = $r[0];
134
135         $hub = get_config('system','huburl');
136
137         // If this is a public conversation, notify the feed hub
138         $notify_hub = true;
139
140         // fill this in with a single salmon slap if applicable
141         $slap = '';
142
143         if($cmd != 'mail' && $cmd != 'suggest') {
144
145                 require_once('include/group.php');
146
147                 $parent = $items[0];
148
149                 if($parent['wall'] == 0 && (! $expire)) {
150                         // local followup to remote post
151                         $followup = true;
152                         $notify_hub = false; // not public
153                         $conversant_str = dbesc($parent['contact-id']);
154                 }
155                 else {
156                         $followup = false;
157
158                         if((strlen($parent['allow_cid'])) 
159                                 || (strlen($parent['allow_gid'])) 
160                                 || (strlen($parent['deny_cid'])) 
161                                 || (strlen($parent['deny_gid']))) {
162                                 $notify_hub = false; // private recipients, not public
163                         }
164
165                         $allow_people = expand_acl($parent['allow_cid']);
166                         $allow_groups = expand_groups(expand_acl($parent['allow_gid']));
167                         $deny_people  = expand_acl($parent['deny_cid']);
168                         $deny_groups  = expand_groups(expand_acl($parent['deny_gid']));
169
170                         $conversants = array();
171
172                         foreach($items as $item) {
173                                 $recipients[] = $item['contact-id'];
174                                 $conversants[] = $item['contact-id'];
175                                 // pull out additional tagged people to notify (if public message)
176                                 if($notify_hub && strlen($item['inform'])) {
177                                         $people = explode(',',$item['inform']);
178                                         foreach($people as $person) {
179                                                 if(substr($person,0,4) === 'cid:') {
180                                                         $recipients[] = intval(substr($person,4));
181                                                         $conversants[] = intval(substr($person,4));
182                                                 }
183                                                 else {
184                                                         $url_recipients[] = substr($person,4);
185                                                 }
186                                         }
187                                 }
188                         }
189
190                         logger('notifier: url_recipients' . print_r($url_recipients,true));
191
192                         $conversants = array_unique($conversants);
193
194
195                         $recipients = array_unique(array_merge($recipients,$allow_people,$allow_groups));
196                         $deny = array_unique(array_merge($deny_people,$deny_groups));
197                         $recipients = array_diff($recipients,$deny);
198
199                         $conversant_str = dbesc(implode(', ',$conversants));
200                 }
201
202                 $r = q("SELECT * FROM `contact` WHERE `id` IN ( $conversant_str ) AND `blocked` = 0 AND `pending` = 0");
203
204
205                 if(count($r))
206                         $contacts = $r;
207         }
208
209         $feed_template = get_markup_template('atom_feed.tpl');
210         $mail_template = get_markup_template('atom_mail.tpl');
211
212         $atom = '';
213         $slaps = array();
214
215         $hubxml = feed_hublinks();
216
217         $birthday = feed_birthday($owner['uid'],$owner['timezone']);
218
219         if(strlen($birthday))
220                 $birthday = '<dfrn:birthday>' . xmlify($birthday) . '</dfrn:birthday>';
221
222         $atom .= replace_macros($feed_template, array(
223                         '$version'      => xmlify(FRIENDIKA_VERSION),
224                         '$feed_id'      => xmlify($a->get_baseurl() . '/profile/' . $owner['nickname'] ),
225                         '$feed_title'   => xmlify($owner['name']),
226                         '$feed_updated' => xmlify(datetime_convert('UTC', 'UTC', $updated . '+00:00' , ATOM_TIME)) ,
227                         '$hub'          => $hubxml,
228                         '$salmon'       => '',  // private feed, we don't use salmon here
229                         '$name'         => xmlify($owner['name']),
230                         '$profile_page' => xmlify($owner['url']),
231                         '$photo'        => xmlify($owner['photo']),
232                         '$thumb'        => xmlify($owner['thumb']),
233                         '$picdate'      => xmlify(datetime_convert('UTC','UTC',$owner['avatar-date'] . '+00:00' , ATOM_TIME)) ,
234                         '$uridate'      => xmlify(datetime_convert('UTC','UTC',$owner['uri-date']    . '+00:00' , ATOM_TIME)) ,
235                         '$namdate'      => xmlify(datetime_convert('UTC','UTC',$owner['name-date']   . '+00:00' , ATOM_TIME)) ,
236                         '$birthday'     => $birthday
237         ));
238
239         if($cmd === 'mail') {
240                 $notify_hub = false;  // mail is  not public
241
242                 $body = fix_private_photos($item['body'],$owner['uid']);
243
244                 $atom .= replace_macros($mail_template, array(
245                         '$name'         => xmlify($owner['name']),
246                         '$profile_page' => xmlify($owner['url']),
247                         '$thumb'        => xmlify($owner['thumb']),
248                         '$item_id'      => xmlify($item['uri']),
249                         '$subject'      => xmlify($item['title']),
250                         '$created'      => xmlify(datetime_convert('UTC', 'UTC', $item['created'] . '+00:00' , ATOM_TIME)),
251                         '$content'      => xmlify($body),
252                         '$parent_id'    => xmlify($item['parent-uri'])
253                 ));
254         }
255         elseif($cmd === 'suggest') {
256                 $notify_hub = false;  // suggestions are not public
257
258                 $sugg_template = get_markup_template('atom_suggest.tpl');
259
260                 $atom .= replace_macros($sugg_template, array(
261                         '$name'         => xmlify($item['name']),
262                         '$url'          => xmlify($item['url']),
263                         '$photo'        => xmlify($item['photo']),
264                         '$request'      => xmlify($item['request']),
265                         '$note'         => xmlify($item['note'])
266                 ));
267
268                 // We don't need this any more
269
270                 q("DELETE FROM `fsuggest` WHERE `id` = %d LIMIT 1",
271                         intval($item['id'])
272                 );
273
274         }
275         else {
276                 if($followup) {
277                         foreach($items as $item) {  // there is only one item
278                                 if(! $item['parent'])
279                                         continue;
280                                 if($item['id'] == $item_id) {
281                                         logger('notifier: followup: item: ' . print_r($item,true), LOGGER_DATA);
282                                         $slap  = atom_entry($item,'html',$owner,$owner,false);
283                                         $atom .= atom_entry($item,'text',$owner,$owner,false);
284                                 }
285                         }
286                 }
287                 else {
288                         foreach($items as $item) {
289
290                                 if(! $item['parent'])
291                                         continue;
292
293                                 // private emails may be in included in public conversations. Filter them.
294
295                                 if(($notify_hub) && $item['private'])
296                                         continue;
297
298                                 $contact = get_item_contact($item,$contacts);
299                                 if(! $contact)
300                                         continue;
301
302                                 $atom .= atom_entry($item,'text',$contact,$owner,true);
303
304                                 if(($top_level) && ($notify_hub) && ($item['author-link'] === $item['owner-link']) && (! $expire)) 
305                                         $slaps[] = atom_entry($item,'html',$contact,$owner,true);
306                         }
307                 }
308         }
309         $atom .= '</feed>' . "\r\n";
310
311         logger('notifier: ' . $atom, LOGGER_DATA);
312
313         logger('notifier: slaps: ' . print_r($slaps,true), LOGGER_DATA);
314
315         // If this is a public message and pubmail is set on the parent, include all your email contacts
316
317         $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
318
319         if(! $mail_disabled) {
320                 if((! strlen($parent_item['allow_cid'])) && (! strlen($parent_item['allow_gid'])) 
321                         && (! strlen($parent_item['deny_cid'])) && (! strlen($parent_item['deny_gid'])) 
322                         && (intval($parent_item['pubmail']))) {
323                         $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `network` = '%s'",
324                                 intval($uid),
325                                 dbesc(NETWORK_MAIL)
326                         );
327                         if(count($r)) {
328                                 foreach($r as $rr)
329                                         $recipients[] = $rr['id'];
330                         }
331                 }
332         }
333
334         if($followup)
335                 $recip_str = $parent['contact-id'];
336         else
337                 $recip_str = implode(', ', $recipients);
338
339         $r = q("SELECT * FROM `contact` WHERE `id` IN ( %s ) AND `blocked` = 0 AND `pending` = 0 ",
340                 dbesc($recip_str)
341         );
342
343         // delivery loop
344
345         require_once('include/salmon.php');
346
347         if(count($r)) {
348                 foreach($r as $contact) {
349                         if($contact['self'])
350                                 continue;
351
352                         $deliver_status = 0;
353
354                         switch($contact['network']) {
355                                 case NETWORK_DFRN:
356                                         logger('notifier: dfrndelivery: ' . $contact['name']);
357                                         $deliver_status = dfrn_deliver($owner,$contact,$atom);
358
359                                         logger('notifier: dfrn_delivery returns ' . $deliver_status);
360         
361                                         if($deliver_status == (-1)) {
362                                                 logger('notifier: delivery failed: queuing message');
363                                                 // queue message for redelivery
364                                                 q("INSERT INTO `queue` ( `cid`, `created`, `last`, `content`)
365                                                         VALUES ( %d, '%s', '%s', '%s') ",
366                                                         intval($contact['id']),
367                                                         dbesc(datetime_convert()),
368                                                         dbesc(datetime_convert()),
369                                                         dbesc($atom)
370                                                 );
371                                         }
372                                         break;
373                                 case NETWORK_OSTATUS:
374
375                                         // Do not send to otatus if we are not configured to send to public networks
376                                         if($owner['prvnets'])
377                                                 break;
378                                         if(get_config('system','ostatus_disabled') || get_config('system','dfrn_only'))
379                                                 break;
380
381                                         if($followup && $contact['notify']) {
382                                                 logger('notifier: slapdelivery: ' . $contact['name']);
383                                                 $deliver_status = slapper($owner,$contact['notify'],$slap);
384
385                                                 if($deliver_status == (-1)) {
386                                                         // queue message for redelivery
387                                                         q("INSERT INTO `queue` ( `cid`, `created`, `last`, `content`)
388                                                                 VALUES ( %d, '%s', '%s', '%s') ",
389                                                                 intval($contact['id']),
390                                                                 dbesc(datetime_convert()),
391                                                                 dbesc(datetime_convert()),
392                                                                 dbesc($slap)
393                                                         );
394
395                                                 }
396                                         }
397                                         else {
398
399                                                 // only send salmon if public - e.g. if it's ok to notify
400                                                 // a public hub, it's ok to send a salmon
401
402                                                 if((count($slaps)) && ($notify_hub) && (! $expire)) {
403                                                         logger('notifier: slapdelivery: ' . $contact['name']);
404                                                         foreach($slaps as $slappy) {
405                                                                 if($contact['notify']) {
406                                                                         $deliver_status = slapper($owner,$contact['notify'],$slappy);
407                                                                         if($deliver_status == (-1)) {
408                                                                                 // queue message for redelivery
409                                                                                 q("INSERT INTO `queue` ( `cid`, `created`, `last`, `content`)
410                                                                                         VALUES ( %d, '%s', '%s', '%s') ",
411                                                                                         intval($contact['id']),
412                                                                                         dbesc(datetime_convert()),
413                                                                                         dbesc(datetime_convert()),
414                                                                                         dbesc($slappy)
415                                                                                 );                                                              
416                                                                         }
417                                                                 }
418                                                         }
419                                                 }
420                                         }
421                                         break;
422
423                                 case NETWORK_MAIL:
424                                                 
425                                         if(get_config('system','dfrn_only'))
426                                                 break;
427
428                                         // WARNING: does not currently convert to RFC2047 header encodings, etc.
429
430                                         $addr = $contact['addr'];
431                                         if(! strlen($addr))
432                                                 break;
433
434                                         if($cmd === 'wall-new' || $cmd === 'comment-new') {
435
436                                                 $it = null;
437                                                 if($cmd === 'wall-new') 
438                                                         $it = $items[0];
439                                                 else {
440                                                         $r = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1", 
441                                                                 intval($argv[2]),
442                                                                 intval($uid)
443                                                         );
444                                                         if(count($r))
445                                                                 $it = $r[0];
446                                                 }
447                                                 if(! $it)
448                                                         break;
449                                                 
450
451
452                                                 $local_user = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
453                                                         intval($uid)
454                                                 );
455                                                 if(! count($local_user))
456                                                         break;
457                                                 
458                                                 $reply_to = '';
459                                                 $r1 = q("SELECT * FROM `mailacct` WHERE `uid` = %d LIMIT 1",
460                                                         intval($uid)
461                                                 );
462                                                 if($r1 && $r1[0]['reply_to'])
463                                                         $reply_to = $r1[0]['reply_to'];
464         
465                                                 $subject  = (($it['title']) ? $it['title'] : t("\x28no subject\x29")) ;
466                                                 $headers  = 'From: ' . $local_user[0]['username'] . ' <' . $local_user[0]['email'] . '>' . "\n";
467
468                                                 if($reply_to)
469                                                         $headers .= 'Reply-to: ' . $reply_to . "\n";
470
471                                                 $headers .= 'Message-id: <' . $it['uri'] . '>' . "\n";
472
473                                                 if($it['uri'] !== $it['parent-uri']) {
474                                                         $header .= 'References: <' . $it['parent-uri'] . '>' . "\n";
475                                                         if(! strlen($it['title'])) {
476                                                                 $r = q("SELECT `title` FROM `item` WHERE `parent-uri` = '%s' LIMIT 1",
477                                                                         dbesc($it['parent-uri'])
478                                                                 );
479                                                                 if(count($r)) {
480                                                                         $subtitle = $r[0]['title'];
481                                                                         if($subtitle) {
482                                                                                 if(strncasecmp($subtitle,'RE:',3))
483                                                                                         $subject = $subtitle;
484                                                                                 else
485                                                                                         $subject = 'Re: ' . $subtitle;
486                                                                         }
487                                                                 }
488                                                         }
489                                                 }
490
491                                                 $headers .= 'MIME-Version: 1.0' . "\n";
492                                                 $headers .= 'Content-Type: text/html; charset=UTF-8' . "\n";
493                                                 $headers .= 'Content-Transfer-Encoding: 8bit' . "\n\n";
494                                                 $html    = prepare_body($it);
495                                                 $message = '<html><body>' . $html . '</body></html>';
496                                                 logger('notifier: email delivery to ' . $addr);
497                                                 mail($addr, $subject, $message, $headers);
498                                         }
499                                         break;
500                                 case NETWORK_DIASPORA:
501                                         if(get_config('system','dfrn_only') || (! get_config('diaspora_enabled')))
502                                                 break;
503                                         if($top_level) {
504                                                 diaspora_send_status($parent_item,$owner,$contact);
505                                                 break;
506                                         }
507
508                                         break;
509
510                                 case NETWORK_FEED:
511                                 case NETWORK_FACEBOOK:
512                                         if(get_config('system','dfrn_only'))
513                                                 break;
514                                 default:
515                                         break;
516                         }
517                 }
518         }
519                 
520         // send additional slaps to mentioned remote tags (@foo@example.com)
521
522         if($slap && count($url_recipients) && ($followup || $top_level) && $notify_hub && (! $expire)) {
523                 if(! get_config('system','dfrn_only')) {
524                         foreach($url_recipients as $url) {
525                                 if($url) {
526                                         logger('notifier: urldelivery: ' . $url);
527                                         $deliver_status = slapper($owner,$url,$slap);
528                                         // TODO: redeliver/queue these items on failure, though there is no contact record
529                                 }
530                         }
531                 }
532         }
533
534         if((strlen($hub)) && ($notify_hub)) {
535                 $hubs = explode(',', $hub);
536                 if(count($hubs)) {
537                         foreach($hubs as $h) {
538                                 $h = trim($h);
539                                 if(! strlen($h))
540                                         continue;
541                                 $params = 'hub.mode=publish&hub.url=' . urlencode($a->get_baseurl() . '/dfrn_poll/' . $owner['nickname'] );
542                                 post_url($h,$params);
543                                 logger('pubsub: publish: ' . $h . ' ' . $params . ' returned ' . $a->get_curl_code());
544                                 if(count($hubs) > 1)
545                                         sleep(7);                               // try and avoid multiple hubs responding at precisely the same time
546                         }
547                 }
548         }
549
550         if($notify_hub) {
551
552                 /**
553                  *
554                  * If you have less than 150 dfrn friends and it's a public message,
555                  * we'll just go ahead and push them out securely with dfrn/rino.
556                  * If you've got more than that, you'll have to rely on PuSH delivery.
557                  *
558                  */
559
560                 $max_allowed = ((get_config('system','maxpubdeliver') === false) ? 150 : intval(get_config('system','maxpubdeliver')));
561                                 
562                 /**
563                  *
564                  * Only get the bare essentials and go back for the full record. 
565                  * If you've got a lot of friends and we grab all the details at once it could exhaust memory. 
566                  *
567                  */
568
569                 $r = q("SELECT `id`, `name` FROM `contact` 
570                         WHERE `network` = 'dfrn' AND `uid` = %d AND `blocked` = 0 AND `pending` = 0
571                         AND `rel` != %d ",
572                         intval($owner['uid']),
573                         intval(CONTACT_IS_SHARING)
574                 );
575
576                 if((count($r)) && (($max_allowed == 0) || (count($r) < $max_allowed))) {
577
578                         logger('pubdeliver: ' . print_r($r,true));
579
580                         foreach($r as $rr) {
581
582                                 /* Don't deliver to folks who have already been delivered to */
583
584                                 if(! in_array($rr['id'], $conversants)) {
585                                         $n = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1",
586                                                         intval($rr['id'])
587                                         );
588
589                                         if(count($n)) {
590                                         
591                                                 logger('notifier: dfrnpubdelivery: ' . $n[0]['name']);
592                                                 $deliver_status = dfrn_deliver($owner,$n[0],$atom);
593                                         }
594                                 }
595                                 else
596                                         logger('notifier: dfrnpubdelivery: ignoring ' . $rr['name']);
597                         }
598                 }
599         }
600
601         return;
602 }
603
604 if (array_search(__file__,get_included_files())===0){
605   notifier_run($argv,$argc);
606   killme();
607 }