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