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