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