]> git.mxchange.org Git - friendica.git/blob - include/notifier.php
4b97311f65df8d3a38ccceb491e9b4a5d9b0f48c
[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`.`timezone`, `user`.`nickname`, `user`.`sprvkey`, `user`.`spubkey`, 
123                 `user`.`page-flags`, `user`.`prvnets`
124                 FROM `contact` LEFT JOIN `user` ON `user`.`uid` = `contact`.`uid` 
125                 WHERE `contact`.`uid` = %d AND `contact`.`self` = 1 LIMIT 1",
126                 intval($uid)
127         );
128
129         if(! count($r))
130                 return;
131
132         $owner = $r[0];
133
134         $hub = get_config('system','huburl');
135
136         // If this is a public conversation, notify the feed hub
137         $notify_hub = true;
138
139         // fill this in with a single salmon slap if applicable
140         $slap = '';
141
142         if($cmd != 'mail' && $cmd != 'suggest') {
143
144                 require_once('include/group.php');
145
146                 $parent = $items[0];
147
148                 if($parent['type'] === 'remote' && (! $expire)) {
149                         // local followup to remote post
150                         $followup = true;
151                         $notify_hub = false; // not public
152                         $conversant_str = dbesc($parent['contact-id']);
153                 }
154                 else {
155                         $followup = false;
156
157                         if((strlen($parent['allow_cid'])) 
158                                 || (strlen($parent['allow_gid'])) 
159                                 || (strlen($parent['deny_cid'])) 
160                                 || (strlen($parent['deny_gid']))) {
161                                 $notify_hub = false; // private recipients, not public
162                         }
163
164                         $allow_people = expand_acl($parent['allow_cid']);
165                         $allow_groups = expand_groups(expand_acl($parent['allow_gid']));
166                         $deny_people  = expand_acl($parent['deny_cid']);
167                         $deny_groups  = expand_groups(expand_acl($parent['deny_gid']));
168
169                         $conversants = array();
170
171                         foreach($items as $item) {
172                                 $recipients[] = $item['contact-id'];
173                                 $conversants[] = $item['contact-id'];
174                                 // pull out additional tagged people to notify (if public message)
175                                 if($notify_hub && strlen($item['inform'])) {
176                                         $people = explode(',',$item['inform']);
177                                         foreach($people as $person) {
178                                                 if(substr($person,0,4) === 'cid:') {
179                                                         $recipients[] = intval(substr($person,4));
180                                                         $conversants[] = intval(substr($person,4));
181                                                 }
182                                                 else {
183                                                         $url_recipients[] = substr($person,4);
184                                                 }
185                                         }
186                                 }
187                         }
188
189                         logger('notifier: url_recipients' . print_r($url_recipients,true));
190
191                         $conversants = array_unique($conversants);
192
193
194                         $recipients = array_unique(array_merge($recipients,$allow_people,$allow_groups));
195                         $deny = array_unique(array_merge($deny_people,$deny_groups));
196                         $recipients = array_diff($recipients,$deny);
197
198                         $conversant_str = dbesc(implode(', ',$conversants));
199                 }
200
201                 $r = q("SELECT * FROM `contact` WHERE `id` IN ( $conversant_str ) AND `blocked` = 0 AND `pending` = 0");
202
203
204                 if(count($r))
205                         $contacts = $r;
206         }
207
208         $feed_template = get_markup_template('atom_feed.tpl');
209         $mail_template = get_markup_template('atom_mail.tpl');
210
211         $atom = '';
212         $slaps = array();
213
214         $hubxml = feed_hublinks();
215
216         $birthday = feed_birthday($owner['uid'],$owner['timezone']);
217
218         if(strlen($birthday))
219                 $birthday = '<dfrn:birthday>' . xmlify($birthday) . '</dfrn:birthday>';
220
221         $atom .= replace_macros($feed_template, array(
222                         '$version'      => xmlify(FRIENDIKA_VERSION),
223                         '$feed_id'      => xmlify($a->get_baseurl() . '/profile/' . $owner['nickname'] ),
224                         '$feed_title'   => xmlify($owner['name']),
225                         '$feed_updated' => xmlify(datetime_convert('UTC', 'UTC', $updated . '+00:00' , ATOM_TIME)) ,
226                         '$hub'          => $hubxml,
227                         '$salmon'       => '',  // private feed, we don't use salmon here
228                         '$name'         => xmlify($owner['name']),
229                         '$profile_page' => xmlify($owner['url']),
230                         '$photo'        => xmlify($owner['photo']),
231                         '$thumb'        => xmlify($owner['thumb']),
232                         '$picdate'      => xmlify(datetime_convert('UTC','UTC',$owner['avatar-date'] . '+00:00' , ATOM_TIME)) ,
233                         '$uridate'      => xmlify(datetime_convert('UTC','UTC',$owner['uri-date']    . '+00:00' , ATOM_TIME)) ,
234                         '$namdate'      => xmlify(datetime_convert('UTC','UTC',$owner['name-date']   . '+00:00' , ATOM_TIME)) ,
235                         '$birthday'     => $birthday
236         ));
237
238         if($cmd === 'mail') {
239                 $notify_hub = false;  // mail is  not public
240
241                 $atom .= replace_macros($mail_template, array(
242                         '$name'         => xmlify($owner['name']),
243                         '$profile_page' => xmlify($owner['url']),
244                         '$thumb'        => xmlify($owner['thumb']),
245                         '$item_id'      => xmlify($item['uri']),
246                         '$subject'      => xmlify($item['title']),
247                         '$created'      => xmlify(datetime_convert('UTC', 'UTC', $item['created'] . '+00:00' , ATOM_TIME)),
248                         '$content'      => xmlify($item['body']),
249                         '$parent_id'    => xmlify($item['parent-uri'])
250                 ));
251         }
252         elseif($cmd === 'suggest') {
253                 $notify_hub = false;  // suggestions are not public
254
255                 $sugg_template = get_markup_template('atom_suggest.tpl');
256
257                 $atom .= replace_macros($sugg_template, array(
258                         '$name'         => xmlify($item['name']),
259                         '$url'          => xmlify($item['url']),
260                         '$photo'        => xmlify($item['photo']),
261                         '$request'      => xmlify($item['request']),
262                         '$note'         => xmlify($item['note'])
263                 ));
264
265                 // We don't need this any more
266
267                 q("DELETE FROM `fsuggest` WHERE `id` = %d LIMIT 1",
268                         intval($item['id'])
269                 );
270
271         }
272         else {
273                 if($followup) {
274                         foreach($items as $item) {  // there is only one item
275                                 if(! $item['parent'])
276                                         continue;
277                                 if($item['id'] == $item_id) {
278                                         logger('notifier: followup: item: ' . print_r($item,true), LOGGER_DATA);
279                                         $slap  = atom_entry($item,'html',$owner,$owner,false);
280                                         $atom .= atom_entry($item,'text',$owner,$owner,false);
281                                 }
282                         }
283                 }
284                 else {
285                         foreach($items as $item) {
286
287                                 if(! $item['parent'])
288                                         continue;
289
290                                 $contact = get_item_contact($item,$contacts);
291                                 if(! $contact)
292                                         continue;
293
294                                 $atom .= atom_entry($item,'text',$contact,$owner,true);
295
296                                 if(($top_level) && ($notify_hub) && ($item['author-link'] === $item['owner-link']) && (! $expire)) 
297                                         $slaps[] = atom_entry($item,'html',$contact,$owner,true);
298                         }
299                 }
300         }
301         $atom .= '</feed>' . "\r\n";
302
303         logger('notifier: ' . $atom, LOGGER_DATA);
304
305         logger('notifier: slaps: ' . print_r($slaps,true), LOGGER_DATA);
306
307         // If this is a public message and pubmail is set on the parent, include all your email contacts
308
309         $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
310
311         if(! $mail_disabled) {
312                 if((! strlen($parent_item['allow_cid'])) && (! strlen($parent_item['allow_gid'])) 
313                         && (! strlen($parent_item['deny_cid'])) && (! strlen($parent_item['deny_gid'])) 
314                         && (intval($parent_item['pubmail']))) {
315                         $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `network` = '%s'",
316                                 intval($uid),
317                                 dbesc(NETWORK_MAIL)
318                         );
319                         if(count($r)) {
320                                 foreach($r as $rr)
321                                         $recipients[] = $rr['id'];
322                         }
323                 }
324         }
325
326         if($followup)
327                 $recip_str = $parent['contact-id'];
328         else
329                 $recip_str = implode(', ', $recipients);
330
331         $r = q("SELECT * FROM `contact` WHERE `id` IN ( %s ) AND `blocked` = 0 AND `pending` = 0 ",
332                 dbesc($recip_str)
333         );
334
335         // delivery loop
336
337         require_once('include/salmon.php');
338
339         if(count($r)) {
340                 foreach($r as $contact) {
341                         if($contact['self'])
342                                 continue;
343
344                         $deliver_status = 0;
345
346                         switch($contact['network']) {
347                                 case 'dfrn':
348                                         logger('notifier: dfrndelivery: ' . $contact['name']);
349                                         $deliver_status = dfrn_deliver($owner,$contact,$atom);
350
351                                         logger('notifier: dfrn_delivery returns ' . $deliver_status);
352         
353                                         if($deliver_status == (-1)) {
354                                                 logger('notifier: delivery failed: queuing message');
355                                                 // queue message for redelivery
356                                                 q("INSERT INTO `queue` ( `cid`, `created`, `last`, `content`)
357                                                         VALUES ( %d, '%s', '%s', '%s') ",
358                                                         intval($contact['id']),
359                                                         dbesc(datetime_convert()),
360                                                         dbesc(datetime_convert()),
361                                                         dbesc($atom)
362                                                 );
363                                         }
364                                         break;
365                                 case 'stat':
366                                         if($owner['prvnets'])
367                                                 break;
368                                         if($followup && $contact['notify']) {
369                                                 logger('notifier: slapdelivery: ' . $contact['name']);
370                                                 $deliver_status = slapper($owner,$contact['notify'],$slap);
371
372                                                 if($deliver_status == (-1)) {
373                                                         // queue message for redelivery
374                                                         q("INSERT INTO `queue` ( `cid`, `created`, `last`, `content`)
375                                                                 VALUES ( %d, '%s', '%s', '%s') ",
376                                                                 intval($contact['id']),
377                                                                 dbesc(datetime_convert()),
378                                                                 dbesc(datetime_convert()),
379                                                                 dbesc($slap)
380                                                         );
381
382                                                 }
383         
384
385                                         }
386                                         else {
387
388                                                 // only send salmon if public - e.g. if it's ok to notify
389                                                 // a public hub, it's ok to send a salmon
390
391                                                 if((count($slaps)) && ($notify_hub) && (! $expire)) {
392                                                         logger('notifier: slapdelivery: ' . $contact['name']);
393                                                         foreach($slaps as $slappy) {
394                                                                 if($contact['notify']) {
395                                                                         $deliver_status = slapper($owner,$contact['notify'],$slappy);
396                                                                         if($deliver_status == (-1)) {
397                                                                                 // queue message for redelivery
398                                                                                 q("INSERT INTO `queue` ( `cid`, `created`, `last`, `content`)
399                                                                                         VALUES ( %d, '%s', '%s', '%s') ",
400                                                                                         intval($contact['id']),
401                                                                                         dbesc(datetime_convert()),
402                                                                                         dbesc(datetime_convert()),
403                                                                                         dbesc($slappy)
404                                                                                 );                                                              
405                                                                         }
406                                                                 }
407                                                         }
408                                                 }
409                                         }
410                                         break;
411
412                                 case 'mail':
413                                                 
414                                         // WARNING: does not currently convert to RFC2047 header encodings, etc.
415
416                                         $addr = $contact['addr'];
417                                         if(! strlen($addr))
418                                                 break;
419
420                                         if($cmd === 'wall-new' || $cmd === 'comment-new') {
421
422                                                 $it = null;
423                                                 if($cmd === 'wall-new') 
424                                                         $it = $items[0];
425                                                 else {
426                                                         $r = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1", 
427                                                                 intval($argv[2]),
428                                                                 intval($uid)
429                                                         );
430                                                         if(count($r))
431                                                                 $it = $r[0];
432                                                 }
433                                                 if(! $it)
434                                                         break;
435                                                 
436
437
438                                                 $local_user = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
439                                                         intval($uid)
440                                                 );
441                                                 if(! count($local_user))
442                                                         break;
443                                                 
444                                                 $reply_to = '';
445                                                 $r1 = q("SELECT * FROM `mailacct` WHERE `uid` = %d LIMIT 1",
446                                                         intval($uid)
447                                                 );
448                                                 if($r1 && $r1[0]['reply_to'])
449                                                         $reply_to = $r1[0]['reply_to'];
450         
451                                                 $subject  = (($it['title']) ? $it['title'] : t("\x28no subject\x29")) ;
452                                                 $headers  = 'From: ' . $local_user[0]['username'] . ' <' . $local_user[0]['email'] . '>' . "\n";
453
454                                                 if($reply_to)
455                                                         $headers .= 'Reply-to: ' . $reply_to . "\n";
456
457                                                 $headers .= 'Message-id: <' . $it['uri'] . '>' . "\n";
458
459                                                 if($it['uri'] !== $it['parent-uri']) {
460                                                         $header .= 'References: <' . $it['parent-uri'] . '>' . "\n";
461                                                         if(! strlen($it['title'])) {
462                                                                 $r = q("SELECT `title` FROM `item` WHERE `parent-uri` = '%s' LIMIT 1",
463                                                                         dbesc($it['parent-uri'])
464                                                                 );
465                                                                 if(count($r)) {
466                                                                         $subtitle = $r[0]['title'];
467                                                                         if($subtitle) {
468                                                                                 if(strncasecmp($subtitle,'RE:',3))
469                                                                                         $subject = $subtitle;
470                                                                                 else
471                                                                                         $subject = 'Re: ' . $subtitle;
472                                                                         }
473                                                                 }
474                                                         }
475                                                 }
476
477                                                 $headers .= 'MIME-Version: 1.0' . "\n";
478                                                 $headers .= 'Content-Type: text/html; charset=UTF-8' . "\n";
479                                                 $headers .= 'Content-Transfer-Encoding: 8bit' . "\n\n";
480                                                 $html    = prepare_body($it);
481                                                 $message = '<html><body>' . $html . '</body></html>';
482                                                 logger('notifier: email delivery to ' . $addr);
483                                                 mail($addr, $subject, $message, $headers);
484                                         }
485                                         break;
486                                 case 'feed':
487                                 case 'face':
488                                 case 'dspr':
489                                 default:
490                                         break;
491                         }
492                 }
493         }
494                 
495         // send additional slaps to mentioned remote tags (@foo@example.com)
496
497         if($slap && count($url_recipients) && $followup && $notify_hub && (! $expire)) {
498                 foreach($url_recipients as $url) {
499                         if($url) {
500                                 logger('notifier: urldelivery: ' . $url);
501                                 $deliver_status = slapper($owner,$url,$slap);
502                                 // TODO: redeliver/queue these items on failure, though there is no contact record
503                         }
504                 }
505         }
506
507         if((strlen($hub)) && ($notify_hub)) {
508                 $hubs = explode(',', $hub);
509                 if(count($hubs)) {
510                         foreach($hubs as $h) {
511                                 $h = trim($h);
512                                 if(! strlen($h))
513                                         continue;
514                                 $params = 'hub.mode=publish&hub.url=' . urlencode($a->get_baseurl() . '/dfrn_poll/' . $owner['nickname'] );
515                                 post_url($h,$params);
516                                 logger('pubsub: publish: ' . $h . ' ' . $params . ' returned ' . $a->get_curl_code());
517                                 if(count($hubs) > 1)
518                                         sleep(7);                               // try and avoid multiple hubs responding at precisely the same time
519                         }
520                 }
521         }
522
523         if($notify_hub) {
524
525                 /**
526                  *
527                  * If you have less than 150 dfrn friends and it's a public message,
528                  * we'll just go ahead and push them out securely with dfrn/rino.
529                  * If you've got more than that, you'll have to rely on PuSH delivery.
530                  *
531                  */
532
533                 $max_allowed = ((get_config('system','maxpubdeliver') === false) ? 150 : intval(get_config('system','maxpubdeliver')));
534                                 
535                 /**
536                  *
537                  * Only get the bare essentials and go back for the full record. 
538                  * If you've got a lot of friends and we grab all the details at once it could exhaust memory. 
539                  *
540                  */
541
542                 $r = q("SELECT `id`, `name` FROM `contact` 
543                         WHERE `network` = 'dfrn' AND `uid` = %d AND `blocked` = 0 AND `pending` = 0
544                         AND `rel` != %d ",
545                         intval($owner['uid']),
546                         intval(REL_FAN)
547                 );
548
549                 if((count($r)) && (($max_allowed == 0) || (count($r) < $max_allowed))) {
550
551                         logger('pubdeliver: ' . print_r($r,true));
552
553                         foreach($r as $rr) {
554
555                                 /* Don't deliver to folks who have already been delivered to */
556
557                                 if(! in_array($rr['id'], $conversants)) {
558                                         $n = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1",
559                                                         intval($rr['id'])
560                                         );
561
562                                         if(count($n)) {
563                                         
564                                                 logger('notifier: dfrnpubdelivery: ' . $n[0]['name']);
565                                                 $deliver_status = dfrn_deliver($owner,$n[0],$atom);
566                                         }
567                                 }
568                                 else
569                                         logger('notifier: dfrnpubdelivery: ignoring ' . $rr['name']);
570                         }
571                 }
572         }
573
574         return;
575 }
576
577 if (array_search(__file__,get_included_files())===0){
578   echo "run!";
579   notifier_run($argv,$argc);
580   killme();
581 }