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