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