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