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