]> git.mxchange.org Git - friendica.git/blob - mod/dfrn_notify.php
3ceb4b3fcc7e1433d0bdda282d5110e8db756b5e
[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                         // name of the automated email sender
177                         $msg['notificationfromname']    = t('Administrator');
178                         // noreply address to send from
179                         $msg['notificationfromemail']   = t('noreply') . '@' . $a->get_hostname();                              
180
181                         // text version
182                         // process the message body to display properly in text mode
183                         //              1) substitute a \n character for the "\" then "n", so it behaves properly (it doesn't come in as a \n character)
184                         //              2) remove escape slashes
185                         //              3) decode any bbcode from the message editor
186                         //              4) decode any encoded html tags
187                         //              5) remove html tags
188                         $msg['textversion']
189                                 = strip_tags(html_entity_decode(bbcode(stripslashes(str_replace(array("\\r\\n", "\\r", "\\n"), "\n",$msg['body']))),ENT_QUOTES,'UTF-8'));
190                                 
191                         // html version
192                         // process the message body to display properly in text mode
193                         //              1) substitute a <br /> tag for the "\" then "n", so it behaves properly (it doesn't come in as a \n character)
194                         //              2) remove escape slashes
195                         //              3) decode any bbcode from the message editor
196                         //              4) decode any encoded html tags
197                         $msg['htmlversion']     
198                                 = html_entity_decode(bbcode(stripslashes(str_replace(array("\\r\\n", "\\r","\\n\\n" ,"\\n"), "<br />\n",$msg['body']))));
199
200                         // load the template for private message notifications
201                         $tpl = load_view_file('view/mail_received_html_body_eml.tpl');
202                         $email_html_body_tpl = replace_macros($tpl,array(
203                                 '$siteName'             => $a->config['sitename'],                              // name of this site
204                                 '$siteurl'              => $a->get_baseurl(),                                   // descriptive url of this site
205                                 '$thumb'                => $importer['thumb'],                                  // thumbnail url for sender icon
206                                 '$email'                => $importer['email'],                                  // email address to send to
207                                 '$url'                  => $importer['url'],                                    // full url for the site
208                                 '$from'                 => $msg['from-name'],                                   // name of the person sending the message
209                                 '$title'                => stripslashes($msg['title']),                 // subject of the message
210                                 '$htmlversion'  => $msg['htmlversion'],                                 // html version of the message
211                                 '$mimeboundary' => $msg['mimeboundary'],                                // mime message divider
212                                 '$hostname'             => $a->get_hostname()                                   // name of this host
213                         ));
214                         
215                         // load the template for private message notifications
216                         $tpl = load_view_file('view/mail_received_text_body_eml.tpl');
217                         $email_text_body_tpl = replace_macros($tpl,array(
218                                 '$siteName'             => $a->config['sitename'],                              // name of this site
219                                 '$siteurl'              => $a->get_baseurl(),                                   // descriptive url of this site
220                                 '$thumb'                => $importer['thumb'],                                  // thumbnail url for sender icon
221                                 '$email'                => $importer['email'],                                  // email address to send to
222                                 '$url'                  => $importer['url'],                                    // full url for the site
223                                 '$from'                 => $msg['from-name'],                                   // name of the person sending the message
224                                 '$title'                => stripslashes($msg['title']),                 // subject of the message
225                                 '$textversion'  => $msg['textversion'],                                 // text version of the message
226                                 '$mimeboundary' => $msg['mimeboundary'],                                // mime message divider
227                                 '$hostname'             => $a->get_hostname()                                   // name of this host
228                         ));
229
230                         // use the EmailNotification library to send the message
231                         require_once("include/EmailNotification.php");
232                         EmailNotification::sendTextHtmlEmail(
233                                 $msg['notificationfromname'],
234                                 $msg['notificationfromemail'],
235                                 $msg['notificationfromemail'],
236                                 $importer['email'],
237                                 t('New mail received at ') . $a->config['sitename'],
238                                 $email_html_body_tpl,
239                                 $email_text_body_tpl
240                         );
241                 }
242                 xml_status(0);
243                 // NOTREACHED
244         }       
245         
246         logger('dfrn_notify: feed item count = ' . $feed->get_item_quantity());
247
248         // process any deleted entries
249
250         $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
251         if(is_array($del_entries) && count($del_entries)) {
252                 foreach($del_entries as $dentry) {
253                         $deleted = false;
254                         if(isset($dentry['attribs']['']['ref'])) {
255                                 $uri = $dentry['attribs']['']['ref'];
256                                 $deleted = true;
257                                 if(isset($dentry['attribs']['']['when'])) {
258                                         $when = $dentry['attribs']['']['when'];
259                                         $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
260                                 }
261                                 else
262                                         $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
263                         }
264                         if($deleted) {
265                                 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
266                                         dbesc($uri),
267                                         intval($importer['importer_uid'])
268                                 );
269                                 if(count($r)) {
270                                         $item = $r[0];
271
272                                         if(! $item['deleted'])
273                                                 logger('dfrn_notify: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
274
275                                         if($item['uri'] == $item['parent-uri']) {
276                                                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s'
277                                                         WHERE `parent-uri` = '%s' AND `uid` = %d",
278                                                         dbesc($when),
279                                                         dbesc(datetime_convert()),
280                                                         dbesc($item['uri']),
281                                                         intval($importer['importer_uid'])
282                                                 );
283                                         }
284                                         else {
285                                                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s' 
286                                                         WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
287                                                         dbesc($when),
288                                                         dbesc(datetime_convert()),
289                                                         dbesc($uri),
290                                                         intval($importer['importer_uid'])
291                                                 );
292                                                 if($item['last-child']) {
293                                                         // ensure that last-child is set in case the comment that had it just got wiped.
294                                                         q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
295                                                                 dbesc(datetime_convert()),
296                                                                 dbesc($item['parent-uri']),
297                                                                 intval($item['uid'])
298                                                         );
299                                                         // who is the last child now? 
300                                                         $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `uid` = %d
301                                                                 ORDER BY `created` DESC LIMIT 1",
302                                                                         dbesc($item['parent-uri']),
303                                                                         intval($importer['importer_uid'])
304                                                         );
305                                                         if(count($r)) {
306                                                                 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
307                                                                         intval($r[0]['id'])
308                                                                 );
309                                                         }       
310                                                 }
311                                         }       
312                                 }
313                         }
314                 }
315         }
316
317
318         foreach($feed->get_items() as $item) {
319
320                 $is_reply = false;              
321                 $item_id = $item->get_id();
322                 $rawthread = $item->get_item_tags( NAMESPACE_THREAD, 'in-reply-to');
323                 if(isset($rawthread[0]['attribs']['']['ref'])) {
324                         $is_reply = true;
325                         $parent_uri = $rawthread[0]['attribs']['']['ref'];
326                 }
327
328                 if($is_reply) {
329                         if($feed->get_item_quantity() == 1) {
330                                 logger('dfrn_notify: received remote comment');
331                                 $is_like = false;
332                                 // remote reply to our post. Import and then notify everybody else.
333                                 $datarray = get_atom_elements($feed,$item);
334                                 $datarray['type'] = 'remote-comment';
335                                 $datarray['wall'] = 1;
336                                 $datarray['parent-uri'] = $parent_uri;
337                                 $datarray['uid'] = $importer['importer_uid'];
338                                 $datarray['contact-id'] = $importer['id'];
339                                 if(($datarray['verb'] == ACTIVITY_LIKE) || ($datarray['verb'] == ACTIVITY_DISLIKE)) {
340                                         $is_like = true;
341                                         $datarray['type'] = 'activity';
342                                         $datarray['gravity'] = GRAVITY_LIKE;
343                                         $datarray['last-child'] = 0;
344                                 }
345                                 $posted_id = item_store($datarray);
346                                 $parent = 0;
347
348                                 if($posted_id) {
349                                         $r = q("SELECT `parent` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
350                                                 intval($posted_id),
351                                                 intval($importer['importer_uid'])
352                                         );
353                                         if(count($r))
354                                                 $parent = $r[0]['parent'];
355                         
356                                         if(! $is_like) {
357                                                 $r1 = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `uid` = %d AND `parent` = %d",
358                                                         dbesc(datetime_convert()),
359                                                         intval($importer['importer_uid']),
360                                                         intval($r[0]['parent'])
361                                                 );
362
363                                                 $r2 = q("UPDATE `item` SET `last-child` = 1, `changed` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
364                                                         dbesc(datetime_convert()),
365                                                         intval($importer['importer_uid']),
366                                                         intval($posted_id)
367                                                 );
368                                         }
369
370                                         if($posted_id && $parent) {
371                                 
372                                                 proc_run('php',"include/notifier.php","comment-import","$posted_id");
373                                         
374                                                 if((! $is_like) && ($importer['notify-flags'] & NOTIFY_COMMENT) && (! $importer['self'])) {
375                                                         require_once('bbcode.php');
376                                                         $from = stripslashes($datarray['author-name']);
377                                                         /*
378                                                         $tpl = load_view_file('view/cmnt_received_eml.tpl');                    
379                                                         $email_tpl = replace_macros($tpl, array(
380                                                                 '$sitename' => $a->config['sitename'],
381                                                                 '$siteurl' =>  $a->get_baseurl(),
382                                                                 '$username' => $importer['username'],
383                                                                 '$email' => $importer['email'],
384                                                                 '$display' => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id, 
385                                                                 '$from' => $from,
386                                                                 '$body' => html_entity_decode(strip_tags(bbcode(stripslashes($datarray['body']))), ENT_QUOTES, 'UTF-8')
387                                                         ));
388         
389                                                         $res = mail($importer['email'], $from . t(' commented on an item at ') . $a->config['sitename'],
390                                                                 $email_tpl, "From: " . t('Administrator') . '@' . $a->get_hostname() );
391                                                         */
392                                                         // name of the automated email sender
393                                                         $msg['notificationfromname']    = stripslashes($datarray['author-name']);;
394                                                         // noreply address to send from
395                                                         $msg['notificationfromemail']   = t('noreply') . '@' . $a->get_hostname();                              
396
397                                                         // text version
398                                                         // process the message body to display properly in text mode
399                                                         $msg['textversion']
400                                                                 = html_entity_decode(strip_tags(bbcode(stripslashes($datarray['body']))), ENT_QUOTES, 'UTF-8');
401                                 
402                                                         // html version
403                                                         // process the message body to display properly in text mode
404                                                         $msg['htmlversion']     
405                                                                 = html_entity_decode(bbcode(stripslashes(str_replace(array("\\r\\n", "\\r","\\n\\n" ,"\\n"), "<br />\n",$datarray['body']))));
406
407                                                         // load the template for private message notifications
408                                                         $tpl = load_view_file('view/cmnt_received_html_body_eml.tpl');
409                                                         $email_html_body_tpl = replace_macros($tpl,array(
410                                                                 '$sitename'             => $a->config['sitename'],                              // name of this site
411                                                                 '$siteurl'              => $a->get_baseurl(),                                   // descriptive url of this site
412                                                                 '$thumb'                => $datarray['author-avatar'],                  // thumbnail url for sender icon
413                                                                 '$email'                => $importer['email'],                                  // email address to send to
414                                                                 '$url'                  => $datarray['author-link'],                    // full url for the site
415                                                                 '$from'                 => $from,                                                               // name of the person sending the message
416                                                                 '$body'                 => 'q1' .$msg['htmlversion'],                                   // html version of the message
417                                                                 '$display'              => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $r,
418                                                         ));
419                         
420                                                         // load the template for private message notifications
421                                                         $tpl = load_view_file('view/cmnt_received_text_body_eml.tpl');
422                                                         $email_text_body_tpl = replace_macros($tpl,array(
423                                                                 '$sitename'             => $a->config['sitename'],                              // name of this site
424                                                                 '$siteurl'              => $a->get_baseurl(),                                   // descriptive url of this site
425                                                                 '$thumb'                => $datarray['author-avatar'],                  // thumbnail url for sender icon
426                                                                 '$email'                => $importer['email'],                                  // email address to send to
427                                                                 '$url'                  => $datarray['author-link'],                    // full url for the site
428                                                                 '$from'                 => $from,                                                               // name of the person sending the message
429                                                                 '$body'                 => $msg['textversion'],                                 // text version of the message
430                                                                 '$display'              => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $r,
431                                                         ));
432
433                                                         // use the EmailNotification library to send the message
434                                                         require_once("include/EmailNotification.php");
435                                                         EmailNotification::sendTextHtmlEmail(
436                                                                 $msg['notificationfromname'],
437                                                                 t("Administrator@") . $a->get_hostname(),
438                                                                 t("noreply") . '@' . $a->get_hostname(),
439                                                                 $importer['email'],
440                                                                 $from . t(" commented on an item at ") . $a->config['sitename'],
441                                                                 $email_html_body_tpl,
442                                                                 $email_text_body_tpl
443                                                         );
444
445                                                 }
446                                         }
447                                         xml_status(0);
448                                         // NOTREACHED
449                                 }
450                         }
451                         else {
452
453                                 // regular comment that is part of this total conversation. Have we seen it? If not, import it.
454
455                                 $item_id  = $item->get_id();
456                                 $datarray = get_atom_elements($feed,$item);
457
458                                 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
459                                         dbesc($item_id),
460                                         intval($importer['importer_uid'])
461                                 );
462
463                                 // Update content if 'updated' changes
464
465                                 if(count($r)) {
466                                         if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {  
467                                                 $r = q("UPDATE `item` SET `body` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
468                                                         dbesc($datarray['body']),
469                                                         dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
470                                                         dbesc($item_id),
471                                                         intval($importer['importer_uid'])
472                                                 );
473                                         }
474
475                                         // update last-child if it changes
476
477                                         $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
478                                         if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
479                                                 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
480                                                         dbesc(datetime_convert()),
481                                                         dbesc($parent_uri),
482                                                         intval($importer['importer_uid'])
483                                                 );
484                                                 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s'  WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
485                                                         intval($allow[0]['data']),
486                                                         dbesc(datetime_convert()),
487                                                         dbesc($item_id),
488                                                         intval($importer['importer_uid'])
489                                                 );
490                                         }
491                                         continue;
492                                 }
493
494                                 $datarray['parent-uri'] = $parent_uri;
495                                 $datarray['uid'] = $importer['importer_uid'];
496                                 $datarray['contact-id'] = $importer['id'];
497                                 if(($datarray['verb'] == ACTIVITY_LIKE) || ($datarray['verb'] == ACTIVITY_DISLIKE)) {
498                                         $datarray['type'] = 'activity';
499                                         $datarray['gravity'] = GRAVITY_LIKE;
500                                 }
501                                 $r = item_store($datarray);
502
503                                 // find out if our user is involved in this conversation and wants to be notified.
504                         
505                                 if(($datarray['type'] != 'activity') && ($importer['notify-flags'] & NOTIFY_COMMENT)) {
506
507                                         $myconv = q("SELECT `author-link`, `author-avatar` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 ",
508                                                 dbesc($parent_uri),
509                                                 intval($importer['importer_uid'])
510                                         );
511                                         if(count($myconv)) {
512                                                 $importer_url = $a->get_baseurl() . '/profile/' . $importer['nickname'];
513                                                 foreach($myconv as $conv) {
514                                                         if(! link_compare($conv['author-link'],$importer_url))
515                                                                 continue;
516                                                         require_once('bbcode.php');
517                                                         $from = stripslashes($datarray['author-name']);
518                                                         /*
519                                                         $tpl = load_view_file('view/cmnt_received_eml.tpl');    
520                                                         $email_tpl = replace_macros($tpl, array(
521                                                                 '$sitename' => $a->config['sitename'],
522                                                                 '$siteurl' =>  $a->get_baseurl(),
523                                                                 '$username' => $importer['username'],
524                                                                 '$email' => $importer['email'],
525                                                                 '$from' => $from,
526                                                                 '$display' => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $r,
527                                                                 '$body' => html_entity_decode(strip_tags(bbcode(stripslashes($datarray['body']))), ENT_QUOTES, 'UTF-8')
528                                                         ));
529
530                                                         $res = mail($importer['email'], $from . t(" commented on an item at ") 
531                                                                 . $a->config['sitename'],
532                                                                 $email_tpl,t("From: Administrator@") . $a->get_hostname() );
533                                                         */      
534                                                         
535                                                                 
536                                                         
537                                                         // name of the automated email sender
538                                                         $msg['notificationfromname']    = stripslashes($datarray['author-name']);;
539                                                         // noreply address to send from
540                                                         $msg['notificationfromemail']   = t('noreply') . '@' . $a->get_hostname();                              
541
542                                                         // text version
543                                                         // process the message body to display properly in text mode
544                                                         $msg['textversion']
545                                                                 = html_entity_decode(strip_tags(bbcode(stripslashes($datarray['body']))), ENT_QUOTES, 'UTF-8');
546                                 
547                                                         // html version
548                                                         // process the message body to display properly in text mode
549                                                         $msg['htmlversion']     
550                                                                 = html_entity_decode(bbcode(stripslashes(str_replace(array("\\r\\n", "\\r","\\n\\n" ,"\\n"), "<br />\n",$datarray['body']))));
551
552                                                         // load the template for private message notifications
553                                                         $tpl = load_view_file('view/cmnt_received_html_body_eml.tpl');
554                                                         $email_html_body_tpl = replace_macros($tpl,array(
555                                                                 '$sitename'             => $a->config['sitename'],                              // name of this site
556                                                                 '$siteurl'              => $a->get_baseurl(),                                   // descriptive url of this site
557                                                                 '$thumb'                => $conv['author-avatar'],                              // thumbnail url for sender icon
558                                                                 '$url'                  => $conv['author-link'],                                // full url for the site
559                                                                 '$from'                 => $from,                                                               // name of the person sending the message
560                                                                 '$body'                 => $msg['htmlversion'],                                 // html version of the message
561                                                                 '$display'              => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $r,
562                                                         ));
563                         
564                                                         // load the template for private message notifications
565                                                         $tpl = load_view_file('view/cmnt_received_text_body_eml.tpl');
566                                                         $email_text_body_tpl = replace_macros($tpl,array(
567                                                                 '$sitename'             => $a->config['sitename'],                              // name of this site
568                                                                 '$siteurl'              => $a->get_baseurl(),                                   // descriptive url of this site
569                                                                 '$thumb'                => $conv['author-avatar'],                              // thumbnail url for sender icon
570                                                                 '$url'                  => $conv['author-link'],                                // full url for the site
571                                                                 '$from'                 => $from,                                                               // name of the person sending the message
572                                                                 '$body'                 => $msg['textversion'],                                 // text version of the message
573                                                                 '$display'              => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $r,
574                                                         ));
575
576                                                         // use the EmailNotification library to send the message
577                                                         require_once("include/EmailNotification.php");
578                                                         EmailNotification::sendTextHtmlEmail(
579                                                                 $msg['notificationfromname'],
580                                                                 t("Administrator@") . $a->get_hostname(),
581                                                                 t("noreply") . '@' . $a->get_hostname(),
582                                                                 $importer['email'],
583                                                                 $from . t(" commented on an item at ") . $a->config['sitename'],
584                                                                 $email_html_body_tpl,
585                                                                 $email_text_body_tpl
586                                                         );
587
588                                                         break;
589                                                 }
590                                         }
591                                 }
592                                 continue;
593                         }
594                 }
595
596                 else {
597
598                         // Head post of a conversation. Have we seen it? If not, import it.
599
600
601                         $item_id  = $item->get_id();
602                         $datarray = get_atom_elements($feed,$item);
603
604                         $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
605                                 dbesc($item_id),
606                                 intval($importer['importer_uid'])
607                         );
608
609                         // Update content if 'updated' changes
610
611                         if(count($r)) {
612                                 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {  
613                                         $r = q("UPDATE `item` SET `body` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
614                                                 dbesc($datarray['body']),
615                                                 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
616                                                 dbesc($item_id),
617                                                 intval($importer['importer_uid'])
618                                         );
619                                 }
620
621                                 // update last-child if it changes
622
623                                 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
624                                 if($allow && $allow[0]['data'] != $r[0]['last-child']) {
625                                         $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
626                                                 intval($allow[0]['data']),
627                                                 dbesc(datetime_convert()),
628                                                 dbesc($item_id),
629                                                 intval($importer['importer_uid'])
630                                         );
631                                 }
632                                 continue;
633                         }
634
635                         $datarray['parent-uri'] = $item_id;
636                         $datarray['uid'] = $importer['importer_uid'];
637                         $datarray['contact-id'] = $importer['id'];
638                         $r = item_store($datarray);
639                         continue;
640                 }
641         }
642
643         xml_status(0);
644         // NOTREACHED
645
646 }
647
648
649 function dfrn_notify_content(&$a) {
650
651         if(x($_GET,'dfrn_id')) {
652
653                 // initial communication from external contact, $direction is their direction.
654                 // If this is a duplex communication, ours will be the opposite.
655
656                 $dfrn_id = notags(trim($_GET['dfrn_id']));
657                 $dfrn_version = (float) $_GET['dfrn_version'];
658
659                 logger('dfrn_notify: new notification dfrn_id=' . $dfrn_id);
660
661                 $direction = (-1);
662                 if(strpos($dfrn_id,':') == 1) {
663                         $direction = intval(substr($dfrn_id,0,1));
664                         $dfrn_id = substr($dfrn_id,2);
665                 }
666
667                 $hash = random_string();
668
669                 $status = 0;
670
671                 $r = q("DELETE FROM `challenge` WHERE `expire` < " . intval(time()));
672
673                 $r = q("INSERT INTO `challenge` ( `challenge`, `dfrn-id`, `expire` )
674                         VALUES( '%s', '%s', %d ) ",
675                         dbesc($hash),
676                         dbesc($dfrn_id),
677                         intval(time() + 90 )
678                 );
679
680                 logger('dfrn_notify: challenge=' . $hash );
681
682                 $sql_extra = '';
683                 switch($direction) {
684                         case (-1):
685                                 $sql_extra = sprintf(" AND ( `issued-id` = '%s' OR `dfrn-id` = '%s' ) ", dbesc($dfrn_id), dbesc($dfrn_id));
686                                 $my_id = $dfrn_id;
687                                 break;
688                         case 0:
689                                 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
690                                 $my_id = '1:' . $dfrn_id;
691                                 break;
692                         case 1:
693                                 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
694                                 $my_id = '0:' . $dfrn_id;
695                                 break;
696                         default:
697                                 $status = 1;
698                                 break; // NOTREACHED
699                 }
700
701                 $r = q("SELECT `contact`.*, `user`.`nickname` FROM `contact` LEFT JOIN `user` ON `user`.`uid` = `contact`.`uid` 
702                                 WHERE `contact`.`blocked` = 0 AND `contact`.`pending` = 0 AND `user`.`nickname` = '%s' $sql_extra LIMIT 1",
703                                 dbesc($a->argv[1])
704                 );
705
706                 if(! count($r))
707                         $status = 1;
708
709                 $challenge = '';
710                 $encrypted_id = '';
711                 $id_str = $my_id . '.' . mt_rand(1000,9999);
712
713                 if((($r[0]['duplex']) && strlen($r[0]['prvkey'])) || (! strlen($r[0]['pubkey']))) {
714                         openssl_private_encrypt($hash,$challenge,$r[0]['prvkey']);
715                         openssl_private_encrypt($id_str,$encrypted_id,$r[0]['prvkey']);
716                 }
717                 else {
718                         openssl_public_encrypt($hash,$challenge,$r[0]['pubkey']);
719                         openssl_public_encrypt($id_str,$encrypted_id,$r[0]['pubkey']);
720                 }
721
722                 $challenge    = bin2hex($challenge);
723                 $encrypted_id = bin2hex($encrypted_id);
724
725                 $rino = ((function_exists('mcrypt_encrypt')) ? 1 : 0);
726
727                 $rino_enable = get_config('system','rino_encrypt');
728
729                 if(! $rino_enable)
730                         $rino = 0;
731
732
733                 header("Content-type: text/xml");
734
735                 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" 
736                         . '<dfrn_notify>' . "\r\n"
737                         . "\t" . '<status>' . $status . '</status>' . "\r\n"
738                         . "\t" . '<dfrn_version>' . DFRN_PROTOCOL_VERSION . '</dfrn_version>' . "\r\n"
739                         . "\t" . '<rino>' . $rino . '</rino>' . "\r\n" 
740                         . "\t" . '<dfrn_id>' . $encrypted_id . '</dfrn_id>' . "\r\n" 
741                         . "\t" . '<challenge>' . $challenge . '</challenge>' . "\r\n"
742                         . '</dfrn_notify>' . "\r\n" ;
743
744                 killme();
745         }
746
747 }