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