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