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