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