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