]> git.mxchange.org Git - friendica.git/blob - mod/dfrn_notify.php
identify email-only contacts
[friendica.git] / mod / dfrn_notify.php
1 <?php
2
3 require_once('simplepie/simplepie.inc');
4 require_once('include/items.php');
5
6
7 function dfrn_notify_post(&$a) {
8
9         $dfrn_id      = ((x($_POST,'dfrn_id'))      ? notags(trim($_POST['dfrn_id']))   : '');
10         $dfrn_version = ((x($_POST,'dfrn_version')) ? (float) $_POST['dfrn_version']    : 2.0);
11         $challenge    = ((x($_POST,'challenge'))    ? notags(trim($_POST['challenge'])) : '');
12         $data         = ((x($_POST,'data'))         ? $_POST['data']                    : '');
13         $key          = ((x($_POST,'key'))          ? $_POST['key']                     : '');
14         $dissolve     = ((x($_POST,'dissolve'))     ? intval($_POST['dissolve'])        :  0);
15
16         $direction = (-1);
17         if(strpos($dfrn_id,':') == 1) {
18                 $direction = intval(substr($dfrn_id,0,1));
19                 $dfrn_id = substr($dfrn_id,2);
20         }
21
22         $r = q("SELECT * FROM `challenge` WHERE `dfrn-id` = '%s' AND `challenge` = '%s' LIMIT 1",
23                 dbesc($dfrn_id),
24                 dbesc($challenge)
25         );
26         if(! count($r)) {
27                 logger('dfrn_notify: could not match challenge to dfrn_id ' . $dfrn_id);
28                 xml_status(3);
29         }
30
31         $r = q("DELETE FROM `challenge` WHERE `dfrn-id` = '%s' AND `challenge` = '%s' LIMIT 1",
32                 dbesc($dfrn_id),
33                 dbesc($challenge)
34         );
35
36         // find the local user who owns this relationship.
37
38         $sql_extra = '';
39         switch($direction) {
40                 case (-1):
41                         $sql_extra = sprintf(" AND ( `issued-id` = '%s' OR `dfrn-id` = '%s' ) ", dbesc($dfrn_id), dbesc($dfrn_id));
42                         break;
43                 case 0:
44                         $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
45                         break;
46                 case 1:
47                         $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
48                         break;
49                 default:
50                         xml_status(3);
51                         break; // NOTREACHED
52         }
53                  
54
55
56
57         $r = q("SELECT `contact`.*, `contact`.`uid` AS `importer_uid`, 
58                 `contact`.`pubkey` AS `cpubkey`, `contact`.`prvkey` AS `cprvkey`, `user`.* FROM `contact` 
59                 LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid` 
60                 WHERE `contact`.`blocked` = 0 AND `contact`.`pending` = 0 
61                 AND `user`.`nickname` = '%s' $sql_extra LIMIT 1",
62                 dbesc($a->argv[1])
63         );
64
65         if(! count($r)) {
66                 logger('dfrn_notify: contact not found for dfrn_id ' . $dfrn_id);
67                 xml_status(3);
68                 //NOTREACHED
69         }
70
71         // $importer in this case contains the contact record for the remote contact joined with the user record of our user. 
72
73         $importer = $r[0];
74
75         logger('dfrn_notify: received notify from ' . $importer['name'] . ' for ' . $importer['username']);
76         logger('dfrn_notify: data: ' . $data, LOGGER_DATA);
77
78         if($dissolve == 1) {
79
80                 /**
81                  * Relationship is dissolved permanently
82                  */
83
84                 require_once('include/Contact.php'); 
85                 contact_remove($importer['id']);
86                 logger('relationship dissolved : ' . $importer['name'] . ' dissolved ' . $importer['username']);
87                 xml_status(0);
88
89         }
90
91         if(strlen($key)) {
92                 $rawkey = hex2bin(trim($key));
93                 logger('rino: md5 raw key: ' . md5($rawkey));
94                 $final_key = '';
95
96                 if((($importer['duplex']) && strlen($importer['cpubkey'])) || (! strlen($importer['cprvkey']))) {
97                         openssl_public_decrypt($rawkey,$final_key,$importer['cpubkey']);
98                 }
99                 else {
100                         openssl_private_decrypt($rawkey,$final_key,$importer['cprvkey']);
101                 }
102
103                 logger('rino: received key : ' . $final_key);
104                 $data = aes_decrypt(hex2bin($data),$final_key);
105                 logger('rino: decrypted data: ' . $data, LOGGER_DATA);
106         }
107
108
109
110
111         if($importer['readonly']) {
112                 // We aren't receiving stuff from this person. But we will quietly ignore them
113                 // rather than a blatant "go away" message.
114                 logger('dfrn_notify: ignoring');
115                 xml_status(0);
116                 //NOTREACHED
117         }
118
119         // Consume notification feed. This may differ from consuming a public feed in several ways
120         // - might contain email
121         // - might contain remote followup to our message
122         //              - in which case we need to accept it and then notify other conversants
123         // - we may need to send various email notifications
124
125         $feed = new SimplePie();
126         $feed->set_raw_data($data);
127         $feed->enable_order_by_date(false);
128         $feed->init();
129
130         $ismail = false;
131
132         $rawmail = $feed->get_feed_tags( NAMESPACE_DFRN, 'mail' );
133         if(isset($rawmail[0]['child'][NAMESPACE_DFRN])) {
134
135                 logger('dfrn_notify: private message received');
136
137                 $ismail = true;
138                 $base = $rawmail[0]['child'][NAMESPACE_DFRN];
139
140                 $msg = array();
141                 $msg['uid'] = $importer['importer_uid'];
142                 $msg['from-name'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['name'][0]['data']));
143                 $msg['from-photo'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['avatar'][0]['data']));
144                 $msg['from-url'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['uri'][0]['data']));
145                 $msg['contact-id'] = $importer['id'];
146                 $msg['title'] = notags(unxmlify($base['subject'][0]['data']));
147                 $msg['body'] = escape_tags(unxmlify($base['content'][0]['data']));
148                 $msg['seen'] = 0;
149                 $msg['replied'] = 0;
150                 $msg['uri'] = notags(unxmlify($base['id'][0]['data']));
151                 $msg['parent-uri'] = notags(unxmlify($base['in-reply-to'][0]['data']));
152                 $msg['created'] = datetime_convert(notags(unxmlify('UTC','UTC',$base['sentdate'][0]['data'])));
153                 
154                 dbesc_array($msg);
155
156                 $r = dbq("INSERT INTO `mail` (`" . implode("`, `", array_keys($msg)) 
157                         . "`) VALUES ('" . implode("', '", array_values($msg)) . "')" );
158
159                 // send email notification if requested.
160
161                 require_once('bbcode.php');
162                 if($importer['notify-flags'] & NOTIFY_MAIL) {
163
164                         $body = html_entity_decode(strip_tags(bbcode(stripslashes($msg['body']))),ENT_QUOTES,'UTF-8');
165
166                         if(function_exists('quoted_printable_encode'))
167                                 $body = quoted_printable_encode($body);
168                         else
169                                 $body = qp($body);
170
171                         $tpl = load_view_file('view/mail_received_eml.tpl');                    
172                         $email_tpl = replace_macros($tpl, array(
173                                 '$sitename' => $a->config['sitename'],
174                                 '$siteurl' =>  $a->get_baseurl(),
175                                 '$username' => $importer['username'],
176                                 '$email' => $importer['email'],
177                                 '$from' => $msg['from-name'],
178                                 '$title' => stripslashes($msg['title']),
179                                 '$body' => $body
180                         ));
181
182                         $res = mail($importer['email'], t('New mail received at ') . $a->config['sitename'],
183                                 $email_tpl, 'From: ' . t('Administrator') . '@' . $a->get_hostname() . "\r\n"
184                                         . 'MIME-Version: 1.0' . "\r\n"
185                                         . 'Content-type: text/plain; charset=UTF-8' . "\r\n" 
186                                         . 'Content-transfer-encoding: quoted-printable' . "\r\n"
187                         );
188                 }
189                 xml_status(0);
190                 // NOTREACHED
191         }       
192         
193         logger('dfrn_notify: feed item count = ' . $feed->get_item_quantity());
194
195         foreach($feed->get_items() as $item) {
196
197                 $deleted = false;
198
199                 $rawdelete = $item->get_item_tags( NAMESPACE_TOMB , 'deleted-entry');
200                 if(isset($rawdelete[0]['attribs']['']['ref'])) {
201                         $uri = $rawthread[0]['attribs']['']['ref'];
202                         $deleted = true;
203                         if(isset($rawdelete[0]['attribs']['']['when'])) {
204                                 $when = $rawthread[0]['attribs']['']['when'];
205                                 $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
206                         }
207                         else
208                                 $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
209                 }
210                 if($deleted) {
211                         $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
212                                 dbesc($uri),
213                                 intval($importer['importer_uid'])
214                         );
215                         if(count($r)) {
216                                 $item = $r[0];
217                                 if($item['uri'] == $item['parent-uri']) {
218                                         $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s'
219                                                 WHERE `parent-uri` = '%s' AND `uid` = %d",
220                                                 dbesc($when),
221                                                 dbesc(datetime_convert()),
222                                                 dbesc($item['uri']),
223                                                 intval($importer['importer_uid'])
224                                         );
225                                 }
226                                 else {
227                                         $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s' 
228                                                 WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
229                                                 dbesc($when),
230                                                 dbesc(datetime_convert()),
231                                                 dbesc($uri),
232                                                 intval($importer['importer_uid'])
233                                         );
234                                         if($item['last-child']) {
235                                                 // ensure that last-child is set in case the comment that had it just got wiped.
236                                                 $q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
237                                                         dbesc(datetime_convert()),
238                                                         dbesc($item['parent-uri']),
239                                                         intval($item['uid'])
240                                                 );
241                                                 // who is the last child now? 
242                                                 $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `uid` = %d
243                                                         ORDER BY `created` DESC LIMIT 1",
244                                                                 dbesc($item['parent-uri']),
245                                                                 intval($importer['importer_uid'])
246                                                 );
247                                                 if(count($r)) {
248                                                         q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
249                                                                 intval($r[0]['id'])
250                                                         );
251                                                 }       
252                                         }
253                                 }
254                         }       
255                         continue;
256                 }
257
258                 $is_reply = false;              
259                 $item_id = $item->get_id();
260                 $rawthread = $item->get_item_tags( NAMESPACE_THREAD, 'in-reply-to');
261                 if(isset($rawthread[0]['attribs']['']['ref'])) {
262                         $is_reply = true;
263                         $parent_uri = $rawthread[0]['attribs']['']['ref'];
264                 }
265
266                 if($is_reply) {
267                         if($feed->get_item_quantity() == 1) {
268                                 logger('dfrn_notify: received remote comment');
269                                 $is_like = false;
270                                 // remote reply to our post. Import and then notify everybody else.
271                                 $datarray = get_atom_elements($feed,$item);
272                                 $datarray['type'] = 'remote-comment';
273                                 $datarray['wall'] = 1;
274                                 $datarray['parent-uri'] = $parent_uri;
275                                 $datarray['uid'] = $importer['importer_uid'];
276                                 $datarray['contact-id'] = $importer['id'];
277                                 if(($datarray['verb'] == ACTIVITY_LIKE) || ($datarray['verb'] == ACTIVITY_DISLIKE)) {
278                                         $is_like = true;
279                                         $datarray['type'] = 'activity';
280                                         $datarray['gravity'] = GRAVITY_LIKE;
281                                         $datarray['last-child'] = 0;
282                                 }
283                                 $posted_id = item_store($datarray);
284
285                                 if($posted_id) {
286                                         if(! $is_like) {
287                                                 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
288                                                         intval($posted_id),
289                                                         intval($importer['importer_uid'])
290                                                 );
291                                                 if(count($r)) {
292                                                         $r1 = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `uid` = %d AND `parent` = %d",
293                                                                 dbesc(datetime_convert()),
294                                                                 intval($importer['importer_uid']),
295                                                                 intval($r[0]['parent'])
296                                                         );
297                                                 }
298                                                 $r2 = q("UPDATE `item` SET `last-child` = 1, `changed` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
299                                                                 dbesc(datetime_convert()),
300                                                                 intval($importer['importer_uid']),
301                                                                 intval($posted_id)
302                                                 );
303                                         }
304
305                                         $php_path = ((strlen($a->config['php_path'])) ? $a->config['php_path'] : 'php');
306
307                                         //proc_close(proc_open("\"$php_path\" \"include/notifier.php\" \"comment-import\" \"$posted_id\" &", array(),$foo));
308                                         proc_run($php_path,"include/notifier.php","comment-import","$posted_id");
309                                         
310                                         if((! $is_like) && ($importer['notify-flags'] & NOTIFY_COMMENT) && (! $importer['self'])) {
311                                                 require_once('bbcode.php');
312                                                 $from = stripslashes($datarray['author-name']);
313                                                 $tpl = load_view_file('view/cmnt_received_eml.tpl');                    
314                                                 $email_tpl = replace_macros($tpl, array(
315                                                         '$sitename' => $a->config['sitename'],
316                                                         '$siteurl' =>  $a->get_baseurl(),
317                                                         '$username' => $importer['username'],
318                                                         '$email' => $importer['email'],
319                                                         '$display' => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id, 
320                                                         '$from' => $from,
321                                                         '$body' => strip_tags(bbcode(stripslashes($datarray['body'])))
322                                                 ));
323         
324                                                 $res = mail($importer['email'], $from . t(' commented on an item at ') . $a->config['sitename'],
325                                                         $email_tpl, "From: " . t('Administrator') . '@' . $a->get_hostname() );
326                                         }
327                                 }
328
329                                 xml_status(0);
330                                 // NOTREACHED
331
332                         }
333                         else {
334                                 // regular comment that is part of this total conversation. Have we seen it? If not, import it.
335
336                                 $item_id = $item->get_id();
337
338                                 $r = q("SELECT `uid`, `last-child`, `edited` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
339                                         dbesc($item_id),
340                                         intval($importer['importer_uid'])
341                                 );
342                                 // FIXME update content if 'updated' changes
343                                 if(count($r)) {
344                                         $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
345                                         if($allow && $allow[0]['data'] != $r[0]['last-child']) {
346                                                 $r = q("UPDATE `item` SET `last-child` = %d, `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
347                                                         intval($allow[0]['data']),
348                                                         dbesc(datetime_convert()),
349                                                         dbesc($item_id),
350                                                         intval($importer['importer_uid'])
351                                                 );
352                                         }
353                                         continue;
354                                 }
355                                 $datarray = get_atom_elements($feed,$item);
356                                 $datarray['parent-uri'] = $parent_uri;
357                                 $datarray['uid'] = $importer['importer_uid'];
358                                 $datarray['contact-id'] = $importer['id'];
359                                 if(($datarray['verb'] == ACTIVITY_LIKE) || ($datarray['verb'] == ACTIVITY_DISLIKE)) {
360                                         $datarray['type'] = 'activity';
361                                         $datarray['gravity'] = GRAVITY_LIKE;
362                                 }
363
364                                 $r = item_store($datarray);
365
366                                 // find out if our user is involved in this conversation and wants to be notified.
367                         
368                                 if(($datarray['type'] != 'activity') && ($importer['notify-flags'] & NOTIFY_COMMENT)) {
369
370                                         $myconv = q("SELECT `author-link` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d",
371                                                 dbesc($parent_uri),
372                                                 intval($importer['importer_uid'])
373                                         );
374                                         if(count($myconv)) {
375                                                 foreach($myconv as $conv) {
376                                                         if($conv['author-link'] != $importer['url'])
377                                                                 continue;
378                                                         require_once('bbcode.php');
379                                                         $from = stripslashes($datarray['author-name']);
380                                                         $tpl = load_view_file('view/cmnt_received_eml.tpl');                    
381                                                         $email_tpl = replace_macros($tpl, array(
382                                                                 '$sitename' => $a->config['sitename'],
383                                                                 '$siteurl' =>  $a->get_baseurl(),
384                                                                 '$username' => $importer['username'],
385                                                                 '$email' => $importer['email'],
386                                                                 '$from' => $from,
387                                                                 '$display' => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $r,
388                                                                 '$body' => strip_tags(bbcode(stripslashes($datarray['body'])))
389                                                         ));
390
391                                                         $res = mail($importer['email'], $from . t(" commented on an item at ") 
392                                                                 . $a->config['sitename'],
393                                                                 $email_tpl,t("From: Administrator@") . $a->get_hostname() );
394                                                         break;
395                                                 }
396                                         }
397                                 }
398                                 continue;
399                         }
400                 }
401                 else {
402                         // Head post of a conversation. Have we seen it? If not, import it.
403
404                         $item_id = $item->get_id();
405                         $r = q("SELECT `uid`, `last-child`, `edited` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
406                                 dbesc($item_id),
407                                 intval($importer['importer_uid'])
408                         );
409                         if(count($r)) {
410                                 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
411                                 if($allow && $allow[0]['data'] != $r[0]['last-child']) {
412                                         $r = q("UPDATE `item` SET `last-child` = %d, `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
413                                                 intval($allow[0]['data']),
414                                                 dbesc(datetime_convert()),
415                                                 dbesc($item_id),
416                                                 intval($importer['importer_uid'])
417                                         );
418                                 }
419                                 continue;
420                         }
421
422
423                         $datarray = get_atom_elements($feed,$item);
424                         $datarray['parent-uri'] = $item_id;
425                         $datarray['uid'] = $importer['importer_uid'];
426                         $datarray['contact-id'] = $importer['id'];
427                         $r = item_store($datarray);
428                         continue;
429                 }
430         }
431
432         xml_status(0);
433         // NOTREACHED
434
435 }
436
437
438 function dfrn_notify_content(&$a) {
439
440         if(x($_GET,'dfrn_id')) {
441
442                 // initial communication from external contact, $direction is their direction.
443                 // If this is a duplex communication, ours will be the opposite.
444
445                 $dfrn_id = notags(trim($_GET['dfrn_id']));
446                 $dfrn_version = (float) $_GET['dfrn_version'];
447
448                 logger('dfrn_notify: new notification dfrn_id=' . $dfrn_id);
449
450                 $direction = (-1);
451                 if(strpos($dfrn_id,':') == 1) {
452                         $direction = intval(substr($dfrn_id,0,1));
453                         $dfrn_id = substr($dfrn_id,2);
454                 }
455
456                 $hash = random_string();
457
458                 $status = 0;
459
460                 $r = q("DELETE FROM `challenge` WHERE `expire` < " . intval(time()));
461
462                 $r = q("INSERT INTO `challenge` ( `challenge`, `dfrn-id`, `expire` )
463                         VALUES( '%s', '%s', '%s') ",
464                         dbesc($hash),
465                         dbesc($dfrn_id),
466                         intval(time() + 60 )
467                 );
468
469
470                 $sql_extra = '';
471                 switch($direction) {
472                         case (-1):
473                                 $sql_extra = sprintf(" AND ( `issued-id` = '%s' OR `dfrn-id` = '%s' ) ", dbesc($dfrn_id), dbesc($dfrn_id));
474                                 $my_id = $dfrn_id;
475                                 break;
476                         case 0:
477                                 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
478                                 $my_id = '1:' . $dfrn_id;
479                                 break;
480                         case 1:
481                                 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
482                                 $my_id = '0:' . $dfrn_id;
483                                 break;
484                         default:
485                                 $status = 1;
486                                 break; // NOTREACHED
487                 }
488
489                 $r = q("SELECT `contact`.*, `user`.`nickname` FROM `contact` LEFT JOIN `user` ON `user`.`uid` = `contact`.`uid` 
490                                 WHERE `contact`.`blocked` = 0 AND `contact`.`pending` = 0 AND `user`.`nickname` = '%s' $sql_extra LIMIT 1",
491                                 dbesc($a->argv[1])
492                 );
493
494                 if(! count($r))
495                         $status = 1;
496
497                 $challenge = '';
498                 $encrypted_id = '';
499                 $id_str = $my_id . '.' . mt_rand(1000,9999);
500
501                 if((($r[0]['duplex']) && strlen($r[0]['pubkey'])) || (! strlen($r[0]['prvkey']))) {
502                         openssl_public_encrypt($hash,$challenge,$r[0]['pubkey']);
503                         openssl_public_encrypt($id_str,$encrypted_id,$r[0]['pubkey']);
504                 }
505                 else {
506                         openssl_private_encrypt($hash,$challenge,$r[0]['prvkey']);
507                         openssl_private_encrypt($id_str,$encrypted_id,$r[0]['prvkey']);
508                 }
509
510                 $challenge    = bin2hex($challenge);
511                 $encrypted_id = bin2hex($encrypted_id);
512
513                 $rino = ((function_exists('mcrypt_encrypt')) ? 1 : 0);
514
515                 $rino_enable = get_config('system','rino_encrypt');
516
517                 if(! $rino_enable)
518                         $rino = 0;
519
520
521                 header("Content-type: text/xml");
522
523                 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" 
524                         . '<dfrn_notify>' . "\r\n"
525                         . "\t" . '<status>' . $status . '</status>' . "\r\n"
526                         . "\t" . '<dfrn_version>' . DFRN_PROTOCOL_VERSION . '</dfrn_version>' . "\r\n"
527                         . "\t" . '<rino>' . $rino . '</rino>' . "\r\n" 
528                         . "\t" . '<dfrn_id>' . $encrypted_id . '</dfrn_id>' . "\r\n" 
529                         . "\t" . '<challenge>' . $challenge . '</challenge>' . "\r\n"
530                         . '</dfrn_notify>' . "\r\n" ;
531
532                 killme();
533         }
534
535 }