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