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